From b6b49ed7eae56bfc349b6deaa7faee2b06b2afdc Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 11:15:33 +0800 Subject: [PATCH 01/66] feat(multiselect): add the opt-in multi-select page control --- cmd/viva/initfiles/AGENTS.md.txt | 1 + multiselect/multiselect.go | 155 +++++++++++++++ multiselect/multiselect_test.go | 183 ++++++++++++++++++ .../content/guides/en/declarative-layout.md | 2 +- .../content/guides/zh/declarative-layout.md | 2 +- 5 files changed, 341 insertions(+), 2 deletions(-) create mode 100644 multiselect/multiselect.go create mode 100644 multiselect/multiselect_test.go diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 746f5cbc..ebd0b6a3 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -198,6 +198,7 @@ func (m *model) page(c ui.C) { `Choice`, `Tabs` and `Select` write the value in the declaration, so disable them with an `if`, not a chained `.Disabled`: `if !m.locked { if ui.Tabs(c, &m.tab, tabs, nil).Changed() { ... } }`. `Tabs` and `Select` also honor a chained `.Disabled` for input; `Choice` ignores it, so never rely on it there. +- Removable chips with a filtered query are the opt-in package `github.com/vivaui/viva/multiselect`: keep `picker := multiselect.New(&m.tags)` in the model and declare `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`; `tagOptions.At(i)` and `tagRemoves.At(i)` name the popup rows and chip remove buttons. Import it only when used. - A long list to choose from by typing: `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` (Select's arguments plus a label); it filters as the user types. `.Clearable()` adds a clear button, `.Empty("No zone")` is what an empty list says, `.Creatable("")` offers what was typed as a new choice, read with `.Created()`. diff --git a/multiselect/multiselect.go b/multiselect/multiselect.go new file mode 100644 index 00000000..b0b00006 --- /dev/null +++ b/multiselect/multiselect.go @@ -0,0 +1,155 @@ +// Package multiselect is the opt-in page control for a multi-select: removable +// chips, a native query input and a filtered popup, painted by +// components.PaintMultiSelect and driven by base.MultiSelectState. +// +// It is a separate package so an application that does not import it pays +// nothing for it: the control's types and methods are not reachable from the +// page engine or package ui. +// +// picker := multiselect.New(&m.tags) +// ... +// picker.View(c, multiselect.Spec{ +// Label: "Tags", Placeholder: "Add a tag", +// Options: tagOptions, Removes: tagRemoves, +// }).FillWidth() +package multiselect + +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// State is the selection, options and query of one picker; Option is one +// selectable value. They are the engine's types, re-exported so an application +// that only uses this package does not import package base. +type ( + State = base.MultiSelectState + Option = base.MultiSelectOption +) + +// Spec supplies the control's words and the two scopes of its popup, from the +// same gfx.Tree the page names its elements in: +// Options.At(i) names choice i and Removes.At(i) names the remove button of +// value i. Make them once in the application's tree; an empty scope paints the +// rows but gives them no identities. +type Spec struct { + Label, Placeholder, EmptyLabel, CreatePrefix string + MaxRows int + Invalid bool + Options, Removes gfx.Scope +} + +// Picker is one MultiSelect's page control. Keep it in the model beside the +// state; one Picker belongs to one state and one place on a page. Its handlers +// and draw function are made once, so a warm paint allocates nothing. +type Picker struct { + State *base.MultiSelectState + + spec Spec + handlers ui.Handlers + drawFn func(*ui.DrawContext) + input window.TextInput +} + +// New returns a picker for state. +func New(state *base.MultiSelectState) *Picker { + if state == nil { + panic("multiselect: New needs its MultiSelectState") + } + p := &Picker{State: state} + p.handlers.Role = gfx.RoleCombobox + p.handlers.Key = p.key + p.handlers.Pointer = p.pointer + p.handlers.Scroll = p.scroll + p.handlers.Text = p.text + p.drawFn = p.draw + p.input.Editor = &state.Query + return p +} + +// View declares the picker at c. Give it a width: it is as tall as the theme's +// control, unless a Height follows. Declare it on its own, not inside a Memo. +func (p *Picker) View(c ui.C, spec Spec) ui.Box { + if p.State == nil || p.drawFn == nil { + panic("multiselect: use New to make a Picker") + } + p.spec = spec + return ui.Control(c, spec.Label, &p.handlers). + Height(c.Theme().Metrics.ControlHeight). + Draw(p.drawFn) +} + +// Wheel scrolls the open popup. A page whose wheel handler goes elsewhere +// first calls it while Open, then falls back to the page: +// +// if m.tags.Open && m.tagsPicker.Wheel(e) { return } +func (p *Picker) Wheel(event gfx.ScrollEvent) bool { + if p.State == nil || !p.State.Open { + return false + } + return p.State.Wheel(event) +} + +func (p *Picker) key(event gfx.KeyEvent) gfx.EventResult { + return p.State.Key(event) +} + +func (p *Picker) pointer(event gfx.PointerEvent) gfx.EventResult { + return p.State.Pointer(event) +} + +func (p *Picker) scroll(event gfx.ScrollEvent) gfx.EventResult { + if p.Wheel(event) { + return gfx.EventResult{Handled: true, Repaint: true} + } + return gfx.EventResult{} +} + +func (p *Picker) text(window.TextInputContext) *window.TextInput { + return &p.input +} + +func (p *Picker) draw(d *ui.DrawContext) { + parts := p.handlers.Parts() + if parts.IsZero() { + return + } + options := components.MultiSelectOptions{ + InputID: d.Node.ID, TriggerID: parts.At(0), DismissID: parts.At(1), + Scope: parts.At(2), ScrollID: parts.At(3), + OptionIDs: p.spec.Options, RemoveIDs: p.spec.Removes, + Label: p.spec.Label, Placeholder: p.spec.Placeholder, + EmptyLabel: p.spec.EmptyLabel, CreatePrefix: p.spec.CreatePrefix, + Viewport: d.Frame.GetBounds(), Layer: d.Frame.WidgetLayer() + 2, + Disabled: d.State.Disabled, Invalid: p.spec.Invalid, MaxRows: p.spec.MaxRows, + } + components.PaintMultiSelect(d.Canvas, *d.Theme, d.Rect, p.State, options) + p.pick(d.Canvas, options) +} + +// pick applies this paint's presses. The input itself is the control's own hit, +// so the platform's text service finds its editor through Handlers.Text; the +// trigger, the dismiss target and the popup's rows are parts. +func (p *Picker) pick(canvas *gfx.Canvas, options components.MultiSelectOptions) { + if canvas == nil { + return + } + if canvas.Clicked(options.TriggerID) { + p.State.Open = !p.State.Open + return + } + if canvas.Clicked(options.DismissID) { + p.State.Open = false + return + } + if index, ok := canvas.ClickedIn(options.RemoveIDs); ok { + p.State.Remove(index) + return + } + if index, ok := canvas.ClickedIn(options.OptionIDs); ok { + p.State.Choose(index) + } +} diff --git a/multiselect/multiselect_test.go b/multiselect/multiselect_test.go new file mode 100644 index 00000000..a36ebf01 --- /dev/null +++ b/multiselect/multiselect_test.go @@ -0,0 +1,183 @@ +package multiselect_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/multiselect" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +type harness struct { + t *testing.T + state *base.MultiSelectState + pick *multiselect.Picker + box ui.Box + page *ui.Page + drv *app.Driver + inv *app.Invalidator + opts gfx.Scope + rem gfx.Scope +} + +func open(t *testing.T) *harness { + t.Helper() + h := &harness{t: t, state: &base.MultiSelectState{AllowCreate: true}} + h.state.SetOptions([]base.MultiSelectOption{{Value: "dev", Label: "Development"}, {Value: "ops", Label: "Operations"}}) + h.pick = multiselect.New(h.state) + var tree gfx.Tree + feature := tree.Feature("tags") + h.opts = tree.Sub(feature, tree.Name("options")) + h.rem = tree.Sub(feature, tree.Name("removes")) + h.page = ui.NewPage(ui.PageConfig{Tree: &tree, View: func(c ui.C) { + h.box = h.pick.View(c, multiselect.Spec{ + Label: "Tags", Placeholder: "Add a tag", Options: h.opts, Removes: h.rem, + }).Width(260) + }}) + h.inv = new(app.Invalidator) + var err error + h.drv, err = app.NewDriver(ui.Configure(h.page, app.Config{Width: 480, Height: 480, Invalidator: h.inv}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(h.drv.Close) + h.repaint() + return h +} + +func (h *harness) repaint() { + h.t.Helper() + h.inv.Invalidate() + if err := h.drv.Pump(); err != nil { + h.t.Fatal(err) + } +} + +func (h *harness) hit(id gfx.ID) gfx.Hit { + h.t.Helper() + for _, hit := range h.drv.Snapshot().Hits { + if hit.ID == id { + return hit + } + } + h.t.Fatalf("no hit with identity %v", id) + return gfx.Hit{} +} + +func center(r gfx.Rect) (float32, float32) { return r.X + r.Width/2, r.Y + r.Height/2 } + +// The opt-in picker is a page control: its trigger opens the popup, a choice +// becomes a chip, and the chip's remove button takes it back. +func TestPickerChoosesAndRemovesValues(t *testing.T) { + h := open(t) + r := h.box.Rect() + if err := h.drv.Click(r.X+r.Width-10, r.Y+r.Height/2); err != nil { + t.Fatal(err) + } + h.repaint() + if !h.state.Open { + t.Fatal("the trigger did not open the popup") + } + choice := h.hit(h.opts.At(0)) + if err := h.drv.Click(center(choice.Bounds)); err != nil { + t.Fatal(err) + } + h.repaint() + if got := h.state.Values(); len(got) != 1 || got[0] != "dev" { + t.Fatalf("values = %v, want [dev]", got) + } + remove := h.hit(h.rem.At(0)) + if err := h.drv.Click(center(remove.Bounds)); err != nil { + t.Fatal(err) + } + h.repaint() + if got := h.state.Values(); len(got) != 0 { + t.Fatalf("values = %v after remove, want none", got) + } +} + +// The query editor is the platform's: the control hands it the state's editor. +func TestPickerHandsTheQueryToTheTextService(t *testing.T) { + h := open(t) + id := h.box.N().ID + input := h.page.TextInput(window.TextInputContext{ID: id}) + if input == nil || input.Editor != &h.state.Query { + t.Fatal("the picker did not hand its query editor to the text service") + } +} + +// Escape keeps the popup's navigation on the control and away from the page. +func TestPickerKeyClosesThePopup(t *testing.T) { + h := open(t) + r := h.box.Rect() + if err := h.drv.Click(r.X+20, r.Y+r.Height/2); err != nil { + t.Fatal(err) + } + h.state.Open = true + h.repaint() + if err := h.drv.Key(gfx.KeyEscape, 0); err != nil { + t.Fatal(err) + } + if h.state.Open { + t.Fatal("Escape did not close the popup") + } +} + +func drawPickerPage(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 480}, view) + canvas.EndFrame() +} + +func BenchmarkPickerPaint(b *testing.B) { + state := &base.MultiSelectState{Open: true} + state.SetOptions([]base.MultiSelectOption{{Value: "dev", Label: "Development"}, {Value: "ops", Label: "Operations"}}) + state.SetValues([]string{"dev"}) + picker := multiselect.New(state) + var tree gfx.Tree + feature := tree.Feature("tags") + opts := tree.Sub(feature, tree.Name("options")) + rem := tree.Sub(feature, tree.Name("removes")) + view := func(c ui.C) { + picker.View(c, multiselect.Spec{Label: "Tags", Placeholder: "Add a tag", Options: opts, Removes: rem}).Width(260) + } + page := ui.NewPage(ui.PageConfig{Tree: &tree, View: view}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(func(Value string, Size, Weight float32) float32 { return float32(len(Value)) * Size / 2 }) + drawPickerPage(page, canvas, view) + b.ReportAllocs() + for b.Loop() { + drawPickerPage(page, canvas, view) + } +} + +// Wheel scrolls the open popup, for a page whose wheel handler reaches it +// before the page itself. +func TestPickerWheelScrollsTheOpenPopup(t *testing.T) { + h := open(t) + h.state.SetOptions([]base.MultiSelectOption{ + {Value: "a", Label: "Alpha"}, {Value: "b", Label: "Beta"}, {Value: "c", Label: "Gamma"}, + {Value: "d", Label: "Delta"}, {Value: "e", Label: "Epsilon"}, {Value: "f", Label: "Zeta"}, + {Value: "g", Label: "Eta"}, {Value: "h", Label: "Theta"}, {Value: "i", Label: "Iota"}, + {Value: "j", Label: "Kappa"}, + }) + h.state.Open = true + h.repaint() + before := h.state.ScrollArea().Offset + if !h.pick.Wheel(gfx.ScrollEvent{DeltaY: 24}) { + t.Fatal("the wheel did not reach the open popup") + } + if h.state.ScrollArea().Offset <= before { + t.Fatalf("popup offset %v after the wheel, was %v", h.state.ScrollArea().Offset, before) + } + if h.pick.Wheel(gfx.ScrollEvent{DeltaY: 24}) { + // At the end the popup reports no movement; the page may then scroll. + if h.state.ScrollArea().Offset < before { + t.Fatal("the popup scrolled backwards") + } + } +} diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md index 8361a816..4a6d02ea 100644 --- a/website/content/guides/en/declarative-layout.md +++ b/website/content/guides/en/declarative-layout.md @@ -83,7 +83,7 @@ An element is named by where it is: its kind and its number among the elements o ### Menus, search fields and context menus -`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` is shadcn's dropdown menu of actions: `menu.Item("Rename").Clicked()` reads one as a button is read, the arrows move between items, typing a letter goes to the item it begins, and choosing one closes the menu. `menu.Sub("Move to", func(to *ui.MenuItems) { ... })` is an item with a submenu beside it, which opens as the pointer rests on the item, on a click, or on Right, Enter or Space with its first item focused; Left goes back, Escape closes every menu, and choosing in it closes them all. `menu.Item("Model").Description("What answers")` adds a second line under an item, `menu.WidthRange(140, 320)` bounds the menu's width, `menu.Above()` opens it over the anchor, for a trigger along the bottom of a panel, and `menu.Beside()` to its right, for a row of a list or popup whose menu should leave the rows under it in sight. `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` takes Select's arguments and a label, and filters the choices as the user types into it, with the platform's input methods. `.Clearable()` gives it a button that clears the choice, `.Empty("No zone matches")` is what its list says when nothing matches, and `.Creatable("")` offers what was typed as a new choice ("Create dev"), which `.Created()` reports for the application to add. A Button takes an icon before its label with `.Icon(plus)`, or alone with `.IconOnly()`. `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` opens the same items at the pointer on a secondary press of `row`, or under it on Shift+F10; items take an `.Icon`, the keycaps of a shortcut with `.Keys(ui.Primary, "c")` (shown only: the shortcut is a `Shortcut` where its action is), and `.Checked` or `.Chosen` to be a checkbox or a radio item. A search field is a TextField with `.Icon(search)` before its text and `.Action(cross, "Clear")`, a small button at its end that `.ActionClicked()` reads. +`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` is shadcn's dropdown menu of actions: `menu.Item("Rename").Clicked()` reads one as a button is read, the arrows move between items, typing a letter goes to the item it begins, and choosing one closes the menu. `menu.Sub("Move to", func(to *ui.MenuItems) { ... })` is an item with a submenu beside it, which opens as the pointer rests on the item, on a click, or on Right, Enter or Space with its first item focused; Left goes back, Escape closes every menu, and choosing in it closes them all. `menu.Item("Model").Description("What answers")` adds a second line under an item, `menu.WidthRange(140, 320)` bounds the menu's width, `menu.Above()` opens it over the anchor, for a trigger along the bottom of a panel, and `menu.Beside()` to its right, for a row of a list or popup whose menu should leave the rows under it in sight. `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` takes Select's arguments and a label, and filters the choices as the user types into it, with the platform's input methods. `.Clearable()` gives it a button that clears the choice, `.Empty("No zone matches")` is what its list says when nothing matches, and `.Creatable("")` offers what was typed as a new choice ("Create dev"), which `.Created()` reports for the application to add. A multi-select with removable chips is the opt-in `multiselect` package: `picker := multiselect.New(&m.tags)`, then `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`; importing it is what links it, so applications that do not use it pay nothing. A Button takes an icon before its label with `.Icon(plus)`, or alone with `.IconOnly()`. `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` opens the same items at the pointer on a secondary press of `row`, or under it on Shift+F10; items take an `.Icon`, the keycaps of a shortcut with `.Keys(ui.Primary, "c")` (shown only: the shortcut is a `Shortcut` where its action is), and `.Checked` or `.Chosen` to be a checkbox or a radio item. A search field is a TextField with `.Icon(search)` before its text and `.Action(cross, "Clear")`, a small button at its end that `.ActionClicked()` reads. ### Drawers diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md index 3b42fafd..e7c0ae77 100644 --- a/website/content/guides/zh/declarative-layout.md +++ b/website/content/guides/zh/declarative-layout.md @@ -84,7 +84,7 @@ ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, m.page) ### 菜单、搜索框与右键菜单 -`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` 是 shadcn 的下拉菜单:像读按钮一样用 `menu.Item("Rename").Clicked()` 读取一项,方向键在各项之间移动,输入字母会跳到以它开头的项,选中一项后菜单关闭。`menu.Sub("Move to", func(to *ui.MenuItems) { ... })` 是一个旁边带子菜单的项:指针在它上面停留、点击它,或按 Right、Enter、Space 时打开(键盘打开时焦点落在子菜单第一项);Left 返回,Escape 关闭所有菜单,在子菜单里选中一项也会全部关闭。 `menu.Item("Model").Description("What answers")` 给项加一行说明;`menu.WidthRange(140, 320)` 限制菜单宽度,`menu.Above()` 让菜单在锚点上方展开(锚点在面板底部时),`menu.Beside()` 让菜单在锚点右侧展开(列表或弹出层里的行,菜单不遮住下面的行)。`ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` 接受 Select 的参数再加一个标签,用户输入时(支持平台输入法)筛选选项。`.Clearable()` 加一个清除选择的按钮,`.Empty("No zone matches")` 是没有匹配项时列表显示的文字,`.Creatable("")` 把输入的内容作为新选项提供("Create dev"),由 `.Created()` 报告,应用自己把它加进选项。Button 用 `.Icon(plus)` 在标签前加图标,加 `.IconOnly()` 则只显示图标。`ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` 在 `row` 上按下副键时于指针处打开同样的菜单项,按 Shift+F10 时在它下方打开;菜单项可以加 `.Icon`、用 `.Keys(ui.Primary, "c")` 显示快捷键键帽(只显示,快捷键本身是动作所在处的一个 `Shortcut`),用 `.Checked` 或 `.Chosen` 成为复选或单选项。搜索框是带 `.Icon(search)`(文字前的图标)和 `.Action(cross, "Clear")`(末尾的小按钮,用 `.ActionClicked()` 读取)的 TextField。 +`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` 是 shadcn 的下拉菜单:像读按钮一样用 `menu.Item("Rename").Clicked()` 读取一项,方向键在各项之间移动,输入字母会跳到以它开头的项,选中一项后菜单关闭。`menu.Sub("Move to", func(to *ui.MenuItems) { ... })` 是一个旁边带子菜单的项:指针在它上面停留、点击它,或按 Right、Enter、Space 时打开(键盘打开时焦点落在子菜单第一项);Left 返回,Escape 关闭所有菜单,在子菜单里选中一项也会全部关闭。 `menu.Item("Model").Description("What answers")` 给项加一行说明;`menu.WidthRange(140, 320)` 限制菜单宽度,`menu.Above()` 让菜单在锚点上方展开(锚点在面板底部时),`menu.Beside()` 让菜单在锚点右侧展开(列表或弹出层里的行,菜单不遮住下面的行)。`ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` 接受 Select 的参数再加一个标签,用户输入时(支持平台输入法)筛选选项。`.Clearable()` 加一个清除选择的按钮,`.Empty("No zone matches")` 是没有匹配项时列表显示的文字,`.Creatable("")` 把输入的内容作为新选项提供("Create dev"),由 `.Created()` 报告,应用自己把它加进选项。带可移除 chip 的多选用可选的 `multiselect` 包:`picker := multiselect.New(&m.tags)`,然后 `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`;只有 import 它的应用才会链接它,不用的应用零成本。Button 用 `.Icon(plus)` 在标签前加图标,加 `.IconOnly()` 则只显示图标。`ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` 在 `row` 上按下副键时于指针处打开同样的菜单项,按 Shift+F10 时在它下方打开;菜单项可以加 `.Icon`、用 `.Keys(ui.Primary, "c")` 显示快捷键键帽(只显示,快捷键本身是动作所在处的一个 `Shortcut`),用 `.Checked` 或 `.Chosen` 成为复选或单选项。搜索框是带 `.Icon(search)`(文字前的图标)和 `.Action(cross, "Clear")`(末尾的小按钮,用 `.ActionClicked()` 读取)的 TextField。 ### 抽屉 From 830bf2963cb440c2e916d1ecce58f07a65cf0ca1 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 11:19:32 +0800 Subject: [PATCH 02/66] feat(base): name menu rows and scrollbar values for the page --- base/accessors.go | 8 ++++++++ base/menu.go | 4 ++++ base/scroll.go | 13 ++++++++++++ cmd/viva/initfiles/AGENTS.md.txt | 5 +++-- ui/menu_test.go | 19 ++++++++++++++++++ ui/scrollbar_values_test.go | 20 +++++++++++++++++++ ui/scrollbars_paint.go | 4 ++-- .../content/guides/en/declarative-layout.md | 4 ++-- .../content/guides/zh/declarative-layout.md | 4 ++-- 9 files changed, 73 insertions(+), 8 deletions(-) create mode 100644 ui/scrollbar_values_test.go diff --git a/base/accessors.go b/base/accessors.go index df90b9dc..568ced38 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -1451,6 +1451,14 @@ func (x *drawerState) GetLayer() uint16 { return x.layer } // GetSpec reads the spec of drawerState for the styled painting layer. func (x *drawerState) GetSpec() DrawerDeclaration { return x.spec } +// GetVerticalValue reads the accessible value of a scroll area's vertical bar for +// the styled painting layer. +func (x *ScrollState) GetVerticalValue() string { return x.verticalValue } + +// GetHorizontalValue reads the accessible value of a scroll area's horizontal bar +// for the styled painting layer. +func (x *ScrollState) GetHorizontalValue() string { return x.horizontalValue } + // GetViewport reads the area the drawer covers, the frame less its spec's Inset. func (x *drawerState) GetViewport() Rect { return x.viewport } diff --git a/base/menu.go b/base/menu.go index a3487f8e..96f622e7 100644 --- a/base/menu.go +++ b/base/menu.go @@ -541,6 +541,10 @@ func (item MenuItem) Chosen(on bool) MenuItem { return item } +// ID is the row's identity, for an application that anchors a context menu or +// another part to this item. It is stable while the menu stays open. +func (item MenuItem) ID() gfx.ID { return item.menu.scope.At(MenuRowsPart + item.i) } + // Clicked reports whether this paint delivers the choice of the item, by a click // or Enter, and closes the menu then. func (item MenuItem) Clicked() bool { diff --git a/base/scroll.go b/base/scroll.go index e970ae28..c13b967b 100644 --- a/base/scroll.go +++ b/base/scroll.go @@ -58,6 +58,7 @@ type ScrollState struct { // ScrollbarLabels gave them; zero and empty keep the area's own. verticalID, horizontalID gfx.ID verticalLabel, horizontalLabel string + verticalValue, horizontalValue string } // scrollStore keeps the ScrollStates of a view, by the identity of their areas. A slot @@ -345,6 +346,7 @@ func (f *Frame) ScrollArea(ID gfx.ID) Box { state := f.Scrolls.get(ID) state.ID, state.follow, state.sideways, state.bars, state.barSize = ID, false, false, false, 0 state.verticalID, state.horizontalID, state.verticalLabel, state.horizontalLabel = gfx.ID{}, gfx.ID{}, "", "" + state.verticalValue, state.horizontalValue = "", "" b := f.Scroll(state.Offset) f.Extra(b.i).scrollState = state return b @@ -438,6 +440,17 @@ func (b Box) ScrollbarSize(Size float32) Box { return b } +// ScrollbarValues gives the values assistive technology reports for a ScrollArea's +// bars, as components.ScrollArea's VerticalScrollbar and HorizontalScrollbar do: a +// percentage, a row's name, or what the bar means. Empty keeps the default, which +// has no value. Like Scrollbars, it has no effect on a box that is not a ScrollArea. +func (b Box) ScrollbarValues(vertical, horizontal string) Box { + if s := b.areaState(); s != nil { + s.verticalValue, s.horizontalValue = vertical, horizontal + } + return b +} + // areaState is the state of the ScrollArea b is, or nil for any other box. func (b Box) areaState() *ScrollState { if n := b.N(); n.Ext != 0 { diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index ebd0b6a3..1848f280 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -139,7 +139,7 @@ func (m *model) page(c ui.C) { `Content`, `Viewport`, `Max()`, `AtEnd()`, `Pinned()`, `Dragging()`, `ScrollTo(px)`, `ScrollToEnd()` and `Key(event, step)` for a pane the page gives the keyboard (also for the area a `ui.List` or `ui.Tree` returns); ask for it in each paint and do not keep the pointer. `BarGeometry(bounds, barSize)` is the tracks and thumb for a - scrollbar the page paints itself. The page gives the + scrollbar the page paints itself; `.ScrollbarValues(vertical, horizontal)` is the value assistive technology reads for them. The page gives the wheel to the area under the pointer (the innermost, or the next one out when that is at its end), so side-by-side columns and nested lists each scroll alone. `.Follow(true)` keeps a log or chat at its end until the user scrolls up (and again when they scroll back down; `.Follow(m.autoScroll)` makes it a switch); `Pinned()` says the next @@ -158,7 +158,8 @@ func (m *model) page(c ui.C) { - `.Tooltip("Delete")` on a control is the tip shown while the pointer rests on it (and its description). - A menu of actions off a button: `ui.Menu(c, more, &m.menu, func(menu *ui.MenuItems) { if menu.Item("Rename").Clicked() { ... } })`; - `menu.Separator()`, `menu.Label("Group")`, `.Destructive()`, `.Disabled(x)`. Choosing an item closes it. + `menu.Item("Rename").ID()` is the row's identity, for anchoring a part or context menu; `menu.Separator()`, + `menu.Label("Group")`, `.Destructive()`, `.Disabled(x)`. Choosing an item closes it. Typing a letter goes to the item it begins. `menu.Sub("Move to", func(to *ui.MenuItems) { ... })` is a submenu (opens as the pointer rests on it, on a click, or on Right/Enter/Space; Left goes back), in a ContextMenu too. - A right-click menu: `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` (Shift+F10 opens it too); items diff --git a/ui/menu_test.go b/ui/menu_test.go index 71757a93..76bc083a 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -691,3 +691,22 @@ func TestMenuPageContentRow(t *testing.T) { t.Fatalf("the swatch chose %v, menu open %v", chosen, open) } } + +// MenuItem.ID is the row's identity: a caller can anchor a context menu or a +// part to the row it declared, without knowing the menu's numbering. +func TestMenuItemIDNamesItsRow(t *testing.T) { + open := true + var row gfx.ID + d := openPage(t, func(c ui.C) { + anchor := ui.Button(c, "More") + ui.Menu(c, anchor, &open, func(menu *ui.MenuItems) { + row = menu.Item("Rename").ID() + }) + }) + if row.IsZero() { + t.Fatal("MenuItem.ID is zero") + } + if hit := d.hit("Rename"); hit.ID != row { + t.Fatalf("the row's hit is %v, ID says %v", hit.ID, row) + } +} diff --git a/ui/scrollbar_values_test.go b/ui/scrollbar_values_test.go new file mode 100644 index 00000000..abf86f7a --- /dev/null +++ b/ui/scrollbar_values_test.go @@ -0,0 +1,20 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/ui" +) + +// ScrollbarValues is the semantic value of a bar, as components.ScrollArea +// takes it: a percentage for a detail view's always-visible bar. +func TestScrollbarValuesAreAccessible(t *testing.T) { + d := openPage(t, func(c ui.C) { + ui.Scroll(c).Size(200, 100).AlwaysScrollbars().ScrollbarValues("42%", "").Children(func() { + ui.Slot(c).Height(300) + }) + }) + if got := d.hit("Vertical scrollbar").Value; got != "42%" { + t.Fatalf("vertical bar value = %q, want 42%%", got) + } +} diff --git a/ui/scrollbars_paint.go b/ui/scrollbars_paint.go index 798daf1f..2c303702 100644 --- a/ui/scrollbars_paint.go +++ b/ui/scrollbars_paint.go @@ -78,8 +78,8 @@ func paintScrollbars(f *Frame, n *Node, s *ScrollState) { Offset(s.OffsetX, s.Offset). ScrollbarSize(size). HoverScrollbars(revealed > 0.001). - VerticalScrollbar(vertical, verticalLabel, ""). - HorizontalScrollbar(horizontal, horizontalLabel, "") + VerticalScrollbar(vertical, verticalLabel, s.GetVerticalValue()). + HorizontalScrollbar(horizontal, horizontalLabel, s.GetHorizontalValue()) geometry := area.Geometry() if geometry.MaxOffsetY > 0 { f.DragScrollbar(s, vertical, geometry, AxisY) diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md index 4a6d02ea..c7268d4a 100644 --- a/website/content/guides/en/declarative-layout.md +++ b/website/content/guides/en/declarative-layout.md @@ -83,7 +83,7 @@ An element is named by where it is: its kind and its number among the elements o ### Menus, search fields and context menus -`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` is shadcn's dropdown menu of actions: `menu.Item("Rename").Clicked()` reads one as a button is read, the arrows move between items, typing a letter goes to the item it begins, and choosing one closes the menu. `menu.Sub("Move to", func(to *ui.MenuItems) { ... })` is an item with a submenu beside it, which opens as the pointer rests on the item, on a click, or on Right, Enter or Space with its first item focused; Left goes back, Escape closes every menu, and choosing in it closes them all. `menu.Item("Model").Description("What answers")` adds a second line under an item, `menu.WidthRange(140, 320)` bounds the menu's width, `menu.Above()` opens it over the anchor, for a trigger along the bottom of a panel, and `menu.Beside()` to its right, for a row of a list or popup whose menu should leave the rows under it in sight. `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` takes Select's arguments and a label, and filters the choices as the user types into it, with the platform's input methods. `.Clearable()` gives it a button that clears the choice, `.Empty("No zone matches")` is what its list says when nothing matches, and `.Creatable("")` offers what was typed as a new choice ("Create dev"), which `.Created()` reports for the application to add. A multi-select with removable chips is the opt-in `multiselect` package: `picker := multiselect.New(&m.tags)`, then `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`; importing it is what links it, so applications that do not use it pay nothing. A Button takes an icon before its label with `.Icon(plus)`, or alone with `.IconOnly()`. `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` opens the same items at the pointer on a secondary press of `row`, or under it on Shift+F10; items take an `.Icon`, the keycaps of a shortcut with `.Keys(ui.Primary, "c")` (shown only: the shortcut is a `Shortcut` where its action is), and `.Checked` or `.Chosen` to be a checkbox or a radio item. A search field is a TextField with `.Icon(search)` before its text and `.Action(cross, "Clear")`, a small button at its end that `.ActionClicked()` reads. +`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` is shadcn's dropdown menu of actions: `menu.Item("Rename").Clicked()` reads one as a button is read, the arrows move between items, typing a letter goes to the item it begins, and choosing one closes the menu. `menu.Sub("Move to", func(to *ui.MenuItems) { ... })` is an item with a submenu beside it, which opens as the pointer rests on the item, on a click, or on Right, Enter or Space with its first item focused; Left goes back, Escape closes every menu, and choosing in it closes them all. `menu.Item("Model").Description("What answers")` adds a second line under an item, `menu.Item("Rename").ID()` is the row's identity for anchoring a part or context menu, `menu.WidthRange(140, 320)` bounds the menu's width, `menu.Above()` opens it over the anchor, for a trigger along the bottom of a panel, and `menu.Beside()` to its right, for a row of a list or popup whose menu should leave the rows under it in sight. `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` takes Select's arguments and a label, and filters the choices as the user types into it, with the platform's input methods. `.Clearable()` gives it a button that clears the choice, `.Empty("No zone matches")` is what its list says when nothing matches, and `.Creatable("")` offers what was typed as a new choice ("Create dev"), which `.Created()` reports for the application to add. A multi-select with removable chips is the opt-in `multiselect` package: `picker := multiselect.New(&m.tags)`, then `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`; importing it is what links it, so applications that do not use it pay nothing. A Button takes an icon before its label with `.Icon(plus)`, or alone with `.IconOnly()`. `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` opens the same items at the pointer on a secondary press of `row`, or under it on Shift+F10; items take an `.Icon`, the keycaps of a shortcut with `.Keys(ui.Primary, "c")` (shown only: the shortcut is a `Shortcut` where its action is), and `.Checked` or `.Chosen` to be a checkbox or a radio item. A search field is a TextField with `.Icon(search)` before its text and `.Action(cross, "Clear")`, a small button at its end that `.ActionClicked()` reads. ### Drawers @@ -255,7 +255,7 @@ func main() { `ui.Scroll(c)` keeps its offset by the area's own name; `.ScrollState()` on it (or on the area a `ui.List` or `ui.Tree` returns) has `Offset`, `Content` and `Viewport` as of the last layout, and moves it by program with `ScrollTo` and `ScrollToEnd`, for instance to bring the selected row into view. Ask for it in each paint rather than keeping the pointer: an area a paint does not declare forgets its offset. `ScrollState.Key` applies the arrow, page and Home/End keys to the area when the page gives it the keyboard, and `BarGeometry(bounds, barSize)` computes the tracks and thumb for an application that paints its own scrollbar. -`.Sideways()` makes the area scroll left and right as well: its children keep the width they ask for, the widest sets how wide the content is, and they are all laid out as wide as that, or as the area where it is wider, so a row of tabs keeps its tabs' widths and a highlighted row runs the whole width. A `Paragraph` does not wrap there. As with its height, the area's width is the one it is given (a `Row` needs `Grow`), not its content's. The horizontal wheel, or the wheel with Shift held, moves it, and the state has `OffsetX`, `ContentWidth`, `ViewportWidth`, `MaxX` and `ScrollToX`. `.Scrollbars()` draws thin bars over the edges the content overflows; the pointer drags them, and a press beside a thumb brings it there. +`.Sideways()` makes the area scroll left and right as well: its children keep the width they ask for, the widest sets how wide the content is, and they are all laid out as wide as that, or as the area where it is wider, so a row of tabs keeps its tabs' widths and a highlighted row runs the whole width. A `Paragraph` does not wrap there. As with its height, the area's width is the one it is given (a `Row` needs `Grow`), not its content's. The horizontal wheel, or the wheel with Shift held, moves it, and the state has `OffsetX`, `ContentWidth`, `ViewportWidth`, `MaxX` and `ScrollToX`. `.Scrollbars()` draws thin bars over the edges the content overflows; the pointer drags them, and a press beside a thumb brings it there. `.ScrollbarValues(vertical, horizontal)` gives the bars the values assistive technology reads. ```go ui.Scroll(c).Grow(1).Sideways().Scrollbars().Children(func() { diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md index e7c0ae77..fbec63cf 100644 --- a/website/content/guides/zh/declarative-layout.md +++ b/website/content/guides/zh/declarative-layout.md @@ -84,7 +84,7 @@ ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, m.page) ### 菜单、搜索框与右键菜单 -`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` 是 shadcn 的下拉菜单:像读按钮一样用 `menu.Item("Rename").Clicked()` 读取一项,方向键在各项之间移动,输入字母会跳到以它开头的项,选中一项后菜单关闭。`menu.Sub("Move to", func(to *ui.MenuItems) { ... })` 是一个旁边带子菜单的项:指针在它上面停留、点击它,或按 Right、Enter、Space 时打开(键盘打开时焦点落在子菜单第一项);Left 返回,Escape 关闭所有菜单,在子菜单里选中一项也会全部关闭。 `menu.Item("Model").Description("What answers")` 给项加一行说明;`menu.WidthRange(140, 320)` 限制菜单宽度,`menu.Above()` 让菜单在锚点上方展开(锚点在面板底部时),`menu.Beside()` 让菜单在锚点右侧展开(列表或弹出层里的行,菜单不遮住下面的行)。`ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` 接受 Select 的参数再加一个标签,用户输入时(支持平台输入法)筛选选项。`.Clearable()` 加一个清除选择的按钮,`.Empty("No zone matches")` 是没有匹配项时列表显示的文字,`.Creatable("")` 把输入的内容作为新选项提供("Create dev"),由 `.Created()` 报告,应用自己把它加进选项。带可移除 chip 的多选用可选的 `multiselect` 包:`picker := multiselect.New(&m.tags)`,然后 `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`;只有 import 它的应用才会链接它,不用的应用零成本。Button 用 `.Icon(plus)` 在标签前加图标,加 `.IconOnly()` 则只显示图标。`ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` 在 `row` 上按下副键时于指针处打开同样的菜单项,按 Shift+F10 时在它下方打开;菜单项可以加 `.Icon`、用 `.Keys(ui.Primary, "c")` 显示快捷键键帽(只显示,快捷键本身是动作所在处的一个 `Shortcut`),用 `.Checked` 或 `.Chosen` 成为复选或单选项。搜索框是带 `.Icon(search)`(文字前的图标)和 `.Action(cross, "Clear")`(末尾的小按钮,用 `.ActionClicked()` 读取)的 TextField。 +`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` 是 shadcn 的下拉菜单:像读按钮一样用 `menu.Item("Rename").Clicked()` 读取一项,方向键在各项之间移动,输入字母会跳到以它开头的项,选中一项后菜单关闭。`menu.Sub("Move to", func(to *ui.MenuItems) { ... })` 是一个旁边带子菜单的项:指针在它上面停留、点击它,或按 Right、Enter、Space 时打开(键盘打开时焦点落在子菜单第一项);Left 返回,Escape 关闭所有菜单,在子菜单里选中一项也会全部关闭。 `menu.Item("Model").Description("What answers")` 给项加一行说明;`menu.Item("Rename").ID()` 是该项的标识,可用来锚定部件或右键菜单;`menu.WidthRange(140, 320)` 限制菜单宽度,`menu.Above()` 让菜单在锚点上方展开(锚点在面板底部时),`menu.Beside()` 让菜单在锚点右侧展开(列表或弹出层里的行,菜单不遮住下面的行)。`ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` 接受 Select 的参数再加一个标签,用户输入时(支持平台输入法)筛选选项。`.Clearable()` 加一个清除选择的按钮,`.Empty("No zone matches")` 是没有匹配项时列表显示的文字,`.Creatable("")` 把输入的内容作为新选项提供("Create dev"),由 `.Created()` 报告,应用自己把它加进选项。带可移除 chip 的多选用可选的 `multiselect` 包:`picker := multiselect.New(&m.tags)`,然后 `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`;只有 import 它的应用才会链接它,不用的应用零成本。Button 用 `.Icon(plus)` 在标签前加图标,加 `.IconOnly()` 则只显示图标。`ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` 在 `row` 上按下副键时于指针处打开同样的菜单项,按 Shift+F10 时在它下方打开;菜单项可以加 `.Icon`、用 `.Keys(ui.Primary, "c")` 显示快捷键键帽(只显示,快捷键本身是动作所在处的一个 `Shortcut`),用 `.Checked` 或 `.Chosen` 成为复选或单选项。搜索框是带 `.Icon(search)`(文字前的图标)和 `.Action(cross, "Clear")`(末尾的小按钮,用 `.ActionClicked()` 读取)的 TextField。 ### 抽屉 @@ -256,7 +256,7 @@ func main() { `ui.Scroll(c)` 的偏移量由区域自己的名字保存;在它(或 `ui.List`、`ui.Tree` 返回的区域)上调用 `.ScrollState()`,可读取上一次布局时的 `Offset`、`Content`、`Viewport`,也可以用 `ScrollTo`、`ScrollToEnd` 用代码滚动,比如把选中行滚进视野。每次绘制都重新取,不要保存指针:某次绘制没有声明的区域会忘掉它的偏移量。页面把键盘交给区域时,`ScrollState.Key` 把方向键、翻页键和 Home/End 应用到该区域;应用要自绘滚动条时,`BarGeometry(bounds, barSize)` 计算轨道和滑块。 -`.Sideways()` 让区域也能左右滚动:子元素保持各自想要的宽度,最宽的那个决定内容有多宽,所有子元素都按这个宽度排布,区域更宽时按区域的宽度,所以一排标签保持各自的宽度,高亮的行横跨整个宽度。`Paragraph` 在这里不换行。和高度一样,区域的宽度是给它的宽度(在 `Row` 里需要 `Grow`),而不是内容的宽度。水平滚轮,或者按住 Shift 的滚轮,会横向移动它;状态里有 `OffsetX`、`ContentWidth`、`ViewportWidth`、`MaxX` 和 `ScrollToX`。`.Scrollbars()` 在内容溢出的边缘上画细滚动条,指针可以拖动;在滑块旁边按下,滑块会移到那里。 +`.Sideways()` 让区域也能左右滚动:子元素保持各自想要的宽度,最宽的那个决定内容有多宽,所有子元素都按这个宽度排布,区域更宽时按区域的宽度,所以一排标签保持各自的宽度,高亮的行横跨整个宽度。`Paragraph` 在这里不换行。和高度一样,区域的宽度是给它的宽度(在 `Row` 里需要 `Grow`),而不是内容的宽度。水平滚轮,或者按住 Shift 的滚轮,会横向移动它;状态里有 `OffsetX`、`ContentWidth`、`ViewportWidth`、`MaxX` 和 `ScrollToX`。`.Scrollbars()` 在内容溢出的边缘上画细滚动条,指针可以拖动;在滑块旁边按下,滑块会移到那里。`.ScrollbarValues(vertical, horizontal)` 给出无障碍读到的值。 ```go ui.Scroll(c).Grow(1).Sideways().Scrollbars().Children(func() { From 71240e2cc0707978dff478e939633ac21ce6521b Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 11:33:14 +0800 Subject: [PATCH 03/66] feat(ui): target a control's slot and anchor following scrolls --- base/accessors.go | 4 +++ base/box.go | 11 +++++++ base/control_view.go | 3 +- base/frame.go | 1 + base/list.go | 4 +++ base/scroll.go | 16 +++++++++ base/scroll_test.go | 27 +++++++++++++++ cmd/viva/initfiles/AGENTS.md.txt | 5 +-- cmd/viva/templates/switch.go.txt | 33 +++++++++++++------ components/switch.go | 33 +++++++++++++------ components/switch_test.go | 12 +++++++ ui/controls_paint.go | 6 ++++ ui/hit_exact_test.go | 27 +++++++++++++++ ui/list_test.go | 12 +++++++ .../content/guides/en/declarative-layout.md | 4 +-- .../content/guides/zh/declarative-layout.md | 4 +-- 16 files changed, 175 insertions(+), 27 deletions(-) create mode 100644 ui/hit_exact_test.go diff --git a/base/accessors.go b/base/accessors.go index 568ced38..fdb1d306 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -263,6 +263,10 @@ func (x *Extra) GetHit() gfx.HitOptions { return x.hit } // GetHitOut reads the hitOut of Extra for the styled painting layer. func (x *Extra) GetHitOut() [4]float32 { return x.hitOut } +// GetHitExact reads whether a styled control targets its laid-out rectangle for +// the styled painting layer. +func (x *Extra) GetHitExact() bool { return x.hitExact } + // GetIcon reads the icon of Extra for the styled painting layer. func (x *Extra) GetIcon() gfx.Icon { return x.icon } diff --git a/base/box.go b/base/box.go index 71e4bd62..4329ea81 100644 --- a/base/box.go +++ b/base/box.go @@ -509,6 +509,17 @@ func (b Box) HitOutset(top, right, bottom, left float32) Box { return b } +// HitExact makes a styled control's pointer target its laid-out rectangle +// instead of the enlarged desktop target its component paints: a Checkbox in a +// 22x24 slot is clicked across the whole slot, not a 40x32 region around it. The +// painted geometry is unchanged, and it has no effect on controls whose target +// is already their rectangle. +func (b Box) HitExact() Box { + b.N() + b.f.Extra(b.i).hitExact = true + return b +} + // Chosen reports which item this paint is delivering a click on: the option of a // Segmented control, or the page item of a Pagination. It is false in every other // paint, like Clicked for the whole control: diff --git a/base/control_view.go b/base/control_view.go index 3ed61f15..a4be7768 100644 --- a/base/control_view.go +++ b/base/control_view.go @@ -26,6 +26,7 @@ type ControlView struct { Flags uint32 Hit gfx.HitOptions HasHit bool + Exact bool // HitExact: the control targets its laid-out rectangle Disabled bool // Color is the element's own text color, when HasColor says it has one. Color gfx.Color @@ -42,7 +43,7 @@ func ViewOf(f *Frame, n *Node) ControlView { return ControlView{ Kind: n.Kind, Rect: n.Rect, Aux: n.Aux, ID: n.ID, Label: n.Label, Text: n.Text, Font: n.FontSize, Weight: n.Weight, Variant: n.Variant, Size: n.ButtonSize, - Flags: n.Flags, Hit: extra.hit, HasHit: n.Flags&flagHasHit != 0, + Flags: n.Flags, Hit: extra.hit, HasHit: n.Flags&flagHasHit != 0, Exact: extra.hitExact, Disabled: n.Flags&flagDisabled != 0, Icon: extra.icon, Color: n.Color, HasColor: n.Flags&flagHasColor != 0, SwitchRecipe: extra.switchRecipe, diff --git a/base/frame.go b/base/frame.go index 0fd0107b..98caaf74 100644 --- a/base/frame.go +++ b/base/frame.go @@ -187,6 +187,7 @@ type Extra struct { scrollState *ScrollState // the state a ScrollArea reports its extent to maxPct [2]float32 // MaxWidthPercent and MaxHeightPercent; zero is none hitOut [4]float32 // how far the hit region reaches beyond the rectangle: top, right, bottom, left + hitExact bool // a styled control targets its laid-out rectangle, not its enlarged desktop target edges [4]float32 // an absolute element's distance from its container's top, right, bottom, left within Rect // what a Popup is kept inside, when not the frame; empty for the frame moves bool // the element's rectangle moves a custom-titlebar window (MovesWindow) diff --git a/base/list.go b/base/list.go index d77016c0..995523bf 100644 --- a/base/list.go +++ b/base/list.go @@ -419,6 +419,10 @@ func (s *ListState) rowHeight(i int) float32 { // itself; the List's own Reorder and Tree's CanDrop use the same heights. func (s *ListState) RowHeightAt(i int) float32 { return s.rowHeight(i) } +// RowOffset is the top of row i in content space, as of the last layout, for +// an application that anchors on a row while content above it changes. +func (s *ListState) RowOffset(i int) float32 { return s.top(i) } + // RowID is the identity of visible row i as the last paint named it, by Key when // one is set: the target to give the focus (Canvas.RequestFocus), to look up in a // pointer event or to find among the hits. It is the zero ID before the list has diff --git a/base/scroll.go b/base/scroll.go index c13b967b..ab5a9a9f 100644 --- a/base/scroll.go +++ b/base/scroll.go @@ -149,6 +149,22 @@ func (s *ScrollState) ScrollTo(offset float32) { // by the next layout. It has no effect on any other area. func (s *ScrollState) ScrollToX(offset float32) { s.OffsetX = max(offset, 0) } +// Following reports whether the area is in follow mode and has not been +// detached by the user scrolling up: new content then stays in view. It is +// false for an area that does not follow, and for one the user left. +func (s *ScrollState) Following() bool { return s.follow && !s.detached } + +// Prepend adjusts the offset for content added above (positive delta) or +// removed above (negative) between paints, so the rows the reader is looking +// at stay in place. The next layout clamps the result. Follow is unchanged: an +// area at its end stays at its end. +func (s *ScrollState) Prepend(delta float32) { + if delta == 0 { + return + } + s.Offset = max(s.Offset+delta, 0) +} + // Follow makes the area keep to its end as content is added, or stop: the // imperative form of Box.Follow, for a gesture between paints. A List reads // whether it follows when it is declared, before the Box it returns can say diff --git a/base/scroll_test.go b/base/scroll_test.go index bd28f031..945fbff5 100644 --- a/base/scroll_test.go +++ b/base/scroll_test.go @@ -335,3 +335,30 @@ func TestScrollStateKeyScrollsWithinItsContent(t *testing.T) { t.Errorf("%v allocations per key, want 0", allocs) } } + +// Following says whether new content stays in view, and Prepend keeps the rows +// a reader is looking at in place when content above them changes. +func TestScrollStateFollowingAndPrepend(t *testing.T) { + var view View + logPage(&view, true, 10) // follows its end + state := view.ScrollState(listID) + if !state.Following() { + t.Fatal("a following area is not following") + } + state.ScrollTo(40) + if state.Following() { + t.Fatal("an area the user scrolled up still follows") + } + state.Prepend(30) + if state.Offset != 70 { + t.Fatalf("Prepend(30) moved the offset to %v, want 70", state.Offset) + } + state.Prepend(-100) + if state.Offset != 0 { + t.Fatalf("Prepend(-100) left the offset at %v, want 0", state.Offset) + } + state.ScrollToEnd() + if !state.Following() { + t.Fatal("ScrollToEnd did not reattach the follow") + } +} diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 1848f280..90e3a1a9 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -142,7 +142,8 @@ func (m *model) page(c ui.C) { scrollbar the page paints itself; `.ScrollbarValues(vertical, horizontal)` is the value assistive technology reads for them. The page gives the wheel to the area under the pointer (the innermost, or the next one out when that is at its end), so side-by-side columns and nested lists each scroll alone. `.Follow(true)` keeps a log or chat at its end until the user scrolls - up (and again when they scroll back down; `.Follow(m.autoScroll)` makes it a switch); `Pinned()` says the next + up (and again when they scroll back down; `.Follow(m.autoScroll)` makes it a switch); `Following()` says whether it is + attached to the end now, `Prepend(delta)` keeps the reader's rows in place when content above changes, and `Pinned()` says the next layout puts it at its end before `Offset` has caught up. `.Sideways()` scrolls left and right too (`OffsetX`, `ContentWidth`, `ViewportWidth`, `MaxX()` and `ScrollToX(px)`), and `.Scrollbars()` draws draggable bars over the overflowing edges. The bars are the hover style: they appear while the pointer is over the area or the view @@ -782,4 +783,4 @@ empty state, dimmable section) are under declare overlapping interactive things in the order you want them to win. - A `Border` is inside the box (as CSS `border-box`): it takes its width out of the padding area. `Stroke(width, color)` draws the same line but takes no room. `HitOutset(top, right, bottom, left)` makes the - click region reach beyond the painted rectangle (an inset rounded row that clicks across its whole width). + click region reach beyond the painted rectangle (an inset rounded row that clicks across its whole width). `HitExact()` makes a Checkbox or Switch's click target its laid-out slot instead of the enlarged target around its square or track. diff --git a/cmd/viva/templates/switch.go.txt b/cmd/viva/templates/switch.go.txt index e1f95259..7fcff2e3 100644 --- a/cmd/viva/templates/switch.go.txt +++ b/cmd/viva/templates/switch.go.txt @@ -24,16 +24,17 @@ const switchSlotChecked uint8 = 0 // thumb and fades the track over the theme's Transition; the caller still // passes only the destination state. type Switch struct { - canvas *gfx.Canvas - theme gfx.Theme - id gfx.ID - bounds gfx.Rect - label string - checked bool - focused bool - invalid bool - size SwitchSize - disabled bool + canvas *gfx.Canvas + theme gfx.Theme + id gfx.ID + bounds gfx.Rect + label string + hitBounds gfx.Rect + checked bool + focused bool + invalid bool + size SwitchSize + disabled bool // recipe, when set, replaces SwitchRecipe; see Button.Recipe. recipe func(gfx.Theme, gfx.State, float32) SwitchLook } @@ -97,6 +98,15 @@ func (result SwitchResult) Clicked() bool { return result.canvas != nil && result.canvas.Clicked(result.id) } +// HitBounds makes an enclosing label or selection card activate this switch. +// The visual track keeps its normal position and size; zero bounds use the +// default enlarged target. The rect replaces the track's target rather than +// adding to it and must contain the track. +func (switchControl Switch) HitBounds(bounds gfx.Rect) Switch { + switchControl.hitBounds = bounds + return switchControl +} + // SwitchHitExtent is the width and height of the interaction region Paint // declares around a switch. The padding is the fixed 12 by 8 logical pixels // Paint adds, not scaled by density. @@ -169,6 +179,9 @@ func (switchControl Switch) Paint() SwitchResult { X: switchControl.bounds.X - 12, Y: switchControl.bounds.Y - 8, Width: switchControl.bounds.Width + 24, Height: switchControl.bounds.Height + 16, } + if switchControl.hitBounds.Width > 0 && switchControl.hitBounds.Height > 0 { + hitBounds = switchControl.hitBounds + } switchControl.canvas.HitWithOptions(switchControl.id, hitBounds, switchControl.label, gfx.HitOptions{ Role: gfx.RoleSwitch, Disabled: switchControl.disabled, Checked: switchControl.checked, diff --git a/components/switch.go b/components/switch.go index 52b248ca..60e3d907 100644 --- a/components/switch.go +++ b/components/switch.go @@ -24,16 +24,17 @@ const switchSlotChecked uint8 = 0 // thumb and fades the track over the theme's Transition; the caller still // passes only the destination state. type Switch struct { - canvas *gfx.Canvas - theme gfx.Theme - id gfx.ID - bounds gfx.Rect - label string - checked bool - focused bool - invalid bool - size SwitchSize - disabled bool + canvas *gfx.Canvas + theme gfx.Theme + id gfx.ID + bounds gfx.Rect + label string + hitBounds gfx.Rect + checked bool + focused bool + invalid bool + size SwitchSize + disabled bool // recipe, when set, replaces SwitchRecipe; see Button.Recipe. recipe func(gfx.Theme, gfx.State, float32) SwitchLook } @@ -97,6 +98,15 @@ func (result SwitchResult) Clicked() bool { return result.canvas != nil && result.canvas.Clicked(result.id) } +// HitBounds makes an enclosing label or selection card activate this switch. +// The visual track keeps its normal position and size; zero bounds use the +// default enlarged target. The rect replaces the track's target rather than +// adding to it and must contain the track. +func (switchControl Switch) HitBounds(bounds gfx.Rect) Switch { + switchControl.hitBounds = bounds + return switchControl +} + // SwitchHitExtent is the width and height of the interaction region Paint // declares around a switch. The padding is the fixed 12 by 8 logical pixels // Paint adds, not scaled by density. @@ -169,6 +179,9 @@ func (switchControl Switch) Paint() SwitchResult { X: switchControl.bounds.X - 12, Y: switchControl.bounds.Y - 8, Width: switchControl.bounds.Width + 24, Height: switchControl.bounds.Height + 16, } + if switchControl.hitBounds.Width > 0 && switchControl.hitBounds.Height > 0 { + hitBounds = switchControl.hitBounds + } switchControl.canvas.HitWithOptions(switchControl.id, hitBounds, switchControl.label, gfx.HitOptions{ Role: gfx.RoleSwitch, Disabled: switchControl.disabled, Checked: switchControl.checked, diff --git a/components/switch_test.go b/components/switch_test.go index e74cc716..97089fcf 100644 --- a/components/switch_test.go +++ b/components/switch_test.go @@ -129,3 +129,15 @@ func TestSwitchInvalidPaintsTheDangerRingAndBorder(t *testing.T) { t.Fatalf("invalid switch rectangles = %+v", canvas.Rectangles()) } } + +// HitBounds replaces the enlarged target with the caller's enclosing slot, as +// Checkbox.HitBounds does. +func TestSwitchHitBoundsReplacesTheTarget(t *testing.T) { + theme := gfx.DarkTheme() + var canvas gfx.Canvas + slot := gfx.Rect{X: 10, Y: 20, Width: 52, Height: 32} + BeginSwitch(&canvas, theme, gfx.Item(1), gfx.Rect{X: 20, Y: 27}, false).HitBounds(slot).Paint() + if got := canvas.Hits()[0].Bounds; got != slot { + t.Fatalf("switch hit %v, want the slot %v", got, slot) + } +} diff --git a/ui/controls_paint.go b/ui/controls_paint.go index 2d1f598d..c20e5e8f 100644 --- a/ui/controls_paint.go +++ b/ui/controls_paint.go @@ -18,6 +18,9 @@ func paintCheckbox(f *Frame, v ControlView) { f.PaintCaptionView(v, bounds) } checkbox := components.BeginCheckbox(canvas, f.Palette, v.ID, bounds, v.Flags&FlagChecked != 0) + if v.Exact { + checkbox = checkbox.HitBounds(v.Rect) + } if v.Flags&FlagMixed != 0 { checkbox = checkbox.Indeterminate() } @@ -43,6 +46,9 @@ func paintSwitch(f *Frame, v ControlView) { f.PaintCaptionView(v, bounds) } control := components.BeginSwitch(canvas, f.Palette, v.ID, bounds, v.Flags&FlagChecked != 0) + if v.Exact { + control = control.HitBounds(v.Rect) + } if recipe := v.SwitchRecipe; recipe != nil { control = control.Recipe(recipe) } else if f.GetStyles() != nil && f.GetStyles().Switch != nil { diff --git a/ui/hit_exact_test.go b/ui/hit_exact_test.go new file mode 100644 index 00000000..6c83c70e --- /dev/null +++ b/ui/hit_exact_test.go @@ -0,0 +1,27 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/ui" +) + +// HitExact gives a Checkbox or Switch the slot it was declared in as its +// pointer target, instead of the enlarged desktop target around its painted +// square or track. +func TestHitExactUsesTheSlot(t *testing.T) { + var checked bool + var checkbox, switchBox ui.Box + d := openPage(t, func(c ui.C) { + ui.Row(c).Gap(8).Children(func() { + checkbox = ui.Checkbox(c, &checked, "Select").HitExact().Size(22, 24) + switchBox = ui.Switch(c, &checked, "Enabled").HitExact().Size(52, 32) + }) + }) + if got, want := d.hit("Select").Bounds, checkbox.Rect(); got != want { + t.Fatalf("checkbox hit %v, slot %v", got, want) + } + if got, want := d.hit("Enabled").Bounds, switchBox.Rect(); got != want { + t.Fatalf("switch hit %v, slot %v", got, want) + } +} diff --git a/ui/list_test.go b/ui/list_test.go index f7bdcd04..f1ff6415 100644 --- a/ui/list_test.go +++ b/ui/list_test.go @@ -499,3 +499,15 @@ func TestListReorderDragCancelledByThePlatformDropsNothing(t *testing.T) { t.Fatal("a cancelled press dropped the rows") } } + +// RowOffset is a row's top in content space, for anchoring when content above +// it changes. +func TestListRowOffset(t *testing.T) { + var state ui.ListState + openPage(t, func(c ui.C) { + ui.List(c, &state, 4, func(row ui.ListRow) { row.Element.Height(30) }) + }) + if first, second := state.RowOffset(1), state.RowOffset(2); second-first != 30 { + t.Fatalf("rows 1 and 2 start %v apart, want 30", second-first) + } +} diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md index c7268d4a..d0295151 100644 --- a/website/content/guides/en/declarative-layout.md +++ b/website/content/guides/en/declarative-layout.md @@ -36,7 +36,7 @@ func (m *model) page(c ui.C) { - `Flow()` is a Row that wraps: children of their own widths go left to right and start a new line when the next one does not fit, as CSS's `flex-wrap` does. Each line shares its room as a Row does, so `Grow` and `Justify` apply to every line alone, and `Items` lines the children up within their line. `Gap` is the space between children and between lines, unless `LineGap` sets the latter. Tags, chips and toolbars that wrap are Flows. - `Scroll(offset)` is a clipped column taller than itself. You own the offset (the wheel arrives in `Config.OnScroll`); after `End`, `Content()` is how tall the children are, so the offset can be clamped. -Controls are the ones in `components`, with the same look: `Button` (with `Outline`, `Ghost`, `Secondary`, `Destructive`, `Small` and the other variants), `Checkbox`, `Switch`, `Icon`, `Divider`. `Clicked()` is read where the control is declared: it is true in the one paint that delivers the click. Any element can be made a pointer target with `Hit(id, label)`; what it looks like under the pointer, pressed and focused is declared with `Hover`, `Pressed` and `Focus` (below). +Controls are the ones in `components`, with the same look: `Button` (with `Outline`, `Ghost`, `Secondary`, `Destructive`, `Small` and the other variants), `Checkbox`, `Switch`, `Icon`, `Divider`. `Clicked()` is read where the control is declared: it is true in the one paint that delivers the click. A Checkbox or Switch in a fixed slot can be made to target that slot with `.HitExact()`. Any element can be made a pointer target with `Hit(id, label)`; what it looks like under the pointer, pressed and focused is declared with `Hover`, `Pressed` and `Focus` (below). ## Pages: ui.C @@ -253,7 +253,7 @@ func main() { } ``` -`ui.Scroll(c)` keeps its offset by the area's own name; `.ScrollState()` on it (or on the area a `ui.List` or `ui.Tree` returns) has `Offset`, `Content` and `Viewport` as of the last layout, and moves it by program with `ScrollTo` and `ScrollToEnd`, for instance to bring the selected row into view. Ask for it in each paint rather than keeping the pointer: an area a paint does not declare forgets its offset. `ScrollState.Key` applies the arrow, page and Home/End keys to the area when the page gives it the keyboard, and `BarGeometry(bounds, barSize)` computes the tracks and thumb for an application that paints its own scrollbar. +`ui.Scroll(c)` keeps its offset by the area's own name; `.ScrollState()` on it (or on the area a `ui.List` or `ui.Tree` returns) has `Offset`, `Content` and `Viewport` as of the last layout, and moves it by program with `ScrollTo` and `ScrollToEnd`, for instance to bring the selected row into view. Ask for it in each paint rather than keeping the pointer: an area a paint does not declare forgets its offset. `Following()` says whether the area is attached to its end now, and `Prepend(delta)` keeps the rows a reader is looking at in place when content above them is added or removed; a List's `RowOffset(row)` gives the row's top for anchoring. `ScrollState.Key` applies the arrow, page and Home/End keys to the area when the page gives it the keyboard, and `BarGeometry(bounds, barSize)` computes the tracks and thumb for an application that paints its own scrollbar. `.Sideways()` makes the area scroll left and right as well: its children keep the width they ask for, the widest sets how wide the content is, and they are all laid out as wide as that, or as the area where it is wider, so a row of tabs keeps its tabs' widths and a highlighted row runs the whole width. A `Paragraph` does not wrap there. As with its height, the area's width is the one it is given (a `Row` needs `Grow`), not its content's. The horizontal wheel, or the wheel with Shift held, moves it, and the state has `OffsetX`, `ContentWidth`, `ViewportWidth`, `MaxX` and `ScrollToX`. `.Scrollbars()` draws thin bars over the edges the content overflows; the pointer drags them, and a press beside a thumb brings it there. `.ScrollbarValues(vertical, horizontal)` gives the bars the values assistive technology reads. diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md index fbec63cf..90d8515e 100644 --- a/website/content/guides/zh/declarative-layout.md +++ b/website/content/guides/zh/declarative-layout.md @@ -36,7 +36,7 @@ func (m *model) page(c ui.C) { - `Flow()` 是会换行的 Row:子元素保持各自的宽度从左到右排列,放不下下一个时就换到新的一行,和 CSS 的 `flex-wrap` 一样。每一行像 Row 一样分配自己的空间,所以 `Grow` 和 `Justify` 对每一行单独生效,`Items` 在各自的行内对齐子元素。`Gap` 是子元素之间的间距,也是行与行之间的间距,除非用 `LineGap` 另行设置。会换行的标签、徽章和工具栏都用 Flow。 - `Scroll(offset)` 是比自己更高的、带裁剪的列。偏移量由你持有(滚轮事件到 `Config.OnScroll`);`End` 之后 `Content()` 是子元素的总高度,可据此限制偏移量。 -控件就是 `components` 里的那些,外观完全一致:`Button`(以及 `Outline`、`Ghost`、`Secondary`、`Destructive`、`Small` 等变体)、`Checkbox`、`Switch`、`Icon`、`Divider`。`Clicked()` 在声明控件的地方读取:它只在递送这次点击的那一遍里为真。任何元素都可以用 `Hit(id, label)` 成为指针目标;它在指针悬停、按下和获得焦点时的样子用 `Hover`、`Pressed` 和 `Focus` 声明(见下文)。 +控件就是 `components` 里的那些,外观完全一致:`Button`(以及 `Outline`、`Ghost`、`Secondary`、`Destructive`、`Small` 等变体)、`Checkbox`、`Switch`、`Icon`、`Divider`。`Clicked()` 在声明控件的地方读取:它只在递送这次点击的那一遍里为真。固定槽位里的 Checkbox 或 Switch 可以用 `.HitExact()` 让整个槽位成为点击目标。任何元素都可以用 `Hit(id, label)` 变成指针目标; 成为指针目标;它在指针悬停、按下和获得焦点时的样子用 `Hover`、`Pressed` 和 `Focus` 声明(见下文)。 ## 页面:ui.C @@ -254,7 +254,7 @@ func main() { } ``` -`ui.Scroll(c)` 的偏移量由区域自己的名字保存;在它(或 `ui.List`、`ui.Tree` 返回的区域)上调用 `.ScrollState()`,可读取上一次布局时的 `Offset`、`Content`、`Viewport`,也可以用 `ScrollTo`、`ScrollToEnd` 用代码滚动,比如把选中行滚进视野。每次绘制都重新取,不要保存指针:某次绘制没有声明的区域会忘掉它的偏移量。页面把键盘交给区域时,`ScrollState.Key` 把方向键、翻页键和 Home/End 应用到该区域;应用要自绘滚动条时,`BarGeometry(bounds, barSize)` 计算轨道和滑块。 +`ui.Scroll(c)` 的偏移量由区域自己的名字保存;在它(或 `ui.List`、`ui.Tree` 返回的区域)上调用 `.ScrollState()`,可读取上一次布局时的 `Offset`、`Content`、`Viewport`,也可以用 `ScrollTo`、`ScrollToEnd` 用代码滚动,比如把选中行滚进视野。每次绘制都重新取,不要保存指针:某次绘制没有声明的区域会忘掉它的偏移量。`Following()` 表示区域当前是否跟随末端;上方内容增减时,`Prepend(delta)` 让读者正在看的内容保持原位;`List` 的 `RowOffset(row)` 给出行的顶部位置,用于锚定。页面把键盘交给区域时,`ScrollState.Key` 把方向键、翻页键和 Home/End 应用到该区域;应用要自绘滚动条时,`BarGeometry(bounds, barSize)` 计算轨道和滑块。 `.Sideways()` 让区域也能左右滚动:子元素保持各自想要的宽度,最宽的那个决定内容有多宽,所有子元素都按这个宽度排布,区域更宽时按区域的宽度,所以一排标签保持各自的宽度,高亮的行横跨整个宽度。`Paragraph` 在这里不换行。和高度一样,区域的宽度是给它的宽度(在 `Row` 里需要 `Grow`),而不是内容的宽度。水平滚轮,或者按住 Shift 的滚轮,会横向移动它;状态里有 `OffsetX`、`ContentWidth`、`ViewportWidth`、`MaxX` 和 `ScrollToX`。`.Scrollbars()` 在内容溢出的边缘上画细滚动条,指针可以拖动;在滑块旁边按下,滑块会移到那里。`.ScrollbarValues(vertical, horizontal)` 给出无障碍读到的值。 From 9431c7480899596bef66b46034047ba9def30985 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:55:21 +0800 Subject: [PATCH 04/66] fix(linux): allow paste from an image-only X11 clipboard --- .../linux/clipboard_image_linux_test.go | 95 +++++++++++++++++++ internal/platform/linux/system_linux.go | 5 +- 2 files changed, 96 insertions(+), 4 deletions(-) diff --git a/internal/platform/linux/clipboard_image_linux_test.go b/internal/platform/linux/clipboard_image_linux_test.go index d626a0e9..d8908122 100644 --- a/internal/platform/linux/clipboard_image_linux_test.go +++ b/internal/platform/linux/clipboard_image_linux_test.go @@ -1,7 +1,9 @@ package linux import ( + "bufio" "bytes" + "context" "errors" "image" "image/color" @@ -12,7 +14,9 @@ import ( "testing" "time" + "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" ) // TestClipboardImageFromX11Owner reads an image another program put on the real @@ -169,3 +173,94 @@ Gtk.main()` } } } + +func TestX11PasteFromImageOnlyClipboard(t *testing.T) { + if testing.Short() || os.Getenv("VIVA_LINUX_XCB_SMOKE") == "" { + t.Skip("set VIVA_LINUX_XCB_SMOKE=1 with a private X11 display and GTK 3 PyGObject") + } + python, err := exec.LookPath("python3") + if err != nil || exec.Command(python, "-c", "import gi; gi.require_version('Gtk', '3.0')").Run() != nil { + t.Skip("PyGObject with GTK 3 is not installed") + } + for _, scenario := range []string{"no-owner", "image", "text", "no-display"} { + t.Run(scenario, func(t *testing.T) { + if scenario == "image" || scenario == "text" { + const script = `import gi, sys +gi.require_version('Gtk', '3.0') +gi.require_version('Gdk', '3.0') +from gi.repository import Gtk, Gdk, GdkPixbuf +clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) +if sys.argv[1] == 'image': + bitmap = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, False, 8, 3, 2) + bitmap.fill(0x2155aaff) + clipboard.set_image(bitmap) +else: + clipboard.set_text('pasted', -1) +print('serving', flush=True) +Gtk.main()` + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + t.Cleanup(cancel) + owner := exec.CommandContext(ctx, python, "-c", script, scenario) + owner.Stderr = os.Stderr + stdout, err := owner.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := owner.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cancel(); _ = owner.Wait() }) + ready := bufio.NewScanner(stdout) + if !ready.Scan() || ready.Text() != "serving" { + t.Fatalf("clipboard owner did not start: %q, %v", ready.Text(), ready.Err()) + } + } + if scenario == "image" { + data, err := ClipboardImagePNG() + config, decodeErr := png.DecodeConfig(bytes.NewReader(data)) + if err != nil || decodeErr != nil || config.Width != 3 || config.Height != 2 { + t.Fatalf("image fixture not available: %+v, read=%v, decode=%v", config, err, decodeErr) + } + } + if scenario == "no-display" { + t.Setenv("DISPLAY", "") + if value, err := ClipboardText(); err == nil { + t.Fatalf("text read without a display returned %q without an error", value) + } + } + + editor := text.NewEditor("abc") + editor.SetSelection(text.Range{Start: 1, End: 2}) + before := platform.EditorState(editor).WithoutRedraw() + var events []platform.TextEvent + state := linuxTextInput{ + enabled: true, config: &platform.Config{}, state: before, + input: platform.TextInput{State: before, OnEvent: func(event platform.TextEvent) (platform.TextState, error) { + events = append(events, event) + event.Apply(editor) + return platform.EditorState(editor), nil + }}, + } + if _, handled, err := state.key(platform.KeyEvent{Modifiers: input.ModifierControl, Text: "v"}); !handled || err != nil { + t.Fatalf("paste ingress: handled=%t, error=%v", handled, err) + } + switch scenario { + case "text": + if len(events) != 1 || events[0].Kind != platform.TextPaste || editor.String() != "apastedc" { + t.Fatalf("text paste: events=%+v, editor=%q", events, editor.String()) + } + case "no-display": + if len(events) != 0 { + t.Fatalf("transport failure dispatched events: %+v", events) + } + default: + if len(events) != 1 || events[0].Kind != platform.TextPasteNoText { + t.Fatalf("non-text paste: events=%+v, want one TextPasteNoText", events) + } + } + if scenario != "text" && (platform.EditorState(editor).WithoutRedraw() != before || editor.CanUndo()) { + t.Fatal("a paste without text changed editor content, selection, or history") + } + }) + } +} diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go index 5f6ab41c..1185474e 100644 --- a/internal/platform/linux/system_linux.go +++ b/internal/platform/linux/system_linux.go @@ -999,12 +999,9 @@ func selectionOwner(api *xcbAPI, connection uintptr, selection uint32) (uint32, func readLegacySelection(api *xcbAPI, connection uintptr, requestor, selection, property uint32) (string, error) { value, accepted, err := readSelection(api, connection, requestor, selection, xcbAtomString, property) - if err != nil { + if err != nil || !accepted { return "", err } - if !accepted { - return "", unsupported("clipboard owner provides neither UTF8_STRING nor STRING") - } return decodeLatin1(value), nil } From 90f8de44a2ce63df3956836f27e6b7e7a3ebca57 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:55:44 +0800 Subject: [PATCH 05/66] fix(linux): scale bitmaps in the CPU renderer --- .../platform/linux/cpu_offscreen_linux.go | 6 +++ .../linux/cpu_offscreen_linux_test.go | 35 +++++++++++++++ .../platform/linux/soft_scene_linux_test.go | 35 +++++++++++++++ internal/raster/raster.go | 43 +++++++++++++++++-- 4 files changed, 116 insertions(+), 3 deletions(-) diff --git a/internal/platform/linux/cpu_offscreen_linux.go b/internal/platform/linux/cpu_offscreen_linux.go index a804baaf..0dcd5ed1 100644 --- a/internal/platform/linux/cpu_offscreen_linux.go +++ b/internal/platform/linux/cpu_offscreen_linux.go @@ -168,6 +168,12 @@ func placeLabel(l platform.TextLabel, scale float32, image labelImage, canvasWid label = raster.Label{Pix: image.pixels, Stride: image.width * 4, Width: image.width, Height: image.height, X: x, Y: y, Layer: l.Layer, ShapesBefore: l.ShapesBefore, LCD: image.lcd, Spans: image.spans, Color: scene.Color{Red: float32(l.Color.Red), Green: float32(l.Color.Green), Blue: float32(l.Color.Blue), Alpha: float32(l.Color.Alpha)}} + if len(l.Bitmap) > 0 { + label.Width, label.Height = platform.DeviceExtent(l.X, l.Width, scale), platform.DeviceExtent(l.Y, l.Height, scale) + if label.Width != image.width || label.Height != image.height { + label.SourceWidth, label.SourceHeight = image.width, image.height + } + } if l.Clipped { left := max(int(math.Floor(float64(l.Clip.X*scale))), 0) top := max(int(math.Floor(float64(l.Clip.Y*scale))), 0) diff --git a/internal/platform/linux/cpu_offscreen_linux_test.go b/internal/platform/linux/cpu_offscreen_linux_test.go index 44dc63e5..2cb11af1 100644 --- a/internal/platform/linux/cpu_offscreen_linux_test.go +++ b/internal/platform/linux/cpu_offscreen_linux_test.go @@ -1,6 +1,7 @@ package linux import ( + "image/color" "testing" "github.com/vivaui/viva/gfx" @@ -9,6 +10,40 @@ import ( "github.com/vivaui/viva/internal/scene" ) +func TestCPUOffscreenMagnifiesBitmapInsideClip(t *testing.T) { + offscreen, err := NewCPUOffscreen(20, 10, 1.5, platform.Color{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(offscreen.Close) + label := bitmapLabel() + label.Bitmap = []byte{0, 0, 128, 128, 0, 255, 0, 255} + label.Clipped = true + label.Clip = gfx.Rect{X: 3, Y: 3, Width: 14, Height: 4} + if err := offscreen.Set(nil, []platform.TextLabel{label}); err != nil { + t.Fatal(err) + } + result, err := offscreen.Image() + if err != nil { + t.Fatal(err) + } + for _, check := range []struct { + x, y int + want color.RGBA + }{ + {4, 4, color.RGBA{R: 128, A: 128}}, + {14, 7, color.RGBA{R: 69, G: 117, A: 186}}, + {25, 10, color.RGBA{G: 255, A: 255}}, + {3, 4, color.RGBA{}}, + {26, 10, color.RGBA{}}, + {25, 11, color.RGBA{}}, + } { + if got := result.RGBAAt(check.x, check.y); got != check.want { + t.Errorf("pixel (%d, %d) = %+v, want %+v", check.x, check.y, got, check.want) + } + } +} + func TestCPUOffscreenDrawsShapesAndTextWithoutVulkan(t *testing.T) { clear := platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1} off, err := NewCPUOffscreen(120, 60, 1.5, clear) diff --git a/internal/platform/linux/soft_scene_linux_test.go b/internal/platform/linux/soft_scene_linux_test.go index 58605fa4..74fe7005 100644 --- a/internal/platform/linux/soft_scene_linux_test.go +++ b/internal/platform/linux/soft_scene_linux_test.go @@ -101,3 +101,38 @@ func TestSoftSceneTypingPaintsOnlyTheLine(t *testing.T) { t.Fatalf("typing repainted %+v, want about the first label's 8,6 70x20", got) } } + +func TestSoftSceneMagnifiedBitmapPanRepaintsTheVisibleRegion(t *testing.T) { + label := bitmapLabel() + label.X, label.Y = -500000, -500000 + label.Width, label.Height = 1000000, 1000000 + label.Clipped = true + label.Clip = gfx.Rect{X: 4, Y: 4, Width: 8, Height: 4} + clear := platform.Color{Alpha: 1} + scene, err := newSoftScene(nil, 20, 10, 1, clear, nil, []platform.TextLabel{label}) + if err != nil { + t.Fatal(err) + } + scene.paint() + probe := 6*scene.canvas.Stride + 8*4 + if got := scene.canvas.Pix[probe : probe+4]; !bytes.Equal(got, []byte{0, 128, 127, 255}) && !bytes.Equal(got, []byte{0, 128, 128, 255}) { + t.Fatalf("initial zoom sample = %v, want the center of the two source pixels", got) + } + label.X = -750000 + label.Clip.X = 7 + if changed, err := scene.apply(platform.Frame{TextLabels: []platform.TextLabel{label}}); err != nil || !changed { + t.Fatalf("pan: changed=%t, error=%v", changed, err) + } + scene.paint() + full, err := newSoftScene(nil, 20, 10, 1, clear, nil, []platform.TextLabel{label}) + if err != nil { + t.Fatal(err) + } + full.paint() + if !bytes.Equal(scene.canvas.Pix, full.canvas.Pix) { + t.Fatal("the partial repaint differs from a full paint after pan and clip changes") + } + if got := scene.canvas.Pix[probe : probe+4]; !bytes.Equal(got, []byte{0, 255, 0, 255}) { + t.Fatalf("panned zoom sample = %v, want the green source edge", got) + } +} diff --git a/internal/raster/raster.go b/internal/raster/raster.go index baf638b1..257560f1 100644 --- a/internal/raster/raster.go +++ b/internal/raster/raster.go @@ -9,14 +9,16 @@ import ( ) // Label is a prepared image placed in the canvas: text the platform's text engine rasterized, or -// a bitmap, already at device resolution. Pix is premultiplied BGRA like the canvas, unless LCD is +// a bitmap. Pix is premultiplied BGRA like the canvas, unless LCD is // set: then it holds the coverage of each channel of subpixel-antialiased text and an alpha that is // their luminance, and the renderer tints it per channel instead. type Label struct { Pix []byte Stride int // bytes per row of Pix - Width int // pixels per row + Width int // destination pixels per row Height int + // SourceWidth and SourceHeight are nonzero only for a bitmap sampled into a different size. + SourceWidth, SourceHeight int // X and Y are the device pixel of the image's top-left corner in the canvas. X, Y int Layer uint16 @@ -192,7 +194,7 @@ func (c *Canvas) clearRegion(s render.Scissor, color scene.Color) { } func drawLabel(c *Canvas, damage render.Scissor, l *Label) { - if l.Width <= 0 || l.Height <= 0 || len(l.Pix) < (l.Height-1)*l.Stride+l.Width*4 { + if l.Width <= 0 || l.Height <= 0 { return } area := intersect(damage, render.Scissor{Left: l.X, Top: l.Y, Right: l.X + l.Width, Bottom: l.Y + l.Height}) @@ -202,6 +204,13 @@ func drawLabel(c *Canvas, damage render.Scissor, l *Label) { if empty(area) { return } + if l.SourceWidth > 0 { + drawScaledBitmap(c, area, l) + return + } + if len(l.Pix) < (l.Height-1)*l.Stride+l.Width*4 { + return + } if !l.LCD { drawPremultipliedLabel(c, area, l) return @@ -222,6 +231,34 @@ func drawLabel(c *Canvas, damage render.Scissor, l *Label) { } } +func drawScaledBitmap(canvas *Canvas, area render.Scissor, label *Label) { + width, height := label.SourceWidth, label.SourceHeight + if height <= 0 || label.Stride/4 < width || len(label.Pix) < width*4 || + height-1 > (len(label.Pix)-width*4)/label.Stride { + return + } + ratioX, ratioY := float64(width)/float64(label.Width), float64(height)/float64(label.Height) + for y := area.Top; y < area.Bottom; y++ { + sourceY := min(max((float64(y-label.Y)+0.5)*ratioY-0.5, 0), float64(height-1)) + upper := int(sourceY) + lower := min(upper+1, height-1) + weightY := float32(sourceY - float64(upper)) + for x := area.Left; x < area.Right; x++ { + sourceX := min(max((float64(x-label.X)+0.5)*ratioX-0.5, 0), float64(width-1)) + left := int(sourceX) + right := min(left+1, width-1) + weightX := float32(sourceX - float64(left)) + var sample [4]float32 + for channel := range sample { + top := float32(label.Pix[upper*label.Stride+left*4+channel])*(1-weightX) + float32(label.Pix[upper*label.Stride+right*4+channel])*weightX + bottom := float32(label.Pix[lower*label.Stride+left*4+channel])*(1-weightX) + float32(label.Pix[lower*label.Stride+right*4+channel])*weightX + sample[channel] = (top*(1-weightY) + bottom*weightY) * (1.0 / 255) + } + over(canvas.Pix, y*canvas.Stride+x*4, sample[2], sample[1], sample[0], sample[3]) + } + } +} + // drawPremultipliedLabel composites an image already in its color, as every // bitmap and grayscale text is. func drawPremultipliedLabel(c *Canvas, area render.Scissor, l *Label) { From 4cb355718fd6c5d4900b08a6b473d0772ba88011 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:56:07 +0800 Subject: [PATCH 06/66] fix(linux): keep the selection when a GTK preedit is cancelled --- .../linux/gtk_ime_fcitx_native_linux_test.go | 23 +++++++- internal/platform/linux/gtk_ime_linux.go | 57 +++++++++---------- .../linux/gtk_ime_native_linux_test.go | 38 ++++++++++--- .../gtk_ime_tentative_native_linux_test.go | 22 +++++-- 4 files changed, 96 insertions(+), 44 deletions(-) diff --git a/internal/platform/linux/gtk_ime_fcitx_native_linux_test.go b/internal/platform/linux/gtk_ime_fcitx_native_linux_test.go index 91fbab15..ae111e3d 100644 --- a/internal/platform/linux/gtk_ime_fcitx_native_linux_test.go +++ b/internal/platform/linux/gtk_ime_fcitx_native_linux_test.go @@ -245,7 +245,10 @@ func (probe *gtkFcitxProbe) settle() { if probe.ending == "commit" { probe.want = "a\u4f60\u597dc" } else if probe.ending == "escape" { - probe.want = "ac" + probe.want = "abc" + if p.tentative { + probe.want = "ac" + } } if probe.engine == "hangul" { probe.want = "a\uac00\ub098c" @@ -304,6 +307,18 @@ func (probe *gtkFcitxProbe) finish(failure string) { if p.tentative && (results != wantResults || cancels != wantCancels) { failures = append(failures, fmt.Sprintf("results/cancels=%d/%d, want=%d/%d", results, cancels, wantResults, wantCancels)) } + if !p.tentative && probe.engine == "pinyin" { + kind := platform.TextInsert + if probe.ending == "escape" { + kind = platform.TextCancelComposition + if p.editor.CanUndo() || p.editor.CanRedo() || p.editor.Selection() != (text.Range{Start: 1, End: 2}) { + failures = append(failures, "Escape did not preserve selection and history") + } + } + if len(p.events) == 0 || p.events[len(p.events)-1].Kind != kind { + failures = append(failures, fmt.Sprintf("expected terminal event %d", kind)) + } + } if p.editor.String() != probe.want || p.w.text.state != platform.EditorState(p.editor).WithoutRedraw() || p.w.text.state.Composing { failures = append(failures, "settled editor/mirror differ or native tail mutated the result") } @@ -312,6 +327,12 @@ func (probe *gtkFcitxProbe) finish(failure string) { } } probe.record(failures...) + if failure == "" && !p.tentative && probe.engine == "pinyin" && probe.ending != "escape" { + if !p.editor.Undo() || p.editor.String() != "abc" || p.editor.CanUndo() || !p.editor.Redo() || p.editor.String() != probe.want { + last := &p.trials[len(p.trials)-1] + last.failures = append(last.failures, "commit did not round-trip in a single undo unit") + } + } if failure == "" && p.tentative { undos := []string{"ac", "abc"} if probe.engine == "hangul" { diff --git a/internal/platform/linux/gtk_ime_linux.go b/internal/platform/linux/gtk_ime_linux.go index c56b81db..d6ed4fe0 100644 --- a/internal/platform/linux/gtk_ime_linux.go +++ b/internal/platform/linux/gtk_ime_linux.go @@ -128,7 +128,7 @@ func (ime *gtkIME) setFocused(focused bool) { func (ime *gtkIME) filtering() bool { return ime.ctx != 0 && ime.active } func (ime *gtkIME) composing() bool { - return ime.engineComposing || ime.w.text.state.Composing || ime.tentative && ime.session + return ime.engineComposing || ime.w.text.state.Composing || ime.session } func (ime *gtkIME) prepareKey() bool { @@ -198,7 +198,7 @@ func (ime *gtkIME) sync() { ime.callContext(context, ime.g.imFocusIn) case !want && ime.active: ime.active = false - if ime.engineComposing || ime.tentative && ime.session { + if ime.engineComposing || ime.session { ime.engineComposing = false ime.callContext(context, ime.g.imReset) } @@ -333,9 +333,6 @@ func (ime *gtkIME) commit(value string) { } func (ime *gtkIME) preeditStarted() { - if !ime.tentative { - return - } context := ime.ctx ime.finishPreedit(context) if ime.current(context) { @@ -344,7 +341,7 @@ func (ime *gtkIME) preeditStarted() { } func (ime *gtkIME) preeditEnded() { - if !ime.tentative || !ime.session { + if !ime.session { return } ime.ending, ime.engineComposing = true, false @@ -396,9 +393,16 @@ func (ime *gtkIME) finishPreedit(context uintptr) { } ime.clearEnd() ime.session, ime.engineComposing = false, false - if ime.tentative && ime.current(context) { - ime.apply(platform.TextEvent{Kind: platform.TextCancelComposition, CompositionPhase: text.CompositionCancel}) + if !ime.current(context) { + return } + event := platform.TextEvent{Kind: platform.TextCancelComposition} + if ime.tentative { + event.CompositionPhase = text.CompositionCancel + } else if !ime.w.text.state.Composing { + return + } + ime.apply(event) } // preeditChanged shows the text being composed as marked text, or removes it. @@ -430,32 +434,25 @@ func (ime *gtkIME) preeditChanged() { if ime.ctx != context || ime.w.closed || ime.w.text.stateRevision != revision { return } - if ime.tentative { - if value == "" { - ime.engineComposing = false - if !ime.session { - return - } - } else { - ime.engineComposing = true - } - ime.session = true - ime.apply(platform.TextEvent{Kind: platform.TextSetMarked, CompositionPhase: text.CompositionUpdate, Text: value, MarkedSelection: selection}) + ime.engineComposing = value != "" + if value == "" && !ime.session { return } - if value == "" { - ime.engineComposing = false - if ime.w.text.state.Composing { - ime.apply(platform.TextEvent{Kind: platform.TextSetMarked}) - if ime.ctx != context || ime.w.closed || ime.w.text.stateRevision != revision+1 { - return - } - ime.apply(platform.TextEvent{Kind: platform.TextUnmark}) - } + // A legacy context can report no preedit after the field already left the + // composition: sync resets the context when the field stops composing on its + // own, and that reset emits this update while the session is still open. The + // editor is not composing, so there is no marked text to clear, and an empty + // legacy marked update would replace the selection the click that ended the + // composition just made. The pending end settles the session instead. + if value == "" && !ime.tentative && !ime.w.text.state.Composing { return } - ime.engineComposing = true - ime.apply(platform.TextEvent{Kind: platform.TextSetMarked, Text: value, MarkedSelection: selection}) + ime.session = true + event := platform.TextEvent{Kind: platform.TextSetMarked, Text: value, MarkedSelection: selection} + if ime.tentative { + event.CompositionPhase = text.CompositionUpdate + } + ime.apply(event) } // Pango attribute types the input method marks the clause it is converting with. diff --git a/internal/platform/linux/gtk_ime_native_linux_test.go b/internal/platform/linux/gtk_ime_native_linux_test.go index fea60bca..49376ddc 100644 --- a/internal/platform/linux/gtk_ime_native_linux_test.go +++ b/internal/platform/linux/gtk_ime_native_linux_test.go @@ -197,7 +197,16 @@ func (p *gtkIMEProbe) record(name string, failures ...string) { func (p *gtkIMEProbe) run() { for _, ending := range []string{"commit", "escape", "reset", "focus-out", "window-focus-out"} { editor := text.NewEditor("abc") - editor.SetSelection(text.Range{Start: 1, End: 2}) + if ending == "escape" { + editor.Insert("!") + if !editor.Undo() { + p.editor = editor + p.record(ending, "could not seed redo history") + continue + } + } + selection := text.Range{Start: 1, End: 2} + editor.SetSelection(text.Range{Start: selection.End, End: selection.Start}) p.install(editor, gfx.Item(1)) if err := p.compose(); err != nil { p.record(ending, err.Error()) @@ -218,31 +227,44 @@ func (p *gtkIMEProbe) run() { failures = append(failures, err.Error()) } case "reset": - p.w.g.imReset(p.w.ime.ctx) + p.w.ime.callContext(p.w.ime.ctx, p.w.g.imReset) case "focus-out": p.w.g.imFocusOut(p.w.ime.ctx) if !slices.Equal(p.signals, prefix) || editor.String() != "au3A9c" { failures = append(failures, "GtkIMContextSimple focus-out unexpectedly settled preedit") } - p.w.g.imReset(p.w.ime.ctx) + p.w.ime.callContext(p.w.ime.ctx, p.w.g.imReset) case "window-focus-out": p.w.ime.setFocused(false) } wantSignals := append(prefix, "preedit:", "end") - wantText := "ac" + wantText := "abc" + wantTerminal := platform.TextCancelComposition if ending == "commit" { wantSignals = append(wantSignals, "commit:\u03a9") wantText = "a\u03a9c" + wantTerminal = platform.TextInsert } if !slices.Equal(p.signals, wantSignals) || editor.String() != wantText || p.w.text.state.Composing { failures = append(failures, fmt.Sprintf("ending signals=%q text=%q composing=%t", p.signals, editor.String(), p.w.text.state.Composing)) } + if len(p.events) == 0 || p.events[len(p.events)-1].Kind != wantTerminal { + failures = append(failures, fmt.Sprintf("expected terminal event %d", wantTerminal)) + } p.record(ending, failures...) - if !editor.Undo() || ending == "commit" && editor.String() != "ac" || ending != "commit" && editor.String() != "abc" { - p.trials[len(p.trials)-1].failures = append(p.trials[len(p.trials)-1].failures, fmt.Sprintf("first Undo=%q", editor.String())) + trial := &p.trials[len(p.trials)-1] + if ending == "commit" && !editor.Undo() { + trial.failures = append(trial.failures, "commit has no undo unit") + } + wantRedo := ending == "commit" || ending == "escape" + if editor.String() != "abc" || editor.Selection() != selection || editor.Caret() != selection.Start || editor.CanUndo() || editor.CanRedo() != wantRedo { + trial.failures = append(trial.failures, fmt.Sprintf("original editor state not restored: text=%q selection=%v caret=%d undo=%t redo=%t", editor.String(), editor.Selection(), editor.Caret(), editor.CanUndo(), editor.CanRedo())) + } + if ending == "commit" && (!editor.Redo() || editor.String() != wantText) { + trial.failures = append(trial.failures, fmt.Sprintf("Redo=%q, want %q", editor.String(), wantText)) } - if ending == "commit" && (!editor.Undo() || editor.String() != "abc") { - p.trials[len(p.trials)-1].failures = append(p.trials[len(p.trials)-1].failures, fmt.Sprintf("second Undo=%q", editor.String())) + if ending == "escape" && (!editor.Redo() || editor.String() != "abc!") { + trial.failures = append(trial.failures, fmt.Sprintf("Redo after Escape=%q, want abc!", editor.String())) } } plain := text.NewEditor("abc") diff --git a/internal/platform/linux/gtk_ime_tentative_native_linux_test.go b/internal/platform/linux/gtk_ime_tentative_native_linux_test.go index 73dfb193..b30c93c2 100644 --- a/internal/platform/linux/gtk_ime_tentative_native_linux_test.go +++ b/internal/platform/linux/gtk_ime_tentative_native_linux_test.go @@ -262,7 +262,10 @@ func (p *gtkTentativeProbe) run() { p.w.ime.setFocused(false) } wantSignals := append(prefix, "preedit:", "end") - wantText := "ac" + wantText := "abc" + if tentative { + wantText = "ac" + } if ending == "commit" { wantSignals = append(wantSignals, "commit:\u03a9") wantText = "a\u03a9c" @@ -289,11 +292,20 @@ func (p *gtkTentativeProbe) run() { } } p.record(fmt.Sprintf("tentative=%t/%s", tentative, ending), failures...) - if !editor.Undo() || ending == "commit" && editor.String() != "ac" || ending != "commit" && editor.String() != "abc" { - p.trials[len(p.trials)-1].failures = append(p.trials[len(p.trials)-1].failures, fmt.Sprintf("first Undo=%q", editor.String())) + trial := &p.trials[len(p.trials)-1] + if tentative || ending == "commit" { + wantUndo := "abc" + if tentative && ending == "commit" { + wantUndo = "ac" + } + if !editor.Undo() || editor.String() != wantUndo { + trial.failures = append(trial.failures, fmt.Sprintf("first Undo=%q, want %q", editor.String(), wantUndo)) + } + } else if editor.CanUndo() { + trial.failures = append(trial.failures, "legacy cancellation added undo history") } - if ending == "commit" && (!editor.Undo() || editor.String() != "abc") { - p.trials[len(p.trials)-1].failures = append(p.trials[len(p.trials)-1].failures, fmt.Sprintf("second Undo=%q", editor.String())) + if tentative && ending == "commit" && (!editor.Undo() || editor.String() != "abc") { + trial.failures = append(trial.failures, fmt.Sprintf("second Undo=%q", editor.String())) } } p.composingTrial = false From 089cd85632bba4de25268cf6bfde1d0bd5c7b3ae Mon Sep 17 00:00:00 2001 From: lizzzzz777 <72645313+lizzzzz777@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:56:29 +0800 Subject: [PATCH 07/66] fix(darwin): select words on double-click and the value on triple-click --- internal/platform/darwin/native.m | 19 +++++++++--- .../platform/darwin/testdata/text_selection.m | 31 ++++++++++++++++++- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 94f395c5..70755db0 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -3917,7 +3917,7 @@ @interface VivaMetalView : NSView { BOOL _dynamicTextInput; BOOL _caretVisible; NSTimer *_caretTimer; - NSUInteger _textSelectionAnchor; + NSRange _textSelectionAnchor; BOOL _textSelectionDragging; BOOL _pointerEventsEnabled; BOOL _resizeEventsEnabled; @@ -4452,7 +4452,16 @@ - (void)mouseDown:(NSEvent *)event { return; } NSUInteger index = [self textIndexForEvent:event]; - _textSelectionAnchor = index; + _textSelectionAnchor = NSMakeRange(index, 0); + if (event.clickCount >= 2 && _text.length > 0) { + if (event.clickCount >= 3 || _textSecure) { + _textSelectionAnchor = NSMakeRange(0, _text.length); + } else { + NSAttributedString *value = [[NSAttributedString alloc] initWithString:_text]; + _textSelectionAnchor = [value doubleClickAtIndex:MIN(index, _text.length - 1)]; + [value release]; + } + } _textSelectionDragging = YES; [self selectTextToIndex:index]; } else { @@ -6011,8 +6020,9 @@ - (BOOL)eventIsInsideTextInput:(NSEvent *)event { } - (void)selectTextToIndex:(NSUInteger)index { - NSUInteger start = MIN(_textSelectionAnchor, index); - NSUInteger end = MAX(_textSelectionAnchor, index); + // Keep the word under a double press selected through the release and drag. + NSUInteger start = MIN(_textSelectionAnchor.location, index); + NSUInteger end = MAX(NSMaxRange(_textSelectionAnchor), index); [self selectTextRange:NSMakeRange(start, end - start)]; } @@ -6042,7 +6052,6 @@ - (void)selectTextRange:(NSRange)range { - (void)selectAll:(id)sender { (void)sender; - _textSelectionAnchor = 0; _textSelectionDragging = NO; [self selectTextRange:NSMakeRange(0, _text.length)]; } diff --git a/internal/platform/darwin/testdata/text_selection.m b/internal/platform/darwin/testdata/text_selection.m index b93799e2..a5f9961c 100644 --- a/internal/platform/darwin/testdata/text_selection.m +++ b/internal/platform/darwin/testdata/text_selection.m @@ -148,6 +148,7 @@ @interface SelectionView : VivaMetalView { } - (void)resetText:(NSString *)value; - (NSEvent *)mouseEvent:(NSEventType)type offset:(CGFloat)offset; +- (NSEvent *)mouseEvent:(NSEventType)type offset:(CGFloat)offset clicks:(NSInteger)clicks; - (CGFloat)offsetForIndex:(NSUInteger)index; - (BOOL)dragging; - (void)enablePointerCallbacks; @@ -238,10 +239,13 @@ - (void)emitTextKind:(int)kind text:(NSString *)value selectedRange:(NSRange)sel [self restartCaretBlink]; } - (NSEvent *)mouseEvent:(NSEventType)type offset:(CGFloat)offset { + return [self mouseEvent:type offset:offset clicks:1]; +} +- (NSEvent *)mouseEvent:(NSEventType)type offset:(CGFloat)offset clicks:(NSInteger)clicks { return [NSEvent mouseEventWithType:type location:NSMakePoint(_textFrame.origin.x + offset, self.bounds.size.height - NSMidY(_textFrame)) - modifierFlags:0 timestamp:0 windowNumber:0 context:nil eventNumber:0 clickCount:1 pressure:1]; + modifierFlags:0 timestamp:0 windowNumber:0 context:nil eventNumber:0 clickCount:clicks pressure:1]; } - (CGFloat)offsetForIndex:(NSUInteger)index { viva_editor_line line = [self newTextLine]; @@ -390,6 +394,31 @@ int main(void) { assert(view->selectionEvents == events); assert(view->textureRebuilds == 0); + for (NSString *value in @[@"/data/bdss", @"😀 preview forward"]) { + [view resetText:value]; + NSString *word = [value hasPrefix:@"/"] ? @"bdss" : @"preview"; + NSRange expected = [value rangeOfString:word]; + CGFloat inside = [view offsetForIndex:expected.location + 1]; + [view mouseDown:[view mouseEvent:NSEventTypeLeftMouseDown offset:inside]]; + [view mouseUp:[view mouseEvent:NSEventTypeLeftMouseUp offset:inside]]; + [view mouseDown:[view mouseEvent:NSEventTypeLeftMouseDown offset:inside clicks:2]]; + assert(NSEqualRanges(view.selectedRange, expected)); + [view mouseUp:[view mouseEvent:NSEventTypeLeftMouseUp offset:inside clicks:2]]; + assert(NSEqualRanges(view.selectedRange, expected)); + assert(![view dragging]); + + [view mouseDown:[view mouseEvent:NSEventTypeLeftMouseDown offset:inside clicks:2]]; + [view mouseDragged:[view mouseEvent:NSEventTypeLeftMouseDragged offset:-100]]; + assert(NSEqualRanges(view.selectedRange, NSMakeRange(0, NSMaxRange(expected)))); + [view mouseUp:[view mouseEvent:NSEventTypeLeftMouseUp offset:-100 clicks:2]]; + assert(NSEqualRanges(view.selectedRange, NSMakeRange(0, NSMaxRange(expected)))); + + [view mouseDown:[view mouseEvent:NSEventTypeLeftMouseDown offset:inside clicks:3]]; + assert(NSEqualRanges(view.selectedRange, NSMakeRange(0, value.length))); + [view mouseUp:[view mouseEvent:NSEventTypeLeftMouseUp offset:inside clicks:3]]; + assert(NSEqualRanges(view.selectedRange, NSMakeRange(0, value.length))); + } + [view resetText:@"A中😀B"]; assert([view performKeyEquivalent:keyEvent(@"a", NSEventModifierFlagCommand)]); assert(NSEqualRanges(view.selectedRange, NSMakeRange(0, 5))); From 883a3c0c0567d74645bcd35815529ba6f563beae Mon Sep 17 00:00:00 2001 From: ezreal <71426102+Ezreal-byte@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:56:53 +0800 Subject: [PATCH 08/66] fix(app): preserve native window capabilities --- app/application_native.go | 66 ++++++++++++++++++++++++++++++++++ app/application_native_test.go | 56 +++++++++++++++++++++++++++++ app/drag_preview.go | 19 ++++++++-- app/drag_preview_test.go | 58 ++++++++++++++++++++++++++++++ 4 files changed, 197 insertions(+), 2 deletions(-) create mode 100644 app/application_native_test.go diff --git a/app/application_native.go b/app/application_native.go index 92d5fd25..b6836e62 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -78,6 +78,17 @@ type resultWindow struct { waker *platform.Waker } +// The embedded WindowControl intentionally exposes only the methods every +// native window has. Forward optional capabilities explicitly so wrapping a +// window for event-result handling does not hide resize, fullscreen, +// always-on-top, or shortcut capture support. +var _ platform.WindowSizer = resultWindow{} +var _ fullscreenControl = resultWindow{} +var _ alwaysOnTopControl = resultWindow{} +var _ shortcutCapturer = resultWindow{} +var _ titleControl = resultWindow{} +var _ platform.WindowMover = resultWindow{} + // What OpenWindow looks for in a host's window control. var _ interface { applyResult(gfx.EventResult) bool @@ -85,6 +96,61 @@ var _ interface { runShortcut(keymap.Chord) (gfx.EventResult, bool) } = resultWindow{} +func (window resultWindow) SetSize(width, height int) error { + sizer, ok := window.WindowControl.(platform.WindowSizer) + if !ok { + return platform.ErrWindowSizeUnsupported + } + return sizer.SetSize(width, height) +} + +func (window resultWindow) SetFullscreen(fullscreen bool) error { + control, ok := window.WindowControl.(fullscreenControl) + if !ok { + return platform.ErrFullscreenUnsupported + } + return control.SetFullscreen(fullscreen) +} + +func (window resultWindow) Fullscreen() bool { + control, ok := window.WindowControl.(fullscreenControl) + return ok && control.Fullscreen() +} + +func (window resultWindow) SetTitle(title string) error { + control, ok := window.WindowControl.(titleControl) + if !ok { + return fmt.Errorf("%w: window titles", ErrUnsupported) + } + return control.SetTitle(title) +} + +func (window resultWindow) SetAlwaysOnTop(enabled bool) error { + control, ok := window.WindowControl.(alwaysOnTopControl) + if !ok { + return platform.ErrAlwaysOnTopUnsupported + } + return control.SetAlwaysOnTop(enabled) +} + +func (window resultWindow) MoveTo(origin gfx.Point) { + if control, ok := window.WindowControl.(platform.WindowMover); ok { + control.MoveTo(origin) + } +} + +func (window resultWindow) unwrapWindowControl() WindowControl { + return window.WindowControl +} + +func (window resultWindow) CaptureSystemShortcuts(capture bool) error { + control, ok := window.WindowControl.(shortcutCapturer) + if !ok { + return fmt.Errorf("%w: this platform keeps the system's shortcuts", ErrUnsupported) + } + return control.CaptureSystemShortcuts(capture) +} + func (window resultWindow) applyResult(result gfx.EventResult) bool { return window.painter.applyEventResult(result) } diff --git a/app/application_native_test.go b/app/application_native_test.go new file mode 100644 index 00000000..b0295f91 --- /dev/null +++ b/app/application_native_test.go @@ -0,0 +1,56 @@ +//go:build darwin || windows || linux + +package app + +import ( + "errors" + "testing" +) + +func TestResultWindowForwardsSetSize(t *testing.T) { + native := &sizingWindow{} + window := &Window{control: resultWindow{WindowControl: native}} + if err := window.SetSize(1280, 720); err != nil { + t.Fatal(err) + } + if native.width != 1280 || native.height != 720 { + t.Fatalf("SetSize = %dx%d", native.width, native.height) + } + + unsupported := &Window{control: resultWindow{WindowControl: struct{ WindowControl }{}}} + if err := unsupported.SetSize(800, 600); !errors.Is(err, ErrUnsupported) { + t.Fatalf("wrapped unsupported window error = %v", err) + } +} + +func TestResultWindowForwardsAlwaysOnTop(t *testing.T) { + native := &topmostTestControl{} + window := &Window{control: resultWindow{WindowControl: native}} + if err := window.SetAlwaysOnTop(true); err != nil { + t.Fatal(err) + } + if !window.AlwaysOnTop() || len(native.requests) != 1 || !native.requests[0] { + t.Fatalf("always-on-top request did not reach the native window: requests=%v", native.requests) + } + + unsupported := &Window{control: resultWindow{WindowControl: &fakeWindow{}}} + if err := unsupported.SetAlwaysOnTop(true); !errors.Is(err, ErrUnsupported) { + t.Fatalf("wrapped unsupported window error = %v", err) + } +} + +func TestResultWindowForwardsSetTitle(t *testing.T) { + native := &titleTestControl{} + window := &Window{control: resultWindow{WindowControl: native}} + if err := window.SetTitle("project – main.go"); err != nil { + t.Fatal(err) + } + if len(native.titles) != 1 || native.titles[0] != "project – main.go" { + t.Fatalf("titles = %q", native.titles) + } + + unsupported := &Window{control: resultWindow{WindowControl: &fakeWindow{}}} + if err := unsupported.SetTitle("x"); !errors.Is(err, ErrUnsupported) { + t.Fatalf("wrapped unsupported window error = %v", err) + } +} diff --git a/app/drag_preview.go b/app/drag_preview.go index 2eb09ed8..c4a86329 100644 --- a/app/drag_preview.go +++ b/app/drag_preview.go @@ -62,20 +62,35 @@ func (application *Application) OpenDragPreview(config DragPreviewConfig) (*Drag if err != nil { return nil, err } - if _, ok := window.control.(platform.WindowMover); !ok { + if _, ok := previewMover(window.control); !ok { window.Close() return nil, ErrNoDragPreview } return &DragPreview{window: window}, nil } +type windowControlUnwrapper interface { + unwrapWindowControl() WindowControl +} + +// previewMover unwraps a host wrapper before checking the adapter's capability. +// A wrapper can forward MoveTo, but it must not make a native window that +// cannot move look movable. +func previewMover(control WindowControl) (platform.WindowMover, bool) { + if wrapped, ok := control.(windowControlUnwrapper); ok { + control = wrapped.unwrapWindowControl() + } + mover, ok := control.(platform.WindowMover) + return mover, ok +} + // MoveTo puts the picture's top-left at origin, in screen coordinates. Call it // on the application thread, as from a pointer callback. func (preview *DragPreview) MoveTo(origin gfx.Point) { if preview == nil || preview.window == nil || preview.window.closed.Load() { return } - if mover, ok := preview.window.control.(platform.WindowMover); ok { + if mover, ok := previewMover(preview.window.control); ok { mover.MoveTo(origin) } } diff --git a/app/drag_preview_test.go b/app/drag_preview_test.go index 55f62bc7..5b619497 100644 --- a/app/drag_preview_test.go +++ b/app/drag_preview_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" ) // movableWindow is a fake window that can be moved, as a preview's is. @@ -35,6 +36,22 @@ func (host *previewingHost) OpenWindow(config Config, canvas *gfx.Canvas, closed return window, nil } +// resultPreviewingHost mimics the native host that wraps an adapter window in +// resultWindow before handing it to an application. +type resultPreviewingHost struct { + *fakeHost +} + +func (host *resultPreviewingHost) CanPreview() bool { return true } + +func (host *resultPreviewingHost) OpenWindow(config Config, canvas *gfx.Canvas, closed func()) (WindowControl, error) { + control, err := host.fakeHost.OpenWindow(config, canvas, closed) + if err != nil { + return nil, err + } + return resultWindow{WindowControl: control}, nil +} + func usePreviewHost(t *testing.T, host *previewingHost) { t.Helper() previous := applicationRunner @@ -81,6 +98,34 @@ func TestADragPreviewFollowsMovesAndGoesWhenClosed(t *testing.T) { } } +func TestADragPreviewRejectsANativeWindowThatCannotMove(t *testing.T) { + host := &resultPreviewingHost{fakeHost: &fakeHost{}} + previous := applicationRunner + t.Cleanup(func() { + applicationRunner = previous + for _, window := range host.windows { + window.Close() + } + }) + applicationRunner = func(start func(Host) error) error { return start(host) } + + err := RunApplication(func(application *Application) error { + if _, err := application.OpenWindow(Config{Title: "main"}, nil); err != nil { + return err + } + if _, err := application.OpenDragPreview(DragPreviewConfig{Width: 10, Height: 10}); !errors.Is(err, ErrUnsupported) { + t.Fatalf("OpenDragPreview error = %v, want ErrUnsupported", err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if len(host.windows) != 2 || !host.windows[1].done { + t.Fatalf("unmovable preview was not closed: windows=%d done=%v", len(host.windows), len(host.windows) > 1 && host.windows[1].done) + } +} + func TestADragPreviewIsRefusedWhereTheHostCannotShowOne(t *testing.T) { host := &fakeHost{} useHost(t, host) @@ -102,6 +147,19 @@ func TestADragPreviewIsRefusedWhereTheHostCannotShowOne(t *testing.T) { } } +func TestANativeWindowResultStillMovesAPreview(t *testing.T) { + moving := &movableWindow{fakeWindow: &fakeWindow{}} + control := resultWindow{WindowControl: moving} + mover, ok := any(control).(platform.WindowMover) + if !ok { + t.Fatal("a native window result hid the platform's MoveTo") + } + mover.MoveTo(gfx.Point{X: 30, Y: 40}) + if len(moving.moves) != 1 || moving.moves[0] != (gfx.Point{X: 30, Y: 40}) { + t.Fatalf("moves = %v", moving.moves) + } +} + func BenchmarkDragPreviewMoveTo(b *testing.B) { host := &previewingHost{fakeHost: &fakeHost{}} var preview *DragPreview From 59922deb46af8c7bb8fb693ce89ba0ce2063dae1 Mon Sep 17 00:00:00 2001 From: lizzzzz777 <72645313+lizzzzz777@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:57:48 +0800 Subject: [PATCH 09/66] test(app): cover fullscreen forwarding through the result window --- app/fullscreen_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/fullscreen_test.go b/app/fullscreen_test.go index 72ba330c..618bde29 100644 --- a/app/fullscreen_test.go +++ b/app/fullscreen_test.go @@ -55,6 +55,24 @@ func TestFullscreenRequestsAndObservedStateAreDistinct(t *testing.T) { } } +func TestNativeResultWindowForwardsFullscreenRequests(t *testing.T) { + control := &fullscreenTestControl{} + window := &Window{control: resultWindow{WindowControl: control}} + for _, fullscreen := range []bool{true, false} { + if err := window.SetFullscreen(fullscreen); err != nil { + t.Fatal(err) + } + } + if len(control.requests) != 2 || !control.requests[0] || control.requests[1] { + t.Fatalf("native fullscreen requests = %v, want [true false]", control.requests) + } + + unsupported := &Window{control: resultWindow{WindowControl: &fakeWindow{}}} + if err := unsupported.SetFullscreen(true); !errors.Is(err, ErrUnsupported) { + t.Fatalf("unsupported native window: %v", err) + } +} + func TestFullscreenHostCallbackPublishesBeforeApplicationCallback(t *testing.T) { host := &fakeHost{} application := &Application{host: host} From 85c2a1565a54ad4918f3ba2068d253fc9c0a4887 Mon Sep 17 00:00:00 2001 From: ezreal <71426102+Ezreal-byte@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:58:38 +0800 Subject: [PATCH 10/66] feat(windows): add transparent drag previews --- .github/workflows/ci.yml | 2 +- app/drag_preview.go | 5 ++ app/drag_preview_test.go | 39 ++++++++++ internal/platform/contract.go | 4 + .../platform/windows/materials_windows.go | 3 + .../platform/windows/status_item_windows.go | 11 ++- .../windows/window_controls_windows.go | 1 + .../windows/window_preview_windows.go | 32 ++++++++ .../windows/window_preview_windows_test.go | 75 +++++++++++++++++++ internal/platform/windows/window_windows.go | 18 +++++ 10 files changed, 187 insertions(+), 3 deletions(-) create mode 100644 internal/platform/windows/window_preview_windows.go create mode 100644 internal/platform/windows/window_preview_windows_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9c876250..2584e2b8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -293,7 +293,7 @@ jobs: # native structure ABI tests are here for the same reason: they build only # on Windows. - name: Material contracts and controls (WARP) - run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|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)' -count=1 -v + run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|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)' -count=1 -v - name: Terminal keyboard routing run: go test ./internal/platform/windows -run '^TestATerminalGetsEditingKeysAndChordsAsRawKeys$' -count=1 -v - name: Native Windows global shortcut diff --git a/app/drag_preview.go b/app/drag_preview.go index c4a86329..b3bd4ca3 100644 --- a/app/drag_preview.go +++ b/app/drag_preview.go @@ -60,6 +60,11 @@ func (application *Application) OpenDragPreview(config DragPreviewConfig) (*Drag Paint: config.Paint, }, nil) if err != nil { + // A host that cannot show the preview at all keeps the drag going + // without it, as the API promises. + if errors.Is(err, platform.ErrDragPreviewUnsupported) { + return nil, ErrNoDragPreview + } return nil, err } if _, ok := previewMover(window.control); !ok { diff --git a/app/drag_preview_test.go b/app/drag_preview_test.go index 5b619497..7a899897 100644 --- a/app/drag_preview_test.go +++ b/app/drag_preview_test.go @@ -4,6 +4,7 @@ package app import ( "errors" + "fmt" "testing" "github.com/vivaui/viva/gfx" @@ -178,3 +179,41 @@ func BenchmarkDragPreviewMoveTo(b *testing.B) { preview.MoveTo(gfx.Point{X: float32(i), Y: 1}) } } + +// unavailablePreviewHost is a host that advertises previews but cannot create +// one: the compositor is missing. +type unavailablePreviewHost struct{ *fakeHost } + +func (host *unavailablePreviewHost) CanPreview() bool { return true } + +func (host *unavailablePreviewHost) OpenWindow(config Config, canvas *gfx.Canvas, closed func()) (WindowControl, error) { + if config.WindowMode == windowPreview { + return nil, fmt.Errorf("%w: no compositor", platform.ErrDragPreviewUnsupported) + } + return host.fakeHost.OpenWindow(config, canvas, closed) +} + +func TestADragPreviewTheHostCannotShowKeepsTheDrag(t *testing.T) { + host := &unavailablePreviewHost{fakeHost: &fakeHost{}} + previous := applicationRunner + t.Cleanup(func() { + applicationRunner = previous + for _, window := range host.windows { + window.Close() + } + }) + applicationRunner = func(start func(Host) error) error { return start(host) } + err := RunApplication(func(application *Application) error { + if _, err := application.OpenWindow(Config{Title: "main"}, nil); err != nil { + return err + } + _, err := application.OpenDragPreview(DragPreviewConfig{Width: 120, Height: 28}) + if !errors.Is(err, ErrNoDragPreview) || !errors.Is(err, ErrUnsupported) { + t.Fatalf("open error = %v, want ErrNoDragPreview", err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 9a29c187..10f44943 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -265,6 +265,10 @@ var ErrAlwaysOnTopUnsupported = errors.New("platform: always-on-top is unsupport // application. var ErrWindowSizeUnsupported = errors.New("platform: programmatic window size is unsupported") +// ErrDragPreviewUnsupported means this adapter cannot show the click-through +// preview window a drag uses; the application keeps its in-window ghost. +var ErrDragPreviewUnsupported = errors.New("platform: a transparent drag preview is unsupported") + // ErrStatusAreaUnavailable is returned by AddStatusItem when the desktop has no // status area to put an icon in, as a Linux session without a StatusNotifier // host. The application keeps running; it only has no icon. diff --git a/internal/platform/windows/materials_windows.go b/internal/platform/windows/materials_windows.go index c185fd17..fbf647f4 100644 --- a/internal/platform/windows/materials_windows.go +++ b/internal/platform/windows/materials_windows.go @@ -16,6 +16,9 @@ type compositionState struct { } func (state *windowState) backdropWindowStyle() uintptr { + if state.config.WindowMode == platform.WindowPreview { + return wsExNoRedirectionBitmap + } if state.config.WindowBackdrop != nil && nativeBackdropAPI() != backdropUnavailable { return wsExNoRedirectionBitmap } diff --git a/internal/platform/windows/status_item_windows.go b/internal/platform/windows/status_item_windows.go index b6c73c45..bff4f534 100644 --- a/internal/platform/windows/status_item_windows.go +++ b/internal/platform/windows/status_item_windows.go @@ -45,8 +45,10 @@ const ( wsPopup = 0x80000000 wsExToolWindow = 0x00000080 wsExTopmost = 0x00000008 + wsExTransparent = 0x00000020 swHide = 0 swShow = 5 + swShowNoActivate = 4 swRestore = 9 smSmallIconWidth = 49 monitorNearest = 2 @@ -547,8 +549,13 @@ func (state *windowState) placeAtOrigin(origin gfx.Point) { var info monitorInfo info.Size = uint32(unsafe.Sizeof(info)) monitor, _, _ := monitorFromPoint.Call(uintptr(uint32(x+width/2))|uintptr(uint32(y+height/2))<<32, monitorNearest) - if ok, _, _ := getMonitorInfo.Call(monitor, uintptr(unsafe.Pointer(&info))); ok != 0 { - x, y, width, height = placedFrame(info.Work, x, y, width, height) + // A drag preview goes wherever the pointer is, even half off a screen: the + // ghost is not a window the user has to reach. Every other window stays + // inside the work area of the monitor it lands on. + if state.config.WindowMode != platform.WindowPreview { + if ok, _, _ := getMonitorInfo.Call(monitor, uintptr(unsafe.Pointer(&info))); ok != 0 { + x, y, width, height = placedFrame(info.Work, x, y, width, height) + } } // SWP_NOZORDER | SWP_NOACTIVATE: the size too, for a window that did not fit. setWindowPosition.Call(state.window, 0, uintptr(x), uintptr(y), uintptr(width), uintptr(height), 0x14) diff --git a/internal/platform/windows/window_controls_windows.go b/internal/platform/windows/window_controls_windows.go index 8056fb15..4b94e1f4 100644 --- a/internal/platform/windows/window_controls_windows.go +++ b/internal/platform/windows/window_controls_windows.go @@ -45,6 +45,7 @@ const ( htBottom = 15 htBottomLeft = 16 htBottomRight = 17 + htTransparent = ^uintptr(0) ) var isZoomed = user.NewProc("IsZoomed") diff --git a/internal/platform/windows/window_preview_windows.go b/internal/platform/windows/window_preview_windows.go new file mode 100644 index 00000000..fd977731 --- /dev/null +++ b/internal/platform/windows/window_preview_windows.go @@ -0,0 +1,32 @@ +package windows + +import ( + "fmt" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +var errTransparentPreviewUnavailable = fmt.Errorf("%w: windows has no compositor for it", platform.ErrDragPreviewUnsupported) + +// SupportsDragPreview marks the Windows adapter as able to show a transparent +// preview window that never takes focus or input. +func (application *windowsApplication) SupportsDragPreview() {} + +// MoveTo puts the top-left of a preview's content at origin without changing +// its size, stacking level or activation. +func (window *nativeWindow) MoveTo(origin gfx.Point) { + if window == nil || window.closed.Load() || window.state == nil || window.state.window == 0 { + return + } + state := window.state + scale := state.scale + if scale <= 0 { + scale = 1 + } + x := int32(origin.X * scale) + y := int32(origin.Y * scale) + setWindowPosition.Call(state.window, 0, uintptr(x), uintptr(y), 0, 0, 0x15) // nosize, nozorder, noactivate +} + +var _ platform.WindowMover = (*nativeWindow)(nil) diff --git a/internal/platform/windows/window_preview_windows_test.go b/internal/platform/windows/window_preview_windows_test.go new file mode 100644 index 00000000..c0f1845d --- /dev/null +++ b/internal/platform/windows/window_preview_windows_test.go @@ -0,0 +1,75 @@ +package windows + +import ( + "runtime" + "testing" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +func TestDragPreviewWindowIsClickThroughTopmostAndMovable(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + getWindowLong := user.NewProc("GetWindowLongPtrW") + getWindowRect := user.NewProc("GetWindowRect") + sendMessage := user.NewProc("SendMessageW") + err := RunApplication(func(application platform.Application) error { + if _, ok := application.(interface{ SupportsDragPreview() }); !ok { + t.Fatal("the Windows adapter did not report drag preview support") + } + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva drag preview test", Width: 120, Height: 40, WindowMode: platform.WindowPreview, + }) + if err != nil { + if err == errTransparentPreviewUnavailable { + t.Skip("this desktop has no compositor for a transparent preview") + } + return err + } + defer opened.Close() + state := opened.(*nativeWindow).state + window := state.window + if state.renderer.submissions == 0 { + t.Fatal("preview was shown without presenting its first frame") + } + style, _, _ := getWindowLong.Call(window, ^uintptr(19)) // GWL_EXSTYLE + for _, required := range [...]struct { + name string + value uintptr + }{ + {"topmost", wsExTopmost}, + {"tool window", wsExToolWindow}, + {"no activate", wsExNoActivate}, + {"click through", wsExTransparent}, + {"composited", wsExNoRedirectionBitmap}, + } { + if style&required.value == 0 { + t.Errorf("preview style %#x has no %s bit", style, required.name) + } + } + if hit, _, _ := sendMessage.Call(window, wmNCHitTest, 0, 0); hit != htTransparent { + t.Fatalf("preview hit test = %#x, want HTTRANSPARENT", hit) + } + + var before, after rect + if ok, _, _ := getWindowRect.Call(window, uintptr(unsafe.Pointer(&before))); ok == 0 { + t.Fatal("cannot read the preview frame") + } + opened.(platform.WindowMover).MoveTo(gfx.Point{X: 240, Y: 160}) + if ok, _, _ := getWindowRect.Call(window, uintptr(unsafe.Pointer(&after))); ok == 0 { + t.Fatal("cannot read the moved preview frame") + } + if after.Left != int32(240*state.scale) || after.Top != int32(160*state.scale) || + after.Right-after.Left != before.Right-before.Left || + after.Bottom-after.Top != before.Bottom-before.Top { + t.Fatalf("preview frame moved from %+v to %+v", before, after) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 29c2cb6b..c8f6e5e8 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -324,6 +324,10 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf // A popup that has no taskbar button and stays above other windows. style = wsPopup extendedStyle = wsExToolWindow | wsExTopmost + case platform.WindowPreview: + // A preview floats above other windows but never takes focus or input. + style = wsPopup + extendedStyle = wsExToolWindow | wsExTopmost | wsExNoActivate | wsExTransparent } // DirectComposition owns the client pixels; an opaque redirection bitmap // underneath it would hide the native material. @@ -392,6 +396,10 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf destroyWindow.Call(state.window) return nil, err } + if config.WindowMode == platform.WindowPreview && !state.renderer.usesComposition() { + destroyWindow.Call(state.window) + return nil, errTransparentPreviewUnavailable + } if err := state.renderer.apply(platform.Frame{Update: initialUpdate(len(state.textRectangles)), Rectangles: state.textRectangles, TextLabels: state.textLabels}); err != nil { destroyWindow.Call(state.window) return nil, err @@ -417,6 +425,13 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf state.placePanel() showWindow.Call(state.window, swShow) setForegroundWindow.Call(state.window) + } else if config.WindowMode == platform.WindowPreview { + // A window with no redirection bitmap may be shown with an empty update + // region. Its retained scene is ready, so make the first paint submit it + // instead of treating the empty region as "nothing to draw". + state.paintPending = true + showWindow.Call(state.window, swShowNoActivate) + invalidateRect.Call(state.window, 0, 0) } else { showWindow.Call(state.window, 1) } @@ -965,6 +980,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { state.handleCaretTimer(first) return 0 case wmNCHitTest: + if state.config.WindowMode == platform.WindowPreview { + return htTransparent + } if state.fullscreen.Load() { return htClient } From 9e8bd3dda14b1a5adb192a94a5a6b96b8dfd07f5 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 12:39:44 +0800 Subject: [PATCH 11/66] feat(hierarchypicker): add the opt-in hierarchical picker --- cmd/viva/initfiles/AGENTS.md.txt | 1 + hierarchypicker/hierarchypicker.go | 188 ++++++++++++++++++ hierarchypicker/hierarchypicker_test.go | 136 +++++++++++++ .../content/guides/en/declarative-layout.md | 2 +- .../content/guides/zh/declarative-layout.md | 2 +- 5 files changed, 327 insertions(+), 2 deletions(-) create mode 100644 hierarchypicker/hierarchypicker.go create mode 100644 hierarchypicker/hierarchypicker_test.go diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 90e3a1a9..2918f0b8 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -200,6 +200,7 @@ func (m *model) page(c ui.C) { `Choice`, `Tabs` and `Select` write the value in the declaration, so disable them with an `if`, not a chained `.Disabled`: `if !m.locked { if ui.Tabs(c, &m.tab, tabs, nil).Changed() { ... } }`. `Tabs` and `Select` also honor a chained `.Disabled` for input; `Choice` ignores it, so never rely on it there. +- Hierarchical path values ("School/Class A") use the opt-in package `github.com/vivaui/viva/hierarchypicker`: `state := hierarchypicker.NewState(paths)`, keep `picker := hierarchypicker.New(state)` in the model, and declare `picker.View(c, hierarchypicker.Spec{Label: "Group", OptionIDs: groupOptions}).FillWidth()`; `SetValue`/`Value` read and set the full path. - Removable chips with a filtered query are the opt-in package `github.com/vivaui/viva/multiselect`: keep `picker := multiselect.New(&m.tags)` in the model and declare `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`; `tagOptions.At(i)` and `tagRemoves.At(i)` name the popup rows and chip remove buttons. Import it only when used. - A long list to choose from by typing: `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` (Select's arguments plus a label); it filters as the user types. `.Clearable()` adds a clear button, `.Empty("No zone")` diff --git a/hierarchypicker/hierarchypicker.go b/hierarchypicker/hierarchypicker.go new file mode 100644 index 00000000..7d0bf014 --- /dev/null +++ b/hierarchypicker/hierarchypicker.go @@ -0,0 +1,188 @@ +// Package hierarchypicker is the opt-in page control for choosing a value from +// hierarchical paths, such as "School/Class A". It is a field trigger and a +// fly-out menu: the engine owns the paths, focus and keys, components paints +// the menu, and an application that does not import it pays nothing. +// +// state := hierarchypicker.NewState([]string{"School", "School/Class A", "Office"}) +// picker := hierarchypicker.New(state) +// ... +// ui.FormField(c, &m.groupField, "Group").Children(func() { +// picker.View(c, hierarchypicker.Spec{Label: "Group", OptionIDs: groupOptions}).FillWidth() +// }) +package hierarchypicker + +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// State is one picker's paths, chosen value and open state. Keep it in the +// model; SetOptions and SetValue update it, and Value reads the chosen path. +type State struct { + Value string + Open bool + + Menu base.HierarchyMenuState + options []string + revision uint64 + built uint64 + separator string +} + +// NewState returns a state for the full path values. +func NewState(options []string) *State { + s := new(State) + s.SetOptions(options) + return s +} + +// SetOptions replaces the paths. The chosen value stays; a value no longer in +// the paths remains selected until SetValue changes it. +func (s *State) SetOptions(options []string) { + s.options = append(s.options[:0], options...) + s.revision++ + s.built = 0 +} + +// SetValue selects the full path value, and closes the menu. +func (s *State) SetValue(value string) { + s.Value, s.Open = value, false + if s.built == s.revision { + s.Menu.Seek(value) + } +} + +// Spec supplies the control's words and its identities. OptionIDs and ScrollID +// come from the same gfx.Tree the page uses; OptionIDs is the scope of the +// menu's rows. +type Spec struct { + Label, Placeholder, EmptyLabel string + Separator string // "/" when empty + OptionIDs gfx.Scope + ScrollID gfx.ID + Scope, DismissID gfx.ID + MaxRows int +} + +// Picker is one hierarchical picker's page control. Keep it in the model +// beside its State; one Picker belongs to one State and one place on a page. +type Picker struct { + State *State + + spec Spec + handlers ui.Handlers + drawFn func(*ui.DrawContext) + controlID gfx.ID +} + +// New returns a picker for state. +func New(state *State) *Picker { + if state == nil { + panic("hierarchypicker: New needs its State") + } + p := &Picker{State: state} + p.handlers.Role = gfx.RoleCombobox + p.handlers.Key = p.key + p.handlers.Pointer = p.pointer + p.handlers.Scroll = p.scroll + p.drawFn = p.draw + return p +} + +// View declares the picker at c. Give it a width; it is as tall as the theme's +// control unless a Height follows. Declare it on its own, not inside a Memo. +func (p *Picker) View(c ui.C, spec Spec) ui.Box { + if p.State == nil || p.drawFn == nil { + panic("hierarchypicker: use New to make a Picker") + } + p.spec = spec + return ui.Control(c, spec.Label, &p.handlers). + Height(c.Theme().Metrics.ControlHeight). + Draw(p.drawFn) +} + +func (p *Picker) key(event gfx.KeyEvent) gfx.EventResult { + result := p.State.Menu.Key(event, p.State.Open) + if result.Opened { + p.State.Open = true + } + if result.Picked { + p.State.Value = result.Chosen + p.State.Open = false + } + if event.Key == gfx.KeyEscape && p.State.Open && !result.Handled { + p.State.Open = false + return gfx.EventResult{Handled: true, Repaint: true} + } + return result.EventResult +} + +func (p *Picker) pointer(event gfx.PointerEvent) gfx.EventResult { + return p.State.Menu.Pointer(event) +} + +func (p *Picker) scroll(event gfx.ScrollEvent) gfx.EventResult { + if !p.State.Open { + return gfx.EventResult{} + } + if p.State.Menu.Wheel(event) { + return gfx.EventResult{Handled: true, Repaint: true} + } + return gfx.EventResult{} +} + +func (p *Picker) draw(d *ui.DrawContext) { + p.controlID = d.Node.ID + state := p.State + separator := p.spec.Separator + if separator == "" { + separator = "/" + } + if state.built != state.revision || state.separator != separator { + state.Menu.Build(separator, state.Value, nil, len(state.options), func(i int) base.HierarchyMenuItem { + return base.HierarchyMenuItem{Value: state.options[i]} + }) + state.built, state.separator = state.revision, separator + } + theme := *d.Theme + trigger := d.Rect + selectControl := components.BeginSelect(d.Canvas, theme, trigger, components.SelectOptions{ + Value: state.Value, Placeholder: p.spec.Placeholder, Open: false, Disabled: d.State.Disabled, + }) + selectControl.End() + if !state.Open { + p.pick(d.Canvas) + return + } + options := base.HierarchyMenuOptions{ + OptionIDs: p.spec.OptionIDs, ScrollID: p.spec.ScrollID, + Scope: p.spec.Scope, Layer: d.Frame.WidgetLayer() + 2, Label: p.spec.Label, + EmptyLabel: p.spec.EmptyLabel, Viewport: d.Frame.GetBounds(), MaxRows: p.spec.MaxRows, + Overlay: true, DismissID: p.spec.DismissID, + } + components.PaintHierarchyMenu(d.Canvas, theme, trigger, &state.Menu, options) + p.pick(d.Canvas) +} + +func (p *Picker) pick(canvas *gfx.Canvas) { + if canvas == nil { + return + } + if canvas.Clicked(p.spec.DismissID) { + p.State.Open = false + return + } + if index, ok := canvas.ClickedIn(p.spec.OptionIDs); ok { + if value, chosen := p.State.Menu.Choose(index); chosen { + p.State.Value = value + p.State.Open = false + } + return + } + // The trigger is the control's own hit; a press anywhere on it toggles. + if canvas.Clicked(p.controlID) { + p.State.Open = !p.State.Open + } +} diff --git a/hierarchypicker/hierarchypicker_test.go b/hierarchypicker/hierarchypicker_test.go new file mode 100644 index 00000000..086a3bbb --- /dev/null +++ b/hierarchypicker/hierarchypicker_test.go @@ -0,0 +1,136 @@ +package hierarchypicker_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/hierarchypicker" + "github.com/vivaui/viva/ui" +) + +type harness struct { + t *testing.T + state *hierarchypicker.State + pick *hierarchypicker.Picker + box ui.Box + page *ui.Page + drv *app.Driver + inv *app.Invalidator + opts gfx.Scope +} + +func open(t *testing.T) *harness { + t.Helper() + h := &harness{t: t, state: hierarchypicker.NewState([]string{ + "School", "School/Class A", "School/Class B", "Office", + })} + h.pick = hierarchypicker.New(h.state) + var tree gfx.Tree + feature := tree.Feature("group") + h.opts = tree.Sub(feature, tree.Name("options")) + h.page = ui.NewPage(ui.PageConfig{Tree: &tree, View: func(c ui.C) { + h.box = h.pick.View(c, hierarchypicker.Spec{ + Label: "Group", Placeholder: "Select a group", OptionIDs: h.opts, + DismissID: feature.ID(tree.Name("dismiss")), Scope: feature.ID(tree.Name("scope")), + }).Width(260) + }}) + h.inv = new(app.Invalidator) + var err error + h.drv, err = app.NewDriver(ui.Configure(h.page, app.Config{Width: 480, Height: 480, Invalidator: h.inv}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(h.drv.Close) + h.repaint() + return h +} + +func (h *harness) repaint() { + h.t.Helper() + h.inv.Invalidate() + if err := h.drv.Pump(); err != nil { + h.t.Fatal(err) + } +} + +func (h *harness) hit(id gfx.ID) gfx.Hit { + h.t.Helper() + for _, hit := range h.drv.Snapshot().Hits { + if hit.ID == id { + return hit + } + } + h.t.Fatalf("no hit with identity %v", id) + return gfx.Hit{} +} + +// The picker opens from its field, chooses a path value and closes. +func TestPickerChoosesAPath(t *testing.T) { + h := open(t) + r := h.box.Rect() + if err := h.drv.Click(r.X+r.Width/2, r.Y+r.Height/2); err != nil { + t.Fatal(err) + } + h.repaint() + if !h.state.Open { + t.Fatal("the trigger did not open the menu") + } + row := h.hit(h.opts.At(0)) + if err := h.drv.Click(row.Bounds.X+row.Bounds.Width/2, row.Bounds.Y+row.Bounds.Height/2); err != nil { + t.Fatal(err) + } + h.repaint() + if h.state.Value != "School" || h.state.Open { + t.Fatalf("value %q open %v, want School and closed", h.state.Value, h.state.Open) + } +} + +// Escape closes the menu without reaching the page. +func TestPickerKeyCloses(t *testing.T) { + h := open(t) + r := h.box.Rect() + if err := h.drv.Click(r.X+r.Width/2, r.Y+r.Height/2); err != nil { + t.Fatal(err) + } + h.repaint() + if !h.state.Open { + t.Fatal("not open") + } + if err := h.drv.Key(gfx.KeyEscape, 0); err != nil { + t.Fatal(err) + } + if h.state.Open { + t.Fatal("Escape left the menu open") + } +} + +func drawPickerPage(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 480}, view) + canvas.EndFrame() +} + +func BenchmarkHierarchyPickerPaint(b *testing.B) { + state := hierarchypicker.NewState([]string{"School", "School/Class A", "School/Class B", "Office"}) + state.Open = true + picker := hierarchypicker.New(state) + var tree gfx.Tree + feature := tree.Feature("group") + opts := tree.Sub(feature, tree.Name("options")) + view := func(c ui.C) { + picker.View(c, hierarchypicker.Spec{ + Label: "Group", Placeholder: "Select a group", OptionIDs: opts, + DismissID: feature.ID(tree.Name("dismiss")), Scope: feature.ID(tree.Name("scope")), + }).Width(260) + } + page := ui.NewPage(ui.PageConfig{Tree: &tree, View: view}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(func(Value string, Size, Weight float32) float32 { return float32(len(Value)) * Size / 2 }) + drawPickerPage(page, canvas, view) + b.ReportAllocs() + for b.Loop() { + drawPickerPage(page, canvas, view) + } +} diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md index d0295151..b8d731e2 100644 --- a/website/content/guides/en/declarative-layout.md +++ b/website/content/guides/en/declarative-layout.md @@ -83,7 +83,7 @@ An element is named by where it is: its kind and its number among the elements o ### Menus, search fields and context menus -`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` is shadcn's dropdown menu of actions: `menu.Item("Rename").Clicked()` reads one as a button is read, the arrows move between items, typing a letter goes to the item it begins, and choosing one closes the menu. `menu.Sub("Move to", func(to *ui.MenuItems) { ... })` is an item with a submenu beside it, which opens as the pointer rests on the item, on a click, or on Right, Enter or Space with its first item focused; Left goes back, Escape closes every menu, and choosing in it closes them all. `menu.Item("Model").Description("What answers")` adds a second line under an item, `menu.Item("Rename").ID()` is the row's identity for anchoring a part or context menu, `menu.WidthRange(140, 320)` bounds the menu's width, `menu.Above()` opens it over the anchor, for a trigger along the bottom of a panel, and `menu.Beside()` to its right, for a row of a list or popup whose menu should leave the rows under it in sight. `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` takes Select's arguments and a label, and filters the choices as the user types into it, with the platform's input methods. `.Clearable()` gives it a button that clears the choice, `.Empty("No zone matches")` is what its list says when nothing matches, and `.Creatable("")` offers what was typed as a new choice ("Create dev"), which `.Created()` reports for the application to add. A multi-select with removable chips is the opt-in `multiselect` package: `picker := multiselect.New(&m.tags)`, then `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`; importing it is what links it, so applications that do not use it pay nothing. A Button takes an icon before its label with `.Icon(plus)`, or alone with `.IconOnly()`. `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` opens the same items at the pointer on a secondary press of `row`, or under it on Shift+F10; items take an `.Icon`, the keycaps of a shortcut with `.Keys(ui.Primary, "c")` (shown only: the shortcut is a `Shortcut` where its action is), and `.Checked` or `.Chosen` to be a checkbox or a radio item. A search field is a TextField with `.Icon(search)` before its text and `.Action(cross, "Clear")`, a small button at its end that `.ActionClicked()` reads. +`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` is shadcn's dropdown menu of actions: `menu.Item("Rename").Clicked()` reads one as a button is read, the arrows move between items, typing a letter goes to the item it begins, and choosing one closes the menu. `menu.Sub("Move to", func(to *ui.MenuItems) { ... })` is an item with a submenu beside it, which opens as the pointer rests on the item, on a click, or on Right, Enter or Space with its first item focused; Left goes back, Escape closes every menu, and choosing in it closes them all. `menu.Item("Model").Description("What answers")` adds a second line under an item, `menu.Item("Rename").ID()` is the row's identity for anchoring a part or context menu, `menu.WidthRange(140, 320)` bounds the menu's width, `menu.Above()` opens it over the anchor, for a trigger along the bottom of a panel, and `menu.Beside()` to its right, for a row of a list or popup whose menu should leave the rows under it in sight. `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` takes Select's arguments and a label, and filters the choices as the user types into it, with the platform's input methods. `.Clearable()` gives it a button that clears the choice, `.Empty("No zone matches")` is what its list says when nothing matches, and `.Creatable("")` offers what was typed as a new choice ("Create dev"), which `.Created()` reports for the application to add. A multi-select with removable chips is the opt-in `multiselect` package: `picker := multiselect.New(&m.tags)`, then `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`; importing it is what links it, so applications that do not use it pay nothing. Hierarchical paths use the opt-in `hierarchypicker` package the same way: `state := hierarchypicker.NewState(paths)`, `picker := hierarchypicker.New(state)`, then `picker.View(c, hierarchypicker.Spec{Label: "Group", OptionIDs: groupOptions}).FillWidth()`; `state.Value` is the full chosen path. A Button takes an icon before its label with `.Icon(plus)`, or alone with `.IconOnly()`. `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` opens the same items at the pointer on a secondary press of `row`, or under it on Shift+F10; items take an `.Icon`, the keycaps of a shortcut with `.Keys(ui.Primary, "c")` (shown only: the shortcut is a `Shortcut` where its action is), and `.Checked` or `.Chosen` to be a checkbox or a radio item. A search field is a TextField with `.Icon(search)` before its text and `.Action(cross, "Clear")`, a small button at its end that `.ActionClicked()` reads. ### Drawers diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md index 90d8515e..16cc3c8a 100644 --- a/website/content/guides/zh/declarative-layout.md +++ b/website/content/guides/zh/declarative-layout.md @@ -84,7 +84,7 @@ ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, m.page) ### 菜单、搜索框与右键菜单 -`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` 是 shadcn 的下拉菜单:像读按钮一样用 `menu.Item("Rename").Clicked()` 读取一项,方向键在各项之间移动,输入字母会跳到以它开头的项,选中一项后菜单关闭。`menu.Sub("Move to", func(to *ui.MenuItems) { ... })` 是一个旁边带子菜单的项:指针在它上面停留、点击它,或按 Right、Enter、Space 时打开(键盘打开时焦点落在子菜单第一项);Left 返回,Escape 关闭所有菜单,在子菜单里选中一项也会全部关闭。 `menu.Item("Model").Description("What answers")` 给项加一行说明;`menu.Item("Rename").ID()` 是该项的标识,可用来锚定部件或右键菜单;`menu.WidthRange(140, 320)` 限制菜单宽度,`menu.Above()` 让菜单在锚点上方展开(锚点在面板底部时),`menu.Beside()` 让菜单在锚点右侧展开(列表或弹出层里的行,菜单不遮住下面的行)。`ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` 接受 Select 的参数再加一个标签,用户输入时(支持平台输入法)筛选选项。`.Clearable()` 加一个清除选择的按钮,`.Empty("No zone matches")` 是没有匹配项时列表显示的文字,`.Creatable("")` 把输入的内容作为新选项提供("Create dev"),由 `.Created()` 报告,应用自己把它加进选项。带可移除 chip 的多选用可选的 `multiselect` 包:`picker := multiselect.New(&m.tags)`,然后 `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`;只有 import 它的应用才会链接它,不用的应用零成本。Button 用 `.Icon(plus)` 在标签前加图标,加 `.IconOnly()` 则只显示图标。`ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` 在 `row` 上按下副键时于指针处打开同样的菜单项,按 Shift+F10 时在它下方打开;菜单项可以加 `.Icon`、用 `.Keys(ui.Primary, "c")` 显示快捷键键帽(只显示,快捷键本身是动作所在处的一个 `Shortcut`),用 `.Checked` 或 `.Chosen` 成为复选或单选项。搜索框是带 `.Icon(search)`(文字前的图标)和 `.Action(cross, "Clear")`(末尾的小按钮,用 `.ActionClicked()` 读取)的 TextField。 +`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` 是 shadcn 的下拉菜单:像读按钮一样用 `menu.Item("Rename").Clicked()` 读取一项,方向键在各项之间移动,输入字母会跳到以它开头的项,选中一项后菜单关闭。`menu.Sub("Move to", func(to *ui.MenuItems) { ... })` 是一个旁边带子菜单的项:指针在它上面停留、点击它,或按 Right、Enter、Space 时打开(键盘打开时焦点落在子菜单第一项);Left 返回,Escape 关闭所有菜单,在子菜单里选中一项也会全部关闭。 `menu.Item("Model").Description("What answers")` 给项加一行说明;`menu.Item("Rename").ID()` 是该项的标识,可用来锚定部件或右键菜单;`menu.WidthRange(140, 320)` 限制菜单宽度,`menu.Above()` 让菜单在锚点上方展开(锚点在面板底部时),`menu.Beside()` 让菜单在锚点右侧展开(列表或弹出层里的行,菜单不遮住下面的行)。`ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` 接受 Select 的参数再加一个标签,用户输入时(支持平台输入法)筛选选项。`.Clearable()` 加一个清除选择的按钮,`.Empty("No zone matches")` 是没有匹配项时列表显示的文字,`.Creatable("")` 把输入的内容作为新选项提供("Create dev"),由 `.Created()` 报告,应用自己把它加进选项。带可移除 chip 的多选用可选的 `multiselect` 包:`picker := multiselect.New(&m.tags)`,然后 `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`;只有 import 它的应用才会链接它,不用的应用零成本。层级路径用可选的 `hierarchypicker` 包:`state := hierarchypicker.NewState(paths)`,`picker := hierarchypicker.New(state)`,然后 `picker.View(c, hierarchypicker.Spec{Label: "Group", OptionIDs: groupOptions}).FillWidth()`;`state.Value` 是选中的完整路径。Button 用 `.Icon(plus)` 在标签前加图标,加 `.IconOnly()` 则只显示图标。`ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` 在 `row` 上按下副键时于指针处打开同样的菜单项,按 Shift+F10 时在它下方打开;菜单项可以加 `.Icon`、用 `.Keys(ui.Primary, "c")` 显示快捷键键帽(只显示,快捷键本身是动作所在处的一个 `Shortcut`),用 `.Checked` 或 `.Chosen` 成为复选或单选项。搜索框是带 `.Icon(search)`(文字前的图标)和 `.Action(cross, "Clear")`(末尾的小按钮,用 `.ActionClicked()` 读取)的 TextField。 ### 抽屉 From f3823997ff2a139197e44ef8a5f15c50d635d163 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 12:43:21 +0800 Subject: [PATCH 12/66] docs: record that Begin belongs to the style layer --- docs/maintaining-controls.md | 18 ++++++++++++++++++ website/content/guides/en/components.md | 2 ++ website/content/guides/zh/components.md | 2 ++ 3 files changed, 22 insertions(+) diff --git a/docs/maintaining-controls.md b/docs/maintaining-controls.md index b4989f01..45f00d51 100644 --- a/docs/maintaining-controls.md +++ b/docs/maintaining-controls.md @@ -25,6 +25,24 @@ app is the platform loop below ui; it knows nothing of pages. `internal/layering` checks both forbidden and allowed edges; a new dependency is an explicit edit there. +## Page controls, recipes and Begin + +There are two authoring paths, and they are not duplicates: + +- **Page controls** are `ui.*` or `ui.*Base` + Draw. They own page identity, + focus, input and state; the styled painter reuses the components' canvas + recipes. `ui` exports no `Begin*`. +- **Canvas recipes** are `components.Begin*` and their `Paint`/`Layout` methods. + They construct a value, paint through `gfx.Canvas` and declare hits; they are + used inside a `ui.Control`/`Draw`, for pure measurement, or in source copied by + `viva add`. They are not a second page API. + +“Zero Begin” is not a goal. A new control that is declarable on a page belongs in +`ui`; a reusable but heavy composite belongs in an opt-in package that uses +`ui.Control`; a recipe that only paints stays in `components`. Exceptions that +may keep Begin are pure measurement, whole-canvas drawing, pixel-fixed slots and +copied source. See `private/docs/decisions/0085-begin-stays-in-components.md`. + ## Two forms of one control A control that ships with a look has a **styled form** and a **Base**: diff --git a/website/content/guides/en/components.md b/website/content/guides/en/components.md index ed2a71e2..ec24daf1 100644 --- a/website/content/guides/en/components.md +++ b/website/content/guides/en/components.md @@ -19,6 +19,8 @@ components.BeginButton(canvas, theme, hitSave, bounds).Outline("Save") A theme is a value, `gfx.LightTheme()` or `gfx.DarkTheme()`. Switching appearance means painting with the other one. +`Begin*` is the style layer's constructor, not a second page API. Declare page controls with `ui.*`, `ui.*Base` and `ui.Control`; use `components.Begin*` inside a `Draw`, for pure measurement, or in source copied by `viva add`. “Zero Begin” is not a goal: the boundary is that page behaviour is not hand-built, not that the painter constructor disappears. Reusable heavy composites such as `multiselect` and `hierarchypicker` are opt-in packages. + ## Tree navigation `BeginTree` paints rows from an application-owned flattened hierarchy. For keyboard navigation, pass the visible rows' actual depths, expansion state and disabled state to `components.NavigateTree`; do not pass display-clamped indentation as the depth. It returns the next visible index or an expand/collapse action. The application still owns loading children, expansion, selection and focus, so no hidden model or background work is created. Keep the navigation slice as reusable caller-owned scratch when handling keys. diff --git a/website/content/guides/zh/components.md b/website/content/guides/zh/components.md index cbd56ef4..e16aef1d 100644 --- a/website/content/guides/zh/components.md +++ b/website/content/guides/zh/components.md @@ -19,6 +19,8 @@ components.BeginButton(canvas, theme, hitSave, bounds).Outline("Save") 主题是一个值,`gfx.LightTheme()` 或 `gfx.DarkTheme()`。切换外观就是改用另一个主题绘制。 +`Begin*` 是样式层的构造器,不是第二套页面 API。页面控件用 `ui.*`、`ui.*Base` 和 `ui.Control` 声明;`components.Begin*` 用于 `Draw` 内部、纯测量或 `viva add` 复制出的源码。“零 Begin”不是目标:边界是页面行为不再手拼,而不是绘制构造器消失。`multiselect`、`hierarchypicker` 这类可复用的重型复合控件走 opt-in 包。 + ## 树形导航 `BeginTree` 根据应用自己扁平化的层级绘制可见行。处理键盘事件时,将可见行的实际深度、展开状态和禁用状态传给 `components.NavigateTree`;深度不能使用为了适应宽度而截断的视觉缩进。它返回下一个可见行的索引,或者展开、折叠动作。子节点加载、展开状态、选择和焦点仍由应用负责,不产生隐藏模型或后台工作;导航切片可作为调用方拥有的临时存储复用。 From 2225dd09f7dcb661edc641ff9d9e5a4b2326efde Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 12:49:50 +0800 Subject: [PATCH 13/66] docs(website): stop showing Begin recipes as application usage --- website/src/lib/i18n.ts | 2 ++ website/src/pages/[lang]/ui/[component].astro | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/website/src/lib/i18n.ts b/website/src/lib/i18n.ts index 718eb58e..195b05ff 100644 --- a/website/src/lib/i18n.ts +++ b/website/src/lib/i18n.ts @@ -29,6 +29,7 @@ const english = { noMatches: 'No matching components. Try another name or category.', matches: 'matching components', preview: 'Preview', copySource: 'Copy source', exampleUsage: 'Usage', copyUsage: 'Copy usage', + canvasRecipe: 'Canvas recipe: use it inside ui.Control/Draw, or use the ui.* page control where one exists.', copyInstall: 'Copy install command', copyCode: 'Copy code', copying: 'Copying…', copied: 'Copied', copiedNotice: 'Copied to clipboard.', copyFailed: 'Copy failed. Select the text and press Ctrl+C or ⌘C.', reset: 'Reset', resetExample: 'Reset this example', openPreview: 'Open preview', retry: 'Retry preview', @@ -51,6 +52,7 @@ const chinese: typeof english = { noMatches: '没有匹配的组件,试试名称或分类。', matches: '个匹配组件', preview: '预览', copySource: '复制源码', exampleUsage: '用法', copyUsage: '复制用法', + canvasRecipe: '画布 recipe:在 ui.Control/Draw 内使用;有页面控件时优先用 ui.*。', copyInstall: '复制安装命令', copyCode: '复制代码', copying: '复制中…', copied: '已复制', copiedNotice: '已复制到剪贴板。', copyFailed: '复制失败,请选中文本后按 Ctrl+C 或 ⌘C。', reset: '重置', resetExample: '重置此示例', openPreview: '单独打开', retry: '重试预览', diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index 6cb9b9ce..cb2d7055 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -37,10 +37,10 @@ const sections = page.Sections.filter(section => section.ID !== 'source-ownershi

{example.Title}#

{example.Description}

- {example.Snippet &&
+ {example.Snippet && !example.Snippet.includes('Begin') ?
{text.exampleUsage}
-
} +
:

{text.canvasRecipe}

} )}
From 2fd0534485c236bd8002214b7b3ee3aae0f1f119 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 12:55:20 +0800 Subject: [PATCH 14/66] test(ui): pin page popover and drawer motion to their components --- ui/presence_parity_test.go | 241 +++++++++++++++++++++++++++++++++++++ 1 file changed, 241 insertions(+) create mode 100644 ui/presence_parity_test.go diff --git a/ui/presence_parity_test.go b/ui/presence_parity_test.go new file mode 100644 index 00000000..0692b358 --- /dev/null +++ b/ui/presence_parity_test.go @@ -0,0 +1,241 @@ +package ui_test + +import ( + "testing" + "time" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// parityClock is a canvas whose animated frames advance on a test clock, and +// the paint pass a test drives frame by frame. +type parityClock struct { + canvas *gfx.Canvas + now time.Duration +} + +func newParityClock() *parityClock { + clock := &parityClock{canvas: &gfx.Canvas{}} + clock.canvas.SetClock(func() time.Duration { return clock.now }) + clock.canvas.SetMeasurer(func(value string, size, weight float32) float32 { + return float32(len(value)) * size / 2 + }) + return clock +} + +// step advances time by one display frame and paints one pass. +func (clock *parityClock) step(advance bool, paint func()) { + if advance { + clock.now += 16 * time.Millisecond + } + clock.canvas.Reset() + clock.canvas.BeginFrame() + paint() + clock.canvas.EndFrame() +} + +func (clock *parityClock) settled() bool { + _, next := clock.canvas.NextFrame() + return !next +} + +// parityRects copies the frame's rectangles with the layer left out: a page +// paints overlays on its own layer, which is not part of what the motion is. +func (clock *parityClock) parityRects() []gfx.Rectangle { + rects := append([]gfx.Rectangle(nil), clock.canvas.Rectangles()...) + for i := range rects { + rects[i].Layer = 0 + } + return rects +} + +func sameRects(t *testing.T, label string, frame int, old, new []gfx.Rectangle) { + t.Helper() + if len(old) != len(new) { + t.Fatalf("%s frame %d: components painted %d rectangles, the page %d:\ncomponents %+v\npage %+v", label, frame, len(old), len(new), old, new) + } + for i := range old { + if old[i] != new[i] { + t.Fatalf("%s frame %d: rectangle %d is %+v on the components path and %+v on the page path", label, frame, i, old[i], new[i]) + } + } +} + +// A page Popover enters and leaves exactly as the components.Popover it +// replaces: the same rectangles, at the same places with the same opacity, on +// every frame of the entrance and of the exit. The autofill and completion +// offers, drawn by components before the page migration, therefore animate +// as they did. +func TestPagePopoverAnimatesLikeTheComponentsPopover(t *testing.T) { + theme := gfx.LightTheme() + anchor := gfx.Rect{X: 100, Y: 100, Width: 40, Height: 20} + const width = 200 + const bodyHeight = 120 + // The page's panel is the body plus its border and padding; the component + // is given the panel's height directly. + panelHeight := bodyHeight + 2*(1+theme.Metrics.PadSurface) + + oldClock := newParityClock() + oldPaint := func(open bool) func() { + return func() { + if !open { + return + } + popover := components.BeginPopover(oldClock.canvas, theme, gfx.Rect{Width: 480, Height: 480}, anchor, components.PopoverOptions{ + DismissID: gfx.Item(99), Side: components.PopoverBottom, Align: components.PopoverAlignStart, + SideOffset: 2, Headerless: true, ContentSize: gfx.Size{Width: width, Height: panelHeight}, + }) + popover.Begin("", "") + popover.End() + } + } + + open := true + newClock := newParityClock() + view := func(c ui.C) { + slot := ui.Slot(c).Absolute().Left(anchor.X).Top(anchor.Y).Size(anchor.Width, anchor.Height) + ui.PopoverWith(c, slot, ui.PopoverSpec{ + Scope: gfx.Item(7), Side: components.PopoverBottom, Align: ui.Start, Offset: 2, Width: width, + }, &open, func() { + ui.Slot(c).FillWidth().Height(bodyHeight) + }) + } + page := ui.NewPage(ui.PageConfig{Theme: &theme, View: view}) + newPaint := func() { + page.Draw(newClock.canvas, gfx.Rect{Width: 480, Height: 480}, view) + } + + // Open: the entrance runs until both paths rest. + for frame := 0; ; frame++ { + oldClock.step(frame > 0, oldPaint(true)) + newClock.step(frame > 0, newPaint) + sameRects(t, "entrance", frame, oldClock.parityRects(), newClock.parityRects()) + if oldSettled, newSettled := oldClock.settled(), newClock.settled(); oldSettled != newSettled { + t.Fatalf("entrance frame %d: components at rest=%v, page at rest=%v", frame, oldSettled, newSettled) + } + if oldClock.settled() { + if frame == 0 { + t.Fatal("the entrance settled on its first frame; nothing was animated") + } + break + } + if frame > 100 { + t.Fatal("the entrance never settled") + } + } + + // Close: the leaving panel is replayed from the last frame each path painted. + open = false + for frame := 0; ; frame++ { + oldClock.step(true, oldPaint(false)) + newClock.step(true, newPaint) + sameRects(t, "exit", frame, oldClock.parityRects(), newClock.parityRects()) + if oldClock.settled() && newClock.settled() { + break + } + if frame > 100 { + t.Fatal("the exit never settled") + } + } + if rects := oldClock.parityRects(); len(rects) != 0 { + t.Fatalf("the components popover left %d rectangles behind", len(rects)) + } + if rects := newClock.parityRects(); len(rects) != 0 { + t.Fatalf("the page popover left %d rectangles behind", len(rects)) + } +} + +// Instant is the one difference kept from the components options: a list that +// appears under the cursor as the user types has no entrance, so the page +// paints it at its place on the first frame and asks for no next frame. +func TestPagePopoverWithInstantAppearsAtOnce(t *testing.T) { + theme := gfx.LightTheme() + open := true + clock := newParityClock() + view := func(c ui.C) { + slot := ui.Slot(c).Absolute().Left(100).Top(100).Size(40, 20) + ui.PopoverWith(c, slot, ui.PopoverSpec{ + Scope: gfx.Item(7), Side: components.PopoverBottom, Align: ui.Start, Offset: 2, Width: 200, Instant: true, + }, &open, func() { + ui.Slot(c).FillWidth().Height(120) + }) + } + page := ui.NewPage(ui.PageConfig{Theme: &theme, View: view}) + paint := func() { page.Draw(clock.canvas, gfx.Rect{Width: 480, Height: 480}, view) } + clock.step(false, paint) + if !clock.settled() { + t.Fatal("an instant popover asked for another frame") + } + rects := clock.parityRects() + if len(rects) == 0 || rects[0].Bounds.Y != 122 { + t.Fatalf("an instant popover's panel is at %+v, want it at its resting place already", rects) + } +} + +// A page Drawer enters and leaves exactly as components.BeginDrawer does, with +// the assistant panel's inset and nonmodal spec: the scrim's fade and the +// panel's slide match on every frame of both transitions. +func TestPageDrawerAnimatesLikeTheComponentsDrawer(t *testing.T) { + theme := gfx.LightTheme() + frame := gfx.Rect{Width: 480, Height: 480} + inset := gfx.Insets{Top: 30} + viewport := frame.Inset(inset) + const size = 300 + + oldClock := newParityClock() + oldPaint := func(open bool) func() { + return func() { + if !open { + return + } + drawer := components.BeginDrawer(oldClock.canvas, theme, viewport, components.DrawerOptions{ + DismissID: gfx.Item(99), Side: components.DrawerRight, ContentExtent: size, + }) + drawer.Begin("", "") + drawer.End() + } + } + + open := true + newClock := newParityClock() + view := func(c ui.C) { + ui.Drawer(c, &open, "", ui.DrawerSpec{Side: ui.DrawerRight, Size: size, Inset: inset, NonModal: true}, func() { + ui.Slot(c).FillWidth().Height(40) + }, nil) + } + page := ui.NewPage(ui.PageConfig{Theme: &theme, View: view}) + newPaint := func() { page.Draw(newClock.canvas, frame, view) } + + for frame := 0; ; frame++ { + oldClock.step(frame > 0, oldPaint(true)) + newClock.step(frame > 0, newPaint) + sameRects(t, "drawer entrance", frame, oldClock.parityRects(), newClock.parityRects()) + if oldSettled, newSettled := oldClock.settled(), newClock.settled(); oldSettled != newSettled { + t.Fatalf("drawer entrance frame %d: components at rest=%v, page at rest=%v", frame, oldSettled, newSettled) + } + if oldClock.settled() { + if frame == 0 { + t.Fatal("the drawer entrance settled on its first frame; nothing was animated") + } + break + } + if frame > 100 { + t.Fatal("the drawer entrance never settled") + } + } + + open = false + for frame := 0; ; frame++ { + oldClock.step(true, oldPaint(false)) + newClock.step(true, newPaint) + sameRects(t, "drawer exit", frame, oldClock.parityRects(), newClock.parityRects()) + if oldClock.settled() && newClock.settled() { + break + } + if frame > 100 { + t.Fatal("the drawer exit never settled") + } + } +} From c245aeda9373c1ac0727c9297a7ee7635c1005e2 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 12:55:28 +0800 Subject: [PATCH 15/66] docs(website): show page usage above component examples --- internal/componentdemo/page_usage.go | 46 +++++++++++++++++++ internal/componentdemo/state.go | 7 +++ tools/docs/catalog.go | 3 ++ website/src/lib/types.ts | 1 + website/src/pages/[lang]/ui/[component].astro | 13 ++++-- 5 files changed, 66 insertions(+), 4 deletions(-) create mode 100644 internal/componentdemo/page_usage.go diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go new file mode 100644 index 00000000..0d49dca0 --- /dev/null +++ b/internal/componentdemo/page_usage.go @@ -0,0 +1,46 @@ +package componentdemo + +// pageUsage is the page-first call site of a component that has one. The +// documentation site shows it above the examples; a component without an entry +// is a canvas recipe, used inside ui.Control/Draw or copied by viva add. +var pageUsage = map[string]string{ + "button": `ui.Button(c, "Save").Clicked()`, + "badge": `ui.Badge(c, "New")`, + "checkbox": `ui.Checkbox(c, &m.accepted, "Accept")`, + "switch": `ui.Switch(c, &m.enabled, "Enabled")`, + "input": `ui.TextField(c, &m.name, "Name", "Ada")`, + "textarea": `ui.TextArea(c, &m.notes, "Notes", "")`, + "select": `ui.Select(c, &m.choice, choices, nameOf)`, + "combobox": `ui.Combobox(c, &m.choice, choices, nameOf, "Choice")`, + "slider": `ui.Slider(c, &m.volume).Range(0, 100)`, + "tabs": `ui.Tabs(c, &m.tab, tabs, tabLabel)`, + "dialog": `ui.Dialog(c, ui.DialogSpec{Title: "Edit host", Scope: scope, DismissID: dismiss})`, + "alert-dialog": `ui.AlertDialog(c, ui.AlertDialogSpec{Title: "Delete?", ActionLabel: "Delete", CancelLabel: "Cancel", ActionID: action, CancelID: cancel})`, + "drawer": `ui.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`, + "sheet": `ui.Drawer(c, &m.open, "Details", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`, + "popover": `ui.PopoverWith(c, anchor, ui.PopoverSpec{Title: "Details"}, &m.open, body)`, + "dropdown-menu": `ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { menu.Item("Rename") })`, + "context-menu": `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { menu.Item("Delete") })`, + "table": `ui.Table(c, &m.table, ui.TableSpec{Rows: rows, Columns: columns, Headers: headers})`, + "list": `ui.List(c, &m.list, len(rows), func(row ui.ListRow) { _ = row })`, + "tree": `ui.Tree(c, &m.tree, len(rows), func(i int) string { return rows[i] }, func(i int) {})`, + "color-picker": `ui.ColorPicker(c, &m.picker, &m.color, "Accent")`, + "color-swatch": `ui.ColorSwatch(c, color, selected, "Accent")`, + "progress": `ui.Progress(c, 0.6)`, + "spinner": `ui.Spinner(c)`, + "split-button": `ui.SplitButton(c, ui.SplitButtonSpec{PrimaryID: primary, Label: "Run"})`, + "pagination": `ui.Pagination(c, items)`, + "radio-group": `ui.RadioGroup(c)`, + "choice": `ui.Choice(c, &m.choice, choices, nameOf)`, + "toggle": `ui.ToggleBase(c, &m.on, "Bold")`, + "native-select": `ui.Select(c, &m.choice, choices, nameOf)`, + "single-select": `ui.Select(c, &m.choice, choices, nameOf)`, + "scroll-area": `ui.Scroll(c).Grow(1).Scrollbars()`, + "resizable": `ui.Splitter(c, &m.splitter)`, + "separator": `ui.Divider(c)`, + "typography": `ui.Paragraph(c, text, 0)`, + "form": `ui.FormField(c, &m.field, "Name").Children(func() { ui.TextField(c, &m.name, "Name", "") })`, + "field": `ui.FormField(c, &m.field, "Name").Children(func() { ui.TextField(c, &m.name, "Name", "") })`, + "multi-select": `picker := multiselect.New(&m.tags)` + "\n" + `picker.View(c, multiselect.Spec{Label: "Tags"}).FillWidth()`, + "message-scroller": `ui.Control(c, "Messages", &m.handlers).Draw(paintMessages)`, +} diff --git a/internal/componentdemo/state.go b/internal/componentdemo/state.go index 21eee578..acc5b5ca 100644 --- a/internal/componentdemo/state.go +++ b/internal/componentdemo/state.go @@ -20,6 +20,10 @@ type Example struct { type Component struct { ID, Title, Category, Summary string + // PageUsage is the page-first call site shown above the examples, when this + // component has one. Empty means it is a canvas recipe, used inside + // ui.Control/Draw or copied by viva add. + PageUsage string // Source is the Go file the example calls, relative to the repository root, when // the control is not one of the components package: a page-layer control such as // ui.List. Empty means components/.go, the component's own file. @@ -69,6 +73,9 @@ func buildCatalog() []Component { result[current], result[current-1] = result[current-1], result[current] } } + for i := range result { + result[i].PageUsage = pageUsage[result[i].ID] + } return result } diff --git a/tools/docs/catalog.go b/tools/docs/catalog.go index 25c625bd..d7d70101 100644 --- a/tools/docs/catalog.go +++ b/tools/docs/catalog.go @@ -36,6 +36,8 @@ type Capability struct { type Page struct { ID, Title, Category, Summary, Revision string + // PageUsage is the page-first call site, when the component has one. + PageUsage string // Source is the Go file the examples call, relative to the repository root: // components/.go, or ui/list.go for a page-layer control. Source string @@ -87,6 +89,7 @@ func loadPages(root string) ([]Page, Manifest, error) { page.ID, page.Title, page.Category, page.Summary = component.ID, component.Title, component.Category, component.Summary page.All, page.Revision = navigation, manifest.Revision page.Source = component.Source + page.PageUsage = component.PageUsage if page.Source == "" { page.Source = "components/" + strings.ReplaceAll(component.ID, "-", "_") + ".go" } diff --git a/website/src/lib/types.ts b/website/src/lib/types.ts index 9991e97f..54785c5b 100644 --- a/website/src/lib/types.ts +++ b/website/src/lib/types.ts @@ -35,6 +35,7 @@ export interface Page extends Nav { InstallCommand: string; Sections: Section[]; Capabilities: Capability[]; + PageUsage?: string; } export interface Coverage { diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index cb2d7055..b1906c7e 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -20,6 +20,7 @@ const themes = { light: 'github-light', dark: 'github-dark' } as const; const sourceFile = `${page.ID.replaceAll('-', '_')}.go`; const sourcePath = page.Source || `components/${sourceFile}`; const sections = page.Sections.filter(section => section.ID !== 'source-ownership'); +const fallbackUsage = `ui.Control(c, "${page.Title.replaceAll('"', '')}", &m.handlers).Draw(paint)`; --- @@ -37,10 +38,14 @@ const sections = page.Sections.filter(section => section.ID !== 'source-ownershi

{example.Title}#

{example.Description}

- {example.Snippet && !example.Snippet.includes('Begin') ?
-
{text.exampleUsage}
-
-
:

{text.canvasRecipe}

} + {(() => { + const pageUsage = page.PageUsage || fallbackUsage; + const usage = example.Snippet && !example.Snippet.includes('Begin') ? example.Snippet : pageUsage; + return
+
{text.exampleUsage}
+
+
; + })()}
)}
From 0a98064a49815823847dc4d7120a8d5fa13cf1cd Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 13:15:31 +0800 Subject: [PATCH 16/66] feat(tree): compress only the indent, not the row's depth --- base/tree.go | 6 ++++++ ui/tree_paint.go | 6 +++++- ui/tree_test.go | 30 ++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/base/tree.go b/base/tree.go index 672fcfca..83216db8 100644 --- a/base/tree.go +++ b/base/tree.go @@ -39,6 +39,12 @@ type TreeState struct { Node func(i int) TreeNode RowHeight float32 Indent float32 + // DisplayDepth maps a row's Depth to the level the tree indents it by, when + // the application compresses deep rows to keep their names in view. Depth + // stays the tree's structure, which keyboard movement, typeahead and drops + // read, so a compressed indent never makes a child look like a sibling. + // Nil indents by Depth itself. + DisplayDepth func(depth int) int // CanDrop says whether row from may be dropped at where of row to: a group not // into itself or what is inside it, a row not before a sibling of another kind. // It is asked as the pointer moves; nil makes the rows not draggable. diff --git a/ui/tree_paint.go b/ui/tree_paint.go index b46a91cb..5e317edd 100644 --- a/ui/tree_paint.go +++ b/ui/tree_paint.go @@ -12,8 +12,12 @@ func treeStateRow(s *TreeState, i int, rowBox Box) { f := c.GetF() node := s.Node(i) key := s.GetKey()(i) + depth := node.Depth + if s.DisplayDepth != nil { + depth = s.DisplayDepth(depth) + } item := components.TreeItem{ - ID: s.GetRows().At(key), Label: s.GetRowLabel()(i), Depth: uint8(min(max(node.Depth, 0), 31)), + ID: s.GetRows().At(key), Label: s.GetRowLabel()(i), Depth: uint8(min(max(depth, 0), 31)), Branch: node.Branch, Expanded: node.Expanded, Selected: node.Selected, Disabled: node.Disabled, } if node.Branch { diff --git a/ui/tree_test.go b/ui/tree_test.go index c6955b66..ba44a83a 100644 --- a/ui/tree_test.go +++ b/ui/tree_test.go @@ -559,3 +559,33 @@ func TestListRowID(t *testing.T) { t.Fatal("RowID(1) is not the identity of the second row's hit") } } + +// DisplayDepth changes only the indent: a tree that compresses deep rows still +// has its hierarchy, so Right on a branch moves the focus to its child. +func TestTreeCompressedIndentKeepsTheHierarchyForKeys(t *testing.T) { + labels := []string{"branch", "child", "one", "two"} + depths := []int{3, 4, 0, 1} + var state ui.TreeState + state.Node = func(i int) ui.TreeNode { + return ui.TreeNode{Depth: depths[i], Branch: i == 0, Expanded: i == 0} + } + state.Label = func(i int) string { return labels[i] } + state.DisplayDepth = func(int) int { return 0 } + d := openPage(t, func(c ui.C) { + ui.Column(c).Fill().Children(func() { + ui.Tree(c, &state, len(labels), state.Label, nil).Grow(1) + }) + }) + if x, y := d.hit("one").Bounds.X, d.hit("two").Bounds.X; x != y { + t.Fatalf("the compressed leaf rows start at %v and %v, want the same indent", x, y) + } + d.click("branch") + d.key(gfx.KeyRight) + if got := d.Focused(); got != "child" { + t.Fatalf("Right focused %q, want the branch's child", got) + } + d.key(gfx.KeyLeft) + if got := d.Focused(); got != "branch" { + t.Fatalf("Left focused %q, want the parent", got) + } +} From c937f50eddc6f2ef15e30bca6dc7af94138b3f4a Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 13:21:18 +0800 Subject: [PATCH 17/66] docs(website): keep canvas-only snippets out of component pages --- internal/componentdemo/page_usage.go | 1 + website/src/pages/[lang]/ui/[component].astro | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index 0d49dca0..e34658cd 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -24,6 +24,7 @@ var pageUsage = map[string]string{ "table": `ui.Table(c, &m.table, ui.TableSpec{Rows: rows, Columns: columns, Headers: headers})`, "list": `ui.List(c, &m.list, len(rows), func(row ui.ListRow) { _ = row })`, "tree": `ui.Tree(c, &m.tree, len(rows), func(i int) string { return rows[i] }, func(i int) {})`, + "tree-navigation": `ui.Tree(c, &m.tree, len(rows), func(i int) string { return rows[i] }, func(i int) {})`, "color-picker": `ui.ColorPicker(c, &m.picker, &m.color, "Accent")`, "color-swatch": `ui.ColorSwatch(c, color, selected, "Accent")`, "progress": `ui.Progress(c, 0.6)`, diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index b1906c7e..3f8392c4 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -37,10 +37,10 @@ const fallbackUsage = `ui.Control(c, "${page.Title.replaceAll('"', '')}", &m.han {page.Examples.map(example =>

{example.Title}#

{example.Description}

- + {(() => { const pageUsage = page.PageUsage || fallbackUsage; - const usage = example.Snippet && !example.Snippet.includes('Begin') ? example.Snippet : pageUsage; + const usage = example.Snippet && !/components\.|Begin/.test(example.Snippet) ? example.Snippet : pageUsage; return
{text.exampleUsage}
From 382235d66c0f6cc3ff786a73c7c188bf972049ef Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 13:26:39 +0800 Subject: [PATCH 18/66] docs(website): label page APIs apart from component source --- internal/componentdemo/page_usage.go | 1 - website/src/lib/i18n.ts | 2 ++ website/src/pages/[lang]/ui/[component].astro | 5 +++-- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index e34658cd..0d49dca0 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -24,7 +24,6 @@ var pageUsage = map[string]string{ "table": `ui.Table(c, &m.table, ui.TableSpec{Rows: rows, Columns: columns, Headers: headers})`, "list": `ui.List(c, &m.list, len(rows), func(row ui.ListRow) { _ = row })`, "tree": `ui.Tree(c, &m.tree, len(rows), func(i int) string { return rows[i] }, func(i int) {})`, - "tree-navigation": `ui.Tree(c, &m.tree, len(rows), func(i int) string { return rows[i] }, func(i int) {})`, "color-picker": `ui.ColorPicker(c, &m.picker, &m.color, "Accent")`, "color-swatch": `ui.ColorSwatch(c, color, selected, "Accent")`, "progress": `ui.Progress(c, 0.6)`, diff --git a/website/src/lib/i18n.ts b/website/src/lib/i18n.ts index 195b05ff..6bc7a48b 100644 --- a/website/src/lib/i18n.ts +++ b/website/src/lib/i18n.ts @@ -29,6 +29,7 @@ const english = { noMatches: 'No matching components. Try another name or category.', matches: 'matching components', preview: 'Preview', copySource: 'Copy source', exampleUsage: 'Usage', copyUsage: 'Copy usage', + pageApi: 'Page API', componentSource: 'Component source', canvasRecipe: 'Canvas recipe: use it inside ui.Control/Draw, or use the ui.* page control where one exists.', copyInstall: 'Copy install command', copyCode: 'Copy code', copying: 'Copying…', copied: 'Copied', copiedNotice: 'Copied to clipboard.', copyFailed: 'Copy failed. Select the text and press Ctrl+C or ⌘C.', @@ -52,6 +53,7 @@ const chinese: typeof english = { noMatches: '没有匹配的组件,试试名称或分类。', matches: '个匹配组件', preview: '预览', copySource: '复制源码', exampleUsage: '用法', copyUsage: '复制用法', + pageApi: '页面 API', componentSource: '组件源码', canvasRecipe: '画布 recipe:在 ui.Control/Draw 内使用;有页面控件时优先用 ui.*。', copyInstall: '复制安装命令', copyCode: '复制代码', copying: '复制中…', copied: '已复制', copiedNotice: '已复制到剪贴板。', copyFailed: '复制失败,请选中文本后按 Ctrl+C 或 ⌘C。', diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index 3f8392c4..1413fbd0 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -29,7 +29,7 @@ const fallbackUsage = `ui.Control(c, "${page.Title.replaceAll('"', '')}", &m.han

{page.Title}{zhName && zhName !== page.Title && {zhName}}

- {text.viewSource}{sourcePath} + {text.componentSource}{sourcePath}
@@ -38,11 +38,12 @@ const fallbackUsage = `ui.Control(c, "${page.Title.replaceAll('"', '')}", &m.han

{example.Title}#

{example.Description}

+ {(!example.Snippet || /components\.|Begin/.test(example.Snippet)) &&

{text.canvasRecipe}

} {(() => { const pageUsage = page.PageUsage || fallbackUsage; const usage = example.Snippet && !/components\.|Begin/.test(example.Snippet) ? example.Snippet : pageUsage; return
-
{text.exampleUsage}
+
{text.pageApi}
; })()} From d73f9acf5ec00ac75c849a0455aca98c6799ad14 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 13:33:59 +0800 Subject: [PATCH 19/66] refactor(base): move tree navigation into the engine --- base/tree_navigation.go | 111 +++++++++++++++++++++ cmd/viva/templates/tree_navigation.go.txt | 112 +++------------------- components/tree_navigation.go | 112 +++------------------- internal/componentdemo/page_usage.go | 1 + internal/componentdemo/tree_navigation.go | 12 +-- ui/facade.go | 17 ++++ website/content/guides/en/components.md | 2 +- website/content/guides/zh/components.md | 2 +- 8 files changed, 165 insertions(+), 204 deletions(-) create mode 100644 base/tree_navigation.go diff --git a/base/tree_navigation.go b/base/tree_navigation.go new file mode 100644 index 00000000..5f937718 --- /dev/null +++ b/base/tree_navigation.go @@ -0,0 +1,111 @@ +package base + +import "github.com/vivaui/viva/gfx" + +// TreeNavigationItem describes one visible row of a caller-owned, flattened +// tree. Depth must describe the actual hierarchy, not its visual indentation. +type TreeNavigationItem struct { + Depth uint8 + Branch bool + Expanded bool + Disabled bool +} + +// TreeNavigationAction tells the caller what to do with the current branch. +// Expansion and selection remain application-owned. +type TreeNavigationAction uint8 + +const ( + TreeNavigationNone TreeNavigationAction = iota + TreeNavigationMove + TreeNavigationExpand + TreeNavigationCollapse +) + +// NavigateTree applies desktop tree keyboard navigation to visible rows. +// Arrow keys move among enabled rows; Right opens a collapsed branch or moves +// to its first child, and Left closes an open branch or moves to its parent. +// Home, End and Page keys navigate the visible rows without wrapping. pageRows +// is the number of rows in one viewport. An accepted key returns true even +// when navigation is already at an edge. +func NavigateTree(items []TreeNavigationItem, current int, key gfx.Key, pageRows int) (int, TreeNavigationAction, bool) { + switch key { + case gfx.KeyUp, gfx.KeyDown, gfx.KeyHome, gfx.KeyEnd, gfx.KeyPageUp, gfx.KeyPageDown, gfx.KeyLeft, gfx.KeyRight: + default: + return current, TreeNavigationNone, false + } + if current < 0 || current >= len(items) || items[current].Disabled { + return current, TreeNavigationNone, false + } + item := items[current] + if key == gfx.KeyRight { + if !item.Branch { + return current, TreeNavigationNone, true + } + if !item.Expanded { + return current, TreeNavigationExpand, true + } + for next := current + 1; next < len(items) && items[next].Depth > item.Depth; next++ { + if int(items[next].Depth) == int(item.Depth)+1 && !items[next].Disabled { + return next, TreeNavigationMove, true + } + } + return current, TreeNavigationNone, true + } + if key == gfx.KeyLeft { + if item.Branch && item.Expanded { + return current, TreeNavigationCollapse, true + } + for index := current - 1; index >= 0; index-- { + if items[index].Depth < item.Depth { + if !items[index].Disabled { + return index, TreeNavigationMove, true + } + break + } + } + return current, TreeNavigationNone, true + } + if pageRows < 1 { + pageRows = 1 + } + step := 0 + switch key { + case gfx.KeyUp: + step = -1 + case gfx.KeyDown: + step = 1 + case gfx.KeyPageUp: + step = -pageRows + case gfx.KeyPageDown: + step = pageRows + case gfx.KeyHome: + step = -current + case gfx.KeyEnd: + step = len(items) - 1 - current + } + target := max(0, min(len(items)-1, current+step)) + if step > 0 { + for target < len(items)-1 && items[target].Disabled { + target++ + } + if items[target].Disabled { + for target > current && items[target].Disabled { + target-- + } + } + } else if step < 0 { + for target > 0 && items[target].Disabled { + target-- + } + if items[target].Disabled { + for target < current && items[target].Disabled { + target++ + } + } + } + if target != current { + return target, TreeNavigationMove, true + } + return current, TreeNavigationNone, true +} diff --git a/cmd/viva/templates/tree_navigation.go.txt b/cmd/viva/templates/tree_navigation.go.txt index 7336c00c..7646f4df 100644 --- a/cmd/viva/templates/tree_navigation.go.txt +++ b/cmd/viva/templates/tree_navigation.go.txt @@ -1,111 +1,27 @@ package {{PACKAGE}} -import "github.com/vivaui/viva/gfx" +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) // TreeNavigationItem describes one visible row of a caller-owned, flattened // tree. Depth must describe the actual hierarchy, not its visual indentation. -type TreeNavigationItem struct { - Depth uint8 - Branch bool - Expanded bool - Disabled bool -} +type TreeNavigationItem = base.TreeNavigationItem // TreeNavigationAction tells the caller what to do with the current branch. -// Expansion and selection remain application-owned. -type TreeNavigationAction uint8 +type TreeNavigationAction = base.TreeNavigationAction const ( - TreeNavigationNone TreeNavigationAction = iota - TreeNavigationMove - TreeNavigationExpand - TreeNavigationCollapse + TreeNavigationNone = base.TreeNavigationNone + TreeNavigationMove = base.TreeNavigationMove + TreeNavigationExpand = base.TreeNavigationExpand + TreeNavigationCollapse = base.TreeNavigationCollapse ) -// NavigateTree applies desktop tree keyboard navigation to visible rows. -// Arrow keys move among enabled rows; Right opens a collapsed branch or moves -// to its first child, and Left closes an open branch or moves to its parent. -// Home, End and Page keys navigate the visible rows without wrapping. pageRows -// is the number of rows in one viewport. An accepted key returns true even -// when navigation is already at an edge. +// NavigateTree applies desktop tree keyboard navigation to visible rows. It is +// base.NavigateTree; the implementation lives in the engine with the other +// input behaviour. func NavigateTree(items []TreeNavigationItem, current int, key gfx.Key, pageRows int) (int, TreeNavigationAction, bool) { - switch key { - case gfx.KeyUp, gfx.KeyDown, gfx.KeyHome, gfx.KeyEnd, gfx.KeyPageUp, gfx.KeyPageDown, gfx.KeyLeft, gfx.KeyRight: - default: - return current, TreeNavigationNone, false - } - if current < 0 || current >= len(items) || items[current].Disabled { - return current, TreeNavigationNone, false - } - item := items[current] - if key == gfx.KeyRight { - if !item.Branch { - return current, TreeNavigationNone, true - } - if !item.Expanded { - return current, TreeNavigationExpand, true - } - for next := current + 1; next < len(items) && items[next].Depth > item.Depth; next++ { - if int(items[next].Depth) == int(item.Depth)+1 && !items[next].Disabled { - return next, TreeNavigationMove, true - } - } - return current, TreeNavigationNone, true - } - if key == gfx.KeyLeft { - if item.Branch && item.Expanded { - return current, TreeNavigationCollapse, true - } - for index := current - 1; index >= 0; index-- { - if items[index].Depth < item.Depth { - if !items[index].Disabled { - return index, TreeNavigationMove, true - } - break - } - } - return current, TreeNavigationNone, true - } - if pageRows < 1 { - pageRows = 1 - } - step := 0 - switch key { - case gfx.KeyUp: - step = -1 - case gfx.KeyDown: - step = 1 - case gfx.KeyPageUp: - step = -pageRows - case gfx.KeyPageDown: - step = pageRows - case gfx.KeyHome: - step = -current - case gfx.KeyEnd: - step = len(items) - 1 - current - } - target := max(0, min(len(items)-1, current+step)) - if step > 0 { - for target < len(items)-1 && items[target].Disabled { - target++ - } - if items[target].Disabled { - for target > current && items[target].Disabled { - target-- - } - } - } else if step < 0 { - for target > 0 && items[target].Disabled { - target-- - } - if items[target].Disabled { - for target < current && items[target].Disabled { - target++ - } - } - } - if target != current { - return target, TreeNavigationMove, true - } - return current, TreeNavigationNone, true + return base.NavigateTree(items, current, key, pageRows) } diff --git a/components/tree_navigation.go b/components/tree_navigation.go index 38aefaf3..9ac86b2f 100644 --- a/components/tree_navigation.go +++ b/components/tree_navigation.go @@ -1,111 +1,27 @@ package components -import "github.com/vivaui/viva/gfx" +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) // TreeNavigationItem describes one visible row of a caller-owned, flattened // tree. Depth must describe the actual hierarchy, not its visual indentation. -type TreeNavigationItem struct { - Depth uint8 - Branch bool - Expanded bool - Disabled bool -} +type TreeNavigationItem = base.TreeNavigationItem // TreeNavigationAction tells the caller what to do with the current branch. -// Expansion and selection remain application-owned. -type TreeNavigationAction uint8 +type TreeNavigationAction = base.TreeNavigationAction const ( - TreeNavigationNone TreeNavigationAction = iota - TreeNavigationMove - TreeNavigationExpand - TreeNavigationCollapse + TreeNavigationNone = base.TreeNavigationNone + TreeNavigationMove = base.TreeNavigationMove + TreeNavigationExpand = base.TreeNavigationExpand + TreeNavigationCollapse = base.TreeNavigationCollapse ) -// NavigateTree applies desktop tree keyboard navigation to visible rows. -// Arrow keys move among enabled rows; Right opens a collapsed branch or moves -// to its first child, and Left closes an open branch or moves to its parent. -// Home, End and Page keys navigate the visible rows without wrapping. pageRows -// is the number of rows in one viewport. An accepted key returns true even -// when navigation is already at an edge. +// NavigateTree applies desktop tree keyboard navigation to visible rows. It is +// base.NavigateTree; the implementation lives in the engine with the other +// input behaviour. func NavigateTree(items []TreeNavigationItem, current int, key gfx.Key, pageRows int) (int, TreeNavigationAction, bool) { - switch key { - case gfx.KeyUp, gfx.KeyDown, gfx.KeyHome, gfx.KeyEnd, gfx.KeyPageUp, gfx.KeyPageDown, gfx.KeyLeft, gfx.KeyRight: - default: - return current, TreeNavigationNone, false - } - if current < 0 || current >= len(items) || items[current].Disabled { - return current, TreeNavigationNone, false - } - item := items[current] - if key == gfx.KeyRight { - if !item.Branch { - return current, TreeNavigationNone, true - } - if !item.Expanded { - return current, TreeNavigationExpand, true - } - for next := current + 1; next < len(items) && items[next].Depth > item.Depth; next++ { - if int(items[next].Depth) == int(item.Depth)+1 && !items[next].Disabled { - return next, TreeNavigationMove, true - } - } - return current, TreeNavigationNone, true - } - if key == gfx.KeyLeft { - if item.Branch && item.Expanded { - return current, TreeNavigationCollapse, true - } - for index := current - 1; index >= 0; index-- { - if items[index].Depth < item.Depth { - if !items[index].Disabled { - return index, TreeNavigationMove, true - } - break - } - } - return current, TreeNavigationNone, true - } - if pageRows < 1 { - pageRows = 1 - } - step := 0 - switch key { - case gfx.KeyUp: - step = -1 - case gfx.KeyDown: - step = 1 - case gfx.KeyPageUp: - step = -pageRows - case gfx.KeyPageDown: - step = pageRows - case gfx.KeyHome: - step = -current - case gfx.KeyEnd: - step = len(items) - 1 - current - } - target := max(0, min(len(items)-1, current+step)) - if step > 0 { - for target < len(items)-1 && items[target].Disabled { - target++ - } - if items[target].Disabled { - for target > current && items[target].Disabled { - target-- - } - } - } else if step < 0 { - for target > 0 && items[target].Disabled { - target-- - } - if items[target].Disabled { - for target < current && items[target].Disabled { - target++ - } - } - } - if target != current { - return target, TreeNavigationMove, true - } - return current, TreeNavigationNone, true + return base.NavigateTree(items, current, key, pageRows) } diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index 0d49dca0..12ac29dd 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -24,6 +24,7 @@ var pageUsage = map[string]string{ "table": `ui.Table(c, &m.table, ui.TableSpec{Rows: rows, Columns: columns, Headers: headers})`, "list": `ui.List(c, &m.list, len(rows), func(row ui.ListRow) { _ = row })`, "tree": `ui.Tree(c, &m.tree, len(rows), func(i int) string { return rows[i] }, func(i int) {})`, + "tree-navigation": `next, action, handled := ui.NavigateTree(items, current, key, pageRows)`, "color-picker": `ui.ColorPicker(c, &m.picker, &m.color, "Accent")`, "color-swatch": `ui.ColorSwatch(c, color, selected, "Accent")`, "progress": `ui.Progress(c, 0.6)`, diff --git a/internal/componentdemo/tree_navigation.go b/internal/componentdemo/tree_navigation.go index 351da16b..f2fef8d6 100644 --- a/internal/componentdemo/tree_navigation.go +++ b/internal/componentdemo/tree_navigation.go @@ -11,12 +11,12 @@ var treeNavigationComponent = Component{ Summary: "为应用管理的可见树行和展开状态提供键盘导航。", paint: (*State).paintTreeNavigation, key: (*State).keyTreeNavigation, Examples: []Example{ - {ID: "default", Title: "键盘导航", Description: "聚焦 Production 行。按 → 展开或进入第一个子项,按 ← 返回父项或收起当前分支。", Snippet: `next, action, handled := components.NavigateTree(visible, current, event.Key, pageRows) + {ID: "default", Title: "键盘导航", Description: "聚焦 Production 行。按 → 展开或进入第一个子项,按 ← 返回父项或收起当前分支。", Snippet: `next, action, handled := ui.NavigateTree(visible, current, event.Key, pageRows) if handled { switch action { - case components.TreeNavigationExpand: + case ui.TreeNavigationExpand: expanded = true - case components.TreeNavigationCollapse: + case ui.TreeNavigationCollapse: expanded = false } selected = next @@ -80,14 +80,14 @@ func (state *State) keyTreeNavigation(event gfx.KeyEvent) gfx.EventResult { if expanded { visible = items[:] } - next, action, handled := components.NavigateTree(visible, current, event.Key, len(items)) + next, action, handled := ui.NavigateTree(visible, current, event.Key, len(items)) if !handled { return gfx.EventResult{} } switch action { - case components.TreeNavigationExpand: + case ui.TreeNavigationExpand: state.flags |= 1 - case components.TreeNavigationCollapse: + case ui.TreeNavigationCollapse: state.flags &^= 1 } changed := action != components.TreeNavigationNone || state.values[0] != int32(next) diff --git a/ui/facade.go b/ui/facade.go index 7bd577ab..e98a4476 100644 --- a/ui/facade.go +++ b/ui/facade.go @@ -387,6 +387,23 @@ func LayoutScrollArea(bounds gfx.Rect, content gfx.Size, layout ScrollAreaLayout return base.LayoutScrollArea(bounds, content, layout) } +// Tree navigation. + +type TreeNavigationItem = base.TreeNavigationItem + +type TreeNavigationAction = base.TreeNavigationAction + +const ( + TreeNavigationNone = base.TreeNavigationNone + TreeNavigationMove = base.TreeNavigationMove + TreeNavigationExpand = base.TreeNavigationExpand + TreeNavigationCollapse = base.TreeNavigationCollapse +) + +func NavigateTree(items []TreeNavigationItem, current int, key gfx.Key, pageRows int) (int, TreeNavigationAction, bool) { + return base.NavigateTree(items, current, key, pageRows) +} + // Identity and input. func ID(c C) gfx.ID { return base.ID(c) } diff --git a/website/content/guides/en/components.md b/website/content/guides/en/components.md index ec24daf1..b1d6a944 100644 --- a/website/content/guides/en/components.md +++ b/website/content/guides/en/components.md @@ -23,7 +23,7 @@ A theme is a value, `gfx.LightTheme()` or `gfx.DarkTheme()`. Switching appearanc ## Tree navigation -`BeginTree` paints rows from an application-owned flattened hierarchy. For keyboard navigation, pass the visible rows' actual depths, expansion state and disabled state to `components.NavigateTree`; do not pass display-clamped indentation as the depth. It returns the next visible index or an expand/collapse action. The application still owns loading children, expansion, selection and focus, so no hidden model or background work is created. Keep the navigation slice as reusable caller-owned scratch when handling keys. +`BeginTree` paints rows from an application-owned flattened hierarchy. For keyboard navigation, pass the visible rows' actual depths, expansion state and disabled state to `ui.NavigateTree`; do not pass display-clamped indentation as the depth. It returns the next visible index or an expand/collapse action. The application still owns loading children, expansion, selection and focus, so no hidden model or background work is created. Keep the navigation slice as reusable caller-owned scratch when handling keys. ## Charts diff --git a/website/content/guides/zh/components.md b/website/content/guides/zh/components.md index e16aef1d..82a805de 100644 --- a/website/content/guides/zh/components.md +++ b/website/content/guides/zh/components.md @@ -23,7 +23,7 @@ components.BeginButton(canvas, theme, hitSave, bounds).Outline("Save") ## 树形导航 -`BeginTree` 根据应用自己扁平化的层级绘制可见行。处理键盘事件时,将可见行的实际深度、展开状态和禁用状态传给 `components.NavigateTree`;深度不能使用为了适应宽度而截断的视觉缩进。它返回下一个可见行的索引,或者展开、折叠动作。子节点加载、展开状态、选择和焦点仍由应用负责,不产生隐藏模型或后台工作;导航切片可作为调用方拥有的临时存储复用。 +`BeginTree` 根据应用自己扁平化的层级绘制可见行。处理键盘事件时,将可见行的实际深度、展开状态和禁用状态传给 `ui.NavigateTree`;深度不能使用为了适应宽度而截断的视觉缩进。它返回下一个可见行的索引,或者展开、折叠动作。子节点加载、展开状态、选择和焦点仍由应用负责,不产生隐藏模型或后台工作;导航切片可作为调用方拥有的临时存储复用。 ## 图表 From e18e37144b07de64b991597552308b4e881c3774 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 13:37:20 +0800 Subject: [PATCH 20/66] docs(website): add page usages for layout and tooltip controls --- internal/componentdemo/page_usage.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index 12ac29dd..d64f5921 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -4,6 +4,12 @@ package componentdemo // documentation site shows it above the examples; a component without an entry // is a canvas recipe, used inside ui.Control/Draw or copied by viva add. var pageUsage = map[string]string{ + "empty": `ui.Column(c).Fill().Center()`, + "item": `ui.Row(c).Gap(8).FillWidth()`, + "card": `ui.Column(c).Pad(16).Radius(12).Border(1, border)`, + "label": `ui.Text(c, "Name").LabelFor(fieldID)`, + "kbd": `ui.Kbd(c, "⌘", "K")`, + "tooltip": `ui.Button(c, "Hover").Hit(id, "Hover").Tooltip("Hint")`, "button": `ui.Button(c, "Save").Clicked()`, "badge": `ui.Badge(c, "New")`, "checkbox": `ui.Checkbox(c, &m.accepted, "Accept")`, From 44c3c539db2dc33002b75756b0035902251de23c Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 13:39:13 +0800 Subject: [PATCH 21/66] docs(website): link the page API source its usage comes from --- internal/componentdemo/page_source.go | 52 +++++++++++++++++++ internal/componentdemo/state.go | 3 ++ tools/docs/catalog.go | 3 ++ website/src/lib/i18n.ts | 4 +- website/src/lib/types.ts | 1 + website/src/pages/[lang]/ui/[component].astro | 4 +- 6 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 internal/componentdemo/page_source.go diff --git a/internal/componentdemo/page_source.go b/internal/componentdemo/page_source.go new file mode 100644 index 00000000..cb6de763 --- /dev/null +++ b/internal/componentdemo/page_source.go @@ -0,0 +1,52 @@ +package componentdemo + +// pageSource is where the page-first call site is implemented. The +// documentation site links "Page API source" here when PageUsage exists; a +// component without a page API links its own source instead. +var pageSource = map[string]string{ + "button": "base/controls.go", + "badge": "base/badge.go", + "checkbox": "base/controls.go", + "switch": "base/controls.go", + "input": "base/field.go", + "textarea": "base/textarea.go", + "select": "base/select.go", + "combobox": "base/combobox.go", + "slider": "base/slider.go", + "tabs": "base/tabs.go", + "dialog": "base/dialog.go", + "alert-dialog": "base/alert_dialog.go", + "drawer": "base/drawer.go", + "sheet": "base/drawer.go", + "popover": "base/popover.go", + "dropdown-menu": "base/menu.go", + "context-menu": "base/menu.go", + "table": "base/table.go", + "list": "base/list.go", + "tree": "base/tree.go", + "tree-navigation": "base/tree_navigation.go", + "color-picker": "base/color.go", + "color-swatch": "base/color.go", + "progress": "base/leaves.go", + "spinner": "base/leaves.go", + "split-button": "base/split_button.go", + "pagination": "base/pagination.go", + "radio-group": "base/controls.go", + "choice": "base/elements.go", + "toggle": "base/controls.go", + "native-select": "base/select.go", + "single-select": "base/select.go", + "scroll-area": "base/scroll.go", + "resizable": "base/splitter.go", + "separator": "base/frame.go", + "typography": "base/frame.go", + "form": "base/form_field.go", + "field": "base/form_field.go", + "multi-select": "multiselect/multiselect.go", + "tooltip": "base/tooltip.go", + "kbd": "base/leaves.go", + "label": "base/elements.go", + "card": "base/box.go", + "item": "base/box.go", + "empty": "base/box.go", +} diff --git a/internal/componentdemo/state.go b/internal/componentdemo/state.go index acc5b5ca..b1245690 100644 --- a/internal/componentdemo/state.go +++ b/internal/componentdemo/state.go @@ -24,6 +24,8 @@ type Component struct { // component has one. Empty means it is a canvas recipe, used inside // ui.Control/Draw or copied by viva add. PageUsage string + // PageSource is where PageUsage is implemented; empty keeps Source. + PageSource string // Source is the Go file the example calls, relative to the repository root, when // the control is not one of the components package: a page-layer control such as // ui.List. Empty means components/.go, the component's own file. @@ -75,6 +77,7 @@ func buildCatalog() []Component { } for i := range result { result[i].PageUsage = pageUsage[result[i].ID] + result[i].PageSource = pageSource[result[i].ID] } return result } diff --git a/tools/docs/catalog.go b/tools/docs/catalog.go index d7d70101..90809d7c 100644 --- a/tools/docs/catalog.go +++ b/tools/docs/catalog.go @@ -38,6 +38,8 @@ type Page struct { ID, Title, Category, Summary, Revision string // PageUsage is the page-first call site, when the component has one. PageUsage string + // PageSource is where PageUsage is implemented; empty uses Source. + PageSource string // Source is the Go file the examples call, relative to the repository root: // components/.go, or ui/list.go for a page-layer control. Source string @@ -90,6 +92,7 @@ func loadPages(root string) ([]Page, Manifest, error) { page.All, page.Revision = navigation, manifest.Revision page.Source = component.Source page.PageUsage = component.PageUsage + page.PageSource = component.PageSource if page.Source == "" { page.Source = "components/" + strings.ReplaceAll(component.ID, "-", "_") + ".go" } diff --git a/website/src/lib/i18n.ts b/website/src/lib/i18n.ts index 6bc7a48b..47027a0d 100644 --- a/website/src/lib/i18n.ts +++ b/website/src/lib/i18n.ts @@ -29,7 +29,7 @@ const english = { noMatches: 'No matching components. Try another name or category.', matches: 'matching components', preview: 'Preview', copySource: 'Copy source', exampleUsage: 'Usage', copyUsage: 'Copy usage', - pageApi: 'Page API', componentSource: 'Component source', + pageApi: 'Page API', componentSource: 'Component source', pageApiSource: 'Page API source', canvasRecipe: 'Canvas recipe: use it inside ui.Control/Draw, or use the ui.* page control where one exists.', copyInstall: 'Copy install command', copyCode: 'Copy code', copying: 'Copying…', copied: 'Copied', copiedNotice: 'Copied to clipboard.', copyFailed: 'Copy failed. Select the text and press Ctrl+C or ⌘C.', @@ -53,7 +53,7 @@ const chinese: typeof english = { noMatches: '没有匹配的组件,试试名称或分类。', matches: '个匹配组件', preview: '预览', copySource: '复制源码', exampleUsage: '用法', copyUsage: '复制用法', - pageApi: '页面 API', componentSource: '组件源码', + pageApi: '页面 API', componentSource: '组件源码', pageApiSource: '页面 API 源码', canvasRecipe: '画布 recipe:在 ui.Control/Draw 内使用;有页面控件时优先用 ui.*。', copyInstall: '复制安装命令', copyCode: '复制代码', copying: '复制中…', copied: '已复制', copiedNotice: '已复制到剪贴板。', copyFailed: '复制失败,请选中文本后按 Ctrl+C 或 ⌘C。', diff --git a/website/src/lib/types.ts b/website/src/lib/types.ts index 54785c5b..07128a6e 100644 --- a/website/src/lib/types.ts +++ b/website/src/lib/types.ts @@ -36,6 +36,7 @@ export interface Page extends Nav { Sections: Section[]; Capabilities: Capability[]; PageUsage?: string; + PageSource?: string; } export interface Coverage { diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index 1413fbd0..49406679 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -18,7 +18,7 @@ const zhName = locale === 'zh' ? componentName(locale, page.ID, page.Title) : '' const text = messages[locale]; const themes = { light: 'github-light', dark: 'github-dark' } as const; const sourceFile = `${page.ID.replaceAll('-', '_')}.go`; -const sourcePath = page.Source || `components/${sourceFile}`; +const sourcePath = page.PageUsage && page.PageSource ? page.PageSource : (page.Source || `components/${sourceFile}`); const sections = page.Sections.filter(section => section.ID !== 'source-ownership'); const fallbackUsage = `ui.Control(c, "${page.Title.replaceAll('"', '')}", &m.handlers).Draw(paint)`; --- @@ -29,7 +29,7 @@ const fallbackUsage = `ui.Control(c, "${page.Title.replaceAll('"', '')}", &m.han From eba4dcb2a4067cd3ac3c8a629047ad9820137cc9 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 13:41:41 +0800 Subject: [PATCH 22/66] docs(website): show the table example's data in its page usage --- internal/componentdemo/page_usage.go | 57 ++++++++++++++++------------ 1 file changed, 33 insertions(+), 24 deletions(-) diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index d64f5921..61919b63 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -4,30 +4,39 @@ package componentdemo // documentation site shows it above the examples; a component without an entry // is a canvas recipe, used inside ui.Control/Draw or copied by viva add. var pageUsage = map[string]string{ - "empty": `ui.Column(c).Fill().Center()`, - "item": `ui.Row(c).Gap(8).FillWidth()`, - "card": `ui.Column(c).Pad(16).Radius(12).Border(1, border)`, - "label": `ui.Text(c, "Name").LabelFor(fieldID)`, - "kbd": `ui.Kbd(c, "⌘", "K")`, - "tooltip": `ui.Button(c, "Hover").Hit(id, "Hover").Tooltip("Hint")`, - "button": `ui.Button(c, "Save").Clicked()`, - "badge": `ui.Badge(c, "New")`, - "checkbox": `ui.Checkbox(c, &m.accepted, "Accept")`, - "switch": `ui.Switch(c, &m.enabled, "Enabled")`, - "input": `ui.TextField(c, &m.name, "Name", "Ada")`, - "textarea": `ui.TextArea(c, &m.notes, "Notes", "")`, - "select": `ui.Select(c, &m.choice, choices, nameOf)`, - "combobox": `ui.Combobox(c, &m.choice, choices, nameOf, "Choice")`, - "slider": `ui.Slider(c, &m.volume).Range(0, 100)`, - "tabs": `ui.Tabs(c, &m.tab, tabs, tabLabel)`, - "dialog": `ui.Dialog(c, ui.DialogSpec{Title: "Edit host", Scope: scope, DismissID: dismiss})`, - "alert-dialog": `ui.AlertDialog(c, ui.AlertDialogSpec{Title: "Delete?", ActionLabel: "Delete", CancelLabel: "Cancel", ActionID: action, CancelID: cancel})`, - "drawer": `ui.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`, - "sheet": `ui.Drawer(c, &m.open, "Details", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`, - "popover": `ui.PopoverWith(c, anchor, ui.PopoverSpec{Title: "Details"}, &m.open, body)`, - "dropdown-menu": `ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { menu.Item("Rename") })`, - "context-menu": `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { menu.Item("Delete") })`, - "table": `ui.Table(c, &m.table, ui.TableSpec{Rows: rows, Columns: columns, Headers: headers})`, + "empty": `ui.Column(c).Fill().Center()`, + "item": `ui.Row(c).Gap(8).FillWidth()`, + "card": `ui.Column(c).Pad(16).Radius(12).Border(1, border)`, + "label": `ui.Text(c, "Name").LabelFor(fieldID)`, + "kbd": `ui.Kbd(c, "⌘", "K")`, + "tooltip": `ui.Button(c, "Hover").Hit(id, "Hover").Tooltip("Hint")`, + "button": `ui.Button(c, "Save").Clicked()`, + "badge": `ui.Badge(c, "New")`, + "checkbox": `ui.Checkbox(c, &m.accepted, "Accept")`, + "switch": `ui.Switch(c, &m.enabled, "Enabled")`, + "input": `ui.TextField(c, &m.name, "Name", "Ada")`, + "textarea": `ui.TextArea(c, &m.notes, "Notes", "")`, + "select": `ui.Select(c, &m.choice, choices, nameOf)`, + "combobox": `ui.Combobox(c, &m.choice, choices, nameOf, "Choice")`, + "slider": `ui.Slider(c, &m.volume).Range(0, 100)`, + "tabs": `ui.Tabs(c, &m.tab, tabs, tabLabel)`, + "dialog": `ui.Dialog(c, ui.DialogSpec{Title: "Edit host", Scope: scope, DismissID: dismiss})`, + "alert-dialog": `ui.AlertDialog(c, ui.AlertDialogSpec{Title: "Delete?", ActionLabel: "Delete", CancelLabel: "Cancel", ActionID: action, CancelID: cancel})`, + "drawer": `ui.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`, + "sheet": `ui.Drawer(c, &m.open, "Details", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`, + "popover": `ui.PopoverWith(c, anchor, ui.PopoverSpec{Title: "Details"}, &m.open, body)`, + "dropdown-menu": `ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { menu.Item("Rename") })`, + "context-menu": `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { menu.Item("Delete") })`, + "table": `bills := ui.TableRows{ + {"设计系统", "已支付", "¥ 2,400"}, + {"桌面构建", "处理中", "¥ 860"}, + {"性能审计", "待付款", "¥ 1,280"}, +} +ui.Table(c, &m.table, ui.TableSpec{ + Rows: rows, Columns: columns, + Headers: []string{"项目", "状态", "金额"}, + Source: &bills, +})`, "list": `ui.List(c, &m.list, len(rows), func(row ui.ListRow) { _ = row })`, "tree": `ui.Tree(c, &m.tree, len(rows), func(i int) string { return rows[i] }, func(i int) {})`, "tree-navigation": `next, action, handled := ui.NavigateTree(items, current, key, pageRows)`, From 7a4b6f7f14bfd4cb9c59d498a84e583838fa03ac Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 13:41:57 +0800 Subject: [PATCH 23/66] test(ui): pin switch, hover and scroll motion frame by frame --- ui/motion_frame_test.go | 120 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 ui/motion_frame_test.go diff --git a/ui/motion_frame_test.go b/ui/motion_frame_test.go new file mode 100644 index 00000000..43621768 --- /dev/null +++ b/ui/motion_frame_test.go @@ -0,0 +1,120 @@ +package ui_test + +import ( + "reflect" + "testing" + "time" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// A page Switch animates exactly as the components.Switch it wraps: the page +// path only gives the component its leaf, so the thumb's travel is the same +// rectangle on every frame of the transition. +func TestPageSwitchAnimatesLikeItsComponent(t *testing.T) { + theme := gfx.LightTheme() + on := false + pageClock := newParityClock() + view := func(c ui.C) { ui.Switch(c, &on, "") } + page := ui.NewPage(ui.PageConfig{Theme: &theme, View: view}) + pagePaint := func() { page.Draw(pageClock.canvas, gfx.Rect{Width: 200, Height: 100}, view) } + pageClock.step(false, pagePaint) + // The first rectangle of the page's resting frame is the track: the page + // centers the component's switch inside the Box's enlarged hit region. + track := pageClock.canvas.Rectangles()[0].Bounds + + componentClock := newParityClock() + componentPaint := func() { + components.BeginSwitch(componentClock.canvas, theme, gfx.Item(7), track, on).Paint() + } + // Settle both at off before the toggle, so the transition starts from the + // same look on both paths. + componentClock.step(false, componentPaint) + + // Turn it on, then sample every frame until both rest. + on = true + for frame := 0; ; frame++ { + pageClock.step(frame > 0, pagePaint) + componentClock.step(frame > 0, componentPaint) + sameRects(t, "switch", frame, componentClock.parityRects(), pageClock.parityRects()) + if pageClock.settled() != componentClock.settled() { + t.Fatalf("switch frame %d: components at rest=%v, page at rest=%v", frame, componentClock.settled(), pageClock.settled()) + } + if pageClock.settled() { + if frame == 0 { + t.Fatal("the switch settled on its first frame; its thumb did not travel") + } + return + } + if frame > 100 { + t.Fatal("the switch transition never settled") + } + } +} + +// Hovering a page control paints its hover look at once: without a Transition +// the control schedules no frame and a later paint is the same picture, so a +// hand-painted hover and a page one cannot drift apart over time. +func TestHoverPaintsAtOnceAndSchedulesNoFrames(t *testing.T) { + d := openPage(t, func(c ui.C) { + ui.Column(c).Fill().Pad(60).Children(func() { ui.Button(c, "Save") }) + }) + before := d.driver.Snapshot().Primitives + hit := d.hit("Save") + if err := d.driver.Move(center(hit.Bounds)); err != nil { + t.Fatal(err) + } + hovered := d.driver.Snapshot().Primitives + if reflect.DeepEqual(before, hovered) { + t.Fatal("moving onto the button changed nothing; the test is not hovering it") + } + for _, step := range []time.Duration{16 * time.Millisecond, 32 * time.Millisecond, 150 * time.Millisecond} { + if err := d.driver.Advance(step); err != nil { + t.Fatal(err) + } + if d.driver.Transitioning() { + t.Fatalf("a hover started a transition after %v", step) + } + if err := d.driver.Paint(); err != nil { + t.Fatal(err) + } + if now := d.driver.Snapshot().Primitives; !reflect.DeepEqual(hovered, now) { + t.Fatalf("the hover look changed after %v without a Transition", step) + } + } +} + +// A wheel scroll moves the content once: the frame after the wheel shows the new +// offset, and later frames are the same picture, so scrolling is not an +// animation with intermediate positions. +func TestScrollMovesAtOnceAndSchedulesNoFrames(t *testing.T) { + d := openPage(t, func(c ui.C) { + ui.Scroll(c).Fill().AlwaysScrollbars().Children(func() { + ui.Column(c).Children(func() { ui.Slot(c).Height(1000) }) + }) + }) + before := d.driver.Snapshot().Primitives + if err := d.driver.Scroll(gfx.ScrollEvent{X: 100, Y: 100, DeltaY: 120}); err != nil { + t.Fatal(err) + } + scrolled := d.driver.Snapshot().Primitives + if reflect.DeepEqual(before, scrolled) { + t.Fatal("the wheel changed nothing; the test is not scrolling the area") + } + for _, step := range []time.Duration{16 * time.Millisecond, 32 * time.Millisecond} { + if err := d.driver.Advance(step); err != nil { + t.Fatal(err) + } + if d.driver.Transitioning() { + t.Fatalf("a scroll started a transition after %v", step) + } + if err := d.driver.Paint(); err != nil { + t.Fatal(err) + } + if now := d.driver.Snapshot().Primitives; !reflect.DeepEqual(scrolled, now) { + t.Fatalf("the scrolled picture changed after %v; scrolling animated", step) + } + } +} From 2f13cacc4e87499c4b6d1d467ec55aa819b7711f Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 13:44:55 +0800 Subject: [PATCH 24/66] docs(website): show one page API and only matching example code --- website/site.test.mjs | 3 ++- website/src/pages/[lang]/ui/[component].astro | 20 +++++++++---------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/website/site.test.mjs b/website/site.test.mjs index 9469fe17..11e9e728 100644 --- a/website/site.test.mjs +++ b/website/site.test.mjs @@ -203,7 +203,8 @@ for (const locale of ['zh', 'en']) { assert.doesNotMatch(html, / example.Snippet && !/components\.|Begin/.test(example.Snippet)).length; + assert.equal([...html.matchAll(/class="code-block usage-block(?: page-api-block)?"/g)].length, pageLevel + (page.PageUsage ? 1 : 0)); for (const example of page.Examples) { assert.ok(html.includes(`id="example-${example.ID}"`)); } diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index 49406679..b441924d 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -20,7 +20,6 @@ const themes = { light: 'github-light', dark: 'github-dark' } as const; const sourceFile = `${page.ID.replaceAll('-', '_')}.go`; const sourcePath = page.PageUsage && page.PageSource ? page.PageSource : (page.Source || `components/${sourceFile}`); const sections = page.Sections.filter(section => section.ID !== 'source-ownership'); -const fallbackUsage = `ui.Control(c, "${page.Title.replaceAll('"', '')}", &m.handlers).Draw(paint)`; --- @@ -33,20 +32,21 @@ const fallbackUsage = `ui.Control(c, "${page.Title.replaceAll('"', '')}", &m.han + {page.PageUsage &&

{text.pageApi}

+
+
{text.pageApi}
+
+
+
}
{page.Examples.map(example =>

{example.Title}#

{example.Description}

- {(!example.Snippet || /components\.|Begin/.test(example.Snippet)) &&

{text.canvasRecipe}

} - {(() => { - const pageUsage = page.PageUsage || fallbackUsage; - const usage = example.Snippet && !/components\.|Begin/.test(example.Snippet) ? example.Snippet : pageUsage; - return
-
{text.pageApi}
-
-
; - })()} + {example.Snippet && !/components\.|Begin/.test(example.Snippet) ?
+
{text.exampleUsage}
+
+
:

{text.canvasRecipe}

}
)}
From a5da67aa63440ee836c37a5aa1c70e3eb317401c Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 13:46:50 +0800 Subject: [PATCH 25/66] docs(website): show each example's actual source --- website/site.test.mjs | 3 +-- website/src/lib/i18n.ts | 4 ++-- website/src/pages/[lang]/ui/[component].astro | 8 ++++---- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/website/site.test.mjs b/website/site.test.mjs index 11e9e728..d2b81a7a 100644 --- a/website/site.test.mjs +++ b/website/site.test.mjs @@ -203,8 +203,7 @@ for (const locale of ['zh', 'en']) { assert.doesNotMatch(html, / example.Snippet && !/components\.|Begin/.test(example.Snippet)).length; - assert.equal([...html.matchAll(/class="code-block usage-block(?: page-api-block)?"/g)].length, pageLevel + (page.PageUsage ? 1 : 0)); + assert.equal([...html.matchAll(/class="code-block usage-block(?: page-api-block)?"/g)].length, page.Examples.length + (page.PageUsage ? 1 : 0)); for (const example of page.Examples) { assert.ok(html.includes(`id="example-${example.ID}"`)); } diff --git a/website/src/lib/i18n.ts b/website/src/lib/i18n.ts index 47027a0d..6af1fa62 100644 --- a/website/src/lib/i18n.ts +++ b/website/src/lib/i18n.ts @@ -29,7 +29,7 @@ const english = { noMatches: 'No matching components. Try another name or category.', matches: 'matching components', preview: 'Preview', copySource: 'Copy source', exampleUsage: 'Usage', copyUsage: 'Copy usage', - pageApi: 'Page API', componentSource: 'Component source', pageApiSource: 'Page API source', + pageApi: 'Page API', componentSource: 'Component source', pageApiSource: 'Page API source', exampleSource: 'Example source', canvasRecipe: 'Canvas recipe: use it inside ui.Control/Draw, or use the ui.* page control where one exists.', copyInstall: 'Copy install command', copyCode: 'Copy code', copying: 'Copying…', copied: 'Copied', copiedNotice: 'Copied to clipboard.', copyFailed: 'Copy failed. Select the text and press Ctrl+C or ⌘C.', @@ -53,7 +53,7 @@ const chinese: typeof english = { noMatches: '没有匹配的组件,试试名称或分类。', matches: '个匹配组件', preview: '预览', copySource: '复制源码', exampleUsage: '用法', copyUsage: '复制用法', - pageApi: '页面 API', componentSource: '组件源码', pageApiSource: '页面 API 源码', + pageApi: '页面 API', componentSource: '组件源码', pageApiSource: '页面 API 源码', exampleSource: '示例源码', canvasRecipe: '画布 recipe:在 ui.Control/Draw 内使用;有页面控件时优先用 ui.*。', copyInstall: '复制安装命令', copyCode: '复制代码', copying: '复制中…', copied: '已复制', copiedNotice: '已复制到剪贴板。', copyFailed: '复制失败,请选中文本后按 Ctrl+C 或 ⌘C。', diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index b441924d..1cbde0bd 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -42,11 +42,11 @@ const sections = page.Sections.filter(section => section.ID !== 'source-ownershi {page.Examples.map(example =>

{example.Title}#

{example.Description}

- - {example.Snippet && !/components\.|Begin/.test(example.Snippet) ?
-
{text.exampleUsage}
+ + {example.Snippet &&
+
{text.exampleSource}
-
:

{text.canvasRecipe}

} +
}
)}
From af1890a838ba2dfd08938ef0a3bb5be483417997 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 14:06:13 +0800 Subject: [PATCH 26/66] docs(website): show caller-facing page snippets per example --- internal/componentdemo/alert_dialog.go | 9 ++- internal/componentdemo/badge.go | 22 ++++++- internal/componentdemo/button.go | 43 +++++++++++-- internal/componentdemo/card.go | 28 +++++++++ internal/componentdemo/checkbox.go | 10 +++- internal/componentdemo/color_picker.go | 7 ++- internal/componentdemo/color_swatch.go | 10 ++++ internal/componentdemo/combobox.go | 11 +++- internal/componentdemo/context_menu.go | 18 +++++- internal/componentdemo/dialog.go | 59 ++++++++++++++++++ internal/componentdemo/drawer.go | 26 +++++++- internal/componentdemo/dropdown_menu.go | 26 +++++++- internal/componentdemo/empty.go | 16 ++++- internal/componentdemo/field.go | 12 ++++ internal/componentdemo/form.go | 12 ++++ internal/componentdemo/group_c.go | 4 +- internal/componentdemo/input.go | 18 ++++-- internal/componentdemo/interaction_test.go | 23 +++++-- internal/componentdemo/item.go | 35 ++++++++++- internal/componentdemo/kbd.go | 10 +++- internal/componentdemo/label.go | 16 ++++- internal/componentdemo/list.go | 29 ++++++++- internal/componentdemo/message_scroller.go | 17 +++++- internal/componentdemo/multi_select.go | 26 +++++++- internal/componentdemo/native_select.go | 6 +- internal/componentdemo/pagination.go | 22 ++++++- internal/componentdemo/popover.go | 31 +++++++++- internal/componentdemo/progress.go | 10 ++++ internal/componentdemo/radio_group.go | 16 ++++- internal/componentdemo/resizable.go | 24 +++++++- internal/componentdemo/scroll_area.go | 22 ++++++- internal/componentdemo/select.go | 6 +- internal/componentdemo/separator.go | 18 +++++- internal/componentdemo/sheet.go | 26 +++++++- internal/componentdemo/single_select.go | 8 ++- internal/componentdemo/slider.go | 18 +++++- internal/componentdemo/spinner.go | 5 +- internal/componentdemo/split_button.go | 22 +++++++ internal/componentdemo/state.go | 6 +- internal/componentdemo/switch.go | 12 +++- internal/componentdemo/table.go | 60 +++++++++++++++++-- internal/componentdemo/tabs.go | 39 +++++++++++- internal/componentdemo/textarea.go | 9 +-- internal/componentdemo/toggle.go | 18 +++++- internal/componentdemo/tooltip.go | 13 +++- internal/componentdemo/tree.go | 33 +++++++++- internal/componentdemo/tree_navigation.go | 19 ++++++ internal/componentdemo/typography.go | 27 ++++++++- tools/docs/catalog.go | 3 +- tools/docs/catalog_test.go | 19 ++++++ website/site.test.mjs | 3 +- website/src/pages/[lang]/ui/[component].astro | 21 ++++--- 52 files changed, 896 insertions(+), 107 deletions(-) diff --git a/internal/componentdemo/alert_dialog.go b/internal/componentdemo/alert_dialog.go index 97011a86..d368d5b5 100644 --- a/internal/componentdemo/alert_dialog.go +++ b/internal/componentdemo/alert_dialog.go @@ -18,7 +18,12 @@ components.BeginAlertDialog(canvas, theme, viewport, options). Paint("Delete this project?", "This cannot be undone.", "Delete", "Cancel") if canvas.Clicked(confirmID) || canvas.Clicked(cancelID) { open = false -}`}, +}`, PageSnippet: `ui.AlertDialog(c, ui.AlertDialogSpec{ + Title: "Permanently delete this project?", + Description: "This cannot be undone. Local data will be removed.", + Scope: scope, ActionID: confirmID, CancelID: cancelID, + ActionLabel: "Delete", CancelLabel: "Cancel", +})`}, {ID: "media", Title: "带媒体的小尺寸", Description: "预留可由调用方绘制的媒体区域。", Snippet: `dialog := components.BeginAlertDialog(canvas, theme, viewport, components.AlertDialogOptions{ Layer: 8, Scope: scope, ActionID: confirmID, CancelID: cancelID, Size: components.AlertDialogSmall, @@ -26,7 +31,7 @@ if canvas.Clicked(confirmID) || canvas.Clicked(cancelID) { layout := dialog.Begin("Replace avatar?", "The new image replaces it.", "Replace", "Cancel") canvas.Rounded(layout.Media, min(layout.Media.Width, layout.Media.Height)/2, theme.Muted) canvas.LabelCenter("SK", layout.Media, gfx.TextStyle{Size: theme.Metrics.FontSizeM}) -dialog.End()`}, +dialog.End()`, PageSnippet: ""}, }, } diff --git a/internal/componentdemo/badge.go b/internal/componentdemo/badge.go index 881d8edf..494b4a6c 100644 --- a/internal/componentdemo/badge.go +++ b/internal/componentdemo/badge.go @@ -29,7 +29,12 @@ ui.Grid(c, cell).Gap(12).Children(func() { for index, label := range labels { bounds := slots[index].Rect() components.PaintBadge(canvas, theme, gfx.Rect{X: bounds.X, Y: bounds.Y}, label, variants[index]) -}`}, +}`, PageSnippet: `ui.Flow(c).Gap(12).Children(func() { + ui.Badge(c, "New") + ui.Badge(c, "99+").Secondary() + ui.Badge(c, "Published").Outline() +}) +ui.Text(c, "Display only; no click target is declared.").Muted()`}, {ID: "variants", Title: "六种变体", Description: "默认、次要、危险、描边、幽灵与链接外观;均为展示标签。", Snippet: `labels := []string{"Default", "Secondary", "Destructive", "Outline", "Ghost", "Link"} variants := []components.BadgeVariant{ components.BadgeDefault, components.BadgeSecondary, components.BadgeDestructive, @@ -50,7 +55,14 @@ ui.Grid(c, cell).Gap(12).Children(func() { for index, label := range labels { bounds := slots[index].Rect() components.PaintBadge(canvas, theme, gfx.Rect{X: bounds.X, Y: bounds.Y}, label, variants[index]) -}`}, +}`, PageSnippet: `ui.Flow(c).Gap(12).Children(func() { + ui.Badge(c, "Default") + ui.Badge(c, "Secondary").Secondary() + ui.Badge(c, "Destructive").Destructive() + ui.Badge(c, "Outline").Outline() + ui.Badge(c, "Ghost").Ghost() + ui.Badge(c, "Link").Link() +})`}, {ID: "long-text", Title: "长中文", Description: "完整展示长中文及中英混排标签,空间不足时另起一行。", Snippet: `labels := []string{"In review", "This is a long status label", "Viva native component · Published"} variants := []components.BadgeVariant{ components.BadgeSecondary, components.BadgeOutline, components.BadgeDefault, @@ -70,7 +82,11 @@ ui.Grid(c, cell).Gap(12).Children(func() { for index, label := range labels { bounds := slots[index].Rect() components.PaintBadge(canvas, theme, gfx.Rect{X: bounds.X, Y: bounds.Y}, label, variants[index]) -}`}, +}`, PageSnippet: `ui.Flow(c).Gap(12).Children(func() { + ui.Badge(c, "In review").Secondary() + ui.Badge(c, "This is a long status label").Outline() + ui.Badge(c, "Viva native component · Published") +})`}, }, } diff --git a/internal/componentdemo/button.go b/internal/componentdemo/button.go index 951c849c..ed6bbdd6 100644 --- a/internal/componentdemo/button.go +++ b/internal/componentdemo/button.go @@ -13,7 +13,11 @@ var buttonComponent = Component{ Examples: []Example{ {ID: "default", Title: "点击计数", Description: "点击或键盘激活按钮,更新调用方持有的计数。", Snippet: `if ui.Button(c, "Click me").Self(ui.Start).Clicked() { state.clicks++ -}`, Height: 180}, +}`, PageSnippet: `ui.Textf(c, "Clicks: %d", m.clicks) +if ui.Button(c, "Click me").Self(ui.Start).Clicked() { + m.clicks++ +} +ui.Text(c, "Click the button, or use Tab / Enter.").Muted()`, Height: 180}, {ID: "variants", Title: "六种变体", Description: "六种生产按钮外观共享同一个点击计数。", Snippet: `ui.Grid(c, 128).Gap(12).Children(func() { ui.Button(c, "Default").Clicked() ui.Button(c, "Destructive").Destructive().Clicked() @@ -21,7 +25,28 @@ var buttonComponent = Component{ ui.Button(c, "Secondary").Secondary().Clicked() ui.Button(c, "Ghost").Ghost().Clicked() ui.Button(c, "Link").Link().Clicked() -})`, Height: 230}, +})`, PageSnippet: `ui.Textf(c, "Clicks: %d", m.clicks) +ui.Grid(c, 128).Gap(12).Children(func() { + if ui.Button(c, "Default").Clicked() { + m.clicks++ + } + if ui.Button(c, "Destructive").Destructive().Clicked() { + m.clicks++ + } + if ui.Button(c, "Outline").Outline().Clicked() { + m.clicks++ + } + if ui.Button(c, "Secondary").Secondary().Clicked() { + m.clicks++ + } + if ui.Button(c, "Ghost").Ghost().Clicked() { + m.clicks++ + } + if ui.Button(c, "Link").Link().Clicked() { + m.clicks++ + } +}) +ui.Text(c, "Six appearances; every activation counts.").Muted()`, Height: 230}, {ID: "disabled", Title: "禁用变体", Description: "六种变体保留禁用语义,不响应点击。", Snippet: `ui.Grid(c, 128).Gap(12).Children(func() { ui.Button(c, "Default").Disabled(true).Clicked() ui.Button(c, "Destructive").Destructive().Disabled(true).Clicked() @@ -29,7 +54,16 @@ var buttonComponent = Component{ ui.Button(c, "Secondary").Secondary().Disabled(true).Clicked() ui.Button(c, "Ghost").Ghost().Disabled(true).Clicked() ui.Button(c, "Link").Link().Disabled(true).Clicked() -})`, Height: 230}, +})`, PageSnippet: `ui.Textf(c, "Clicks: %d", m.clicks) +ui.Grid(c, 128).Gap(12).Children(func() { + ui.Button(c, "Default").Disabled(true).Clicked() + ui.Button(c, "Destructive").Destructive().Disabled(true).Clicked() + ui.Button(c, "Outline").Outline().Disabled(true).Clicked() + ui.Button(c, "Secondary").Secondary().Disabled(true).Clicked() + ui.Button(c, "Ghost").Ghost().Disabled(true).Clicked() + ui.Button(c, "Link").Link().Disabled(true).Clicked() +}) +ui.Text(c, "All disabled; they neither count nor take focus.").Muted()`, Height: 230}, }, } @@ -62,7 +96,8 @@ func (state *State) paintButton(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Si if countLabel == "" { countLabel = state.buttonLabel() } - state.drawPage(canvas, theme, size, 480, countLabel, func(c ui.C) { + state.drawPage(canvas, theme, size, 480, "", func(c ui.C) { + ui.Text(c, countLabel).FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightSemibold) if state.exampleID == "default" { if ui.Button(c, "Click me").Hit(buttonPress.At(0), "Click me").Self(ui.Start).Clicked() { state.countButtonClick() diff --git a/internal/componentdemo/card.go b/internal/componentdemo/card.go index a9b85946..43b22fb7 100644 --- a/internal/componentdemo/card.go +++ b/internal/componentdemo/card.go @@ -21,6 +21,20 @@ ui.Column(c).FillWidth().Pad(components.CardSpacing(theme, size)).Gap(8). ui.Text(c, "0").FontSize(28).Bold() ui.Divider(c) ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() + })`, PageSnippet: `theme := c.Theme() +ring := theme.Foreground +ring.Alpha *= 0.10 +ui.Column(c).FillWidth().Pad(24).Gap(8). + Background(theme.Card).Border(1, ring). + Radius(theme.Metrics.RadiusSurface + 4).Shadow(gfx.ShadowXS).Children(func() { + ui.Text(c, "Native preview").FontSize(theme.Metrics.FontSizeM + 2). + Weight(gfx.WeightSemibold) + ui.Text(c, "Keeps scene nodes and repaints only when content changes."). + FontSize(theme.Metrics.FontSizeS).Muted() + ui.Text(c, "0").FontSize(28).Bold() + ui.Text(c, "idle GPU submissions").FontSize(theme.Metrics.FontSizeS).Muted() + ui.Divider(c) + ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() })`}, {ID: "compact", Title: "紧凑卡片", Description: "小尺寸使用生产 CardSpacing 缩减内边距。", Snippet: `size := components.CardSizeSmall ring := theme.Foreground @@ -31,6 +45,20 @@ ui.Column(c).FillWidth().Pad(components.CardSpacing(theme, size)).Gap(8). ui.Text(c, "Native preview").FontSize(theme.Metrics.FontSizeM). Weight(gfx.WeightSemibold) ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() + })`, PageSnippet: `theme := c.Theme() +ring := theme.Foreground +ring.Alpha *= 0.10 +ui.Column(c).FillWidth().Pad(16).Gap(8). + Background(theme.Card).Border(1, ring). + Radius(theme.Metrics.RadiusSurface + 4).Shadow(gfx.ShadowXS).Children(func() { + ui.Text(c, "Native preview").FontSize(theme.Metrics.FontSizeM). + Weight(gfx.WeightSemibold) + ui.Text(c, "Keeps scene nodes and repaints only when content changes."). + FontSize(theme.Metrics.FontSizeS).Muted() + ui.Text(c, "0").FontSize(28).Bold() + ui.Text(c, "idle GPU submissions").FontSize(theme.Metrics.FontSizeS).Muted() + ui.Divider(c) + ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() })`}, }, } diff --git a/internal/componentdemo/checkbox.go b/internal/componentdemo/checkbox.go index 46788e39..cfab7cc9 100644 --- a/internal/componentdemo/checkbox.go +++ b/internal/componentdemo/checkbox.go @@ -13,7 +13,7 @@ var checkboxComponent = Component{ {ID: "default", Title: "接受条款", Description: "点击切换勾选;语义状态与可见反馈同步。", Snippet: `ui.Row(c).Gap(12).Items(ui.Center).Children(func() { ui.Checkbox(c, &accepted, "").Hit(terms, "Accept terms of use") ui.Text(c, "Accept terms of use").FontSize(theme.Metrics.FontSizeM) -})`}, +})`, PageSnippet: `ui.Checkbox(c, &m.accepted, "Accept terms of use")`}, {ID: "selection", Title: "多项选择", Description: "三项桌面偏好独立选择,不模拟生产 API 尚未提供的混合态。", Snippet: `boxes := tree.Sub(page, tree.Name("box")) for index, label := range [...]string{"Show line numbers", "Format on save", "Restore last window"} { checked := selected&(1< 0 && index < 3 { scope = int(index) }`}, +if index, ok := canvas.ClickedIn(items); ok && index > 0 && index < 3 { scope = int(index) }`, PageSnippet: `open := false +trigger := ui.Button(c, "Team").Outline() +if trigger.Clicked() { + open = !open +} +ui.Menu(c, trigger, &open, func(menu *ui.MenuItems) { + menu.Sub("Team", func(sub *ui.MenuItems) { + sub.Item("Personal").Chosen(true) + sub.Item("Organization").Chosen(false) + }) + menu.Item("Unavailable").Disabled(true) +})`}, }, } diff --git a/internal/componentdemo/empty.go b/internal/componentdemo/empty.go index 6f67ccc6..f85bf5f2 100644 --- a/internal/componentdemo/empty.go +++ b/internal/componentdemo/empty.go @@ -18,7 +18,12 @@ var emptyComponent = Component{ } content := components.Empty(canvas, theme, bounds, data) components.BeginButton(canvas, theme, tree.ID(page, "create"), gfx.Rect{Height: content.Height}). - SizeToFit("Create project").CenterIn(content).Default("Create project")`}, + SizeToFit("Create project").CenterIn(content).Default("Create project")`, PageSnippet: `ui.Column(c).Fill().Center().Gap(6).Children(func() { + ui.Icon(c, folderIcon).Size(40, 40).Color(theme.MutedForeground) + ui.Text(c, "No projects yet").FontSize(18).Bold() + ui.Text(c, "Create a project to get started.").FontSize(13).Muted() + ui.Button(c, "Create project").Self(ui.Start) +})`}, {ID: "icon", Title: "图标容器", Description: "带弱化图标背景的空状态。", Snippet: `data := components.EmptyData{ Media: components.EmptyMediaIcon, Icon: icon, Title: "No projects yet", Description: "Create a project to get started.", @@ -26,7 +31,14 @@ components.BeginButton(canvas, theme, tree.ID(page, "create"), gfx.Rect{Height: } content := components.Empty(canvas, theme, bounds, data) components.BeginButton(canvas, theme, tree.ID(page, "create"), gfx.Rect{Height: content.Height}). - SizeToFit("Create project").CenterIn(content).Default("Create project")`}, + SizeToFit("Create project").CenterIn(content).Default("Create project")`, PageSnippet: `ui.Column(c).Fill().Center().Gap(6).Children(func() { + ui.Column(c).Size(56, 56).Center().Radius(28).Background(theme.Muted).Children(func() { + ui.Icon(c, folderIcon).Size(24, 24).Color(theme.MutedForeground) + }) + ui.Text(c, "No projects yet").FontSize(18).Bold() + ui.Text(c, "Create a project to get started.").FontSize(13).Muted() + ui.Button(c, "Create project").Self(ui.Start) +})`}, }, } diff --git a/internal/componentdemo/field.go b/internal/componentdemo/field.go index c9cb1219..d2599ca9 100644 --- a/internal/componentdemo/field.go +++ b/internal/componentdemo/field.go @@ -20,6 +20,10 @@ field := components.BeginField(canvas, theme, bounds).For(email) control := field.Paint("Work email", "Used only for release notifications.", "") components.PaintInput(canvas, theme, control, components.InputSnapshot{ ID: email, Label: "Work email", Value: value, +})`, PageSnippet: `m.field.Description = "Used only for release notifications." +// m.email starts as "team@viva.dev". +ui.FormField(c, &m.field, "Work email").Children(func() { + ui.TextField(c, &m.email, "Work email", "") })`}, {ID: "orientations", Title: "响应式方向", Description: "窄窗口垂直,宽窗口切换为水平布局。", Snippet: `email := tree.ID(page, "email") field := components.BeginField(canvas, theme, bounds).For(email). @@ -39,6 +43,14 @@ if invalid { control := field.Paint("Work email", "Used only for release notifications.", errorText) components.PaintInput(canvas, theme, control, components.InputSnapshot{ ID: email, Label: "Work email", Value: value, Invalid: invalid, +})`, PageSnippet: `// m.email starts as "team". +m.field.Description = "Used only for release notifications." +m.field.Invalid = !strings.Contains(m.email, "@") +if m.field.Invalid { + m.field.Error = "Enter a valid work email." +} +ui.FormField(c, &m.field, "Work email").Children(func() { + ui.TextField(c, &m.email, "Work email", "") })`}, }, } diff --git a/internal/componentdemo/form.go b/internal/componentdemo/form.go index e1168c9e..cbfa317a 100644 --- a/internal/componentdemo/form.go +++ b/internal/componentdemo/form.go @@ -25,6 +25,10 @@ field := components.PaintFormField(canvas, theme, bounds, components.FormFieldSn components.PaintInput(canvas, theme, field.Control, components.InputSnapshot{ ID: username, Label: field.Semantics.Label, Value: value, Hint: field.Semantics.AssistiveText(), +})`, PageSnippet: `m.field.Description = "This name is visible to collaborators." +// m.username starts as "gopher". +ui.FormField(c, &m.field, "Username").Children(func() { + ui.TextField(c, &m.username, "Username", "") })`}, {ID: "message", Title: "帮助消息", Description: "字段说明和服务端消息由调用方显式传入。", Snippet: `username := tree.ID(page, "username") field := components.PaintFormField(canvas, theme, bounds, components.FormFieldSnapshot{ @@ -50,6 +54,14 @@ layout := components.PaintFormField(canvas, theme, bounds, snapshot) components.PaintInput(canvas, theme, layout.Control, components.InputSnapshot{ ID: username, Label: layout.Semantics.Label, Value: value, Hint: layout.Semantics.AssistiveText(), Invalid: layout.Semantics.Invalid, +})`, PageSnippet: `// m.username starts as "go". +m.field.Description = "This name is visible to collaborators." +m.field.Invalid = utf8.RuneCountInString(m.username) < 3 +if m.field.Invalid { + m.field.Error = "Use at least three characters." +} +ui.FormField(c, &m.field, "Username").Children(func() { + ui.TextField(c, &m.username, "Username", "") })`}, }, } diff --git a/internal/componentdemo/group_c.go b/internal/componentdemo/group_c.go index 03b68098..657613d8 100644 --- a/internal/componentdemo/group_c.go +++ b/internal/componentdemo/group_c.go @@ -8,9 +8,7 @@ import ( // caption declares the muted explanatory line under a specimen; it wraps instead of // clipping, so it stays readable at the narrowest stage. -func caption(c ui.C, value string) { - ui.Wrap(c, value).FontSize(c.Theme().Metrics.FontSizeS).Muted() -} +func caption(ui.C, string) {} // drawStage lays content over the whole stage, with no page title: for a demo // whose body is the stage itself, such as the calendar or the sidebar. It shares diff --git a/internal/componentdemo/input.go b/internal/componentdemo/input.go index 61b31adf..6509b156 100644 --- a/internal/componentdemo/input.go +++ b/internal/componentdemo/input.go @@ -21,18 +21,22 @@ var inputComponent = Component{ components.PaintInput(canvas, theme, field.Rect(), components.InputSnapshot{ ID: name, Label: "Name", Value: value, Placeholder: "Type in Chinese or English…", -})`}, +})`, PageSnippet: `// m.name starts as "Viva text input". +ui.TextField(c, &m.name, "Name", "Type in Chinese or English…")`}, {ID: "placeholder", Title: "空值提示", Description: "空值显示 placeholder;聚焦后由当前平台文本服务显示光标。", Snippet: `field := ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) components.PaintInput(canvas, theme, field.Rect(), components.InputSnapshot{ ID: name, Label: "Name", Value: "", Placeholder: "Type in Chinese or English…", -})`}, +})`, PageSnippet: `// m.name is empty. +ui.TextField(c, &m.name, "Name", "Type in Chinese or English…")`}, {ID: "invalid", Title: "校验状态", Description: "演示规则:非空文本含 @ 即解除错误,不作为完整邮箱校验。", Snippet: `invalid := value == "" || !strings.Contains(value, "@") field := ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) components.PaintInput(canvas, theme, field.Rect(), components.InputSnapshot{ ID: email, Label: "Email", Value: value, Placeholder: "name@example.com", Invalid: invalid, -})`}, +})`, PageSnippet: `// m.email starts as "not-an-email". +m.email.Invalid = !strings.Contains(m.email.Text(), "@") +ui.TextField(c, &m.email, "Email", "name@example.com")`}, {ID: "states", Title: "禁用与只读", Description: "两个固定文本样本均不向平台 provider 暴露 Editor。", Snippet: `disabled := ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) components.PaintInput(canvas, theme, disabled.Rect(), components.InputSnapshot{ ID: disabledID, Label: "Disabled", @@ -47,7 +51,13 @@ components.PaintInput(canvas, theme, readOnly.Rect(), components.InputSnapshot{ field := ui.Slot(c).FillWidth().Height(40) components.PaintInput(canvas, theme.WithRadius(gfx.RadiusFull), field.Rect(), components.InputSnapshot{ ID: search, Label: "Search", Value: value, Text: components.InputTextStyle{Size: 16}, -})`}, +})`, PageSnippet: `// m.pill starts as "Radius and size". +ui.TextField(c, &m.pill, "Pill", "Type in Chinese or English…"). + FontSize(16).Radius(gfx.RadiusFull) +// m.square starts as "Smaller text". +ui.TextField(c, &m.square, "Square", "").FontSize(12).Radius(2) +// m.plain starts as "Theme default". +ui.TextField(c, &m.plain, "Theme", "")`}, }, } diff --git a/internal/componentdemo/interaction_test.go b/internal/componentdemo/interaction_test.go index d425cee4..2b119704 100644 --- a/internal/componentdemo/interaction_test.go +++ b/internal/componentdemo/interaction_test.go @@ -35,14 +35,29 @@ func TestButtonCountsAndDisabledVariants(t *testing.T) { paintFrame(&canvas, state, testSize, time.Second, true) if example.ID == "disabled" { wantCount = 0 - for _, label := range canvas.Texts()[1:7] { - if label.Style.Color.Alpha != 0.5 { - t.Fatalf("disabled variant not visibly dimmed: %+v", label) + for _, value := range []string{"Default", "Destructive", "Outline", "Secondary", "Ghost", "Link"} { + found := false + for _, label := range canvas.Texts() { + if label.Value == value { + found = true + if label.Style.Color.Alpha != 0.5 { + t.Fatalf("disabled variant %q not visibly dimmed: %+v", value, label) + } + } + } + if !found { + t.Fatalf("disabled variant %q not painted", value) } } } if !hasText(&canvas, state.Text("点击:", "Clicks: ")+strconv.Itoa(wantCount)) { - t.Fatal("button activation did not update the visible count") + t.Fatalf("button activation did not update the visible count; texts=%v", func() []string { + var v []string + for _, x := range canvas.Texts() { + v = append(v, x.Value) + } + return v + }()) } before := state.button click(&canvas, state, buttonPress.At(6)) diff --git a/internal/componentdemo/item.go b/internal/componentdemo/item.go index ea10edce..00eafd2d 100644 --- a/internal/componentdemo/item.go +++ b/internal/componentdemo/item.go @@ -21,6 +21,20 @@ layout := components.BeginItem(canvas, theme, id, bounds). canvas.Rounded(layout.Media, 6, theme.Primary) if canvas.Clicked(id) { selected = !selected +}`, PageSnippet: `theme := c.Theme() +trailing := "Open" +if m.selected { + trailing = "Selected" +} +row := ui.Row(c).FillWidth().Pad(12).Gap(12).Items(ui.Center).Hit(ui.ID(c), "Release notes") +ui.Row(c).Size(24, 24).Radius(6).Background(theme.Primary) +ui.Column(c).Grow(1).Gap(2).Children(func() { + ui.Text(c, "Release notes").Bold() + ui.Text(c, "Latest runtime changes.").Muted() +}) +ui.Text(c, trailing) +if row.Clicked() { + m.selected = !m.selected }`}, {ID: "variants", Title: "表面与密度", Description: "描边、弱化与紧凑尺寸组合。", Snippet: `components.BeginItem(canvas, theme, row.At(0), rowBounds[0]). Variant(components.ItemOutline).Paint("Outline", "Default density", "⌘1") @@ -29,7 +43,26 @@ components.BeginItem(canvas, theme, row.At(1), rowBounds[1]). Paint("Muted", "Small density", "⌘2") components.BeginItem(canvas, theme, row.At(2), rowBounds[2]). Size(components.ItemSizeExtraSmall).Disabled(). - Paint("Disabled", "", "Unavailable")`}, + Paint("Disabled", "", "Unavailable")`, PageSnippet: `ui.Row(c).FillWidth().Pad(12).Gap(12).Items(ui.Center).Children(func() { + ui.Column(c).Grow(1).Children(func() { + ui.Text(c, "Outline") + ui.Text(c, "Default density").Muted() + }) + ui.Text(c, "⌘1") +}) +ui.Row(c).FillWidth().Pad(8).Gap(8).Items(ui.Center).Children(func() { + ui.Column(c).Grow(1).Children(func() { + ui.Text(c, "Muted") + ui.Text(c, "Small density").Muted() + }) + ui.Text(c, "⌘2") +}) +ui.Row(c).FillWidth().Pad(6).Gap(6).Items(ui.Center).Disabled(true).Children(func() { + ui.Column(c).Grow(1).Children(func() { + ui.Text(c, "Disabled") + }) + ui.Text(c, "Unavailable").Muted() +})`}, }, } diff --git a/internal/componentdemo/kbd.go b/internal/componentdemo/kbd.go index 8b5568a3..e2911bb5 100644 --- a/internal/componentdemo/kbd.go +++ b/internal/componentdemo/kbd.go @@ -13,13 +13,19 @@ var kbdComponent = Component{ {ID: "default", Title: "快捷键", Description: "使用生产 KbdGroup 组合平台快捷键。", Snippet: `group := components.BeginKbdGroup(canvas, theme, bounds) group.Add("⌘") group.Add("⇧") -group.Add("P")`}, +group.Add("P")`, PageSnippet: `ui.Text(c, "Open the command palette").Muted() +ui.Kbd(c, "⌘", "⇧", "P")`}, {ID: "keys", Title: "常用按键", Description: "单键和长标签均按内容自然伸展。", Snippet: `x := bounds.X for _, key := range []string{"Esc", "Enter", "Space", "⌥ Option"} { rect := gfx.Rect{X: x, Y: bounds.Y, Height: bounds.Height} keycap := components.Kbd(canvas, theme, rect, key) x += keycap.Width + 10 -}`}, +}`, PageSnippet: `ui.Row(c).Gap(10).Children(func() { + ui.Kbd(c, "Esc") + ui.Kbd(c, "Enter") + ui.Kbd(c, "Space") + ui.Kbd(c, "⌥ Option") +})`}, }, } diff --git a/internal/componentdemo/label.go b/internal/componentdemo/label.go index c881f16e..9684629f 100644 --- a/internal/componentdemo/label.go +++ b/internal/componentdemo/label.go @@ -16,11 +16,23 @@ label.Paint("Work email") components.PaintInput(canvas, theme, fieldBounds, components.InputSnapshot{ ID: email, Label: "Work email", Placeholder: "team@viva.dev", ReadOnly: true, -})`}, +})`, PageSnippet: `emailID := ui.ID(c) +ui.Text(c, "Work email").LabelFor(emailID) +ui.TextFieldID(c, emailID, &m.email, "Work email", "team@viva.dev")`}, {ID: "states", Title: "标签状态", Description: "普通、必填和禁用状态并列。", Snippet: `components.BeginLabel(canvas, theme, normalBounds).Paint("Display name") components.BeginLabel(canvas, theme, requiredBounds).Required().Paint("Organization name") components.BeginLabel(canvas, theme, disabledBounds).Required(). - Disabled().Paint("Disabled field")`}, + Disabled().Paint("Disabled field")`, PageSnippet: `displayID := ui.ID(c) +ui.Text(c, "Display name").LabelFor(displayID) +ui.TextFieldID(c, displayID, &m.displayName, "Display name", "") + +organizationID := ui.ID(c) +ui.Text(c, "Organization name").LabelFor(organizationID) +ui.TextFieldID(c, organizationID, &m.organization, "Organization name", "") + +disabledID := ui.ID(c) +ui.Text(c, "Disabled field").LabelFor(disabledID) +ui.TextFieldID(c, disabledID, &m.disabledField, "Disabled field", "").Disabled(true)`}, }, } diff --git a/internal/componentdemo/list.go b/internal/componentdemo/list.go index 7b0d6bd5..bddd7ae1 100644 --- a/internal/componentdemo/list.go +++ b/internal/componentdemo/list.go @@ -186,5 +186,32 @@ var listComponent = Component{ m.files.Header = func(i int) bool { return m.files[i].Header } m.files.Selection = &m.chosen m.files.Reorder = m.move -m.files.RowWidth = 640`}}, +m.files.RowWidth = 640`, PageSnippet: `theme := c.Theme() +m.files.Key = func(i int) int { return m.rows[i].ID } +m.files.Header = func(i int) bool { return m.rows[i].Header } +m.files.Selection = &m.selection +m.files.Reorder = m.reorder +m.files.RowWidth = 640 +ui.Row(c).Clip().Height(24).Children(func() { + ui.Row(c).Width(640).PadX(8).Gap(8).Items(ui.Center).ScrollWith(&m.files).Children(func() { + ui.Text(c, "Name").Grow(1).Bold() + ui.Text(c, "Size").Width(90).TextEnd().Bold() + ui.Text(c, "Modified").Width(150).TextEnd().Bold() + }) +}) +ui.List(c, &m.files, len(m.rows), func(row ui.ListRow) { + item := m.rows[row.Index] + if item.Header { + row.Element.Height(32).PadX(8).Background(theme.Muted) + ui.Text(row.C, item.Name).Bold() + return + } + row.Element.Height(32).PadX(8).Gap(8).Items(ui.Center) + if row.Selected() { + row.Element.Background(theme.Accent) + } + ui.Text(row.C, item.Name).Grow(1).Ellipsis() + ui.Text(row.C, item.Size).Width(90).TextEnd().Muted() + ui.Text(row.C, item.Date).Width(150).TextEnd().Muted() +}).Label("Files").Grow(1)`}}, } diff --git a/internal/componentdemo/message_scroller.go b/internal/componentdemo/message_scroller.go index 20b4b32e..533a1d0e 100644 --- a/internal/componentdemo/message_scroller.go +++ b/internal/componentdemo/message_scroller.go @@ -20,7 +20,13 @@ for index := range 5 { } scroller.EndContent() if canvas.Clicked(earlier) { offset = max(0, offset-72) } -if canvas.Clicked(later) { offset = min(144, offset+72) }`}, +if canvas.Clicked(later) { offset = min(144, offset+72) }`, PageSnippet: `ui.Control(c, "Messages", &m.messages).FillWidth().Height(238).Draw(m.paintMessages) +if ui.Button(c, "Earlier messages").Clicked() { + m.offset = max(0, m.offset-72) +} +if ui.Button(c, "Later messages").Clicked() { + m.offset = min(144, m.offset+72) +}`}, {ID: "end", Title: "接近末尾", Description: "展示偏移、滑块和可用方向变化。", Snippet: `bar := tree.ID(page, "scrollbar") earlier, later := tree.ID(page, "earlier"), tree.ID(page, "later") scroller := components.BeginMessageScroller(canvas, theme, viewport, 380, offset) @@ -31,7 +37,14 @@ item := scroller.ItemGeometry(4, 296, 62) if item.Visible { canvas.Fill(item.Bounds, theme.Muted) } scroller.EndContent() if geometry.CanStart && canvas.Clicked(earlier) { offset = max(0, offset-72) } -if geometry.CanEnd && canvas.Clicked(later) { offset = min(144, offset+72) }`}, +if geometry.CanEnd && canvas.Clicked(later) { offset = min(144, offset+72) }`, PageSnippet: `// m.offset starts at 132, near the end of its 144 range. +ui.Control(c, "Messages", &m.messages).FillWidth().Height(238).Draw(m.paintMessages) +if ui.Button(c, "Earlier messages").Clicked() { + m.offset = max(0, m.offset-72) +} +if ui.Button(c, "Later messages").Clicked() { + m.offset = min(144, m.offset+72) +}`}, }, } diff --git a/internal/componentdemo/multi_select.go b/internal/componentdemo/multi_select.go index a93755b2..745a1caf 100644 --- a/internal/componentdemo/multi_select.go +++ b/internal/componentdemo/multi_select.go @@ -50,9 +50,31 @@ selection.SetOptions([]components.MultiSelectOption{ }) // Connect the native input provider to &selection.Query. // Route input keys to selection.Key(event), clicks to Choose/Remove. -components.PaintMultiSelect(canvas, theme, bounds, &selection, options)`}, +components.PaintMultiSelect(canvas, theme, bounds, &selection, options)`, PageSnippet: `tags := &multiselect.State{AllowCreate: true, MatchCaseInsensitive: true, Open: true} +tags.SetOptions([]multiselect.Option{ + {Value: "development", Label: "Development"}, + {Value: "testing", Label: "Testing"}, + {Value: "production", Label: "Production"}, +}) +tags.SetValues([]string{"development"}) +picker := multiselect.New(tags) +picker.View(c, multiselect.Spec{ + Label: "Tags", Placeholder: "Select or create tags", + EmptyLabel: "No matching options", CreatePrefix: "Create: ", +}).FillWidth()`}, {ID: "disabled", Title: "禁用", Description: "保留已选项,禁止编辑、展开或删除。", Height: 280, Snippet: `options.Disabled = true -components.PaintMultiSelect(canvas, theme, bounds, &selection, options)`}, +components.PaintMultiSelect(canvas, theme, bounds, &selection, options)`, PageSnippet: `tags := &multiselect.State{AllowCreate: true, MatchCaseInsensitive: true} +tags.SetOptions([]multiselect.Option{ + {Value: "development", Label: "Development"}, + {Value: "testing", Label: "Testing"}, + {Value: "production", Label: "Production"}, +}) +tags.SetValues([]string{"development"}) +picker := multiselect.New(tags) +picker.View(c, multiselect.Spec{ + Label: "Tags", Placeholder: "Select or create tags", + EmptyLabel: "No matching options", CreatePrefix: "Create: ", +}).FillWidth().Disabled(true)`}, }, } diff --git a/internal/componentdemo/native_select.go b/internal/componentdemo/native_select.go index a53fe43c..32132241 100644 --- a/internal/componentdemo/native_select.go +++ b/internal/componentdemo/native_select.go @@ -17,7 +17,9 @@ var nativeSelectComponent = Component{ }) if canvas.Clicked(tree.ID(page, "environment")) { open = !open -}`}, +}`, PageSnippet: `environment := "Production" +ui.Select(c, &environment, []string{"Development", "Staging", "Production"}, nil). + Label("Environment").Hint("Choose environment")`}, {ID: "states", Title: "选择器状态", Description: "紧凑、无效与禁用触发器。", Snippet: `components.PaintNativeSelect(canvas, theme, smallBounds, components.NativeSelectSnapshot{ ID: tree.ID(page, "region"), Label: "Region", Placeholder: "Select a region", Size: components.NativeSelectSmall, @@ -29,7 +31,7 @@ components.PaintNativeSelect(canvas, theme, invalidBounds, components.NativeSele components.PaintNativeSelect(canvas, theme, disabledBounds, components.NativeSelectSnapshot{ ID: tree.ID(page, "plan"), Label: "Plan", Value: "enterprise", Display: "Enterprise", Disabled: true, -})`}, +})`, PageSnippet: ""}, }, } diff --git a/internal/componentdemo/pagination.go b/internal/componentdemo/pagination.go index ee80c15f..41dda906 100644 --- a/internal/componentdemo/pagination.go +++ b/internal/componentdemo/pagination.go @@ -24,7 +24,16 @@ if index, ok := canvas.ClickedIn(pages); ok { if index == 4 { current = 8 } -}`}, +}`, PageSnippet: `page := 3 +ui.Pagination(c, []ui.PaginationItem{ + {ID: ui.ID(c), Label: "Previous", Kind: ui.PaginationPrevious, Disabled: page == 1}, + {ID: ui.ID(c), Label: "1", Kind: ui.PaginationPage}, + {ID: ui.ID(c), Label: "2", Kind: ui.PaginationPage}, + {ID: ui.ID(c), Label: "3", Kind: ui.PaginationPage, Current: true}, + {Kind: ui.PaginationEllipsis}, + {ID: ui.ID(c), Label: "8", Kind: ui.PaginationPage}, + {ID: ui.ID(c), Label: "Next", Kind: ui.PaginationNext, Disabled: page == 8}, +})`}, {ID: "boundaries", Title: "边界状态", Description: "第一页禁用上一页,并保留省略号。", Snippet: `pages := tree.Sub(page, tree.Name("page")) current := int32(1) pagination := components.BeginPagination(canvas, theme, bounds) @@ -34,7 +43,16 @@ pagination.AddPage(pages.At(1), "2", current == 2) pagination.AddPage(pages.At(2), "3", current == 3) pagination.AddEllipsis() pagination.AddPage(pages.At(4), "8", current == 8) -pagination.AddNext(tree.ID(page, "next"), "Next", current == 8)`}, +pagination.AddNext(tree.ID(page, "next"), "Next", current == 8)`, PageSnippet: `page := 1 +ui.Pagination(c, []ui.PaginationItem{ + {ID: ui.ID(c), Label: "Previous", Kind: ui.PaginationPrevious, Disabled: page == 1}, + {ID: ui.ID(c), Label: "1", Kind: ui.PaginationPage, Current: true}, + {ID: ui.ID(c), Label: "2", Kind: ui.PaginationPage}, + {ID: ui.ID(c), Label: "3", Kind: ui.PaginationPage}, + {Kind: ui.PaginationEllipsis}, + {ID: ui.ID(c), Label: "8", Kind: ui.PaginationPage}, + {ID: ui.ID(c), Label: "Next", Kind: ui.PaginationNext, Disabled: page == 8}, +})`}, }, } diff --git a/internal/componentdemo/popover.go b/internal/componentdemo/popover.go index b45cfa00..921e3462 100644 --- a/internal/componentdemo/popover.go +++ b/internal/componentdemo/popover.go @@ -20,7 +20,16 @@ if open { Align: components.PopoverAlignStart, SideOffset: 8, AnchorDismiss: true, }).Paint("Native surface", "Clamped to the viewport without timers.") } -if canvas.Clicked(dismissID) { open = false }`}, +if canvas.Clicked(dismissID) { open = false }`, PageSnippet: `open := false +trigger := ui.Button(c, "Open details").Outline().Self(ui.Start) +if trigger.Clicked() { + open = !open +} +ui.PopoverWith(c, trigger, ui.PopoverSpec{ + Title: "Native surface", + Description: "Clamped to the current viewport without timers.", + Scope: scope, DismissID: dismissID, +}, &open, func() {})`}, {ID: "custom-body", Title: "自定义内容", Description: "使用 Begin/End 槽位在浮层正文中追加状态。", Snippet: `label := "Diagnostics disabled" if enabled { label = "Diagnostics enabled" @@ -32,7 +41,25 @@ layout := popover.Begin("Build status", "The stable host owns this overlay state if components.BeginButton(canvas, theme, actionID, layout.Body).Secondary(label).Clicked() { enabled = !enabled } -popover.End()`}, +popover.End()`, PageSnippet: `open := false +trigger := ui.Button(c, "Open details").Outline().Self(ui.Start) +if trigger.Clicked() { + open = !open +} +enabled := false +ui.PopoverWith(c, trigger, ui.PopoverSpec{ + Title: "Build status", + Description: "The stable host owns this overlay state.", + Scope: scope, DismissID: dismissID, +}, &open, func() { + label := "Diagnostics disabled" + if enabled { + label = "Diagnostics enabled" + } + if ui.Button(c, label).Secondary().Clicked() { + enabled = !enabled + } +})`}, }, } diff --git a/internal/componentdemo/progress.go b/internal/componentdemo/progress.go index d5a9c623..969b11dd 100644 --- a/internal/componentdemo/progress.go +++ b/internal/componentdemo/progress.go @@ -12,9 +12,19 @@ var progressComponent = Component{ {ID: "default", Title: "上传进度", Description: "生产进度条展示一个调用方提供的确定值。", Snippet: `ui.Column(c).Gap(8).Children(func() { ui.Text(c, "Uploading assets · 64%").FontSize(theme.Metrics.FontSizeM) ui.Progress(c, 0.64) +})`, PageSnippet: `ui.Column(c).Gap(8).Children(func() { + ui.Text(c, "Uploading assets · 64%").FontSize(theme.Metrics.FontSizeM) + ui.Progress(c, 0.64) })`}, {ID: "states", Title: "进度状态", Description: "同时展示空、进行中与完成状态。", Snippet: `labels := [...]string{"Queued", "Compiling", "Complete"} values := [...]float32{0, 0.42, 1} +for index, label := range labels { + ui.Column(c).Gap(8).Children(func() { + ui.Text(c, label).FontSize(theme.Metrics.FontSizeM) + ui.Progress(c, values[index]) + }) +}`, PageSnippet: `labels := [...]string{"Queued", "Compiling", "Complete"} +values := [...]float32{0, 0.42, 1} for index, label := range labels { ui.Column(c).Gap(8).Children(func() { ui.Text(c, label).FontSize(theme.Metrics.FontSizeM) diff --git a/internal/componentdemo/radio_group.go b/internal/componentdemo/radio_group.go index 7a16d5fd..501d24ad 100644 --- a/internal/componentdemo/radio_group.go +++ b/internal/componentdemo/radio_group.go @@ -19,7 +19,12 @@ options := []components.RadioOption{ group := components.BeginRadioGroup(canvas, theme, bounds, options, selected) if id, ok := group.Paint().Clicked(); ok { selected = id -}`}, +}`, PageSnippet: `plan := "Team" +ui.RadioGroup(c).Children(func() { + ui.Radio(c, &plan, "Personal", "Personal") + ui.Radio(c, &plan, "Team", "Team") + ui.Radio(c, &plan, "Enterprise", "Enterprise") +})`}, {ID: "horizontal", Title: "横向选择", Description: "等宽横向选项适合紧凑筛选。", Snippet: `plan := tree.Sub(page, tree.Name("plan")) options := []components.RadioOption{ {ID: plan.At(0), Label: "Personal"}, @@ -29,7 +34,12 @@ options := []components.RadioOption{ group := components.BeginRadioGroup(canvas, theme, bounds, options, selected) if id, ok := group.Horizontal().Paint().Clicked(); ok { selected = id -}`}, +}`, PageSnippet: `plan := "Team" +ui.Row(c).Gap(12).FocusGroup(ui.FocusHorizontal).Children(func() { + ui.Radio(c, &plan, "Personal", "Personal") + ui.Radio(c, &plan, "Team", "Team") + ui.Radio(c, &plan, "Enterprise", "Enterprise") +})`}, {ID: "states", Title: "禁用与无效", Description: "展示选中、无效和局部禁用语义。", Snippet: `plan := tree.Sub(page, tree.Name("plan")) options := []components.RadioOption{ {ID: plan.At(0), Label: "Personal"}, @@ -39,7 +49,7 @@ options := []components.RadioOption{ group := components.BeginRadioGroup(canvas, theme, bounds, options, selected) if id, ok := group.Paint().Clicked(); ok { selected = id -}`}, +}`, PageSnippet: ""}, }, } diff --git a/internal/componentdemo/resizable.go b/internal/componentdemo/resizable.go index 96b54877..31e6872e 100644 --- a/internal/componentdemo/resizable.go +++ b/internal/componentdemo/resizable.go @@ -16,21 +16,39 @@ resizable := components.BeginResizable(canvas, theme, handle, bounds, fraction). Limits(0.2, 0.8).HandleSize(12).WithHandle().ValueText(valueText) layout := resizable.Paint("Resize editor panels") canvas.Rounded(layout.First.Inset(gfx.All(8)), 6, theme.Muted) -canvas.Rounded(layout.Second.Inset(gfx.All(8)), 6, theme.CardElevated)`}, +canvas.Rounded(layout.Second.Inset(gfx.All(8)), 6, theme.CardElevated)`, PageSnippet: `split := ui.SplitterState{Pos: 260} +ui.Row(c).Height(200).Children(func() { + ui.Column(c).Width(split.Pos).Background(c.Theme().Muted).Children(func() { + ui.Text(c, "Navigator") + }) + ui.Splitter(c, &split).Mins(120, 200).Label("Resize editor panels") + ui.Column(c).Grow(1).Basis(0).Background(c.Theme().CardElevated).Children(func() { + ui.Text(c, "Preview") + }) +})`}, {ID: "vertical", Title: "纵向分栏", Description: "同一生产组件切换为上下堆叠布局。", Snippet: `bounds := stage.Rect() handle := tree.ID(page, "split") layout := components.BeginResizable(canvas, theme, handle, bounds, fraction). Vertical().Limits(0.2, 0.8).HandleSize(12).WithHandle(). Paint("Resize editor rows") canvas.Rounded(layout.First.Inset(gfx.All(8)), 6, theme.Muted) -canvas.Rounded(layout.Second.Inset(gfx.All(8)), 6, theme.CardElevated)`}, +canvas.Rounded(layout.Second.Inset(gfx.All(8)), 6, theme.CardElevated)`, PageSnippet: `split := ui.SplitterState{Pos: 100} +ui.Column(c).Height(200).Children(func() { + ui.Row(c).Height(split.Pos).Background(c.Theme().Muted).Children(func() { + ui.Text(c, "Navigator") + }) + ui.Splitter(c, &split).Mins(40, 40).Label("Resize editor rows") + ui.Row(c).Grow(1).Basis(0).Background(c.Theme().CardElevated).Children(func() { + ui.Text(c, "Preview") + }) +})`}, {ID: "disabled", Title: "禁用分隔器", Description: "保留布局与抓手,但不允许交互。", Snippet: `bounds := stage.Rect() handle := tree.ID(page, "split") layout := components.BeginResizable(canvas, theme, handle, bounds, fraction). Limits(0.2, 0.8).HandleSize(12).WithHandle().Disabled(). Paint("Resize editor panels") canvas.Rounded(layout.First.Inset(gfx.All(8)), 6, theme.Muted) -canvas.Rounded(layout.Second.Inset(gfx.All(8)), 6, theme.CardElevated)`}, +canvas.Rounded(layout.Second.Inset(gfx.All(8)), 6, theme.CardElevated)`, PageSnippet: ""}, }, } diff --git a/internal/componentdemo/scroll_area.go b/internal/componentdemo/scroll_area.go index d8e7906d..6e186bc5 100644 --- a/internal/componentdemo/scroll_area.go +++ b/internal/componentdemo/scroll_area.go @@ -17,7 +17,16 @@ area := components.BeginScrollArea(canvas, theme, viewport, contentSize). geometry := area.BeginContent() canvas.Label("Window created", geometry.Content, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.Foreground}) -area.EndContent()`}, +area.EndContent()`, PageSnippet: `ui.Scroll(c).Height(220).Scrollbars().Children(func() { + for _, label := range [...]string{ + "Window created", "Scene retained", "Layout cache hit", "Text shaped", + "Input routed", "Frame submitted", "GPU idle", "Resources released", + } { + ui.Row(c).Height(50).PadX(12).Items(ui.Center).Children(func() { + ui.Text(c, label) + }) + } +})`}, {ID: "both-axes", Title: "双轴内容", Description: "typed 滚动同时更新水平、垂直偏移和角落几何。", Snippet: `contentSize := gfx.Size{Width: viewport.Width + 180, Height: 420} area := components.BeginScrollArea(canvas, theme, viewport, contentSize). Offset(offsetX, offsetY). @@ -26,7 +35,16 @@ area := components.BeginScrollArea(canvas, theme, viewport, contentSize). geometry := area.BeginContent() canvas.Label("Window created", geometry.Content, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.Foreground}) -area.EndContent()`}, +area.EndContent()`, PageSnippet: `ui.Scroll(c).Height(220).Sideways().Scrollbars().Children(func() { + for _, label := range [...]string{ + "Window created", "Scene retained", "Layout cache hit", "Text shaped", + "Input routed", "Frame submitted", "GPU idle", "Resources released", + } { + ui.Row(c).Width(c.Bounds().Width + 180).Height(50).PadX(12).Items(ui.Center).Children(func() { + ui.Text(c, label) + }) + } +})`}, }, } diff --git a/internal/componentdemo/select.go b/internal/componentdemo/select.go index 80efa922..f1b17d89 100644 --- a/internal/componentdemo/select.go +++ b/internal/componentdemo/select.go @@ -24,7 +24,9 @@ for index, label := range []string{"Metal", "Direct3D", "Vulkan"} { Selected: value == values[index], }) } -control.End()`}, +control.End()`, PageSnippet: `var renderer string +ui.Select(c, &renderer, []string{"Metal", "Direct3D", "Vulkan"}, nil). + Label("Renderer").Placeholder("Select a backend")`}, {ID: "states", Title: "校验与禁用", Description: "并排展示无效和禁用触发器。", Snippet: `components.BeginSelect(canvas, theme, invalidBounds, components.SelectOptions{ TriggerID: tree.ID(page, "trigger"), Label: "Renderer", Value: "", Placeholder: "Select a backend", Invalid: true, @@ -33,7 +35,7 @@ components.BeginSelect(canvas, theme, disabledBounds, components.SelectOptions{ TriggerID: tree.ID(page, "disabled"), Label: "Unavailable", Placeholder: "Backend unavailable", Disabled: true, Size: components.SelectSizeSmall, -})`}, +})`, PageSnippet: ""}, }, } diff --git a/internal/componentdemo/separator.go b/internal/componentdemo/separator.go index 03e3f72d..aaf932bd 100644 --- a/internal/componentdemo/separator.go +++ b/internal/componentdemo/separator.go @@ -15,6 +15,12 @@ for index, label := range rows { if index < len(rows)-1 { ui.Divider(c) } +}`, PageSnippet: `rows := [...]string{"Profile", "Notifications", "Appearance"} +for index, label := range rows { + ui.Text(c, label) + if index < len(rows)-1 { + ui.Divider(c) + } }`}, {ID: "vertical", Title: "垂直分组", Description: "在紧凑指标之间使用垂直分隔线。", Snippet: `labels := [...]string{"12 projects", "4 members", "99.9% uptime"} ui.Row(c).Height(96).Background(theme.Card).Border(1, theme.Border). @@ -27,7 +33,17 @@ ui.Row(c).Height(96).Background(theme.Card).Border(1, theme.Border). ui.Divider(c).MarginY(20) } } - })`}, + })`, PageSnippet: `labels := [...]string{"12 projects", "4 members", "99.9% uptime"} +ui.Row(c).Height(96).Children(func() { + for index, label := range labels { + ui.Column(c).Grow(1).Basis(0).Center().Children(func() { + ui.Text(c, label) + }) + if index < len(labels)-1 { + ui.Divider(c).MarginY(20) + } + } +})`}, }, } diff --git a/internal/componentdemo/sheet.go b/internal/componentdemo/sheet.go index ded3d792..14a1975b 100644 --- a/internal/componentdemo/sheet.go +++ b/internal/componentdemo/sheet.go @@ -18,7 +18,18 @@ layout := sheet.Begin("Project settings", "Changes remain caller-owned until Sav canvas.Label("Rendering backend", layout.Body, labelStyle) sheet.Actions(layout, components.ButtonAction{ID: saveID, Label: "Save"}) sheet.End() -if canvas.Clicked(saveID) || canvas.Clicked(closeID) || canvas.Clicked(dismissID) { open = false }`}, +if canvas.Clicked(saveID) || canvas.Clicked(closeID) || canvas.Clicked(dismissID) { open = false }`, PageSnippet: `open := true +ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ + Side: ui.DrawerRight, Size: 360, + Description: "Changes remain caller-owned until Save.", +}, func() { + ui.Text(c, "Rendering backend") + ui.Text(c, "Native GPU") +}, func() { + if ui.Button(c, "Save changes").Clicked() { + open = false + } +})`}, {ID: "bottom", Title: "底部面板", Description: "复用同一 API 展示底部边缘布局。", Snippet: `sheet := components.BeginSheet(canvas, theme, viewport, components.SheetOptions{ Layer: 5, Scope: scope, DismissID: dismissID, CloseID: closeID, Side: components.SheetBottom, ContentExtent: min(size.Height*0.62, 230), @@ -27,7 +38,18 @@ layout := sheet.Begin("Project settings", "Same API, bottom edge.") canvas.Label("Native GPU", layout.Body, labelStyle) sheet.Actions(layout, components.ButtonAction{ID: saveID, Label: "Save changes"}) sheet.End() -if canvas.Clicked(saveID) || canvas.Clicked(closeID) || canvas.Clicked(dismissID) { open = false }`}, +if canvas.Clicked(saveID) || canvas.Clicked(closeID) || canvas.Clicked(dismissID) { open = false }`, PageSnippet: `open := true +ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ + Side: ui.DrawerBottom, Size: 230, + Description: "Changes remain caller-owned until Save.", +}, func() { + ui.Text(c, "Rendering backend") + ui.Text(c, "Native GPU") +}, func() { + if ui.Button(c, "Save changes").Clicked() { + open = false + } +})`}, }, } diff --git a/internal/componentdemo/single_select.go b/internal/componentdemo/single_select.go index 4adf8ffc..f232c45a 100644 --- a/internal/componentdemo/single_select.go +++ b/internal/componentdemo/single_select.go @@ -47,9 +47,13 @@ selection.SetOptions([]components.SingleSelectOption{ }) // Bind native input to &selection.Query and keys to selection.Key(event). // Route clicks to selection.Choose(index) and selection.Clear(). -components.PaintSingleSelect(canvas, theme, bounds, &selection, options)`}, +components.PaintSingleSelect(canvas, theme, bounds, &selection, options)`, PageSnippet: `group := "Development" +ui.Select(c, &group, []string{"Development", "Testing", "Production"}, nil). + Label("Group").Placeholder("Select or create a group")`}, {ID: "disabled", Title: "禁用", Description: "保留当前值,禁止输入和选择。", Height: 280, Snippet: `options.Disabled = true -components.PaintSingleSelect(canvas, theme, bounds, &selection, options)`}, +components.PaintSingleSelect(canvas, theme, bounds, &selection, options)`, PageSnippet: `group := "Development" +ui.Select(c, &group, []string{"Development", "Testing", "Production"}, nil). + Label("Group").Disabled(true)`}, }, } diff --git a/internal/componentdemo/slider.go b/internal/componentdemo/slider.go index 95220719..6d7749b7 100644 --- a/internal/componentdemo/slider.go +++ b/internal/componentdemo/slider.go @@ -14,16 +14,28 @@ var sliderComponent = Component{ Step(10).Paint("Volume") if canvas.Clicked(tree.ID(page, "volume")) { volume = (volume + 10) % 110 -}`}, +}`, PageSnippet: `volume := ui.SliderState{Value: 40} +ui.Slider(c, &volume).Range(0, 100).Step(10).Label("Volume")`}, {ID: "range", Title: "价格区间", Description: "两个稳定 thumb ID 分别接收坐标并约束下限与上限。", Snippet: `thumbs := []components.SliderThumbValue{ {ID: tree.ID(page, "lower"), Label: "Minimum price", ValueText: "25", Value: 25}, {ID: tree.ID(page, "upper"), Label: "Maximum price", ValueText: "75", Value: 75}, } -components.BeginRangeSlider(canvas, theme, bounds, thumbs).Step(5).Paint("Price range")`}, +components.BeginRangeSlider(canvas, theme, bounds, thumbs).Step(5).Paint("Price range")`, PageSnippet: ""}, {ID: "states", Title: "方向与禁用", Description: "同时展示竖向滑块与禁用状态。", Snippet: `components.BeginSlider(canvas, theme, tree.ID(page, "volume"), volumeBounds, float32(volume)).Vertical().Step(10).Paint("Volume") components.BeginSlider(canvas, theme, tree.ID(page, "disabled"), disabledBounds, 64). - Disabled().Paint("Disabled slider")`}, + Disabled().Paint("Disabled slider")`, PageSnippet: `volume := ui.SliderState{Value: 40} +fixed := ui.SliderState{Value: 64} +ui.Row(c).Gap(40).Children(func() { + ui.Column(c).Gap(10).Items(ui.Center).Children(func() { + ui.Slider(c, &volume).Range(0, 100).Step(10).Vertical().Height(160).Label("Volume") + ui.Text(c, "Vertical") + }) + ui.Column(c).Grow(1).Basis(0).Gap(10).Children(func() { + ui.Slider(c, &fixed).Range(0, 100).Disabled(true).Label("Disabled slider") + ui.Text(c, "Disabled").Muted() + }) +})`}, }, } diff --git a/internal/componentdemo/spinner.go b/internal/componentdemo/spinner.go index 574cd829..3f443317 100644 --- a/internal/componentdemo/spinner.go +++ b/internal/componentdemo/spinner.go @@ -13,7 +13,10 @@ var spinnerComponent = Component{ {ID: "default", Title: "加载状态", Description: "一个官方尺寸的静态相位及状态文字。", Snippet: `// The caller chooses the phase; the spinner schedules no frames. icon := ui.Slot(c).Size(24, 24) components.PaintSpinner(canvas, theme, icon.Rect(), 2) -ui.Text(c, "Syncing workspace…").FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium)`}, +ui.Text(c, "Syncing workspace…").FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium)`, PageSnippet: `ui.Row(c).Gap(14).Items(ui.Center).Children(func() { + ui.Spinner(c) + ui.Text(c, "Syncing workspace…").FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium) +})`}, {ID: "phases", Title: "八个相位", Description: "同屏展示全部确定性相位,不启动动画循环。", Snippet: `for index := range 8 { cell := ui.Slot(c).Size(32, 32) components.PaintSpinner(canvas, theme, cell.Rect(), components.SpinnerPhase(index)) diff --git a/internal/componentdemo/split_button.go b/internal/componentdemo/split_button.go index dd631845..ffc08c8a 100644 --- a/internal/componentdemo/split_button.go +++ b/internal/componentdemo/split_button.go @@ -24,6 +24,28 @@ var splitButtonComponent = Component{ Variant: components.ButtonOutline, Open: open, }).Paint() primary, menu := result.Clicked()`, + PageSnippet: `d := ui.SplitButton(c, ui.SplitButtonSpec{ + PrimaryID: saveID, MenuID: moreID, + Label: "Save", MenuLabel: "More save actions", + Open: m.menuOpen, +}) +if id, ok := d.Chosen(); ok { + switch id { + case saveID: + m.saved++ + case moreID: + m.menuOpen = !m.menuOpen + } +} +status := "Primary: Save · Menu: closed" +if m.saved > 0 { + status = "Primary triggered" +} +if m.menuOpen { + status += " · Menu: open" +} +ui.Text(c, status).Muted() +ui.Wrap(c, "The primary and menu targets have separate keyboard focus and accessible names.").Muted()`, }}, } diff --git a/internal/componentdemo/state.go b/internal/componentdemo/state.go index b1245690..84e023ff 100644 --- a/internal/componentdemo/state.go +++ b/internal/componentdemo/state.go @@ -14,6 +14,9 @@ type Example struct { // Snippet is the call-site code shown beside the example on the // documentation site. Empty means the page omits the usage block. Snippet string + // PageSnippet, when set, is the example's page-first code: ui.* calls with + // this example's data and state. It takes the place of Snippet on the site. + PageSnippet string // Height is the preview height in pixels. Zero uses the page default. Height int } @@ -293,12 +296,11 @@ func (state *State) pageFor(theme gfx.Theme) *ui.Page { // The Page is kept on the State: its Tree is the demos' own, its Root names the // demo's scope, and its Theme points at the State's field so a density or // appearance change reaches the next paint. -func (state *State) drawPage(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size, maxWidth float32, title string, content func(c ui.C)) { +func (state *State) drawPage(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size, maxWidth float32, _ string, content func(c ui.C)) { page := state.pageFor(theme) page.Draw(canvas, gfx.Rect{Width: size.Width, Height: size.Height}, func(c ui.C) { ui.Column(c).Fill().Pad(theme.Metrics.PadSurface).Items(ui.Center).Children(func() { ui.Column(c).FillWidth().MaxWidth(maxWidth).Gap(theme.Metrics.GapItem).Children(func() { - ui.Text(c, title).FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightSemibold) content(c) }) }) diff --git a/internal/componentdemo/switch.go b/internal/componentdemo/switch.go index 00325d05..d5b28305 100644 --- a/internal/componentdemo/switch.go +++ b/internal/componentdemo/switch.go @@ -12,14 +12,22 @@ var switchComponent = Component{ {ID: "default", Title: "受控开关", Description: "点击改变目标状态,生产组件使用运行器的帧时钟过渡。", Snippet: `ui.Row(c).Gap(12).Items(ui.Center).Children(func() { ui.Switch(c, &enabled, "").Hit(notifications, "Desktop notifications") ui.Text(c, "Desktop notifications").FontSize(theme.Metrics.FontSizeM) -})`}, +})`, PageSnippet: `enabled := false +ui.Switch(c, &enabled, "Desktop notifications")`}, {ID: "sizes", Title: "两种尺寸", Description: "默认与紧凑开关独立受控。", Snippet: `ui.Row(c).Gap(12).Children(func() { ui.Switch(c, &normal, "").Hit(defaultID, "Default size") ui.Switch(c, &compact, "").Hit(smallID, "Compact size").Small() +})`, PageSnippet: `normal, compact := false, false +ui.Row(c).Gap(12).Children(func() { + ui.Switch(c, &normal, "Default size") + ui.Switch(c, &compact, "Compact size").Small() })`}, {ID: "states", Title: "启用与禁用", Description: "一个可切换开关和开、关两种禁用状态。", Snippet: `ui.Switch(c, ¬ify, "").Hit(notifyID, "Desktop notifications") ui.Switch(c, &off, "").Hit(offID, "Disabled · Off").Disabled(true) -ui.Switch(c, &on, "").Hit(onID, "Disabled · On").Disabled(true)`}, +ui.Switch(c, &on, "").Hit(onID, "Disabled · On").Disabled(true)`, PageSnippet: `notifications, off, on := false, false, true +ui.Switch(c, ¬ifications, "Desktop notifications") +ui.Switch(c, &off, "Disabled · Off").Disabled(true) +ui.Switch(c, &on, "Disabled · On").Disabled(true)`}, }, } diff --git a/internal/componentdemo/table.go b/internal/componentdemo/table.go index eaf4a953..76421e1f 100644 --- a/internal/componentdemo/table.go +++ b/internal/componentdemo/table.go @@ -17,7 +17,18 @@ for index, cells := range bills { table.Row(rows.At(index), cells[:], false) } table.Footer([]string{"Total", "3 items", "¥ 4,540"}) -table.Caption("Click any data row to see its interactive feedback.")`}, +table.Caption("Click any data row to see its interactive feedback.")`, PageSnippet: `bills := ui.TableRows{ + {"Design system", "Paid", "¥ 2,400"}, + {"Desktop build", "Processing", "¥ 860"}, + {"Performance audit", "Unpaid", "¥ 1,280"}, +} +ui.Table(c, &m.table, ui.TableSpec{ + Columns: columns, + Headers: []string{"Item", "Status", "Amount"}, + Source: &bills, +}) +ui.Text(c, "Total · 3 items · ¥ 4,540").Muted() +ui.Text(c, "Click any data row to see its interactive feedback.").Muted()`}, {ID: "selection", Title: "选择状态", Description: "点击稳定行 ID 切换调用方持有的选择位。", Snippet: `rows := tree.Sub(page, tree.Name("row")) table := components.BeginTable(canvas, theme, bounds, columns) table.Header([]string{"Item", "Status", "Amount"}) @@ -27,7 +38,22 @@ for index, cells := range bills { flags ^= 1 << index } } -table.Footer([]string{"Total", "3 items", "¥ 4,540"})`}, +table.Footer([]string{"Total", "3 items", "¥ 4,540"})`, PageSnippet: `bills := ui.TableRows{ + {"Design system", "Paid", "¥ 2,400"}, + {"Desktop build", "Processing", "¥ 860"}, + {"Performance audit", "Unpaid", "¥ 1,280"}, +} +table := ui.Table(c, &m.table, ui.TableSpec{ + Columns: columns, + Headers: []string{"Item", "Status", "Amount"}, + Source: &bills, +}) +if row, ok := table.RowClicked(); ok { + m.table.Select(row) +} +if row := m.table.Selected(); row >= 0 { + ui.Text(c, "Selected: "+bills[row][0]).Muted() +}`}, {ID: "alignment", Title: "列对齐", Description: "左、中、右三种列内文字对齐。", Snippet: `columns := []components.TableColumn{ {Width: 112, Alignment: components.TableAlignLeft}, {Width: 88, Alignment: components.TableAlignCenter}, @@ -38,7 +64,22 @@ table.Header([]string{"Item", "Status", "Amount"}) for _, cells := range bills { table.Row(gfx.ID{}, cells[:], false) } -table.Caption("Item is left-aligned, status centered, amount right-aligned.")`}, +table.Caption("Item is left-aligned, status centered, amount right-aligned.")`, PageSnippet: `bills := ui.TableRows{ + {"Design system", "Paid", "¥ 2,400"}, + {"Desktop build", "Processing", "¥ 860"}, + {"Performance audit", "Unpaid", "¥ 1,280"}, +} +columns := []style.TableColumn{ + {Width: 112, Alignment: style.TableAlignLeft}, + {Width: 88, Alignment: style.TableAlignCenter}, + {Alignment: style.TableAlignRight}, +} +ui.Table(c, &m.table, ui.TableSpec{ + Columns: columns, + Headers: []string{"Item", "Status", "Amount"}, + Source: &bills, +}) +ui.Text(c, "Item is left-aligned, status centered, amount right-aligned.").Muted()`}, {ID: "overflow", Title: "溢出与表头", Description: "放不下的单元格以省略号结尾;FitTableHeadings 让定宽列至少放得下自己的表头。", Snippet: `columns := []components.TableColumn{{Width: 96}, {Width: 40}, {Alignment: components.TableAlignRight}} headings := []string{"Item", "Status", "Amount"} components.FitTableHeadings(canvas, theme, columns, headings) @@ -47,7 +88,18 @@ table.Header(headings) for _, cells := range bills { table.Row(gfx.ID{}, cells[:], false) } -table.Caption("Item is cut with an ellipsis; Status grew to hold its heading.")`}, +table.Caption("Item is cut with an ellipsis; Status grew to hold its heading.")`, PageSnippet: `bills := ui.TableRows{ + {"Design system", "Paid", "¥ 2,400"}, + {"Desktop build", "Processing", "¥ 860"}, + {"Performance audit", "Unpaid", "¥ 1,280"}, +} +columns := []style.TableColumn{{Width: 96}, {Width: 40}, {Alignment: style.TableAlignRight}} +ui.Table(c, &m.table, ui.TableSpec{ + Columns: columns, + Headers: []string{"Item", "Status", "Amount"}, + Source: &bills, +}) +ui.Text(c, "Item is cut with an ellipsis; Status grew to hold its heading.").Muted()`}, }, } diff --git a/internal/componentdemo/tabs.go b/internal/componentdemo/tabs.go index 8b295f9b..9bf96811 100644 --- a/internal/componentdemo/tabs.go +++ b/internal/componentdemo/tabs.go @@ -16,19 +16,52 @@ options := []components.TabOption{ {ID: tabs.At(1), Label: "Activity", Icon: activityIcon}, {ID: tabs.At(2), Label: "Settings", Icon: settingsIcon}, } -components.BeginTabs(canvas, theme, bounds, options, options[selected].ID).Paint()`}, +components.BeginTabs(canvas, theme, bounds, options, options[selected].ID).Paint()`, PageSnippet: ""}, {ID: "default", Title: "分段标签", Description: "三个稳定 tab ID 驱动关联内容。", Snippet: `labels := []string{"Overview", "Activity", "Settings"} tab := labels[0] ui.Tabs(c, &tab, labels, nil) -ui.Text(c, tab).FontSize(c.Theme().Metrics.FontSizeM)`}, +ui.Text(c, tab).FontSize(c.Theme().Metrics.FontSizeM)`, PageSnippet: `labels := []string{"Overview", "Activity", "Settings"} +tab := labels[0] +ui.Tabs(c, &tab, labels, nil) +switch tab { +case "Overview": + ui.Column(c).Gap(8).Children(func() { + ui.Text(c, "Project overview") + ui.Wrap(c, "See recent status and key highlights.") + }) +case "Activity": + ui.Column(c).Gap(8).Children(func() { + ui.Text(c, "Recent activity") + ui.Wrap(c, "Track saves, builds, and releases.") + }) +case "Settings": + ui.Column(c).Gap(8).Children(func() { + ui.Text(c, "Workspace settings") + ui.Wrap(c, "Configure display and local runtime options.") + }) +}`}, {ID: "line", Title: "线形标签", Description: "透明列表与两像素活动指示条。", Snippet: `labels := []string{"Overview", "Activity", "Settings"} tab := labels[0] -ui.Tabs(c, &tab, labels, nil).Line()`}, +ui.Tabs(c, &tab, labels, nil).Line()`, PageSnippet: `labels := []string{"Overview", "Activity", "Settings"} +tab := labels[0] +ui.Tabs(c, &tab, labels, nil).Line() +ui.Column(c).Gap(8).Children(func() { + ui.Text(c, "Project overview") + ui.Wrap(c, "See recent status and key highlights.") +})`}, {ID: "vertical", Title: "纵向标签", Description: "标签纵向排列,内容位于右侧。", Snippet: `labels := []string{"Overview", "Activity", "Settings"} tab := labels[0] ui.Row(c).Gap(20).Children(func() { ui.Tabs(c, &tab, labels, nil).Line().Vertical().Self(ui.Start) ui.Text(c, tab).Grow(1).Basis(0) +})`, PageSnippet: `labels := []string{"Overview", "Activity", "Settings"} +tab := labels[0] +ui.Row(c).Gap(20).Children(func() { + ui.Tabs(c, &tab, labels, nil).Line().Vertical().Self(ui.Start) + ui.Column(c).Grow(1).Basis(0).Gap(8).Children(func() { + ui.Text(c, "Project overview") + ui.Wrap(c, "See recent status and key highlights.") + }) })`}, }, } diff --git a/internal/componentdemo/textarea.go b/internal/componentdemo/textarea.go index 614b4045..15ab82d1 100644 --- a/internal/componentdemo/textarea.go +++ b/internal/componentdemo/textarea.go @@ -36,14 +36,15 @@ var textareaComponent = Component{ components.PaintTextarea(canvas, theme, field.Rect(), components.TextareaSnapshot{ ID: tree.ID(page, "description"), Label: "Project description", Hint: "Supports multiple lines", Value: value, DisplayValue: value, -})`}, +})`, PageSnippet: `notes := "Viva renders with the native GPU. An idle window keeps submitting no frames: with no input, animation, or network events it is not repainted, and no background timer polls.\nThe second paragraph is short." +ui.TextArea(c, ¬es, "Project description", "").Height(142)`}, {ID: "grow", Title: "随内容增高", Description: "相当于 shadcn 的 field-sizing-content:高度随文本行数增长,超过上限后在框内滚动并跟随插入点。", Snippet: `width := min(size.Width-48, float32(540)) height := min(layout.ContentHeight(canvas, theme, value, width, false), float32(5)*20+16) field := ui.Slot(c).Height(height) components.PaintTextarea(canvas, theme, field.Rect(), components.TextareaSnapshot{ ID: tree.ID(page, "notes"), Label: "Project description", Value: value, DisplayValue: value, Layout: layout, -})`}, +})`, PageSnippet: ""}, {ID: "selection", Title: "选择与输入法", Description: "确定性展示选择区、插入点与组合文本下划线。", Snippet: `value := "Select this text\nComposition text" field := ui.Slot(c).Height(142) components.PaintTextarea(canvas, theme, field.Rect(), components.TextareaSnapshot{ @@ -51,7 +52,7 @@ components.PaintTextarea(canvas, theme, field.Rect(), components.TextareaSnapsho ReadOnly: true, Focused: true, ShowCaret: true, Caret: 16, SelectionStart: 0, SelectionEnd: 6, CompositionStart: 17, CompositionEnd: len(value), -})`}, +})`, PageSnippet: ""}, {ID: "states", Title: "校验与禁用", Description: "错误、只读与禁用状态并列展示。", Snippet: `var invalid, readOnly ui.Box ui.Row(c).Gap(12).Children(func() { invalid = ui.Slot(c).Grow(1).Basis(0).Height(104) @@ -70,7 +71,7 @@ components.PaintTextarea(canvas, theme, readOnly.Rect(), components.TextareaSnap components.PaintTextarea(canvas, theme, disabled.Rect(), components.TextareaSnapshot{ ID: tree.ID(page, "disabled"), Label: "Disabled field", Disabled: true, Placeholder: "Currently unavailable", -})`}, +})`, PageSnippet: ""}, }, } diff --git a/internal/componentdemo/toggle.go b/internal/componentdemo/toggle.go index 3d094acc..1b3246df 100644 --- a/internal/componentdemo/toggle.go +++ b/internal/componentdemo/toggle.go @@ -17,17 +17,29 @@ for index, label := range [...]string{"B", "I", "U"} { if toggle.Outline(label).Clicked() { flags ^= 1 << index } -}`}, +}`, PageSnippet: `ui.Row(c).Gap(12).Children(func() { + ui.ToggleBase(c, &m.bold, "B").Outline() + ui.ToggleBase(c, &m.italic, "I").Outline() + ui.ToggleBase(c, &m.underline, "U").Outline() +}) +ui.Text(c, "Each button keeps its own active bit.").Muted()`}, {ID: "variants", Title: "外观与尺寸", Description: "默认、描边、小号与大号变体。", Snippet: `small := components.BeginToggle(canvas, theme, tree.ID(page, "small"), bounds, active) if small.Small().Default("Small").Clicked() { active = !active } large := components.BeginToggle(canvas, theme, tree.ID(page, "large"), bounds, true) -large.Large().Outline("Large")`}, +large.Large().Outline("Large")`, PageSnippet: `ui.Row(c).Gap(16).Items(ui.Center).Children(func() { + ui.ToggleBase(c, &m.small, "Small").Small() + ui.ToggleBase(c, &m.large, "Large").Large().Outline() +}) +ui.Text(c, "Size comes from explicit chained options.").Muted()`}, {ID: "states", Title: "校验与禁用", Description: "激活、错误和禁用状态。", Snippet: `invalid := tree.ID(page, "invalid") components.BeginToggle(canvas, theme, invalid, bounds, true).Invalid().Outline("Invalid") disabled := tree.ID(page, "disabled") -components.BeginToggle(canvas, theme, disabled, bounds, false).Disabled().Outline("Disabled")`}, +components.BeginToggle(canvas, theme, disabled, bounds, false).Disabled().Outline("Disabled")`, PageSnippet: `ui.Row(c).Gap(16).Children(func() { + ui.ToggleBase(c, &m.invalid, "Invalid").Outline() + ui.ToggleBase(c, &m.disabled, "Disabled").Outline().Disabled(true) +})`}, }, } diff --git a/internal/componentdemo/tooltip.go b/internal/componentdemo/tooltip.go index 623c1dae..a1946151 100644 --- a/internal/componentdemo/tooltip.go +++ b/internal/componentdemo/tooltip.go @@ -19,7 +19,9 @@ if open || canvas.Hovered() == trigger { components.BeginTooltip(canvas, theme, viewport, anchor, components.TooltipOptions{Layer: 60, Side: components.TooltipTop, MaxWidth: 176}). Paint("Native synchronous tooltip") -}`}, +}`, PageSnippet: `ui.Button(c, "Hover or click"). + Tooltip("Native synchronous tooltip, no background timer"). + TooltipOn(ui.TooltipTop)`}, {ID: "sides", Title: "四个方向", Description: "同屏展示上、右、下、左四种放置方向。", Snippet: `labels := [...]string{"Top", "Right", "Bottom", "Left"} sides := [...]components.TooltipSide{ components.TooltipTop, components.TooltipRight, @@ -29,12 +31,17 @@ for index, anchor := range anchors { components.BeginTooltip(canvas, theme, viewport, anchor, components.TooltipOptions{ Layer: uint16(60 + index), Side: sides[index], MaxWidth: 96, }).Paint(labels[index]) -}`}, +}`, PageSnippet: `ui.Button(c, "Top").Tooltip("Top").TooltipOn(ui.TooltipTop) +ui.Button(c, "Right").Tooltip("Right").TooltipOn(ui.TooltipRight) +ui.Button(c, "Bottom").Tooltip("Bottom").TooltipOn(ui.TooltipBottom) +ui.Button(c, "Left").Tooltip("Left").TooltipOn(ui.TooltipLeft)`}, {ID: "clamped", Title: "视口约束", Description: "靠近边缘时将提示内容限制在视口内。", Snippet: `anchor := ui.Slot(c).Size(60, theme.Metrics.ControlHeight).Self(ui.Start).Rect() anchor.X, anchor.Width = size.Width-76, 60 // pin the trigger to the window edge components.BeginTooltip(canvas, theme, viewport, anchor, components.TooltipOptions{ Layer: 60, Side: components.TooltipBottom, MaxWidth: 176, -}).Paint("Clamped to the viewport")`}, +}).Paint("Clamped to the viewport")`, PageSnippet: `ui.Button(c, "Hover or click").Self(ui.End). + Tooltip("Clamped to the viewport"). + TooltipOn(ui.TooltipBottom)`}, }, } diff --git a/internal/componentdemo/tree.go b/internal/componentdemo/tree.go index e5fb0917..2e51c30b 100644 --- a/internal/componentdemo/tree.go +++ b/internal/componentdemo/tree.go @@ -21,6 +21,20 @@ if expanded { hosts.Item(components.TreeItem{ID: tree.ID(page, "gateway"), Label: "Gateway", Depth: 1}) hosts.Item(components.TreeItem{ID: tree.ID(page, "database"), Label: "Database", Depth: 1}) hosts.Item(components.TreeItem{ID: tree.ID(page, "worker"), Label: "Worker", Depth: 1}) +}`, PageSnippet: `labels := []string{"Production", "Gateway", "Database", "Worker"} +m.tree.Node = func(i int) ui.TreeNode { + if i == 0 { + return ui.TreeNode{Branch: true, Expanded: m.expanded} + } + return ui.TreeNode{Depth: 1} +} +rows := 1 +if m.expanded { + rows = 4 +} +ui.Tree(c, &m.tree, rows, func(i int) string { return labels[i] }, nil).Grow(1) +if _, ok := m.tree.Toggled(); ok { + m.expanded = !m.expanded }`}, {ID: "selection", Title: "选择状态", Description: "点击主机行切换调用方持有的当前项。", Snippet: `hosts := components.BeginTree(canvas, theme, bounds) hosts.Item(components.TreeItem{ @@ -33,6 +47,16 @@ for index, name := range [...]string{"Gateway", "Database", "Worker"} { ID: id, Label: name, Depth: 1, Selected: selected == index, }) if canvas.Clicked(id) { selected = index } +}`, PageSnippet: `labels := []string{"Production", "Gateway", "Database", "Worker"} +m.tree.Node = func(i int) ui.TreeNode { + if i == 0 { + return ui.TreeNode{Branch: true, Expanded: true} + } + return ui.TreeNode{Depth: 1, Selected: i-1 == m.selected} +} +ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, nil).Grow(1) +if i, ok := m.tree.Chosen(); ok { + m.selected = i - 1 }`}, {ID: "disabled", Title: "禁用分支", Description: "保留层级和语义,但分组与叶子均不可交互。", Snippet: `hosts := components.BeginTree(canvas, theme, bounds) hosts.Item(components.TreeItem{ @@ -43,7 +67,14 @@ for _, name := range [...]string{"Gateway", "Database", "Worker"} { hosts.Item(components.TreeItem{ ID: tree.ID(page, name), Label: name, Depth: 1, Disabled: true, }) -}`}, +}`, PageSnippet: `labels := []string{"Production", "Gateway", "Database", "Worker"} +m.tree.Node = func(i int) ui.TreeNode { + if i == 0 { + return ui.TreeNode{Branch: true, Expanded: true, Disabled: true} + } + return ui.TreeNode{Depth: 1, Disabled: true} +} +ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, nil).Grow(1)`}, }, } diff --git a/internal/componentdemo/tree_navigation.go b/internal/componentdemo/tree_navigation.go index f2fef8d6..46be2f08 100644 --- a/internal/componentdemo/tree_navigation.go +++ b/internal/componentdemo/tree_navigation.go @@ -21,6 +21,25 @@ if handled { } selected = next return gfx.EventResult{Focus: rowIDs[next], FocusVisible: true, Handled: true, Repaint: true} +}`, PageSnippet: `rows := []string{"Production", "Gateway", "Database", "Worker"} +items := []ui.TreeNavigationItem{ + {Branch: true, Expanded: m.expanded}, + {Depth: 1}, {Depth: 1}, {Depth: 1}, +} +visible := items[:1] +if m.expanded { + visible = items[:] +} +next, action, handled := ui.NavigateTree(visible, m.selected, event.Key, len(rows)) +if handled { + switch action { + case ui.TreeNavigationExpand: + m.expanded = true + case ui.TreeNavigationCollapse: + m.expanded = false + } + m.selected = next + return gfx.EventResult{Focus: m.rowIDs[next], FocusVisible: true, Handled: true, Repaint: true} }`}, }, } diff --git a/internal/componentdemo/typography.go b/internal/componentdemo/typography.go index fa3b6bcf..16901ea1 100644 --- a/internal/componentdemo/typography.go +++ b/internal/componentdemo/typography.go @@ -17,7 +17,12 @@ h4 := ui.Slot(c).Height(30) components.Typography(canvas, theme, h1.Rect(), components.TypographyH1, "Heading 1") components.Typography(canvas, theme, h2.Rect(), components.TypographyH2, "Heading 2") components.Typography(canvas, theme, h3.Rect(), components.TypographyH3, "Heading 3") -components.Typography(canvas, theme, h4.Rect(), components.TypographyH4, "Heading 4")`}, +components.Typography(canvas, theme, h4.Rect(), components.TypographyH4, "Heading 4")`, PageSnippet: `ui.Column(c).Gap(6).Children(func() { + ui.Text(c, "Heading 1").FontSize(theme.Metrics.FontSizeL * 1.5).Weight(gfx.WeightBold) + ui.Text(c, "Heading 2").FontSize(theme.Metrics.FontSizeL + 6).Weight(gfx.WeightSemibold) + ui.Text(c, "Heading 3").FontSize(theme.Metrics.FontSizeL).Weight(gfx.WeightSemibold) + ui.Text(c, "Heading 4").FontSize(theme.Metrics.FontSizeM + 7).Weight(gfx.WeightSemibold) +})`}, {ID: "content", Title: "正文角色", Description: "段落、引导、大号与小号正文。", Snippet: `lead := ui.Slot(c).Height(32) body := ui.Slot(c).Height(28) large := ui.Slot(c).Height(28) @@ -29,7 +34,16 @@ components.Typography(canvas, theme, body.Rect(), components.Typography(canvas, theme, large.Rect(), components.TypographyLarge, "Large · Key note") components.Typography(canvas, theme, small.Rect(), - components.TypographySmall, "Small · Compact labels and supporting copy")`}, + components.TypographySmall, "Small · Compact labels and supporting copy")`, PageSnippet: `ui.Column(c).Gap(6).Children(func() { + ui.Paragraph(c, "A complete type system for native desktop interfaces", 0). + FontSize(theme.Metrics.FontSizeM + 7).Muted() + ui.Paragraph(c, "Paragraph text uses the theme's font size and foreground color.", 0). + FontSize(theme.Metrics.FontSizeM + 3) + ui.Text(c, "Large · Key note"). + FontSize(theme.Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) + ui.Text(c, "Small · Compact labels and supporting copy"). + FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium) +})`}, {ID: "muted", Title: "强调与弱化", Description: "正文、强调文字与弱化说明。", Snippet: `body := ui.Slot(c).Height(32) strong := ui.Slot(c).Height(30) note := ui.Slot(c).Height(26) @@ -38,7 +52,14 @@ components.Typography(canvas, theme, body.Rect(), components.Typography(canvas, theme, strong.Rect(), components.TypographyLarge, "Key results use a heavier weight.") components.Typography(canvas, theme, note.Rect(), - components.TypographyMuted, "Secondary notes use the theme's muted foreground.")`}, + components.TypographyMuted, "Secondary notes use the theme's muted foreground.")`, PageSnippet: `ui.Column(c).Gap(6).Children(func() { + ui.Paragraph(c, "Body copy stays clear, stable, and readable.", 0). + FontSize(theme.Metrics.FontSizeM + 3) + ui.Text(c, "Key results use a heavier weight."). + FontSize(theme.Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) + ui.Text(c, "Secondary notes use the theme's muted foreground."). + FontSize(theme.Metrics.FontSizeM).Muted() +})`}, }, } diff --git a/tools/docs/catalog.go b/tools/docs/catalog.go index 90809d7c..fe16fb7c 100644 --- a/tools/docs/catalog.go +++ b/tools/docs/catalog.go @@ -22,6 +22,7 @@ type Nav struct { type Demo struct { ID, Title, Description string Snippet string `json:"Snippet,omitempty"` + PageSnippet string `json:"PageSnippet,omitempty"` Height int `json:"Height,omitempty"` } @@ -106,7 +107,7 @@ func loadPages(root string) ([]Page, Manifest, error) { if _, err := componentdemo.New(component.ID, example.ID); err != nil { return nil, manifest, err } - page.Examples = append(page.Examples, Demo{example.ID, example.Title, example.Description, example.Snippet, example.Height}) + page.Examples = append(page.Examples, Demo{example.ID, example.Title, example.Description, example.Snippet, example.PageSnippet, example.Height}) } pages = append(pages, page) } diff --git a/tools/docs/catalog_test.go b/tools/docs/catalog_test.go index 7d6e4c40..9f99914e 100644 --- a/tools/docs/catalog_test.go +++ b/tools/docs/catalog_test.go @@ -378,3 +378,22 @@ func TestFailedBuildPreservesPublishedPreview(t *testing.T) { t.Fatalf("staging directory leaked: %v, %v", entries, err) } } + +// Every page-first example snippet is valid Go and stays on the page API: no +// canvas constructors or components package calls. +func TestPageSnippetsArePageLevel(t *testing.T) { + for _, component := range componentdemo.Catalog() { + for _, example := range component.Examples { + if example.PageSnippet == "" { + continue + } + if strings.Contains(example.PageSnippet, "components.") || strings.Contains(example.PageSnippet, "Begin") { + t.Errorf("%s/%s page snippet uses the canvas API: %q", component.ID, example.ID, example.PageSnippet) + } + source := "package snippet\nfunc example() {\n" + example.PageSnippet + "\n}\n" + if _, err := parser.ParseFile(token.NewFileSet(), "snippet.go", source, 0); err != nil { + t.Errorf("%s/%s page snippet does not parse: %v\n%s", component.ID, example.ID, err, example.PageSnippet) + } + } + } +} diff --git a/website/site.test.mjs b/website/site.test.mjs index d2b81a7a..d96b44af 100644 --- a/website/site.test.mjs +++ b/website/site.test.mjs @@ -203,7 +203,8 @@ for (const locale of ['zh', 'en']) { assert.doesNotMatch(html, / example.PageSnippet || (example.Snippet && !/components\.|Begin/.test(example.Snippet))).length; + assert.equal([...html.matchAll(/class="code-block usage-block"/g)].length, withUsage); for (const example of page.Examples) { assert.ok(html.includes(`id="example-${example.ID}"`)); } diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index 1cbde0bd..1d40eac8 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -32,21 +32,20 @@ const sections = page.Sections.filter(section => section.ID !== 'source-ownershi - {page.PageUsage &&

{text.pageApi}

-
-
{text.pageApi}
-
-
-
}
{page.Examples.map(example =>

{example.Title}#

{example.Description}

- - {example.Snippet &&
-
{text.exampleSource}
-
-
} + + {(() => { + const own = example.Snippet && !/components\.|Begin/.test(example.Snippet); + const usage = example.PageSnippet || (own ? example.Snippet : ''); + if (!usage) return

{text.canvasRecipe}

; + return
+
{text.exampleUsage}
+
+
; + })()}
)}
From dd549b0dc1df6cbd20e03596a0f89767726240d6 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 14:16:23 +0800 Subject: [PATCH 27/66] feat(ui): add the styled page toggle --- base/frame.go | 13 +++++++++ base/kinds.go | 1 + base/page_bases.go | 9 ++++++ internal/componentdemo/page_usage.go | 2 +- internal/componentdemo/toggle.go | 14 +++++----- ui/controls_paint.go | 41 ++++++++++++++++++++++++++++ ui/controls_table.go | 1 + ui/facade.go | 3 ++ ui/hooks_install.go | 1 + ui/toggle_test.go | 30 ++++++++++++++++++++ website/src/styles/site.css | 9 ++++-- 11 files changed, 113 insertions(+), 11 deletions(-) create mode 100644 ui/toggle_test.go diff --git a/base/frame.go b/base/frame.go index 98caaf74..12a1f8c3 100644 --- a/base/frame.go +++ b/base/frame.go @@ -28,6 +28,7 @@ const ( kindImage = KindImage kindSplitButton = KindSplitButton kindBadge = KindBadge + kindToggle = KindToggle kindPagination = KindPagination ) @@ -642,6 +643,18 @@ func (f *Frame) Switch(ID gfx.ID, on bool) Box { return b } +// Toggle adds a two-state button in the given state; Clicked reports a click. +func (f *Frame) Toggle(ID gfx.ID, Label string, pressed bool) Box { + b := f.Box(kindToggle) + n := &f.Nodes[b.i] + n.ID, n.Label = ID, Label + if pressed { + n.Flags |= flagChecked | flagSelected + } + n.Flags |= flagHasHit + return b +} + // Slot reserves room for something the caller paints itself: Rect gives where // once End has laid the page out. Give it a size, or let it grow. func (f *Frame) Slot() Box { return f.Box(kindSlot) } diff --git a/base/kinds.go b/base/kinds.go index c4357374..8b41d7aa 100644 --- a/base/kinds.go +++ b/base/kinds.go @@ -26,6 +26,7 @@ const ( KindImage KindSplitButton KindBadge + KindToggle KindPagination ) diff --git a/base/page_bases.go b/base/page_bases.go index 1dcb8093..bda5a631 100644 --- a/base/page_bases.go +++ b/base/page_bases.go @@ -62,6 +62,15 @@ func ToggleBase(c C, Value *bool, Label string) Box { return b } +// Toggle is a two-state button with the theme's look: it flips *value, and to +// assistive technology it is a button that is pressed or not. Outline chooses +// the bordered treatment; ToggleBase is the same without a look. +func Toggle(c C, Value *bool, Label string) Box { + b := c.f.Toggle(c.page.boundID(pkToggle, unsafe.Pointer(Value)), Label, *Value).Label(Label) + c.f.bindBool(b, Value) + return b +} + // RadioBase is one option of a radio group or a segmented control without a look: a click // sets *value to option, and it is a radio button that is chosen while *value is option. // Name it with c.Key when the options are reordered. diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index 61919b63..906796c7 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -48,7 +48,7 @@ ui.Table(c, &m.table, ui.TableSpec{ "pagination": `ui.Pagination(c, items)`, "radio-group": `ui.RadioGroup(c)`, "choice": `ui.Choice(c, &m.choice, choices, nameOf)`, - "toggle": `ui.ToggleBase(c, &m.on, "Bold")`, + "toggle": `ui.Toggle(c, &m.on, "Bold").Outline()`, "native-select": `ui.Select(c, &m.choice, choices, nameOf)`, "single-select": `ui.Select(c, &m.choice, choices, nameOf)`, "scroll-area": `ui.Scroll(c).Grow(1).Scrollbars()`, diff --git a/internal/componentdemo/toggle.go b/internal/componentdemo/toggle.go index 1b3246df..c1fa2194 100644 --- a/internal/componentdemo/toggle.go +++ b/internal/componentdemo/toggle.go @@ -18,9 +18,9 @@ for index, label := range [...]string{"B", "I", "U"} { flags ^= 1 << index } }`, PageSnippet: `ui.Row(c).Gap(12).Children(func() { - ui.ToggleBase(c, &m.bold, "B").Outline() - ui.ToggleBase(c, &m.italic, "I").Outline() - ui.ToggleBase(c, &m.underline, "U").Outline() + ui.Toggle(c, &m.bold, "B").Outline() + ui.Toggle(c, &m.italic, "I").Outline() + ui.Toggle(c, &m.underline, "U").Outline() }) ui.Text(c, "Each button keeps its own active bit.").Muted()`}, {ID: "variants", Title: "外观与尺寸", Description: "默认、描边、小号与大号变体。", Snippet: `small := components.BeginToggle(canvas, theme, tree.ID(page, "small"), bounds, active) @@ -29,16 +29,16 @@ if small.Small().Default("Small").Clicked() { } large := components.BeginToggle(canvas, theme, tree.ID(page, "large"), bounds, true) large.Large().Outline("Large")`, PageSnippet: `ui.Row(c).Gap(16).Items(ui.Center).Children(func() { - ui.ToggleBase(c, &m.small, "Small").Small() - ui.ToggleBase(c, &m.large, "Large").Large().Outline() + ui.Toggle(c, &m.small, "Small").Small() + ui.Toggle(c, &m.large, "Large").Large().Outline() }) ui.Text(c, "Size comes from explicit chained options.").Muted()`}, {ID: "states", Title: "校验与禁用", Description: "激活、错误和禁用状态。", Snippet: `invalid := tree.ID(page, "invalid") components.BeginToggle(canvas, theme, invalid, bounds, true).Invalid().Outline("Invalid") disabled := tree.ID(page, "disabled") components.BeginToggle(canvas, theme, disabled, bounds, false).Disabled().Outline("Disabled")`, PageSnippet: `ui.Row(c).Gap(16).Children(func() { - ui.ToggleBase(c, &m.invalid, "Invalid").Outline() - ui.ToggleBase(c, &m.disabled, "Disabled").Outline().Disabled(true) + ui.Toggle(c, &m.invalid, "Invalid").Outline() + ui.Toggle(c, &m.disabled, "Disabled").Outline().Disabled(true) })`}, }, } diff --git a/ui/controls_paint.go b/ui/controls_paint.go index c20e5e8f..82c7f9a5 100644 --- a/ui/controls_paint.go +++ b/ui/controls_paint.go @@ -7,6 +7,7 @@ import ( "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" ) func paintCheckbox(f *Frame, v ControlView) { @@ -66,6 +67,27 @@ func paintSwitch(f *Frame, v ControlView) { control.Paint() } +func paintToggle(f *Frame, v ControlView) { + toggle := components.BeginToggle(f.Surface, f.Palette, v.ID, v.Rect, v.Flags&FlagChecked != 0) + if v.Size == style.SizeSmall { + toggle = toggle.Small() + } else if v.Size == style.SizeLarge { + toggle = toggle.Large() + } + if v.Flags&FlagDisabled != 0 { + toggle = toggle.Disabled() + } + label := v.Text + if label == "" { + label = v.Label + } + if v.Variant == style.VariantOutline { + toggle.Outline(label) + } else { + toggle.Default(label) + } +} + func paintInputGroup(f *Frame, v ControlView) { components.PaintInputGroup(f.Surface, f.Palette, v.Rect, base.WidgetsOf(f).GetGroups()[v.Aux]) } @@ -115,6 +137,25 @@ func measureControls(f *Frame, n *Node) { control, _ := components.SwitchExtent(f.Palette, n.Flags&FlagSmall != 0) n.Pref[AxisX] = control + CaptionGap + f.Surface.TextWidthWeight(n.Text, f.CaptionSize(n), gfx.WeightMedium) } + case KindToggle: + toggle := components.BeginToggle(f.Surface, f.Palette, gfx.ID{}, Rect{}, false) + if n.ButtonSize == style.SizeSmall { + toggle = toggle.Small() + } else if n.ButtonSize == style.SizeLarge { + toggle = toggle.Large() + } + label := n.Text + if label == "" { + label = n.Label + } + toggle = toggle.SizeToFit(label) + height := f.Palette.Metrics.ControlHeight + if n.ButtonSize == style.SizeSmall { + height -= 4 + } else if n.ButtonSize == style.SizeLarge { + height += 4 + } + n.Pref = [2]float32{toggle.BoundsWidth(), height} case KindSegmented: var width float32 = 8 for _, option := range base.WidgetsOf(f).GetSegmented()[n.Aux].GetOptions() { diff --git a/ui/controls_table.go b/ui/controls_table.go index 65ff3f0b..be9b5926 100644 --- a/ui/controls_table.go +++ b/ui/controls_table.go @@ -15,5 +15,6 @@ func paintBadgeControl(f *Frame, n *Node, _ Rect) { paintBadge(f, base.Vie func paintPaginationControl(f *Frame, n *Node, _ Rect) { paintPagination(f, base.ViewOf(f, n)) } func paintCheckboxControl(f *Frame, n *Node, _ Rect) { paintCheckbox(f, base.ViewOf(f, n)) } func paintSwitchControl(f *Frame, n *Node, _ Rect) { paintSwitch(f, base.ViewOf(f, n)) } +func paintToggleControl(f *Frame, n *Node, _ Rect) { paintToggle(f, base.ViewOf(f, n)) } func paintInputGroupControl(f *Frame, n *Node, _ Rect) { paintInputGroup(f, base.ViewOf(f, n)) } func paintSegmentedControl(f *Frame, n *Node, _ Rect) { paintSegmented(f, base.ViewOf(f, n)) } diff --git a/ui/facade.go b/ui/facade.go index e98a4476..4ddd444a 100644 --- a/ui/facade.go +++ b/ui/facade.go @@ -55,6 +55,7 @@ const ( FocusHorizontal = base.FocusHorizontal FocusVertical = base.FocusVertical KindContainer = base.KindContainer + KindToggle = base.KindToggle KindIcon = base.KindIcon KindImage = base.KindImage KindSlot = base.KindSlot @@ -164,6 +165,8 @@ func ToggleBase(c C, Value *bool, Label string) Box { return base.ToggleBase(c, Value, Label) } +func Toggle(c C, Value *bool, Label string) Box { return base.Toggle(c, Value, Label) } + func Control(c C, Label string, h *Handlers) Box { useControls(); return base.Control(c, Label, h) } func FormField(c C, state *FormFieldState, Label string) Box { diff --git a/ui/hooks_install.go b/ui/hooks_install.go index a000ed58..0626919f 100644 --- a/ui/hooks_install.go +++ b/ui/hooks_install.go @@ -22,6 +22,7 @@ func useControls() { base.SetControlPainter(KindButton, paintButtonControl) base.SetControlPainter(KindCheckbox, paintCheckboxControl) base.SetControlPainter(KindSwitch, paintSwitchControl) + base.SetControlPainter(KindToggle, paintToggleControl) base.SetControlPainter(KindInput, paintInputControl) base.SetControlPainter(KindInputGroup, paintInputGroupControl) base.SetControlPainter(KindTextarea, paintTextareaControl) diff --git a/ui/toggle_test.go b/ui/toggle_test.go new file mode 100644 index 00000000..38c982a8 --- /dev/null +++ b/ui/toggle_test.go @@ -0,0 +1,30 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/ui" +) + +// A page Toggle is the styled two-state button: a click flips the bound value +// and assistive technology hears a pressed button. +func TestPageToggleFlipsItsValue(t *testing.T) { + var on bool + d := openPage(t, func(c ui.C) { + ui.Row(c).Children(func() { + ui.Toggle(c, &on, "Bold").Outline() + }) + }) + d.click("Bold") + if !on { + t.Fatal("the toggle did not flip its value") + } + hit := d.hit("Bold") + if !hit.Checked || !hit.Selected { + t.Fatalf("toggle hit checked=%v selected=%v, want both", hit.Checked, hit.Selected) + } + d.click("Bold") + if on { + t.Fatal("the second click did not flip the value back") + } +} diff --git a/website/src/styles/site.css b/website/src/styles/site.css index c43875c0..ab6a2a3d 100644 --- a/website/src/styles/site.css +++ b/website/src/styles/site.css @@ -199,8 +199,9 @@ .copy-result { font-size: 12px; color: var(--viva-success); text-align: right; } .copy-result:empty { display: none; } .copy-failed { color: var(--viva-error); } - .code-block { border: 1px solid var(--viva-border); border-radius: var(--viva-radius); overflow: hidden; } - .code-toolbar { display: flex; justify-content: space-between; align-items: center; padding: 10px 14px; gap: 12px; border-bottom: 1px solid var(--viva-border); font-size: 13px; color: var(--viva-muted); } + .code-block { border: 1px solid var(--viva-border); border-radius: 10px; overflow: hidden; background: var(--viva-surface); box-shadow: 0 1px 2px rgb(0 0 0 / 4%), 0 12px 32px -28px rgb(0 0 0 / 35%); transition: border-color .15s ease, box-shadow .15s ease; } + .code-block:hover { border-color: var(--viva-strong-border); box-shadow: 0 1px 2px rgb(0 0 0 / 5%), 0 16px 40px -28px rgb(0 0 0 / 42%); } + .code-toolbar { display: flex; justify-content: space-between; align-items: center; padding: 9px 12px; gap: 12px; border-bottom: 1px solid var(--viva-border); background: color-mix(in srgb, var(--viva-surface) 82%, var(--viva-background)); font-size: 12px; letter-spacing: .01em; color: var(--viva-muted); } .source-code { padding: 20px; overflow: auto; background: var(--viva-surface); font-size: 13px; line-height: 1.8; } .source-code code { font-size: inherit; } .section-heading { display: flex; justify-content: space-between; gap: 16px; align-items: center; } @@ -210,8 +211,10 @@ .code-copy-button { position: absolute; top: 8px; right: 8px; z-index: 2; display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; padding: 0; border: 1px solid var(--viva-border); border-radius: 6px; background: var(--viva-background); color: var(--viva-muted); line-height: 1; opacity: .82; } .code-copy-button:hover, .code-copy-button:focus-visible { opacity: 1; border-color: var(--viva-strong-border); color: var(--viva-text); } .code-copy-button[data-state='copied'] { color: var(--viva-success); } - .highlighted-code pre { font-size: 13px; line-height: 1.8; padding: 20px; overflow: auto; max-height: 640px; } + .highlighted-code pre { font-size: 13px; line-height: 1.75; padding: 18px 20px; overflow: auto; max-height: 640px; tab-size: 2; scrollbar-width: thin; } .highlighted-code code { font-size: inherit; } + .highlighted-code pre::-webkit-scrollbar { height: 10px; } + .highlighted-code pre::-webkit-scrollbar-thumb { background: var(--viva-border); border: 3px solid var(--viva-surface); border-radius: 999px; } .usage-block { margin-top: 14px; } .usage-block .highlighted-code pre { max-height: 420px; } .astro-code { color: var(--shiki-light); background-color: var(--shiki-light-bg); } From 9d4672a083d480ec9234d849087c6a6d1aab4da8 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 14:21:38 +0800 Subject: [PATCH 28/66] feat(ui): add the page range slider --- base/range_slider.go | 174 +++++++++++++++++++++++++++++++++++++++ ui/engine.go | 3 + ui/facade.go | 24 ++++++ ui/range_slider_paint.go | 20 +++++ ui/range_slider_test.go | 33 ++++++++ 5 files changed, 254 insertions(+) create mode 100644 base/range_slider.go create mode 100644 ui/range_slider_paint.go create mode 100644 ui/range_slider_test.go diff --git a/base/range_slider.go b/base/range_slider.go new file mode 100644 index 00000000..3d87165e --- /dev/null +++ b/base/range_slider.go @@ -0,0 +1,174 @@ +package base + +import "github.com/vivaui/viva/gfx" + +// RangeSliderState is a page range slider: two values on one track. The +// application owns Low and High; Min, Max and Step are the range and the snapping +// step (0..100 and 1 when zero). Handlers and Paint are the page control's bridge +// and are set by package ui. +type RangeSliderState struct { + Low, High float32 + Min, Max, Step float32 + + Handlers Handlers + // Paint paints the slider for the Control Draw; ui sets it. + Paint func(*DrawContext) + + lowID, highID gfx.ID + rect Rect + dragging int // 1 low, 2 high, 0 none + draw func(*DrawContext) +} + +// NewRangeSliderState returns a range slider holding low and high. +func NewRangeSliderState(low, high float32) *RangeSliderState { + return &RangeSliderState{Low: low, High: high, Min: 0, Max: 100, Step: 1} +} + +// SetTrack records the rectangle and thumb identities of the last paint, for +// the pointer handlers. +func (s *RangeSliderState) SetTrack(rect Rect, lowID, highID gfx.ID) { + s.rect, s.lowID, s.highID = rect, lowID, highID +} + +// DrawFunc is Draw as a stable function value, so a warm paint allocates nothing. +func (s *RangeSliderState) DrawFunc() func(*DrawContext) { + if s.draw == nil { + s.draw = s.Draw + } + return s.draw +} + +func (s *RangeSliderState) bounds() (minimum, maximum, step float32) { + minimum, maximum, step = s.Min, s.Max, s.Step + if maximum <= minimum { + maximum = minimum + 100 + } + if step <= 0 { + step = 1 + } + return +} + +// Draw paints the slider when package ui installed the painter. +func (s *RangeSliderState) Draw(d *DrawContext) { + if s.Paint != nil { + s.Paint(d) + } +} + +// Key moves the focused thumb with the arrows, PageUp/PageDown, Home and End. +func (s *RangeSliderState) Key(event gfx.KeyEvent) gfx.EventResult { + if event.Release { + return gfx.EventResult{} + } + index := -1 + if event.Target == s.lowID { + index = 0 + } else if event.Target == s.highID { + index = 1 + } + if index < 0 { + return gfx.EventResult{} + } + minimum, maximum, step := s.bounds() + value := s.value(index) + page := max((maximum-minimum)*0.1, step) + target := value + switch event.Key { + case gfx.KeyLeft, gfx.KeyDown: + target -= step + case gfx.KeyRight, gfx.KeyUp: + target += step + case gfx.KeyPageDown: + target -= page + case gfx.KeyPageUp: + target += page + case gfx.KeyHome: + target = minimum + case gfx.KeyEnd: + target = maximum + default: + return gfx.EventResult{} + } + target = min(max(target, minimum), maximum) + if index == 0 { + target = min(target, s.High) + } else { + target = max(target, s.Low) + } + if target == value { + return gfx.EventResult{Handled: true} + } + s.setValue(index, target) + return gfx.EventResult{Handled: true, Repaint: true, Focus: event.Target, FocusVisible: true} +} + +// Pointer drags the thumb under the pointer, or the clicked track position. +func (s *RangeSliderState) Pointer(event gfx.PointerEvent) gfx.EventResult { + switch event.Kind { + case gfx.PointerDown: + switch event.Target { + case s.lowID: + s.dragging = 1 + case s.highID: + s.dragging = 2 + default: + return gfx.EventResult{} + } + return gfx.EventResult{Handled: true, Repaint: true, Focus: event.Target, FocusVisible: true} + case gfx.PointerMove: + if s.dragging == 0 { + return gfx.EventResult{} + } + target := s.valueAt(event.X) + if s.dragging == 1 { + target = min(target, s.High) + } else { + target = max(target, s.Low) + } + s.setValue(s.dragging-1, target) + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.PointerUp: + if s.dragging == 0 { + return gfx.EventResult{} + } + s.dragging = 0 + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.PointerExit: + if s.dragging != 0 { + s.dragging = 0 + return gfx.EventResult{Handled: true} + } + } + return gfx.EventResult{} +} + +func (s *RangeSliderState) value(index int) float32 { + if index == 0 { + return s.Low + } + return s.High +} + +func (s *RangeSliderState) setValue(index int, value float32) { + minimum, maximum, step := s.bounds() + value = min(max(value, minimum), maximum) + if step > 0 { + value = minimum + float32(int((value-minimum)/step+0.5))*step + } + if index == 0 { + s.Low = min(value, s.High) + } else { + s.High = max(value, s.Low) + } +} + +func (s *RangeSliderState) valueAt(x float32) float32 { + minimum, maximum, _ := s.bounds() + if s.rect.Width <= 0 { + return minimum + } + fraction := (x - s.rect.X) / s.rect.Width + return min(max(minimum+fraction*(maximum-minimum), minimum), maximum) +} diff --git a/ui/engine.go b/ui/engine.go index a2fb65e6..b9569f9e 100644 --- a/ui/engine.go +++ b/ui/engine.go @@ -64,6 +64,9 @@ type PopoverDecl = base.PopoverDecl type PopoverSpec = base.PopoverSpec type ScrollState = base.ScrollState +// RangeSliderState is the two values and range of a RangeSlider. +type RangeSliderState = base.RangeSliderState + // ScrollAreaGeometry is the complete deterministic layout of one scroll area: // its viewport, translated content, tracks, thumbs and corner. type ScrollAreaGeometry = base.ScrollAreaGeometry diff --git a/ui/facade.go b/ui/facade.go index 4ddd444a..4b23bf48 100644 --- a/ui/facade.go +++ b/ui/facade.go @@ -251,6 +251,30 @@ func Slider(c C, state *SliderState) Box { return base.Slider(c, state) } func SliderBase(c C, state *SliderState) Box { return base.SliderBase(c, state) } +// NewRangeSliderState returns a range slider holding low and high. +func NewRangeSliderState(low, high float32) *RangeSliderState { + return base.NewRangeSliderState(low, high) +} + +// RangeSlider is a two-thumb slider over one track: Low and High are the +// values, Min, Max and Step the range. It is a Control, so its thumbs take the +// focus and the keyboard. +func RangeSlider(c C, state *RangeSliderState) Box { + if state == nil { + panic("ui: RangeSlider needs its RangeSliderState") + } + if state.Handlers.Key == nil { + state.Handlers.Key = state.Key + state.Handlers.Pointer = state.Pointer + } + if state.Paint == nil { + state.Paint = func(d *base.DrawContext) { paintRangeSlider(d, state) } + } + return Control(c, "Range", &state.Handlers). + Height(c.Theme().Metrics.ControlHeight). + Draw(state.DrawFunc()) +} + func Splitter(c C, state *SplitterState) Box { return base.Splitter(c, state) } func SplitButton(c C, spec SplitButtonSpec) Box { return base.SplitButton(c, spec) } diff --git a/ui/range_slider_paint.go b/ui/range_slider_paint.go new file mode 100644 index 00000000..81cde1b6 --- /dev/null +++ b/ui/range_slider_paint.go @@ -0,0 +1,20 @@ +package ui + +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" +) + +// paintRangeSlider paints a page range slider and records the thumb rectangles +// its pointer handlers use. +func paintRangeSlider(d *base.DrawContext, s *base.RangeSliderState) { + parts := s.Handlers.Parts() + lowID, highID := parts.At(0), parts.At(1) + s.SetTrack(d.Rect, lowID, highID) + thumbs := []components.SliderThumbValue{ + {ID: lowID, Label: "Minimum", Value: s.Low}, + {ID: highID, Label: "Maximum", Value: s.High}, + } + components.BeginRangeSlider(d.Canvas, *d.Theme, d.Rect, thumbs). + Range(s.Min, s.Max).Step(s.Step).Paint("Range") +} diff --git a/ui/range_slider_test.go b/ui/range_slider_test.go new file mode 100644 index 00000000..5d36e215 --- /dev/null +++ b/ui/range_slider_test.go @@ -0,0 +1,33 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// A RangeSlider is a page control with two focusable thumbs; dragging the low +// thumb moves its value and keeps it below the high one. +func TestRangeSliderDragsItsThumbs(t *testing.T) { + state := ui.NewRangeSliderState(20, 80) + d := openPage(t, func(c ui.C) { + ui.Row(c).Children(func() { + ui.RangeSlider(c, state).Width(240) + }) + }) + low := d.hit("Minimum").Bounds + x, y := center(low) + if err := d.driver.Press(x, y, gfx.PointerButtonPrimary); err != nil { + t.Fatal(err) + } + if err := d.driver.Move(x+40, y); err != nil { + t.Fatal(err) + } + if err := d.driver.Release(x+40, y, gfx.PointerButtonPrimary); err != nil { + t.Fatal(err) + } + if state.Low <= 20 || state.Low >= state.High { + t.Fatalf("low=%v high=%v after dragging", state.Low, state.High) + } +} From 18cf83958fcdd62fbe1d981c30afd220626661bb Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 14:24:45 +0800 Subject: [PATCH 29/66] docs(website): center the docs grid and restyle code blocks --- website/src/styles/site.css | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/website/src/styles/site.css b/website/src/styles/site.css index ab6a2a3d..9d53b5ca 100644 --- a/website/src/styles/site.css +++ b/website/src/styles/site.css @@ -85,8 +85,8 @@ .language-switch { display: flex; gap: 3px; padding: 3px; border: 1px solid var(--viva-border); border-radius: 6px; font-size: 13px; } .language-switch a { padding: 1px 7px; color: var(--viva-muted); border-radius: 3px; } .language-switch a[aria-current] { color: var(--viva-text); background: var(--viva-surface-hover); } - .docs-grid { max-width: 1440px; margin: auto; padding: 0 32px; display: grid; grid-template-columns: 200px minmax(0, 760px) 180px; gap: 40px; } - .docs-grid-wide { grid-template-columns: 200px minmax(0, 1fr); } + .docs-grid { max-width: 1536px; margin: auto; padding: 0 48px; display: grid; grid-template-columns: 240px minmax(0, 800px) 200px; gap: 48px; justify-content: center; } + .docs-grid-wide { grid-template-columns: 240px minmax(0, 1fr); } .sidebar { min-width: 0; } .sidebar-shell { position: sticky; top: var(--viva-header-height); } .sidebar-panel { display: flex; flex-direction: column; height: calc(100dvh - var(--viva-header-height)); padding: 40px 0 24px; gap: 32px; overflow-y: auto; } @@ -184,10 +184,10 @@ .section-intro { margin: 10px 0 18px; font-size: 15px; } .example-section { margin-top: 36px; } .example-summary { margin: 8px 0 16px; font-size: 15px; } - .example-demo { border: 1px solid var(--viva-border); border-radius: var(--viva-radius); overflow: hidden; } + .example-demo { border: 1px solid var(--viva-border); border-radius: 12px; overflow: hidden; background: var(--viva-background); } .example-toolbar { display: flex; align-items: center; justify-content: flex-end; gap: 8px; padding: 10px 12px; border-bottom: 1px solid var(--viva-border); } .preview-actions { display: flex; align-items: center; gap: 4px; } - .preview-canvas { position: relative; height: 260px; background: var(--viva-background); } + .preview-canvas { position: relative; height: 260px; background-color: var(--viva-background); background-image: radial-gradient(color-mix(in srgb, var(--viva-border) 55%, transparent) 1px, transparent 1px); background-size: 16px 16px; background-position: 0 0; } .preview-mount, .preview-frame { width: 100%; height: 100%; } .preview-frame { display: block; border: 0; background: var(--viva-background); } .preview-canvas:not([data-state='ready']) .preview-frame { visibility: hidden; } @@ -199,9 +199,10 @@ .copy-result { font-size: 12px; color: var(--viva-success); text-align: right; } .copy-result:empty { display: none; } .copy-failed { color: var(--viva-error); } - .code-block { border: 1px solid var(--viva-border); border-radius: 10px; overflow: hidden; background: var(--viva-surface); box-shadow: 0 1px 2px rgb(0 0 0 / 4%), 0 12px 32px -28px rgb(0 0 0 / 35%); transition: border-color .15s ease, box-shadow .15s ease; } - .code-block:hover { border-color: var(--viva-strong-border); box-shadow: 0 1px 2px rgb(0 0 0 / 5%), 0 16px 40px -28px rgb(0 0 0 / 42%); } - .code-toolbar { display: flex; justify-content: space-between; align-items: center; padding: 9px 12px; gap: 12px; border-bottom: 1px solid var(--viva-border); background: color-mix(in srgb, var(--viva-surface) 82%, var(--viva-background)); font-size: 12px; letter-spacing: .01em; color: var(--viva-muted); } + .code-block { position: relative; border: 1px solid transparent; border-radius: 12px; overflow: hidden; background: color-mix(in srgb, var(--viva-surface) 72%, var(--viva-background)); transition: border-color .15s ease, background-color .15s ease; } + .code-block:hover { border-color: var(--viva-border); background: color-mix(in srgb, var(--viva-surface) 86%, var(--viva-background)); } + .code-toolbar { position: absolute; top: 8px; right: 8px; z-index: 2; display: flex; align-items: center; justify-content: flex-end; padding: 0; gap: 0; border: 0; background: transparent; font-size: 0; color: var(--viva-muted); } + .code-toolbar > span { display: none; } .source-code { padding: 20px; overflow: auto; background: var(--viva-surface); font-size: 13px; line-height: 1.8; } .source-code code { font-size: inherit; } .section-heading { display: flex; justify-content: space-between; gap: 16px; align-items: center; } @@ -211,8 +212,10 @@ .code-copy-button { position: absolute; top: 8px; right: 8px; z-index: 2; display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; padding: 0; border: 1px solid var(--viva-border); border-radius: 6px; background: var(--viva-background); color: var(--viva-muted); line-height: 1; opacity: .82; } .code-copy-button:hover, .code-copy-button:focus-visible { opacity: 1; border-color: var(--viva-strong-border); color: var(--viva-text); } .code-copy-button[data-state='copied'] { color: var(--viva-success); } - .highlighted-code pre { font-size: 13px; line-height: 1.75; padding: 18px 20px; overflow: auto; max-height: 640px; tab-size: 2; scrollbar-width: thin; } + .highlighted-code pre { counter-reset: code-line; font-size: 13px; line-height: 1.75; padding: 18px 24px 18px 60px; overflow: auto; max-height: 640px; tab-size: 2; scrollbar-width: thin; background: transparent !important; } .highlighted-code code { font-size: inherit; } + .highlighted-code .line { display: block; position: relative; white-space: pre; } + .highlighted-code .line::before { counter-increment: code-line; content: counter(code-line); position: absolute; left: -38px; width: 26px; text-align: right; color: var(--viva-muted); opacity: .55; user-select: none; pointer-events: none; } .highlighted-code pre::-webkit-scrollbar { height: 10px; } .highlighted-code pre::-webkit-scrollbar-thumb { background: var(--viva-border); border: 3px solid var(--viva-surface); border-radius: 999px; } .usage-block { margin-top: 14px; } @@ -266,7 +269,7 @@ .docs-grid-guide .sidebar-shell { width: 220px; } } @media (max-width: 1150px) { - .docs-grid { grid-template-columns: 190px minmax(0, 1fr); gap: 32px; } + .docs-grid { grid-template-columns: 220px minmax(0, 1fr); gap: 32px; padding: 0 32px; } .on-this-page { display: none; } } @media (max-width: 800px) { @@ -307,7 +310,7 @@ } @layer layout { - .docs-grid-guide { grid-template-columns: 240px minmax(0, 780px) 200px; } + .docs-grid-guide { grid-template-columns: 240px minmax(0, 820px) 200px; } .guide-navigation { justify-content: flex-start; } .guide-navigation .component-group + .component-group { margin-top: 28px; } .home { max-width: 1200px; margin: auto; padding: 0 32px 72px; } From e83773b39e5552c7a76f1097486efc6b9a92a78e Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 14:32:28 +0800 Subject: [PATCH 30/66] docs(website): localize snippets and refine the component presentation --- internal/componentdemo/alert_dialog.go | 5 ++ internal/componentdemo/badge.go | 18 +++++- internal/componentdemo/button.go | 40 ++++++++++++- internal/componentdemo/card.go | 28 +++++++++ internal/componentdemo/checkbox.go | 10 +++- internal/componentdemo/color_picker.go | 4 ++ internal/componentdemo/color_swatch.go | 10 ++++ internal/componentdemo/combobox.go | 9 ++- internal/componentdemo/context_menu.go | 14 +++++ internal/componentdemo/dialog.go | 59 +++++++++++++++++++ internal/componentdemo/drawer.go | 20 +++++++ internal/componentdemo/dropdown_menu.go | 22 +++++++ internal/componentdemo/empty.go | 12 ++++ internal/componentdemo/field.go | 12 ++++ internal/componentdemo/form.go | 12 ++++ internal/componentdemo/input.go | 14 ++++- internal/componentdemo/item.go | 33 +++++++++++ internal/componentdemo/kbd.go | 6 ++ internal/componentdemo/label.go | 16 ++++- internal/componentdemo/list.go | 29 ++++++++- internal/componentdemo/message_scroller.go | 13 ++++ internal/componentdemo/multi_select.go | 22 +++++++ internal/componentdemo/native_select.go | 2 + internal/componentdemo/pagination.go | 18 ++++++ internal/componentdemo/popover.go | 27 +++++++++ internal/componentdemo/progress.go | 10 ++++ internal/componentdemo/radio_group.go | 10 ++++ internal/componentdemo/resizable.go | 18 ++++++ internal/componentdemo/scroll_area.go | 18 ++++++ internal/componentdemo/select.go | 2 + internal/componentdemo/separator.go | 16 +++++ internal/componentdemo/sheet.go | 22 +++++++ internal/componentdemo/single_select.go | 8 ++- internal/componentdemo/slider.go | 14 ++++- internal/componentdemo/spinner.go | 3 + internal/componentdemo/split_button.go | 23 +++++++- internal/componentdemo/state.go | 2 + internal/componentdemo/switch.go | 12 +++- internal/componentdemo/table.go | 58 +++++++++++++++++- internal/componentdemo/tabs.go | 33 +++++++++++ internal/componentdemo/textarea.go | 3 +- internal/componentdemo/toggle.go | 16 ++++- internal/componentdemo/tooltip.go | 7 +++ internal/componentdemo/tree.go | 31 ++++++++++ internal/componentdemo/tree_navigation.go | 19 ++++++ internal/componentdemo/typography.go | 21 +++++++ tools/docs/catalog.go | 3 +- tools/docs/catalog_test.go | 13 +++- website/site.test.mjs | 2 +- website/src/components/Preview.svelte | 8 ++- website/src/components/Sidebar.svelte | 19 ++---- website/src/pages/[lang]/ui/[component].astro | 3 +- website/src/styles/site.css | 22 +++++-- 53 files changed, 821 insertions(+), 50 deletions(-) diff --git a/internal/componentdemo/alert_dialog.go b/internal/componentdemo/alert_dialog.go index d368d5b5..0c6f690c 100644 --- a/internal/componentdemo/alert_dialog.go +++ b/internal/componentdemo/alert_dialog.go @@ -23,6 +23,11 @@ if canvas.Clicked(confirmID) || canvas.Clicked(cancelID) { Description: "This cannot be undone. Local data will be removed.", Scope: scope, ActionID: confirmID, CancelID: cancelID, ActionLabel: "Delete", CancelLabel: "Cancel", +})`, PageSnippetZh: `ui.AlertDialog(c, ui.AlertDialogSpec{ + Title: "永久删除这个项目?", + Description: "此操作无法撤销,本地数据将被移除。", + Scope: scope, ActionID: confirmID, CancelID: cancelID, + ActionLabel: "删除", CancelLabel: "取消", })`}, {ID: "media", Title: "带媒体的小尺寸", Description: "预留可由调用方绘制的媒体区域。", Snippet: `dialog := components.BeginAlertDialog(canvas, theme, viewport, components.AlertDialogOptions{ Layer: 8, Scope: scope, ActionID: confirmID, CancelID: cancelID, diff --git a/internal/componentdemo/badge.go b/internal/componentdemo/badge.go index 494b4a6c..bf215392 100644 --- a/internal/componentdemo/badge.go +++ b/internal/componentdemo/badge.go @@ -34,7 +34,12 @@ for index, label := range labels { ui.Badge(c, "99+").Secondary() ui.Badge(c, "Published").Outline() }) -ui.Text(c, "Display only; no click target is declared.").Muted()`}, +ui.Text(c, "Display only; no click target is declared.").Muted()`, PageSnippetZh: `ui.Flow(c).Gap(12).Children(func() { + ui.Badge(c, "New") + ui.Badge(c, "99+").Secondary() + ui.Badge(c, "已发布").Outline() +}) +ui.Text(c, "仅展示状态,不声明点击区域。").Muted()`}, {ID: "variants", Title: "六种变体", Description: "默认、次要、危险、描边、幽灵与链接外观;均为展示标签。", Snippet: `labels := []string{"Default", "Secondary", "Destructive", "Outline", "Ghost", "Link"} variants := []components.BadgeVariant{ components.BadgeDefault, components.BadgeSecondary, components.BadgeDestructive, @@ -62,6 +67,13 @@ for index, label := range labels { ui.Badge(c, "Outline").Outline() ui.Badge(c, "Ghost").Ghost() ui.Badge(c, "Link").Link() +})`, PageSnippetZh: `ui.Flow(c).Gap(12).Children(func() { + ui.Badge(c, "Default") + ui.Badge(c, "Secondary").Secondary() + ui.Badge(c, "Destructive").Destructive() + ui.Badge(c, "Outline").Outline() + ui.Badge(c, "Ghost").Ghost() + ui.Badge(c, "Link").Link() })`}, {ID: "long-text", Title: "长中文", Description: "完整展示长中文及中英混排标签,空间不足时另起一行。", Snippet: `labels := []string{"In review", "This is a long status label", "Viva native component · Published"} variants := []components.BadgeVariant{ @@ -86,6 +98,10 @@ for index, label := range labels { ui.Badge(c, "In review").Secondary() ui.Badge(c, "This is a long status label").Outline() ui.Badge(c, "Viva native component · Published") +})`, PageSnippetZh: `ui.Flow(c).Gap(12).Children(func() { + ui.Badge(c, "审核中").Secondary() + ui.Badge(c, "这是一条长中文状态标签").Outline() + ui.Badge(c, "Viva 原生组件 · 已发布") })`}, }, } diff --git a/internal/componentdemo/button.go b/internal/componentdemo/button.go index ed6bbdd6..46473c8a 100644 --- a/internal/componentdemo/button.go +++ b/internal/componentdemo/button.go @@ -17,7 +17,11 @@ var buttonComponent = Component{ if ui.Button(c, "Click me").Self(ui.Start).Clicked() { m.clicks++ } -ui.Text(c, "Click the button, or use Tab / Enter.").Muted()`, Height: 180}, +ui.Text(c, "Click the button, or use Tab / Enter.").Muted()`, PageSnippetZh: `ui.Textf(c, "点击:%d", m.clicks) +if ui.Button(c, "Click me").Self(ui.Start).Clicked() { + m.clicks++ +} +ui.Text(c, "点击按钮,或用 Tab / Enter 操作。").Muted()`, Height: 180}, {ID: "variants", Title: "六种变体", Description: "六种生产按钮外观共享同一个点击计数。", Snippet: `ui.Grid(c, 128).Gap(12).Children(func() { ui.Button(c, "Default").Clicked() ui.Button(c, "Destructive").Destructive().Clicked() @@ -46,7 +50,28 @@ ui.Grid(c, 128).Gap(12).Children(func() { m.clicks++ } }) -ui.Text(c, "Six appearances; every activation counts.").Muted()`, Height: 230}, +ui.Text(c, "Six appearances; every activation counts.").Muted()`, PageSnippetZh: `ui.Textf(c, "点击:%d", m.clicks) +ui.Grid(c, 128).Gap(12).Children(func() { + if ui.Button(c, "Default").Clicked() { + m.clicks++ + } + if ui.Button(c, "Destructive").Destructive().Clicked() { + m.clicks++ + } + if ui.Button(c, "Outline").Outline().Clicked() { + m.clicks++ + } + if ui.Button(c, "Secondary").Secondary().Clicked() { + m.clicks++ + } + if ui.Button(c, "Ghost").Ghost().Clicked() { + m.clicks++ + } + if ui.Button(c, "Link").Link().Clicked() { + m.clicks++ + } +}) +ui.Text(c, "六种外观;每次激活都会计数。").Muted()`, Height: 230}, {ID: "disabled", Title: "禁用变体", Description: "六种变体保留禁用语义,不响应点击。", Snippet: `ui.Grid(c, 128).Gap(12).Children(func() { ui.Button(c, "Default").Disabled(true).Clicked() ui.Button(c, "Destructive").Destructive().Disabled(true).Clicked() @@ -63,7 +88,16 @@ ui.Grid(c, 128).Gap(12).Children(func() { ui.Button(c, "Ghost").Ghost().Disabled(true).Clicked() ui.Button(c, "Link").Link().Disabled(true).Clicked() }) -ui.Text(c, "All disabled; they neither count nor take focus.").Muted()`, Height: 230}, +ui.Text(c, "All disabled; they neither count nor take focus.").Muted()`, PageSnippetZh: `ui.Textf(c, "点击:%d", m.clicks) +ui.Grid(c, 128).Gap(12).Children(func() { + ui.Button(c, "Default").Disabled(true).Clicked() + ui.Button(c, "Destructive").Destructive().Disabled(true).Clicked() + ui.Button(c, "Outline").Outline().Disabled(true).Clicked() + ui.Button(c, "Secondary").Secondary().Disabled(true).Clicked() + ui.Button(c, "Ghost").Ghost().Disabled(true).Clicked() + ui.Button(c, "Link").Link().Disabled(true).Clicked() +}) +ui.Text(c, "全部禁用;不会计数或获得焦点。").Muted()`, Height: 230}, }, } diff --git a/internal/componentdemo/card.go b/internal/componentdemo/card.go index 43b22fb7..56fd3270 100644 --- a/internal/componentdemo/card.go +++ b/internal/componentdemo/card.go @@ -35,6 +35,20 @@ ui.Column(c).FillWidth().Pad(24).Gap(8). ui.Text(c, "idle GPU submissions").FontSize(theme.Metrics.FontSizeS).Muted() ui.Divider(c) ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() + })`, PageSnippetZh: `theme := c.Theme() +ring := theme.Foreground +ring.Alpha *= 0.10 +ui.Column(c).FillWidth().Pad(24).Gap(8). + Background(theme.Card).Border(1, ring). + Radius(theme.Metrics.RadiusSurface + 4).Shadow(gfx.ShadowXS).Children(func() { + ui.Text(c, "Native preview").FontSize(theme.Metrics.FontSizeM + 2). + Weight(gfx.WeightSemibold) + ui.Text(c, "保留场景节点,只在内容变化时重绘。"). + FontSize(theme.Metrics.FontSizeS).Muted() + ui.Text(c, "0").FontSize(28).Bold() + ui.Text(c, "idle GPU submissions").FontSize(theme.Metrics.FontSizeS).Muted() + ui.Divider(c) + ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() })`}, {ID: "compact", Title: "紧凑卡片", Description: "小尺寸使用生产 CardSpacing 缩减内边距。", Snippet: `size := components.CardSizeSmall ring := theme.Foreground @@ -59,6 +73,20 @@ ui.Column(c).FillWidth().Pad(16).Gap(8). ui.Text(c, "idle GPU submissions").FontSize(theme.Metrics.FontSizeS).Muted() ui.Divider(c) ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() + })`, PageSnippetZh: `theme := c.Theme() +ring := theme.Foreground +ring.Alpha *= 0.10 +ui.Column(c).FillWidth().Pad(16).Gap(8). + Background(theme.Card).Border(1, ring). + Radius(theme.Metrics.RadiusSurface + 4).Shadow(gfx.ShadowXS).Children(func() { + ui.Text(c, "Native preview").FontSize(theme.Metrics.FontSizeM). + Weight(gfx.WeightSemibold) + ui.Text(c, "保留场景节点,只在内容变化时重绘。"). + FontSize(theme.Metrics.FontSizeS).Muted() + ui.Text(c, "0").FontSize(28).Bold() + ui.Text(c, "idle GPU submissions").FontSize(theme.Metrics.FontSizeS).Muted() + ui.Divider(c) + ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() })`}, }, } diff --git a/internal/componentdemo/checkbox.go b/internal/componentdemo/checkbox.go index cfab7cc9..2453d074 100644 --- a/internal/componentdemo/checkbox.go +++ b/internal/componentdemo/checkbox.go @@ -13,7 +13,7 @@ var checkboxComponent = Component{ {ID: "default", Title: "接受条款", Description: "点击切换勾选;语义状态与可见反馈同步。", Snippet: `ui.Row(c).Gap(12).Items(ui.Center).Children(func() { ui.Checkbox(c, &accepted, "").Hit(terms, "Accept terms of use") ui.Text(c, "Accept terms of use").FontSize(theme.Metrics.FontSizeM) -})`, PageSnippet: `ui.Checkbox(c, &m.accepted, "Accept terms of use")`}, +})`, PageSnippet: `ui.Checkbox(c, &m.accepted, "Accept terms of use")`, PageSnippetZh: `ui.Checkbox(c, &m.accepted, "接受使用条款")`}, {ID: "selection", Title: "多项选择", Description: "三项桌面偏好独立选择,不模拟生产 API 尚未提供的混合态。", Snippet: `boxes := tree.Sub(page, tree.Name("box")) for index, label := range [...]string{"Show line numbers", "Format on save", "Restore last window"} { checked := selected&(1< 0 { + status = "主操作已触发" +} +if m.menuOpen { + status += " · 菜单:展开" +} +ui.Text(c, status).Muted() +ui.Wrap(c, "主操作与菜单热区各自支持键盘焦点和独立可访问名称。").Muted()`, }}, } diff --git a/internal/componentdemo/state.go b/internal/componentdemo/state.go index 84e023ff..163dbbba 100644 --- a/internal/componentdemo/state.go +++ b/internal/componentdemo/state.go @@ -17,6 +17,8 @@ type Example struct { // PageSnippet, when set, is the example's page-first code: ui.* calls with // this example's data and state. It takes the place of Snippet on the site. PageSnippet string + // PageSnippetZh is the Chinese site's page-first code for the same example. + PageSnippetZh string // Height is the preview height in pixels. Zero uses the page default. Height int } diff --git a/internal/componentdemo/switch.go b/internal/componentdemo/switch.go index d5b28305..c3a2b97e 100644 --- a/internal/componentdemo/switch.go +++ b/internal/componentdemo/switch.go @@ -13,7 +13,8 @@ var switchComponent = Component{ ui.Switch(c, &enabled, "").Hit(notifications, "Desktop notifications") ui.Text(c, "Desktop notifications").FontSize(theme.Metrics.FontSizeM) })`, PageSnippet: `enabled := false -ui.Switch(c, &enabled, "Desktop notifications")`}, +ui.Switch(c, &enabled, "Desktop notifications")`, PageSnippetZh: `enabled := false +ui.Switch(c, &enabled, "桌面通知")`}, {ID: "sizes", Title: "两种尺寸", Description: "默认与紧凑开关独立受控。", Snippet: `ui.Row(c).Gap(12).Children(func() { ui.Switch(c, &normal, "").Hit(defaultID, "Default size") ui.Switch(c, &compact, "").Hit(smallID, "Compact size").Small() @@ -21,13 +22,20 @@ ui.Switch(c, &enabled, "Desktop notifications")`}, ui.Row(c).Gap(12).Children(func() { ui.Switch(c, &normal, "Default size") ui.Switch(c, &compact, "Compact size").Small() +})`, PageSnippetZh: `normal, compact := false, false +ui.Row(c).Gap(12).Children(func() { + ui.Switch(c, &normal, "默认尺寸") + ui.Switch(c, &compact, "紧凑尺寸").Small() })`}, {ID: "states", Title: "启用与禁用", Description: "一个可切换开关和开、关两种禁用状态。", Snippet: `ui.Switch(c, ¬ify, "").Hit(notifyID, "Desktop notifications") ui.Switch(c, &off, "").Hit(offID, "Disabled · Off").Disabled(true) ui.Switch(c, &on, "").Hit(onID, "Disabled · On").Disabled(true)`, PageSnippet: `notifications, off, on := false, false, true ui.Switch(c, ¬ifications, "Desktop notifications") ui.Switch(c, &off, "Disabled · Off").Disabled(true) -ui.Switch(c, &on, "Disabled · On").Disabled(true)`}, +ui.Switch(c, &on, "Disabled · On").Disabled(true)`, PageSnippetZh: `notifications, off, on := false, false, true +ui.Switch(c, ¬ifications, "桌面通知") +ui.Switch(c, &off, "禁用 · 关闭").Disabled(true) +ui.Switch(c, &on, "禁用 · 开启").Disabled(true)`}, }, } diff --git a/internal/componentdemo/table.go b/internal/componentdemo/table.go index 76421e1f..bd10cc57 100644 --- a/internal/componentdemo/table.go +++ b/internal/componentdemo/table.go @@ -28,7 +28,18 @@ ui.Table(c, &m.table, ui.TableSpec{ Source: &bills, }) ui.Text(c, "Total · 3 items · ¥ 4,540").Muted() -ui.Text(c, "Click any data row to see its interactive feedback.").Muted()`}, +ui.Text(c, "Click any data row to see its interactive feedback.").Muted()`, PageSnippetZh: `bills := ui.TableRows{ + {"设计系统", "已支付", "¥ 2,400"}, + {"桌面构建", "处理中", "¥ 860"}, + {"性能审计", "待付款", "¥ 1,280"}, +} +ui.Table(c, &m.table, ui.TableSpec{ + Columns: columns, + Headers: []string{"项目", "状态", "金额"}, + Source: &bills, +}) +ui.Text(c, "合计 · 3 项 · ¥ 4,540").Muted() +ui.Text(c, "点击任意数据行以查看交互反馈。").Muted()`}, {ID: "selection", Title: "选择状态", Description: "点击稳定行 ID 切换调用方持有的选择位。", Snippet: `rows := tree.Sub(page, tree.Name("row")) table := components.BeginTable(canvas, theme, bounds, columns) table.Header([]string{"Item", "Status", "Amount"}) @@ -51,6 +62,21 @@ table := ui.Table(c, &m.table, ui.TableSpec{ if row, ok := table.RowClicked(); ok { m.table.Select(row) } +if row := m.table.Selected(); row >= 0 { + ui.Text(c, "Selected: "+bills[row][0]).Muted() +}`, PageSnippetZh: `bills := ui.TableRows{ + {"设计系统", "已支付", "¥ 2,400"}, + {"桌面构建", "处理中", "¥ 860"}, + {"性能审计", "待付款", "¥ 1,280"}, +} +table := ui.Table(c, &m.table, ui.TableSpec{ + Columns: columns, + Headers: []string{"项目", "状态", "金额"}, + Source: &bills, +}) +if row, ok := table.RowClicked(); ok { + m.table.Select(row) +} if row := m.table.Selected(); row >= 0 { ui.Text(c, "Selected: "+bills[row][0]).Muted() }`}, @@ -79,7 +105,22 @@ ui.Table(c, &m.table, ui.TableSpec{ Headers: []string{"Item", "Status", "Amount"}, Source: &bills, }) -ui.Text(c, "Item is left-aligned, status centered, amount right-aligned.").Muted()`}, +ui.Text(c, "Item is left-aligned, status centered, amount right-aligned.").Muted()`, PageSnippetZh: `bills := ui.TableRows{ + {"设计系统", "已支付", "¥ 2,400"}, + {"桌面构建", "处理中", "¥ 860"}, + {"性能审计", "待付款", "¥ 1,280"}, +} +columns := []style.TableColumn{ + {Width: 112, Alignment: style.TableAlignLeft}, + {Width: 88, Alignment: style.TableAlignCenter}, + {Alignment: style.TableAlignRight}, +} +ui.Table(c, &m.table, ui.TableSpec{ + Columns: columns, + Headers: []string{"项目", "状态", "金额"}, + Source: &bills, +}) +ui.Text(c, "项目左对齐,状态居中,金额右对齐。").Muted()`}, {ID: "overflow", Title: "溢出与表头", Description: "放不下的单元格以省略号结尾;FitTableHeadings 让定宽列至少放得下自己的表头。", Snippet: `columns := []components.TableColumn{{Width: 96}, {Width: 40}, {Alignment: components.TableAlignRight}} headings := []string{"Item", "Status", "Amount"} components.FitTableHeadings(canvas, theme, columns, headings) @@ -99,7 +140,18 @@ ui.Table(c, &m.table, ui.TableSpec{ Headers: []string{"Item", "Status", "Amount"}, Source: &bills, }) -ui.Text(c, "Item is cut with an ellipsis; Status grew to hold its heading.").Muted()`}, +ui.Text(c, "Item is cut with an ellipsis; Status grew to hold its heading.").Muted()`, PageSnippetZh: `bills := ui.TableRows{ + {"设计系统", "已支付", "¥ 2,400"}, + {"桌面构建", "处理中", "¥ 860"}, + {"性能审计", "待付款", "¥ 1,280"}, +} +columns := []style.TableColumn{{Width: 96}, {Width: 40}, {Alignment: style.TableAlignRight}} +ui.Table(c, &m.table, ui.TableSpec{ + Columns: columns, + Headers: []string{"项目", "状态", "金额"}, + Source: &bills, +}) +ui.Text(c, "项目被省略号截断;状态列已长到放得下表头。").Muted()`}, }, } diff --git a/internal/componentdemo/tabs.go b/internal/componentdemo/tabs.go index 9bf96811..f858bdbc 100644 --- a/internal/componentdemo/tabs.go +++ b/internal/componentdemo/tabs.go @@ -39,6 +39,25 @@ case "Settings": ui.Text(c, "Workspace settings") ui.Wrap(c, "Configure display and local runtime options.") }) +}`, PageSnippetZh: `labels := []string{"概览", "活动", "设置"} +tab := labels[0] +ui.Tabs(c, &tab, labels, nil) +switch tab { +case "概览": + ui.Column(c).Gap(8).Children(func() { + ui.Text(c, "项目概览") + ui.Wrap(c, "查看近期状态与关键摘要。") + }) +case "活动": + ui.Column(c).Gap(8).Children(func() { + ui.Text(c, "最近活动") + ui.Wrap(c, "跟踪保存、构建和发布记录。") + }) +case "设置": + ui.Column(c).Gap(8).Children(func() { + ui.Text(c, "工作区设置") + ui.Wrap(c, "配置显示与本地运行选项。") + }) }`}, {ID: "line", Title: "线形标签", Description: "透明列表与两像素活动指示条。", Snippet: `labels := []string{"Overview", "Activity", "Settings"} tab := labels[0] @@ -48,6 +67,12 @@ ui.Tabs(c, &tab, labels, nil).Line() ui.Column(c).Gap(8).Children(func() { ui.Text(c, "Project overview") ui.Wrap(c, "See recent status and key highlights.") +})`, PageSnippetZh: `labels := []string{"概览", "活动", "设置"} +tab := labels[0] +ui.Tabs(c, &tab, labels, nil).Line() +ui.Column(c).Gap(8).Children(func() { + ui.Text(c, "项目概览") + ui.Wrap(c, "查看近期状态与关键摘要。") })`}, {ID: "vertical", Title: "纵向标签", Description: "标签纵向排列,内容位于右侧。", Snippet: `labels := []string{"Overview", "Activity", "Settings"} tab := labels[0] @@ -62,6 +87,14 @@ ui.Row(c).Gap(20).Children(func() { ui.Text(c, "Project overview") ui.Wrap(c, "See recent status and key highlights.") }) +})`, PageSnippetZh: `labels := []string{"概览", "活动", "设置"} +tab := labels[0] +ui.Row(c).Gap(20).Children(func() { + ui.Tabs(c, &tab, labels, nil).Line().Vertical().Self(ui.Start) + ui.Column(c).Grow(1).Basis(0).Gap(8).Children(func() { + ui.Text(c, "项目概览") + ui.Wrap(c, "查看近期状态与关键摘要。") + }) })`}, }, } diff --git a/internal/componentdemo/textarea.go b/internal/componentdemo/textarea.go index 15ab82d1..dc922122 100644 --- a/internal/componentdemo/textarea.go +++ b/internal/componentdemo/textarea.go @@ -37,7 +37,8 @@ components.PaintTextarea(canvas, theme, field.Rect(), components.TextareaSnapsho ID: tree.ID(page, "description"), Label: "Project description", Hint: "Supports multiple lines", Value: value, DisplayValue: value, })`, PageSnippet: `notes := "Viva renders with the native GPU. An idle window keeps submitting no frames: with no input, animation, or network events it is not repainted, and no background timer polls.\nThe second paragraph is short." -ui.TextArea(c, ¬es, "Project description", "").Height(142)`}, +ui.TextArea(c, ¬es, "Project description", "").Height(142)`, PageSnippetZh: `notes := "Viva 使用原生 GPU 渲染。空闲时不会持续提交帧:没有输入、动画或网络事件时,窗口不会被重绘,也不会有后台定时器在轮询。\n第二段很短。" +ui.TextArea(c, ¬es, "项目说明", "").Height(142)`}, {ID: "grow", Title: "随内容增高", Description: "相当于 shadcn 的 field-sizing-content:高度随文本行数增长,超过上限后在框内滚动并跟随插入点。", Snippet: `width := min(size.Width-48, float32(540)) height := min(layout.ContentHeight(canvas, theme, value, width, false), float32(5)*20+16) field := ui.Slot(c).Height(height) diff --git a/internal/componentdemo/toggle.go b/internal/componentdemo/toggle.go index c1fa2194..90cf576c 100644 --- a/internal/componentdemo/toggle.go +++ b/internal/componentdemo/toggle.go @@ -22,7 +22,12 @@ for index, label := range [...]string{"B", "I", "U"} { ui.Toggle(c, &m.italic, "I").Outline() ui.Toggle(c, &m.underline, "U").Outline() }) -ui.Text(c, "Each button keeps its own active bit.").Muted()`}, +ui.Text(c, "Each button keeps its own active bit.").Muted()`, PageSnippetZh: `ui.Row(c).Gap(12).Children(func() { + ui.Toggle(c, &m.bold, "B").Outline() + ui.Toggle(c, &m.italic, "I").Outline() + ui.Toggle(c, &m.underline, "U").Outline() +}) +ui.Text(c, "每个按钮独立保存激活位。").Muted()`}, {ID: "variants", Title: "外观与尺寸", Description: "默认、描边、小号与大号变体。", Snippet: `small := components.BeginToggle(canvas, theme, tree.ID(page, "small"), bounds, active) if small.Small().Default("Small").Clicked() { active = !active @@ -32,13 +37,20 @@ large.Large().Outline("Large")`, PageSnippet: `ui.Row(c).Gap(16).Items(ui.Center ui.Toggle(c, &m.small, "Small").Small() ui.Toggle(c, &m.large, "Large").Large().Outline() }) -ui.Text(c, "Size comes from explicit chained options.").Muted()`}, +ui.Text(c, "Size comes from explicit chained options.").Muted()`, PageSnippetZh: `ui.Row(c).Gap(16).Items(ui.Center).Children(func() { + ui.Toggle(c, &m.small, "Small").Small() + ui.Toggle(c, &m.large, "Large").Large().Outline() +}) +ui.Text(c, "尺寸由显式链式选项决定。").Muted()`}, {ID: "states", Title: "校验与禁用", Description: "激活、错误和禁用状态。", Snippet: `invalid := tree.ID(page, "invalid") components.BeginToggle(canvas, theme, invalid, bounds, true).Invalid().Outline("Invalid") disabled := tree.ID(page, "disabled") components.BeginToggle(canvas, theme, disabled, bounds, false).Disabled().Outline("Disabled")`, PageSnippet: `ui.Row(c).Gap(16).Children(func() { ui.Toggle(c, &m.invalid, "Invalid").Outline() ui.Toggle(c, &m.disabled, "Disabled").Outline().Disabled(true) +})`, PageSnippetZh: `ui.Row(c).Gap(16).Children(func() { + ui.Toggle(c, &m.invalid, "Invalid").Outline() + ui.Toggle(c, &m.disabled, "Disabled").Outline().Disabled(true) })`}, }, } diff --git a/internal/componentdemo/tooltip.go b/internal/componentdemo/tooltip.go index a1946151..2f3dd36a 100644 --- a/internal/componentdemo/tooltip.go +++ b/internal/componentdemo/tooltip.go @@ -21,6 +21,8 @@ if open || canvas.Hovered() == trigger { Paint("Native synchronous tooltip") }`, PageSnippet: `ui.Button(c, "Hover or click"). Tooltip("Native synchronous tooltip, no background timer"). + TooltipOn(ui.TooltipTop)`, PageSnippetZh: `ui.Button(c, "悬停或点击"). + Tooltip("原生同步提示,无后台延时器"). TooltipOn(ui.TooltipTop)`}, {ID: "sides", Title: "四个方向", Description: "同屏展示上、右、下、左四种放置方向。", Snippet: `labels := [...]string{"Top", "Right", "Bottom", "Left"} sides := [...]components.TooltipSide{ @@ -34,6 +36,9 @@ for index, anchor := range anchors { }`, PageSnippet: `ui.Button(c, "Top").Tooltip("Top").TooltipOn(ui.TooltipTop) ui.Button(c, "Right").Tooltip("Right").TooltipOn(ui.TooltipRight) ui.Button(c, "Bottom").Tooltip("Bottom").TooltipOn(ui.TooltipBottom) +ui.Button(c, "Left").Tooltip("Left").TooltipOn(ui.TooltipLeft)`, PageSnippetZh: `ui.Button(c, "Top").Tooltip("Top").TooltipOn(ui.TooltipTop) +ui.Button(c, "Right").Tooltip("Right").TooltipOn(ui.TooltipRight) +ui.Button(c, "Bottom").Tooltip("Bottom").TooltipOn(ui.TooltipBottom) ui.Button(c, "Left").Tooltip("Left").TooltipOn(ui.TooltipLeft)`}, {ID: "clamped", Title: "视口约束", Description: "靠近边缘时将提示内容限制在视口内。", Snippet: `anchor := ui.Slot(c).Size(60, theme.Metrics.ControlHeight).Self(ui.Start).Rect() anchor.X, anchor.Width = size.Width-76, 60 // pin the trigger to the window edge @@ -41,6 +46,8 @@ components.BeginTooltip(canvas, theme, viewport, anchor, components.TooltipOptio Layer: 60, Side: components.TooltipBottom, MaxWidth: 176, }).Paint("Clamped to the viewport")`, PageSnippet: `ui.Button(c, "Hover or click").Self(ui.End). Tooltip("Clamped to the viewport"). + TooltipOn(ui.TooltipBottom)`, PageSnippetZh: `ui.Button(c, "悬停或点击").Self(ui.End). + Tooltip("原生同步提示,无后台延时器"). TooltipOn(ui.TooltipBottom)`}, }, } diff --git a/internal/componentdemo/tree.go b/internal/componentdemo/tree.go index 2e51c30b..19f5201b 100644 --- a/internal/componentdemo/tree.go +++ b/internal/componentdemo/tree.go @@ -33,6 +33,20 @@ if m.expanded { rows = 4 } ui.Tree(c, &m.tree, rows, func(i int) string { return labels[i] }, nil).Grow(1) +if _, ok := m.tree.Toggled(); ok { + m.expanded = !m.expanded +}`, PageSnippetZh: `labels := []string{"Production", "Gateway", "Database", "Worker"} +m.tree.Node = func(i int) ui.TreeNode { + if i == 0 { + return ui.TreeNode{Branch: true, Expanded: m.expanded} + } + return ui.TreeNode{Depth: 1} +} +rows := 1 +if m.expanded { + rows = 4 +} +ui.Tree(c, &m.tree, rows, func(i int) string { return labels[i] }, nil).Grow(1) if _, ok := m.tree.Toggled(); ok { m.expanded = !m.expanded }`}, @@ -55,6 +69,16 @@ m.tree.Node = func(i int) ui.TreeNode { return ui.TreeNode{Depth: 1, Selected: i-1 == m.selected} } ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, nil).Grow(1) +if i, ok := m.tree.Chosen(); ok { + m.selected = i - 1 +}`, PageSnippetZh: `labels := []string{"Production", "Gateway", "Database", "Worker"} +m.tree.Node = func(i int) ui.TreeNode { + if i == 0 { + return ui.TreeNode{Branch: true, Expanded: true} + } + return ui.TreeNode{Depth: 1, Selected: i-1 == m.selected} +} +ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, nil).Grow(1) if i, ok := m.tree.Chosen(); ok { m.selected = i - 1 }`}, @@ -74,6 +98,13 @@ m.tree.Node = func(i int) ui.TreeNode { } return ui.TreeNode{Depth: 1, Disabled: true} } +ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, nil).Grow(1)`, PageSnippetZh: `labels := []string{"Production", "Gateway", "Database", "Worker"} +m.tree.Node = func(i int) ui.TreeNode { + if i == 0 { + return ui.TreeNode{Branch: true, Expanded: true, Disabled: true} + } + return ui.TreeNode{Depth: 1, Disabled: true} +} ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, nil).Grow(1)`}, }, } diff --git a/internal/componentdemo/tree_navigation.go b/internal/componentdemo/tree_navigation.go index 46be2f08..9da9c5ad 100644 --- a/internal/componentdemo/tree_navigation.go +++ b/internal/componentdemo/tree_navigation.go @@ -31,6 +31,25 @@ if m.expanded { visible = items[:] } next, action, handled := ui.NavigateTree(visible, m.selected, event.Key, len(rows)) +if handled { + switch action { + case ui.TreeNavigationExpand: + m.expanded = true + case ui.TreeNavigationCollapse: + m.expanded = false + } + m.selected = next + return gfx.EventResult{Focus: m.rowIDs[next], FocusVisible: true, Handled: true, Repaint: true} +}`, PageSnippetZh: `rows := []string{"Production", "Gateway", "Database", "Worker"} +items := []ui.TreeNavigationItem{ + {Branch: true, Expanded: m.expanded}, + {Depth: 1}, {Depth: 1}, {Depth: 1}, +} +visible := items[:1] +if m.expanded { + visible = items[:] +} +next, action, handled := ui.NavigateTree(visible, m.selected, event.Key, len(rows)) if handled { switch action { case ui.TreeNavigationExpand: diff --git a/internal/componentdemo/typography.go b/internal/componentdemo/typography.go index 16901ea1..05cb040b 100644 --- a/internal/componentdemo/typography.go +++ b/internal/componentdemo/typography.go @@ -22,6 +22,11 @@ components.Typography(canvas, theme, h4.Rect(), components.TypographyH4, "Headin ui.Text(c, "Heading 2").FontSize(theme.Metrics.FontSizeL + 6).Weight(gfx.WeightSemibold) ui.Text(c, "Heading 3").FontSize(theme.Metrics.FontSizeL).Weight(gfx.WeightSemibold) ui.Text(c, "Heading 4").FontSize(theme.Metrics.FontSizeM + 7).Weight(gfx.WeightSemibold) +})`, PageSnippetZh: `ui.Column(c).Gap(6).Children(func() { + ui.Text(c, "一级标题").FontSize(theme.Metrics.FontSizeL * 1.5).Weight(gfx.WeightBold) + ui.Text(c, "二级标题").FontSize(theme.Metrics.FontSizeL + 6).Weight(gfx.WeightSemibold) + ui.Text(c, "三级标题").FontSize(theme.Metrics.FontSizeL).Weight(gfx.WeightSemibold) + ui.Text(c, "四级标题").FontSize(theme.Metrics.FontSizeM + 7).Weight(gfx.WeightSemibold) })`}, {ID: "content", Title: "正文角色", Description: "段落、引导、大号与小号正文。", Snippet: `lead := ui.Slot(c).Height(32) body := ui.Slot(c).Height(28) @@ -43,6 +48,15 @@ components.Typography(canvas, theme, small.Rect(), FontSize(theme.Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) ui.Text(c, "Small · Compact labels and supporting copy"). FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium) +})`, PageSnippetZh: `ui.Column(c).Gap(6).Children(func() { + ui.Paragraph(c, "原生桌面界面的完整文字系统", 0). + FontSize(theme.Metrics.FontSizeM + 7).Muted() + ui.Paragraph(c, "段落文字使用主题字号与前景色。", 0). + FontSize(theme.Metrics.FontSizeM + 3) + ui.Text(c, "Large · 关键说明"). + FontSize(theme.Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) + ui.Text(c, "Small · 紧凑标签与辅助内容"). + FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium) })`}, {ID: "muted", Title: "强调与弱化", Description: "正文、强调文字与弱化说明。", Snippet: `body := ui.Slot(c).Height(32) strong := ui.Slot(c).Height(30) @@ -59,6 +73,13 @@ components.Typography(canvas, theme, note.Rect(), FontSize(theme.Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) ui.Text(c, "Secondary notes use the theme's muted foreground."). FontSize(theme.Metrics.FontSizeM).Muted() +})`, PageSnippetZh: `ui.Column(c).Gap(6).Children(func() { + ui.Paragraph(c, "正文保持清晰、稳定且可读。", 0). + FontSize(theme.Metrics.FontSizeM + 3) + ui.Text(c, "关键结果使用更高字重。"). + FontSize(theme.Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) + ui.Text(c, "次要说明使用主题的弱化前景色。"). + FontSize(theme.Metrics.FontSizeM).Muted() })`}, }, } diff --git a/tools/docs/catalog.go b/tools/docs/catalog.go index fe16fb7c..c91183d6 100644 --- a/tools/docs/catalog.go +++ b/tools/docs/catalog.go @@ -23,6 +23,7 @@ type Demo struct { ID, Title, Description string Snippet string `json:"Snippet,omitempty"` PageSnippet string `json:"PageSnippet,omitempty"` + PageSnippetZh string `json:"PageSnippetZh,omitempty"` Height int `json:"Height,omitempty"` } @@ -107,7 +108,7 @@ func loadPages(root string) ([]Page, Manifest, error) { if _, err := componentdemo.New(component.ID, example.ID); err != nil { return nil, manifest, err } - page.Examples = append(page.Examples, Demo{example.ID, example.Title, example.Description, example.Snippet, example.PageSnippet, example.Height}) + page.Examples = append(page.Examples, Demo{example.ID, example.Title, example.Description, example.Snippet, example.PageSnippet, example.PageSnippetZh, example.Height}) } pages = append(pages, page) } diff --git a/tools/docs/catalog_test.go b/tools/docs/catalog_test.go index 9f99914e..f0015d7e 100644 --- a/tools/docs/catalog_test.go +++ b/tools/docs/catalog_test.go @@ -384,8 +384,17 @@ func TestFailedBuildPreservesPublishedPreview(t *testing.T) { func TestPageSnippetsArePageLevel(t *testing.T) { for _, component := range componentdemo.Catalog() { for _, example := range component.Examples { - if example.PageSnippet == "" { - continue + for _, snippet := range []string{example.PageSnippet, example.PageSnippetZh} { + if snippet == "" { + continue + } + if strings.Contains(snippet, "components.") || strings.Contains(snippet, "Begin") { + t.Errorf("%s/%s page snippet uses the canvas API: %q", component.ID, example.ID, snippet) + } + source := "package snippet\nfunc example() {\n" + snippet + "\n}\n" + if _, err := parser.ParseFile(token.NewFileSet(), "snippet.go", source, 0); err != nil { + t.Errorf("%s/%s page snippet does not parse: %v\n%s", component.ID, example.ID, err, snippet) + } } if strings.Contains(example.PageSnippet, "components.") || strings.Contains(example.PageSnippet, "Begin") { t.Errorf("%s/%s page snippet uses the canvas API: %q", component.ID, example.ID, example.PageSnippet) diff --git a/website/site.test.mjs b/website/site.test.mjs index d96b44af..841742eb 100644 --- a/website/site.test.mjs +++ b/website/site.test.mjs @@ -203,7 +203,7 @@ for (const locale of ['zh', 'en']) { assert.doesNotMatch(html, / example.PageSnippet || (example.Snippet && !/components\.|Begin/.test(example.Snippet))).length; + const withUsage = page.Examples.filter(example => (locale === 'zh' ? example.PageSnippetZh : example.PageSnippet) || example.PageSnippet || (example.Snippet && !/components\.|Begin/.test(example.Snippet))).length; assert.equal([...html.matchAll(/class="code-block usage-block"/g)].length, withUsage); for (const example of page.Examples) { assert.ok(html.includes(`id="example-${example.ID}"`)); diff --git a/website/src/components/Preview.svelte b/website/src/components/Preview.svelte index 61ab3b25..377579ea 100644 --- a/website/src/components/Preview.svelte +++ b/website/src/components/Preview.svelte @@ -101,9 +101,11 @@
-
- - + + {example.Title} +
+ +
diff --git a/website/src/components/Sidebar.svelte b/website/src/components/Sidebar.svelte index 2c7da79b..811a4b1e 100644 --- a/website/src/components/Sidebar.svelte +++ b/website/src/components/Sidebar.svelte @@ -19,9 +19,7 @@ const scrollKey = $derived(`viva-docs-sidebar-scroll:${locale}`); const current = $derived(items.find(item => item.ID === currentID)); const filtered = $derived(filterNavigation(items.map(item => ({ ...item, Title: componentLabel(locale, item.ID, item.Title), Category: categoryLabel(locale, item.Category) })), query)); - const groups = $derived([...new Set(filtered.map(item => item.Category))].map(category => ({ - category, items: filtered.filter(item => item.Category === category), - }))); + onMount(() => { mounted = true; @@ -104,16 +102,11 @@
{#if !filtered.length}

{text.noMatches}

{/if}

{query ? `${filtered.length} ${text.matches}` : ''}

diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index 1d40eac8..ca6f55ff 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -39,7 +39,8 @@ const sections = page.Sections.filter(section => section.ID !== 'source-ownershi {(() => { const own = example.Snippet && !/components\.|Begin/.test(example.Snippet); - const usage = example.PageSnippet || (own ? example.Snippet : ''); + const localized = locale === 'zh' ? example.PageSnippetZh : example.PageSnippet; + const usage = localized || example.PageSnippet || (own ? example.Snippet : ''); if (!usage) return

{text.canvasRecipe}

; return
{text.exampleUsage}
diff --git a/website/src/styles/site.css b/website/src/styles/site.css index 9d53b5ca..cbd9e892 100644 --- a/website/src/styles/site.css +++ b/website/src/styles/site.css @@ -11,6 +11,7 @@ its artwork. Prefixing keeps third-party page styles out of this theme. */ --viva-background: #fff; --viva-surface: #fafafa; + --viva-code-bg: #f4f4f5; --viva-surface-hover: #f4f4f5; --viva-text: #18181b; --viva-doc-secondary: #52525b; @@ -31,6 +32,7 @@ :root[data-theme='dark'] { --viva-background: #09090b; --viva-surface: #111113; + --viva-code-bg: #18181b; --viva-surface-hover: #27272a; --viva-text: #fafafa; --viva-doc-secondary: #a1a1aa; @@ -185,7 +187,17 @@ .example-section { margin-top: 36px; } .example-summary { margin: 8px 0 16px; font-size: 15px; } .example-demo { border: 1px solid var(--viva-border); border-radius: 12px; overflow: hidden; background: var(--viva-background); } - .example-toolbar { display: flex; align-items: center; justify-content: flex-end; gap: 8px; padding: 10px 12px; border-bottom: 1px solid var(--viva-border); } + .example-toolbar { position: relative; display: flex; align-items: center; height: 38px; padding: 0 12px; border-bottom: 1px solid var(--viva-border); background: var(--viva-surface); } + .window-dots { display: flex; align-items: center; gap: 7px; } + .window-dot { width: 10px; height: 10px; border-radius: 50%; } + .window-dot-close { background: #ff5f57; } + .window-dot-min { background: #febc2e; } + .window-dot-max { background: #28c840; } + .window-title { position: absolute; left: 50%; transform: translateX(-50%); max-width: 55%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 500; color: var(--viva-muted); } + .window-actions { display: flex; align-items: center; gap: 2px; margin-left: auto; } + .window-action { display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 26px; padding: 0; border: 0; border-radius: 6px; background: transparent; color: var(--viva-muted); } + .window-action:hover { background: var(--viva-surface-hover); color: var(--viva-text); } + .window-action:disabled { opacity: .45; } .preview-actions { display: flex; align-items: center; gap: 4px; } .preview-canvas { position: relative; height: 260px; background-color: var(--viva-background); background-image: radial-gradient(color-mix(in srgb, var(--viva-border) 55%, transparent) 1px, transparent 1px); background-size: 16px 16px; background-position: 0 0; } .preview-mount, .preview-frame { width: 100%; height: 100%; } @@ -199,8 +211,8 @@ .copy-result { font-size: 12px; color: var(--viva-success); text-align: right; } .copy-result:empty { display: none; } .copy-failed { color: var(--viva-error); } - .code-block { position: relative; border: 1px solid transparent; border-radius: 12px; overflow: hidden; background: color-mix(in srgb, var(--viva-surface) 72%, var(--viva-background)); transition: border-color .15s ease, background-color .15s ease; } - .code-block:hover { border-color: var(--viva-border); background: color-mix(in srgb, var(--viva-surface) 86%, var(--viva-background)); } + .code-block { position: relative; border: 1px solid transparent; border-radius: 12px; overflow: hidden; background: var(--viva-code-bg); transition: border-color .15s ease, background-color .15s ease; } + .code-block:hover { border-color: var(--viva-border); background: color-mix(in srgb, var(--viva-code-bg) 88%, var(--viva-surface)); } .code-toolbar { position: absolute; top: 8px; right: 8px; z-index: 2; display: flex; align-items: center; justify-content: flex-end; padding: 0; gap: 0; border: 0; background: transparent; font-size: 0; color: var(--viva-muted); } .code-toolbar > span { display: none; } .source-code { padding: 20px; overflow: auto; background: var(--viva-surface); font-size: 13px; line-height: 1.8; } @@ -214,8 +226,8 @@ .code-copy-button[data-state='copied'] { color: var(--viva-success); } .highlighted-code pre { counter-reset: code-line; font-size: 13px; line-height: 1.75; padding: 18px 24px 18px 60px; overflow: auto; max-height: 640px; tab-size: 2; scrollbar-width: thin; background: transparent !important; } .highlighted-code code { font-size: inherit; } - .highlighted-code .line { display: block; position: relative; white-space: pre; } - .highlighted-code .line::before { counter-increment: code-line; content: counter(code-line); position: absolute; left: -38px; width: 26px; text-align: right; color: var(--viva-muted); opacity: .55; user-select: none; pointer-events: none; } + .highlighted-code .line { display: inline; } + .highlighted-code .line::before { counter-increment: code-line; content: counter(code-line); display: inline-block; width: 24px; margin-left: -38px; margin-right: 14px; text-align: right; color: var(--viva-muted); opacity: .55; user-select: none; pointer-events: none; } .highlighted-code pre::-webkit-scrollbar { height: 10px; } .highlighted-code pre::-webkit-scrollbar-thumb { background: var(--viva-border); border: 3px solid var(--viva-surface); border-radius: 999px; } .usage-block { margin-top: 14px; } From 0db15f4658dc3862d7b836ce6ca146e2b22b7d82 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 14:33:53 +0800 Subject: [PATCH 31/66] docs(website): shrink the copy control and dismiss its notice --- website/src/components/CopyButton.svelte | 19 +++++++++++++++---- website/src/styles/site.css | 7 ++++--- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/website/src/components/CopyButton.svelte b/website/src/components/CopyButton.svelte index ea0b26cd..a5aac1dc 100644 --- a/website/src/components/CopyButton.svelte +++ b/website/src/components/CopyButton.svelte @@ -3,6 +3,7 @@ import Icon from './Icon.svelte'; import { Button } from '$lib/components/ui/button'; import { messages, type Locale } from '../lib/i18n'; + import { onDestroy } from 'svelte'; let { text, label, prominent = false, locale }: { text: string; label?: string; prominent?: boolean; locale: Locale } = $props(); const wording = $derived(messages[locale]); @@ -10,13 +11,23 @@ let pending = $state(false); let result = $state(''); let failed = $state(false); + let timer: ReturnType | undefined; + + function flash(message: string) { + clearTimeout(timer); + result = message; + timer = setTimeout(() => { result = ''; }, 1600); + } $effect(() => { text; + clearTimeout(timer); result = ''; failed = false; }); + onDestroy(() => clearTimeout(timer)); + async function copy() { const snapshot = text; pending = true; @@ -25,12 +36,12 @@ await copyText(snapshot); if (text === snapshot) { failed = false; - result = wording.copiedNotice; + flash(wording.copiedNotice); } } catch { if (text === snapshot) { failed = true; - result = wording.copyFailed; + flash(wording.copyFailed); } } finally { pending = false; @@ -39,8 +50,8 @@
- {result}
diff --git a/website/src/styles/site.css b/website/src/styles/site.css index cbd9e892..9e5f2fa1 100644 --- a/website/src/styles/site.css +++ b/website/src/styles/site.css @@ -207,10 +207,11 @@ .preview-overlay p { max-width: 44ch; overflow-wrap: anywhere; } .preview-error > svg { color: var(--viva-error); } - .copy-control { display: inline-flex; flex-direction: column; align-items: flex-end; gap: 4px; max-width: 260px; } - .copy-result { font-size: 12px; color: var(--viva-success); text-align: right; } + .copy-control { position: relative; display: inline-flex; flex-direction: column; align-items: flex-end; gap: 0; max-width: 260px; } + .copy-icon-button { width: 26px; height: 26px; padding: 0; } + .copy-result { position: absolute; top: calc(100% + 6px); right: 0; z-index: 3; padding: 4px 8px; border-radius: 6px; background: var(--viva-text); color: var(--viva-background); font-size: 11px; line-height: 1.4; white-space: nowrap; text-align: right; box-shadow: 0 6px 18px -8px rgb(0 0 0 / 35%); } .copy-result:empty { display: none; } - .copy-failed { color: var(--viva-error); } + .copy-failed { background: var(--viva-error); color: #fff; } .code-block { position: relative; border: 1px solid transparent; border-radius: 12px; overflow: hidden; background: var(--viva-code-bg); transition: border-color .15s ease, background-color .15s ease; } .code-block:hover { border-color: var(--viva-border); background: color-mix(in srgb, var(--viva-code-bg) 88%, var(--viva-surface)); } .code-toolbar { position: absolute; top: 8px; right: 8px; z-index: 2; display: flex; align-items: center; justify-content: flex-end; padding: 0; gap: 0; border: 0; background: transparent; font-size: 0; color: var(--viva-muted); } From 82b73d59b8c7ec4d746da236bf20753c2e19ca88 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 14:35:46 +0800 Subject: [PATCH 32/66] docs(website): keep the copy control small and visible --- website/src/styles/site.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/website/src/styles/site.css b/website/src/styles/site.css index 9e5f2fa1..857b9725 100644 --- a/website/src/styles/site.css +++ b/website/src/styles/site.css @@ -208,13 +208,13 @@ .preview-error > svg { color: var(--viva-error); } .copy-control { position: relative; display: inline-flex; flex-direction: column; align-items: flex-end; gap: 0; max-width: 260px; } - .copy-icon-button { width: 26px; height: 26px; padding: 0; } + .code-toolbar .copy-icon-button { width: 28px !important; height: 28px !important; min-height: 0 !important; padding: 0 !important; border-radius: 7px; } .copy-result { position: absolute; top: calc(100% + 6px); right: 0; z-index: 3; padding: 4px 8px; border-radius: 6px; background: var(--viva-text); color: var(--viva-background); font-size: 11px; line-height: 1.4; white-space: nowrap; text-align: right; box-shadow: 0 6px 18px -8px rgb(0 0 0 / 35%); } .copy-result:empty { display: none; } .copy-failed { background: var(--viva-error); color: #fff; } .code-block { position: relative; border: 1px solid transparent; border-radius: 12px; overflow: hidden; background: var(--viva-code-bg); transition: border-color .15s ease, background-color .15s ease; } .code-block:hover { border-color: var(--viva-border); background: color-mix(in srgb, var(--viva-code-bg) 88%, var(--viva-surface)); } - .code-toolbar { position: absolute; top: 8px; right: 8px; z-index: 2; display: flex; align-items: center; justify-content: flex-end; padding: 0; gap: 0; border: 0; background: transparent; font-size: 0; color: var(--viva-muted); } + .code-toolbar { position: absolute; top: 10px; right: 10px; z-index: 2; display: flex; align-items: center; justify-content: flex-end; padding: 0; gap: 0; border: 0; background: transparent; font-size: 0; color: var(--viva-muted); } .code-toolbar > span { display: none; } .source-code { padding: 20px; overflow: auto; background: var(--viva-surface); font-size: 13px; line-height: 1.8; } .source-code code { font-size: inherit; } From eb04a15693775452390db3f479f76b1a86fd3096 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 14:36:44 +0800 Subject: [PATCH 33/66] docs(website): drop the copied notice --- website/src/components/CopyButton.svelte | 1 - 1 file changed, 1 deletion(-) diff --git a/website/src/components/CopyButton.svelte b/website/src/components/CopyButton.svelte index a5aac1dc..ffcf5f06 100644 --- a/website/src/components/CopyButton.svelte +++ b/website/src/components/CopyButton.svelte @@ -53,5 +53,4 @@ - {result}
From 8363b0e87d692ae5c9a98916c6fe5c5e59c49c50 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 14:37:47 +0800 Subject: [PATCH 34/66] docs(website): set the code font to Geist Mono --- website/src/styles/site.css | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/website/src/styles/site.css b/website/src/styles/site.css index 857b9725..b165ecb0 100644 --- a/website/src/styles/site.css +++ b/website/src/styles/site.css @@ -1,3 +1,4 @@ +@import url('https://fonts.googleapis.com/css2?family=Geist+Mono:wght@400;500&display=swap'); @layer base { *, *::before, *::after { box-sizing: border-box; } :root { @@ -24,7 +25,7 @@ --viva-accent-border: #e4e4e7; --viva-error: #b91c1c; --viva-success: #15803d; - --viva-mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace; + --viva-mono: "Geist Mono", "SFMono-Regular", Consolas, "Liberation Mono", monospace; --viva-radius: 8px; --viva-header-height: 56px; color-scheme: light; From eaf280dc43c745640f131a85136c5898894ccd0c Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 14:41:45 +0800 Subject: [PATCH 35/66] docs(website): give every example a page call site --- internal/componentdemo/page_source.go | 1 + internal/componentdemo/page_usage.go | 1 + internal/componentdemo/toggle_group.go | 30 +++++++++++++++++-- website/site.test.mjs | 3 +- website/src/pages/[lang]/ui/[component].astro | 3 +- 5 files changed, 31 insertions(+), 7 deletions(-) diff --git a/internal/componentdemo/page_source.go b/internal/componentdemo/page_source.go index cb6de763..0a627b41 100644 --- a/internal/componentdemo/page_source.go +++ b/internal/componentdemo/page_source.go @@ -4,6 +4,7 @@ package componentdemo // documentation site links "Page API source" here when PageUsage exists; a // component without a page API links its own source instead. var pageSource = map[string]string{ + "toggle-group": "base/page_bases.go", "button": "base/controls.go", "badge": "base/badge.go", "checkbox": "base/controls.go", diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index 906796c7..833f92ae 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -4,6 +4,7 @@ package componentdemo // documentation site shows it above the examples; a component without an entry // is a canvas recipe, used inside ui.Control/Draw or copied by viva add. var pageUsage = map[string]string{ + "toggle-group": `ui.Row(c).Gap(0).Children(func() { ui.Toggle(c, &m.left, "Left").Outline(); ui.Toggle(c, &m.right, "Right").Outline() })`, "empty": `ui.Column(c).Fill().Center()`, "item": `ui.Row(c).Gap(8).FillWidth()`, "card": `ui.Column(c).Pad(16).Radius(12).Border(1, border)`, diff --git a/internal/componentdemo/toggle_group.go b/internal/componentdemo/toggle_group.go index bf44d22f..128d4b72 100644 --- a/internal/componentdemo/toggle_group.go +++ b/internal/componentdemo/toggle_group.go @@ -19,7 +19,15 @@ options := []components.ToggleGroupOption{ group := components.BeginToggleGroup(canvas, theme, bounds, options).Outline().Spacing(0) if id, ok := group.Paint().Clicked(); ok { selected, _ = id.In(items) -}`}, +}`, PageSnippet: `ui.Row(c).Gap(0).Children(func() { + ui.Toggle(c, &m.left, "Left").Outline() + ui.Toggle(c, &m.center, "Center").Outline() + ui.Toggle(c, &m.right, "Right").Outline() +})`, PageSnippetZh: `ui.Row(c).Gap(0).Children(func() { + ui.Toggle(c, &m.left, "左对齐").Outline() + ui.Toggle(c, &m.center, "居中").Outline() + ui.Toggle(c, &m.right, "右对齐").Outline() +})`}, {ID: "multiple", Title: "文本样式", Description: "每个选项独立切换的多选按钮组。", Snippet: `items := tree.Sub(page, tree.Name("item")) options := []components.ToggleGroupOption{ {ID: items.At(0), Label: "Bold", Active: flags&1 != 0}, @@ -31,7 +39,15 @@ group = group.Spacing(0).SizeToFit() if id, ok := group.Paint().Clicked(); ok { index, _ := id.In(items) flags ^= 1 << index -}`}, +}`, PageSnippet: `ui.Row(c).Gap(0).Children(func() { + ui.Toggle(c, &m.bold, "Bold").Outline() + ui.Toggle(c, &m.italic, "Italic").Outline() + ui.Toggle(c, &m.underline, "Underline").Outline() +})`, PageSnippetZh: `ui.Row(c).Gap(0).Children(func() { + ui.Toggle(c, &m.bold, "粗体").Outline() + ui.Toggle(c, &m.italic, "斜体").Outline() + ui.Toggle(c, &m.underline, "下划线").Outline() +})`}, {ID: "vertical", Title: "纵向与禁用", Description: "纵向描边组,包含一个禁用选项。", Snippet: `items := tree.Sub(page, tree.Name("item")) options := []components.ToggleGroupOption{ {ID: items.At(0), Label: "Left", Active: selected == 0}, @@ -42,7 +58,15 @@ group := components.BeginToggleGroup(canvas, theme, bounds, options).Vertical() group = group.Outline().Spacing(1) if id, ok := group.Paint().Clicked(); ok { selected, _ = id.In(items) -}`}, +}`, PageSnippet: `ui.Column(c).Gap(0).Children(func() { + ui.Toggle(c, &m.left, "Left").Outline() + ui.Toggle(c, &m.center, "Center").Outline() + ui.Toggle(c, &m.right, "Right").Outline() +})`, PageSnippetZh: `ui.Column(c).Gap(0).Children(func() { + ui.Toggle(c, &m.left, "左对齐").Outline() + ui.Toggle(c, &m.center, "居中").Outline() + ui.Toggle(c, &m.right, "右对齐").Outline() +})`}, }, } diff --git a/website/site.test.mjs b/website/site.test.mjs index 841742eb..9469fe17 100644 --- a/website/site.test.mjs +++ b/website/site.test.mjs @@ -203,8 +203,7 @@ for (const locale of ['zh', 'en']) { assert.doesNotMatch(html, / (locale === 'zh' ? example.PageSnippetZh : example.PageSnippet) || example.PageSnippet || (example.Snippet && !/components\.|Begin/.test(example.Snippet))).length; - assert.equal([...html.matchAll(/class="code-block usage-block"/g)].length, withUsage); + assert.equal([...html.matchAll(/class="code-block usage-block"/g)].length, page.Examples.length); for (const example of page.Examples) { assert.ok(html.includes(`id="example-${example.ID}"`)); } diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index ca6f55ff..004c1a57 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -40,8 +40,7 @@ const sections = page.Sections.filter(section => section.ID !== 'source-ownershi {(() => { const own = example.Snippet && !/components\.|Begin/.test(example.Snippet); const localized = locale === 'zh' ? example.PageSnippetZh : example.PageSnippet; - const usage = localized || example.PageSnippet || (own ? example.Snippet : ''); - if (!usage) return

{text.canvasRecipe}

; + const usage = localized || example.PageSnippet || (own ? example.Snippet : '') || `ui.Control(c, "${example.Title.replaceAll('"', '')}", &m.handlers).Draw(paint)`; return
{text.exampleUsage}
From c028841622dc61d48e4c087ca9e018467c153288 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 17:07:55 +0800 Subject: [PATCH 36/66] fix(windows): run a hidden window's wake without waiting for WM_PAINT --- internal/platform/windows/window_windows.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index c8f6e5e8..e2f6fdac 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -569,6 +569,21 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { case wmRedraw: // Keep posted redraws coalesced until WM_PAINT lets hardware input run first. state.redrawRequested = true + // A hidden or minimized window never receives WM_PAINT, so a wake that + // only invalidated the window would never run OnWake. Run the redraw + // here: the visibility gate runs OnWake and skips the paint, remembering + // the frame the first wake after Show must draw. + if state.hiddenByShow || state.iconic() { + state.redrawRequested = false + state.redraws.begin() + if state.config.OnRedraw != nil { + frame, redrawErr := state.config.OnRedraw() + if err := state.frameWithText(frame, redrawErr, false); err != nil || state.window == 0 { + return 0 + } + } + return 0 + } invalidateRect.Call(window, 0, 0) return 0 case wmGetObject: From 362a5dbee78920de5b540cbb88f91adfb23f22dc Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 17:16:10 +0800 Subject: [PATCH 37/66] feat(ui): add page-first views for canvas components --- app/painter.go | 2 +- base/accessors.go | 6 +- base/bases.go | 12 + base/drawer.go | 7 + base/elements.go | 29 +- base/page.go | 6 +- base/page_bases.go | 10 + base/select.go | 2 +- base/tabs.go | 13 + base/widgets.go | 7 +- cmd/gallery-web/main.go | 29 +- cmd/viva/initfiles/AGENTS.md.txt | 7 +- docs/maintaining-controls.md | 11 + internal/componentdemo/accordion.go | 46 +- internal/componentdemo/alert.go | 68 +- internal/componentdemo/alert_dialog.go | 42 +- internal/componentdemo/aspect_ratio.go | 16 +- internal/componentdemo/attachment.go | 229 +++-- internal/componentdemo/avatar.go | 198 ++++- internal/componentdemo/avatar_editor.go | 118 +-- internal/componentdemo/breadcrumb.go | 40 +- internal/componentdemo/bubble.go | 58 +- internal/componentdemo/button_group.go | 92 +- internal/componentdemo/calendar.go | 139 ++- internal/componentdemo/card.go | 64 +- internal/componentdemo/carousel.go | 209 ++++- internal/componentdemo/chart.go | 147 +++- internal/componentdemo/chart_area.go | 476 +++++++++- internal/componentdemo/code_diff.go | 44 + internal/componentdemo/code_editor.go | 8 +- internal/componentdemo/code_merge.go | 52 ++ internal/componentdemo/collapsible.go | 38 +- internal/componentdemo/color_picker.go | 10 +- internal/componentdemo/column_resize.go | 9 +- internal/componentdemo/combobox.go | 8 +- internal/componentdemo/command.go | 182 +++- internal/componentdemo/dialog.go | 18 +- internal/componentdemo/drawer.go | 22 +- internal/componentdemo/empty.go | 12 +- internal/componentdemo/field.go | 8 + internal/componentdemo/form.go | 8 + internal/componentdemo/hover_card.go | 157 +++- internal/componentdemo/icon_hover.go | 16 +- internal/componentdemo/image_view.go | 4 +- internal/componentdemo/input.go | 12 +- internal/componentdemo/input_group.go | 38 +- internal/componentdemo/input_otp.go | 10 +- internal/componentdemo/item.go | 8 +- internal/componentdemo/list.go | 64 +- internal/componentdemo/markdown.go | 121 ++- internal/componentdemo/marker.go | 52 +- internal/componentdemo/menubar.go | 144 +++- internal/componentdemo/message.go | 180 ++-- internal/componentdemo/message_scroller.go | 274 ++++-- internal/componentdemo/metric_card.go | 64 +- internal/componentdemo/native_select.go | 16 +- internal/componentdemo/navigation_menu.go | 191 ++-- internal/componentdemo/page_source.go | 133 ++- internal/componentdemo/page_usage.go | 84 +- internal/componentdemo/popover.go | 14 +- internal/componentdemo/progress.go | 12 +- internal/componentdemo/questionnaire.go | 50 +- internal/componentdemo/radio_group.go | 12 +- internal/componentdemo/reorder_grid.go | 142 +-- internal/componentdemo/reorder_list.go | 22 +- internal/componentdemo/resizable.go | 20 +- internal/componentdemo/segmented_control.go | 14 +- internal/componentdemo/select.go | 16 +- internal/componentdemo/sheet.go | 16 +- internal/componentdemo/sidebar.go | 204 ++++- internal/componentdemo/skeleton.go | 54 +- internal/componentdemo/slider.go | 8 +- internal/componentdemo/sonner.go | 38 +- internal/componentdemo/spinner.go | 36 +- internal/componentdemo/split_button.go | 12 +- internal/componentdemo/table.go | 20 + internal/componentdemo/tabs.go | 95 +- internal/componentdemo/textarea.go | 24 +- internal/componentdemo/toast.go | 40 +- internal/componentdemo/toggle_group.go | 4 +- internal/componentdemo/tooltip.go | 23 +- internal/componentdemo/tree_navigation.go | 6 +- internal/componentdemo/typography.go | 44 +- internal/gallery/gallery_drive_test.go | 15 +- tools/docs/catalog_test.go | 231 +++++ tools/docs/content.go | 2 - tools/webcheck/fixture/main.go | 27 +- ui/attachmentview/attachmentview.go | 396 +++++++++ ui/attachmentview/attachmentview_test.go | 217 +++++ ui/avatareditorview/avatareditorview.go | 217 +++++ ui/avatareditorview/avatareditorview_test.go | 234 +++++ ui/avatarview/avatarview.go | 384 +++++++++ ui/avatarview/avatarview_test.go | 179 ++++ ui/base_parity_test.go | 20 + ui/base_scan_test.go | 2 +- ui/bubble.go | 68 ++ ui/bubble_test.go | 36 + ui/calendarview/calendarview.go | 123 +++ ui/calendarview/calendarview_test.go | 203 +++++ ui/carouselview/carouselview.go | 214 +++++ ui/carouselview/carouselview_test.go | 221 +++++ ui/chartview/bar.go | 107 +++ ui/chartview/chartview.go | 251 ++++++ ui/chartview/chartview_test.go | 354 ++++++++ ui/chartview/container.go | 112 +++ ui/chartview/page.go | 90 ++ ui/codeeditor/canvas.go | 98 +++ ui/codeeditor/codeeditor.go | 172 ++++ ui/codeeditor/codeeditor_test.go | 404 +++++++++ ui/codeeditor/diff.go | 115 +++ ui/codeeditor/findbar.go | 146 ++++ ui/codeeditor/merge.go | 113 +++ ui/columnresizeview/columnresizeview.go | 131 +++ ui/columnresizeview/columnresizeview_test.go | 82 ++ ui/commandview/commandview.go | 502 +++++++++++ ui/commandview/commandview_test.go | 251 ++++++ ui/disclosure.go | 166 ++++ ui/disclosure_test.go | 113 +++ ui/engine.go | 15 +- ui/facade.go | 9 +- .../hierarchypicker}/hierarchypicker.go | 0 .../hierarchypicker}/hierarchypicker_test.go | 2 +- ui/hovercardview/hovercardview.go | 357 ++++++++ ui/hovercardview/hovercardview_test.go | 281 ++++++ ui/markdownview/markdownview.go | 277 ++++++ ui/markdownview/markdownview_test.go | 186 ++++ ui/menubarview/menubarview.go | 613 +++++++++++++ ui/menubarview/menubarview_test.go | 239 +++++ ui/messagescrollerview/messagescrollerview.go | 321 +++++++ .../messagescrollerview_test.go | 217 +++++ ui/messageview/messageview.go | 255 ++++++ ui/messageview/messageview_test.go | 194 +++++ .../multiselect}/multiselect.go | 0 .../multiselect}/multiselect_test.go | 2 +- ui/navigationmenuview/navigationmenuview.go | 815 ++++++++++++++++++ .../navigationmenuview_test.go | 229 +++++ ui/page_test.go | 15 +- ui/reordergridview/reordergridview.go | 293 +++++++ ui/reordergridview/reordergridview_test.go | 207 +++++ ui/tabs_icon_test.go | 26 + ui/tabs_paint.go | 20 +- website/content/guides/en/components.md | 2 +- .../content/guides/en/declarative-layout.md | 2 +- website/content/guides/zh/components.md | 2 +- .../content/guides/zh/declarative-layout.md | 2 +- website/src/lib/i18n.test.ts | 8 +- website/src/lib/i18n.ts | 19 +- website/src/pages/[lang]/ui/[component].astro | 35 +- 148 files changed, 14570 insertions(+), 1065 deletions(-) create mode 100644 ui/attachmentview/attachmentview.go create mode 100644 ui/attachmentview/attachmentview_test.go create mode 100644 ui/avatareditorview/avatareditorview.go create mode 100644 ui/avatareditorview/avatareditorview_test.go create mode 100644 ui/avatarview/avatarview.go create mode 100644 ui/avatarview/avatarview_test.go create mode 100644 ui/bubble.go create mode 100644 ui/bubble_test.go create mode 100644 ui/calendarview/calendarview.go create mode 100644 ui/calendarview/calendarview_test.go create mode 100644 ui/carouselview/carouselview.go create mode 100644 ui/carouselview/carouselview_test.go create mode 100644 ui/chartview/bar.go create mode 100644 ui/chartview/chartview.go create mode 100644 ui/chartview/chartview_test.go create mode 100644 ui/chartview/container.go create mode 100644 ui/chartview/page.go create mode 100644 ui/codeeditor/canvas.go create mode 100644 ui/codeeditor/codeeditor.go create mode 100644 ui/codeeditor/codeeditor_test.go create mode 100644 ui/codeeditor/diff.go create mode 100644 ui/codeeditor/findbar.go create mode 100644 ui/codeeditor/merge.go create mode 100644 ui/columnresizeview/columnresizeview.go create mode 100644 ui/columnresizeview/columnresizeview_test.go create mode 100644 ui/commandview/commandview.go create mode 100644 ui/commandview/commandview_test.go create mode 100644 ui/disclosure.go create mode 100644 ui/disclosure_test.go rename {hierarchypicker => ui/hierarchypicker}/hierarchypicker.go (100%) rename {hierarchypicker => ui/hierarchypicker}/hierarchypicker_test.go (98%) create mode 100644 ui/hovercardview/hovercardview.go create mode 100644 ui/hovercardview/hovercardview_test.go create mode 100644 ui/markdownview/markdownview.go create mode 100644 ui/markdownview/markdownview_test.go create mode 100644 ui/menubarview/menubarview.go create mode 100644 ui/menubarview/menubarview_test.go create mode 100644 ui/messagescrollerview/messagescrollerview.go create mode 100644 ui/messagescrollerview/messagescrollerview_test.go create mode 100644 ui/messageview/messageview.go create mode 100644 ui/messageview/messageview_test.go rename {multiselect => ui/multiselect}/multiselect.go (100%) rename {multiselect => ui/multiselect}/multiselect_test.go (99%) create mode 100644 ui/navigationmenuview/navigationmenuview.go create mode 100644 ui/navigationmenuview/navigationmenuview_test.go create mode 100644 ui/reordergridview/reordergridview.go create mode 100644 ui/reordergridview/reordergridview_test.go create mode 100644 ui/tabs_icon_test.go diff --git a/app/painter.go b/app/painter.go index dd666258..5e2d5ca1 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1318,7 +1318,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { alignment := input.Alignment if bounds == (gfx.Rect{}) { bounds = context.TextBounds - if bounds == (gfx.Rect{}) { + if bounds.Width <= 0 || bounds.Height <= 0 { bounds = context.Bounds } } diff --git a/base/accessors.go b/base/accessors.go index fdb1d306..b2b83cd5 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -761,9 +761,6 @@ func (x *Page) GetHeld() [2]armedButton { return x.held } // GetHoverArea reads the hoverArea of Page for the styled painting layer. func (x *Page) GetHoverArea() gfx.ID { return x.hoverArea } -// GetIcons reads the icons of Page for the styled painting layer. -func (x *Page) GetIcons() []gfx.Icon { return x.icons } - // GetIntKeys reads the intKeys of Page for the styled painting layer. func (x *Page) GetIntKeys() map[intKey]keyEntry { return x.intKeys } @@ -1209,6 +1206,9 @@ func (x *TableState) GetSortColumn() int32 { return x.sortColumn } // GetLabels reads the labels of TabsDecl for the styled painting layer. func (x *TabsDecl) GetLabels() []string { return x.labels } +// GetIcon reads the icon function of TabsDecl for the styled painting layer. +func (x *TabsDecl) GetIcon() func(index int) gfx.Icon { return x.icon } + // GetLine reads the line of TabsDecl for the styled painting layer. func (x *TabsDecl) GetLine() bool { return x.line } diff --git a/base/bases.go b/base/bases.go index b4da6923..ba4b7ec1 100644 --- a/base/bases.go +++ b/base/bases.go @@ -88,6 +88,18 @@ func (f *Frame) ComboboxBase(ID gfx.ID, Label, Value string, open bool) Box { return b.HitWith(ID, Label, gfx.HitOptions{Role: gfx.RoleCombobox, Value: Value, Expanded: open, Expandable: true}) } +// DisclosureBase adds a disclosure header without a look: a row that reports Clicked and, +// to assistive technology, is a button that is expanded or not. The caller paints the +// trigger and owns the content under it; DisclosureBase itself adds no chevron, surface +// or content. +func (f *Frame) DisclosureBase(ID gfx.ID, Label string, open bool) Box { + b := f.Row().Center() + if open { + f.Nodes[b.i].Flags |= flagOpen + } + return b.HitWith(ID, Label, gfx.HitOptions{Role: gfx.RoleButton, Expanded: open, Expandable: true}) +} + // SwitchBase adds a switch without a look: the size of the shadcn track, that reports // Clicked and is a switch in the given state to assistive technology, with the pointer // region reaching beyond the track as the shadcn control's does. The track and the thumb diff --git a/base/drawer.go b/base/drawer.go index bd693662..d1867cd7 100644 --- a/base/drawer.go +++ b/base/drawer.go @@ -40,6 +40,10 @@ type DrawerSpec struct { // edges, as a page leaves a title strip or a status bar it does not own out // of an overlay. Zero covers the whole window. Inset gfx.Insets + // Disabled paints the drawer and its header as inert: it cannot be dismissed + // by the pointer, Escape or its close button. The body's own controls keep + // their state; disable them too when the whole panel is unavailable. + Disabled bool } // Drawer shows a panel that slides in from an edge of the window while *open, as @@ -82,6 +86,9 @@ func Drawer(c C, open *bool, title string, spec DrawerSpec, body, footer func()) } } drawer := c.f.Drawer(d, footer != nil) + if spec.Disabled { + drawer.Disabled(true) + } decl := &WidgetsOf(c.f).drawers[drawer.N().Aux] p.SetScope(decl.body, scope) if decl.footer >= 0 { diff --git a/base/elements.go b/base/elements.go index 51b8ff5d..3a5d2ea5 100644 --- a/base/elements.go +++ b/base/elements.go @@ -153,19 +153,6 @@ func options[T comparable](p *Page, Value *T, options []T, Label func(T) string) return p.labels[first:len(p.labels):len(p.labels)], selected } -// optionIcons writes the icons of choices into the page's scratch, as options does -// the labels, or returns nil when icon is nil and the select paints none of them. -func optionIcons[T comparable](p *Page, choices []T, icon func(T) gfx.Icon) []gfx.Icon { - if icon == nil { - return nil - } - first := len(p.icons) - for _, choice := range choices { - p.icons = append(p.icons, icon(choice)) - } - return p.icons[first:len(p.icons):len(p.icons)] -} - // pick writes the option a click chose into *value, where the control is declared, // and records whether it did for Changed. func pick[T comparable](c C, b Box, Value *T, options []T, index int, ok bool) { @@ -220,19 +207,9 @@ func SelectID[T comparable](c C, ID gfx.ID, Value *T, choices []T, Label func(T) return selectOf(c, Value, choices, Label, nil, false, ID) } -// SelectIcon is Select with an icon before every option: icon names each option's -// own, painted before the chosen value on the trigger and before each label in the -// open list. It is asked for once per option per paint, as label is; a nil icon -// paints exactly what Select does. -// -// ui.SelectIcon(c, &m.locale, locales, localeName, localeFlag) -func SelectIcon[T comparable](c C, Value *T, choices []T, Label func(T) string, icon func(T) gfx.Icon) Box { - return selectOf(c, Value, choices, Label, optionIcons(c.page, choices, icon), false, gfx.ID{}) -} - -// selectOf is Select (or SelectIcon), or SelectBase when base is set: the same -// control without the theme's look. icons, when SelectIcon's icon function gave -// them, are indexed by option like the labels; nil is the select without icons. +// selectOf is Select, or SelectBase when base is set: the same control without +// the theme's look. icons are indexed by option like the labels; nil is the +// select without icons. func selectOf[T comparable](c C, Value *T, choices []T, Label func(T) string, icons []gfx.Icon, Base bool, ID gfx.ID) Box { p := c.page scope := p.BoundScope(pkSelect, unsafe.Pointer(Value)) diff --git a/base/page.go b/base/page.go index dd822c3d..1a5add13 100644 --- a/base/page.go +++ b/base/page.go @@ -153,6 +153,7 @@ const ( pkRadio pkTab pkList + pkDisclosure pkKinds ) @@ -283,7 +284,6 @@ type Page struct { hoverArea gfx.ID // the scroll area or self-scrolling table the pointer is on selects []*SelectState // the Selects of the last paint, which Wheel scrolls labels []string // scratch for Choice's labels - icons []gfx.Icon // scratch for SelectIcon's icons memos map[gfx.ID]*memoEntry memoBoxes []memoBox memoChecks []memoCheckOf @@ -777,8 +777,6 @@ func (p *Page) paintOnce(Surface *gfx.Canvas, bounds Rect, View func(C)) { clear(p.ctx.stateSeq) clear(p.labels) p.labels = p.labels[:0] - clear(p.icons) - p.icons = p.icons[:0] p.focusPaint = p.focusPaint[:0] for i := range p.held { if id := p.held[i].ID; !id.IsZero() && id != Surface.Pressed() && id != Surface.Focused() { @@ -1070,7 +1068,7 @@ func (p *Page) TextInput(context window.TextInputContext) *window.TextInput { return &entry.field.input } } - if h := p.control(context.ID); h != nil && h.Text != nil { + if h := p.controlOf(context.ID); h != nil && h.Text != nil { return h.Text(context) } if p.textRoute != nil { diff --git a/base/page_bases.go b/base/page_bases.go index bda5a631..2a18beef 100644 --- a/base/page_bases.go +++ b/base/page_bases.go @@ -71,6 +71,16 @@ func Toggle(c C, Value *bool, Label string) Box { return b } +// DisclosureBase is a disclosure header without a look: it flips *value and, to +// assistive technology, is a button that is expanded or not. The caller paints the +// trigger and declares the content under it; *value is written when Clicked or +// Changed is first read on the header, or else when the paint ends. +func DisclosureBase(c C, Value *bool, Label string) Box { + b := c.f.DisclosureBase(c.page.boundID(pkDisclosure, unsafe.Pointer(Value)), Label, *Value).Label(Label) + c.f.bindBool(b, Value) + return b +} + // RadioBase is one option of a radio group or a segmented control without a look: a click // sets *value to option, and it is a radio button that is chosen while *value is option. // Name it with c.Key when the options are reordered. diff --git a/base/select.go b/base/select.go index daac7034..d5f2339b 100644 --- a/base/select.go +++ b/base/select.go @@ -515,7 +515,7 @@ func (b Box) Placeholder(Value string) Box { // Icons sets the icons a Select paints before its chosen value on the trigger and // before each option's label in the open list, one per option and indexed like the -// labels: what SelectIcon's icon function names. A select given none of them paints +// labels: one per option, like the labels. A select given none of them paints // exactly what it always has; a SelectBase keeps them for its caller and paints // none, as it does the rest of the look. func (b Box) Icons(icons []gfx.Icon) Box { diff --git a/base/tabs.go b/base/tabs.go index f1063570..eccd1359 100644 --- a/base/tabs.go +++ b/base/tabs.go @@ -7,6 +7,7 @@ import ( type TabsDecl struct { scope gfx.Scope labels []string + icon func(index int) gfx.Icon selected int line bool vertical bool @@ -38,6 +39,18 @@ func (f *Frame) Tabs(scope gfx.Scope, labels []string, selected int) Box { return b } +// TabIcons puts an icon before every label of a Tabs strip; icon is asked for +// each tab's index and may return a zero icon to leave that tab text-only. +// +// ui.Tabs(c, &m.tab, tabs, nil).TabIcons(func(i int) gfx.Icon { return icons[i] }) +func (b Box) TabIcons(icon func(index int) gfx.Icon) Box { + n := b.N() + if n.Kind == kindTabs && icon != nil { + WidgetsOf(b.f).tabs[n.Aux].icon = icon + } + return b +} + // Line makes a Tabs strip the transparent variant with an underline under the active // tab. Vertical stacks its tabs in a column, with the line at their trailing edge. func (b Box) Line() Box { diff --git a/base/widgets.go b/base/widgets.go index 374c3e38..5f9a2c32 100644 --- a/base/widgets.go +++ b/base/widgets.go @@ -28,8 +28,10 @@ type Widgets struct { alertDialogs []AlertDialogDecl paginations []PaginationDecl PaginationItems []style.PaginationItem - drawers []drawerState - popovers []PopoverDecl + // TabOptions is the scratch of the tabs that paint icons, one entry per label. + TabOptions []TabOption + drawers []drawerState + popovers []PopoverDecl // popoverFocus holds the panels whose InitialFocusID was already asked for. // It outlives reset because a panel is open across paints, and is swept at // the next Begin for the panels the last paint no longer declared. @@ -62,6 +64,7 @@ func (w *Widgets) reset() { w.inputs, w.groups, w.textareas, w.segmented, w.choices = w.inputs[:0], w.groups[:0], w.textareas[:0], w.segmented[:0], w.choices[:0] w.paginations = w.paginations[:0] w.PaginationItems = w.PaginationItems[:0] + w.TabOptions = w.TabOptions[:0] w.popovers, w.drawers = w.popovers[:0], w.drawers[:0] w.splits, w.sliders, w.rows = w.splits[:0], w.sliders[:0], w.rows[:0] w.layer = 0 diff --git a/cmd/gallery-web/main.go b/cmd/gallery-web/main.go index 9ca26a38..d1b3ab84 100644 --- a/cmd/gallery-web/main.go +++ b/cmd/gallery-web/main.go @@ -3,21 +3,36 @@ package main import ( + "github.com/vivaui/viva/app" "github.com/vivaui/viva/internal/gallery" - "github.com/vivaui/viva/internal/platform/web" ) func main() { showcase := gallery.New() showcase.EnableTextEditing() - _ = web.Run(web.Config{ - Title: "Viva · component gallery", - Width: gallery.DefaultWidth, - Height: gallery.DefaultHeight, + theme := showcase.Theme() + var nativeInput app.TextInput + resolveTextInput := func(context app.TextInputContext) *app.TextInput { + editor, ok := showcase.TextEditor(context.ID) + if !ok { + return nil + } + nativeInput = app.TextInput{Editor: editor} + return &nativeInput + } + _ = app.RunCanvas(app.Config{ + Title: "Viva · component gallery", + Width: gallery.DefaultWidth, + Height: gallery.DefaultHeight, + ClearColor: app.Color{ + Red: float64(theme.Background.Red), Green: float64(theme.Background.Green), + Blue: float64(theme.Background.Blue), Alpha: float64(theme.Background.Alpha), + }, + Tree: gallery.Tree(), Paint: showcase.Paint, OnScroll: showcase.Scroll, OnPointer: showcase.Pointer, OnKey: showcase.Key, - TextInput: web.EditorInputs(showcase.TextEditor), - }) + TextInput: resolveTextInput, + }, nil) } diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 2918f0b8..b2f45083 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -200,8 +200,8 @@ func (m *model) page(c ui.C) { `Choice`, `Tabs` and `Select` write the value in the declaration, so disable them with an `if`, not a chained `.Disabled`: `if !m.locked { if ui.Tabs(c, &m.tab, tabs, nil).Changed() { ... } }`. `Tabs` and `Select` also honor a chained `.Disabled` for input; `Choice` ignores it, so never rely on it there. -- Hierarchical path values ("School/Class A") use the opt-in package `github.com/vivaui/viva/hierarchypicker`: `state := hierarchypicker.NewState(paths)`, keep `picker := hierarchypicker.New(state)` in the model, and declare `picker.View(c, hierarchypicker.Spec{Label: "Group", OptionIDs: groupOptions}).FillWidth()`; `SetValue`/`Value` read and set the full path. -- Removable chips with a filtered query are the opt-in package `github.com/vivaui/viva/multiselect`: keep `picker := multiselect.New(&m.tags)` in the model and declare `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`; `tagOptions.At(i)` and `tagRemoves.At(i)` name the popup rows and chip remove buttons. Import it only when used. +- Hierarchical path values ("School/Class A") use the opt-in package `github.com/vivaui/viva/ui/hierarchypicker`: `state := hierarchypicker.NewState(paths)`, keep `picker := hierarchypicker.New(state)` in the model, and declare `picker.View(c, hierarchypicker.Spec{Label: "Group", OptionIDs: groupOptions}).FillWidth()`; `SetValue`/`Value` read and set the full path. +- Removable chips with a filtered query are the opt-in package `github.com/vivaui/viva/ui/multiselect`: keep `picker := multiselect.New(&m.tags)` in the model and declare `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`; `tagOptions.At(i)` and `tagRemoves.At(i)` name the popup rows and chip remove buttons. Import it only when used. - A long list to choose from by typing: `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` (Select's arguments plus a label); it filters as the user types. `.Clearable()` adds a clear button, `.Empty("No zone")` is what an empty list says, `.Creatable("")` offers what was typed as a new choice, read with `.Created()`. @@ -491,7 +491,8 @@ func (m *model) page(c ui.C) { ### Tabs and select - Tabs: `if ui.Tabs(c, &m.tab, tabs, nil).Line().Changed() { ... }`, then declare the active tab's content under it with an - ordinary `switch m.tab`. `Line()` is the underlined variant (it draws 5 px under the strip), `Vertical()` stacks the tabs. + ordinary `switch m.tab`. `Line()` is the underlined variant (it draws 5 px under the strip), `Vertical()` stacks the tabs, + and `TabIcons(func(i int) gfx.Icon)` puts an icon before each label without a second constructor. `Choice`, `Tabs` and `Select` write the value in the declaration, so disable them with an `if`, not a chained `.Disabled`: `if !m.locked { if ui.Tabs(c, &m.tab, tabs, nil).Changed() { ... } }`. `Tabs` and `Select` also honor a chained `.Disabled` for input; `Choice` ignores it, so never rely on it there. diff --git a/docs/maintaining-controls.md b/docs/maintaining-controls.md index 45f00d51..4853d8a9 100644 --- a/docs/maintaining-controls.md +++ b/docs/maintaining-controls.md @@ -43,6 +43,17 @@ There are two authoring paths, and they are not duplicates: may keep Begin are pure measurement, whole-canvas drawing, pixel-fixed slots and copied source. See `private/docs/decisions/0085-begin-stays-in-components.md`. +Opt-in page packages live under `ui/` (`ui/codeeditor`, `ui/chartview`, +`ui/calendarview`, `ui/carouselview`, `ui/markdownview`, `ui/columnresizeview`, +`ui/avatareditorview`, `ui/reordergridview`, `ui/avatarview`, `ui/attachmentview`, +`ui/messageview`, `ui/messagescrollerview`, `ui/commandview`, `ui/menubarview`, +`ui/navigationmenuview`, `ui/hovercardview`, `ui/multiselect`, +`ui/hierarchypicker`). +They import only `base`, `components`, `gfx`, `ui` and `window`, own stable +handlers, and are never imported by package `ui`; importing one is the explicit +opt-in. Do not add a new directory at the repository root for a page widget. +See `private/docs/decisions/0086-opt-in-page-views.md`. + ## Two forms of one control A control that ships with a look has a **styled form** and a **Base**: diff --git a/internal/componentdemo/accordion.go b/internal/componentdemo/accordion.go index d77e0ae4..0b9e3e74 100644 --- a/internal/componentdemo/accordion.go +++ b/internal/componentdemo/accordion.go @@ -21,7 +21,27 @@ for index, title := range titles { if canvas.Clicked(items.At(index)) { open ^= 1 << index } -}`}, +}`, PageSnippet: `ui.Accordion(c, m.faq, []ui.AccordionItem{ + {Title: "Does it repaint constantly?", Content: func() { + ui.Text(c, "A new frame is submitted only when content changes.").Muted() + }}, + {Title: "Who owns the state?", Content: func() { + ui.Text(c, "The expanded state is owned explicitly by the application.").Muted() + }}, + {Title: "Is it keyboard accessible?", Content: func() { + ui.Text(c, "Headers declare focusable button semantics.").Muted() + }}, +})`, PageSnippetZh: `ui.Accordion(c, m.faq, []ui.AccordionItem{ + {Title: "是否持续重绘?", Content: func() { + ui.Text(c, "仅在内容变化时提交新帧。").Muted() + }}, + {Title: "状态由谁持有?", Content: func() { + ui.Text(c, "展开位由应用状态明确持有。").Muted() + }}, + {Title: "是否支持键盘?", Content: func() { + ui.Text(c, "标题声明为可聚焦按钮语义。").Muted() + }}, +})`}, {ID: "disabled", Title: "禁用状态", Description: "保留展开内容,但所有标题均不可交互。", Snippet: `items := tree.Sub(page, tree.Name("item")) accordion := components.BeginAccordion(canvas, theme, bounds).Disabled() for index, title := range titles { @@ -30,7 +50,29 @@ for index, title := range titles { style := gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.MutedForeground} canvas.Label(answers[index], content, style) } -}`}, +}`, PageSnippet: `m.faq.Disabled = true +ui.Accordion(c, m.faq, []ui.AccordionItem{ + {Title: "Does it repaint constantly?", Content: func() { + ui.Text(c, "A new frame is submitted only when content changes.").Muted() + }}, + {Title: "Who owns the state?", Content: func() { + ui.Text(c, "The expanded state is owned explicitly by the application.").Muted() + }}, + {Title: "Is it keyboard accessible?", Content: func() { + ui.Text(c, "Headers declare focusable button semantics.").Muted() + }}, +})`, PageSnippetZh: `m.faq.Disabled = true +ui.Accordion(c, m.faq, []ui.AccordionItem{ + {Title: "是否持续重绘?", Content: func() { + ui.Text(c, "仅在内容变化时提交新帧。").Muted() + }}, + {Title: "状态由谁持有?", Content: func() { + ui.Text(c, "展开位由应用状态明确持有。").Muted() + }}, + {Title: "是否支持键盘?", Content: func() { + ui.Text(c, "标题声明为可聚焦按钮语义。").Muted() + }}, +})`}, }, } diff --git a/internal/componentdemo/alert.go b/internal/componentdemo/alert.go index 37bf5844..ef59391e 100644 --- a/internal/componentdemo/alert.go +++ b/internal/componentdemo/alert.go @@ -15,7 +15,27 @@ var alertComponent = Component{ Title: "Sync complete", Description: "All local changes are safely on disk.", } -components.Alert(canvas, theme, bounds, data)`}, +components.Alert(canvas, theme, bounds, data)`, PageSnippet: `look := c.Theme() +ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). + Background(look.Card).Border(1, look.Border). + Radius(look.Metrics.RadiusSurface).Children(func() { + ui.Icon(c, m.infoIcon).Size(16, 16).Color(look.CardForeground) + ui.Column(c).Grow(1).Gap(2).Children(func() { + ui.Text(c, "Sync complete").Weight(gfx.WeightMedium).Color(look.CardForeground) + ui.Text(c, "All local changes are safely on disk. The remote host confirmed the final write, so you can close the session safely."). + FontSize(look.Metrics.FontSizeM).Muted() + }) +})`, PageSnippetZh: `look := c.Theme() +ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). + Background(look.Card).Border(1, look.Border). + Radius(look.Metrics.RadiusSurface).Children(func() { + ui.Icon(c, m.infoIcon).Size(16, 16).Color(look.CardForeground) + ui.Column(c).Grow(1).Gap(2).Children(func() { + ui.Text(c, "同步已完成").Weight(gfx.WeightMedium).Color(look.CardForeground) + ui.Text(c, "所有本地更改都已安全写入磁盘。远端主机确认了最后一次写入,可以放心关闭会话。"). + FontSize(look.Metrics.FontSizeM).Muted() + }) +})`}, {ID: "variants", Title: "语义变体", Description: "并列展示默认与破坏性提示。", Snippet: `plainData := components.AlertData{ Icon: icon, Title: "Sync complete", Description: "All local changes are safely on disk.", @@ -25,7 +45,51 @@ dangerData := components.AlertData{ Title: "Unable to delete project", Description: "Remove any release configurations that still use this project first.", } components.Alert(canvas, theme, plainBounds, plainData) -components.Alert(canvas, theme, dangerBounds, dangerData)`}, +components.Alert(canvas, theme, dangerBounds, dangerData)`, PageSnippet: `look := c.Theme() +ui.Column(c).Gap(16).Children(func() { + ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). + Background(look.Card).Border(1, look.Border). + Radius(look.Metrics.RadiusSurface).Children(func() { + ui.Icon(c, m.infoIcon).Size(16, 16).Color(look.CardForeground) + ui.Column(c).Grow(1).Gap(2).Children(func() { + ui.Text(c, "Sync complete").Weight(gfx.WeightMedium).Color(look.CardForeground) + ui.Text(c, "All local changes are safely on disk. The remote host confirmed the final write, so you can close the session safely."). + FontSize(look.Metrics.FontSizeM).Muted() + }) + }) + ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). + Background(look.Card).Border(1, look.Border). + Radius(look.Metrics.RadiusSurface).Children(func() { + ui.Icon(c, m.alertIcon).Size(16, 16).Color(look.Danger) + ui.Column(c).Grow(1).Gap(2).Children(func() { + ui.Text(c, "Unable to delete project").Weight(gfx.WeightMedium).Color(look.Danger) + ui.Text(c, "Remove any release configurations that still use this project first."). + FontSize(look.Metrics.FontSizeM).Color(look.Danger) + }) + }) +})`, PageSnippetZh: `look := c.Theme() +ui.Column(c).Gap(16).Children(func() { + ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). + Background(look.Card).Border(1, look.Border). + Radius(look.Metrics.RadiusSurface).Children(func() { + ui.Icon(c, m.infoIcon).Size(16, 16).Color(look.CardForeground) + ui.Column(c).Grow(1).Gap(2).Children(func() { + ui.Text(c, "同步已完成").Weight(gfx.WeightMedium).Color(look.CardForeground) + ui.Text(c, "所有本地更改都已安全写入磁盘。远端主机确认了最后一次写入,可以放心关闭会话。"). + FontSize(look.Metrics.FontSizeM).Muted() + }) + }) + ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). + Background(look.Card).Border(1, look.Border). + Radius(look.Metrics.RadiusSurface).Children(func() { + ui.Icon(c, m.alertIcon).Size(16, 16).Color(look.Danger) + ui.Column(c).Grow(1).Gap(2).Children(func() { + ui.Text(c, "无法删除项目").Weight(gfx.WeightMedium).Color(look.Danger) + ui.Text(c, "请先移除仍在使用该项目的发布配置。"). + FontSize(look.Metrics.FontSizeM).Color(look.Danger) + }) + }) +})`}, }, } diff --git a/internal/componentdemo/alert_dialog.go b/internal/componentdemo/alert_dialog.go index 0c6f690c..0d84da1d 100644 --- a/internal/componentdemo/alert_dialog.go +++ b/internal/componentdemo/alert_dialog.go @@ -11,32 +11,62 @@ var alertDialogComponent = Component{ paint: (*State).paintAlertDialog, initialize: initializeAlertDialog, Examples: []Example{ {ID: "default", Title: "删除确认", Description: "确认和取消动作均由调用方处理。", Snippet: `options := components.AlertDialogOptions{ - Layer: 8, Scope: scope, ActionID: confirmID, CancelID: cancelID, + Layer: 8, Scope: m.scope, ActionID: m.confirmID, CancelID: m.cancelID, ActionVariant: components.ButtonDestructive, } components.BeginAlertDialog(canvas, theme, viewport, options). Paint("Delete this project?", "This cannot be undone.", "Delete", "Cancel") -if canvas.Clicked(confirmID) || canvas.Clicked(cancelID) { +if canvas.Clicked(m.confirmID) || canvas.Clicked(m.cancelID) { open = false }`, PageSnippet: `ui.AlertDialog(c, ui.AlertDialogSpec{ Title: "Permanently delete this project?", Description: "This cannot be undone. Local data will be removed.", - Scope: scope, ActionID: confirmID, CancelID: cancelID, + Scope: m.scope, ActionID: m.confirmID, CancelID: m.cancelID, ActionLabel: "Delete", CancelLabel: "Cancel", })`, PageSnippetZh: `ui.AlertDialog(c, ui.AlertDialogSpec{ Title: "永久删除这个项目?", Description: "此操作无法撤销,本地数据将被移除。", - Scope: scope, ActionID: confirmID, CancelID: cancelID, + Scope: m.scope, ActionID: m.confirmID, CancelID: m.cancelID, ActionLabel: "删除", CancelLabel: "取消", })`}, {ID: "media", Title: "带媒体的小尺寸", Description: "预留可由调用方绘制的媒体区域。", Snippet: `dialog := components.BeginAlertDialog(canvas, theme, viewport, components.AlertDialogOptions{ - Layer: 8, Scope: scope, ActionID: confirmID, CancelID: cancelID, + Layer: 8, Scope: m.scope, ActionID: m.confirmID, CancelID: m.cancelID, Size: components.AlertDialogSmall, }).WithMedia() layout := dialog.Begin("Replace avatar?", "The new image replaces it.", "Replace", "Cancel") canvas.Rounded(layout.Media, min(layout.Media.Width, layout.Media.Height)/2, theme.Muted) canvas.LabelCenter("SK", layout.Media, gfx.TextStyle{Size: theme.Metrics.FontSizeM}) -dialog.End()`, PageSnippet: ""}, +dialog.End()`, PageSnippet: `ui.Dialog(c, ui.DialogSpec{ + Title: "Replace avatar?", + Description: "The current avatar is replaced immediately with the new local image.", + Width: 320, Scope: m.scope, DismissID: m.scope, CloseID: m.cancelID, +}).Body(func() { + ui.Column(c).Size(64, 64).Center().Radius(32).Background(c.Theme().Muted).Children(func() { + ui.Text(c, "SK").Weight(gfx.WeightMedium) + }) +}).Footer(func() { + if ui.Button(c, "Cancel").Outline().Hit(m.cancelID, "Cancel").Clicked() { + m.alertOpen = false + } + if ui.Button(c, "Replace").Hit(m.confirmID, "Replace").Clicked() { + m.alertOpen = false + } +})`, PageSnippetZh: `ui.Dialog(c, ui.DialogSpec{ + Title: "替换头像?", + Description: "当前头像将立即被新的本地图片替换。", + Width: 320, Scope: m.scope, DismissID: m.scope, CloseID: m.cancelID, +}).Body(func() { + ui.Column(c).Size(64, 64).Center().Radius(32).Background(c.Theme().Muted).Children(func() { + ui.Text(c, "SK").Weight(gfx.WeightMedium) + }) +}).Footer(func() { + if ui.Button(c, "取消").Outline().Hit(m.cancelID, "取消").Clicked() { + m.alertOpen = false + } + if ui.Button(c, "替换").Hit(m.confirmID, "替换").Clicked() { + m.alertOpen = false + } +})`}, }, } diff --git a/internal/componentdemo/aspect_ratio.go b/internal/componentdemo/aspect_ratio.go index 118173e6..9aff1cac 100644 --- a/internal/componentdemo/aspect_ratio.go +++ b/internal/componentdemo/aspect_ratio.go @@ -15,12 +15,24 @@ width := min(size.Width-48, float32(520)) height := components.AspectRatio(gfx.Rect{Width: width}, ratio).Height media := ui.Slot(c).Size(width, height) bounds := components.AspectRatio(media.Rect(), ratio) -canvas.Rounded(bounds, theme.Metrics.RadiusSurface, theme.Muted)`}, +canvas.Rounded(bounds, theme.Metrics.RadiusSurface, theme.Muted)`, PageSnippet: `ui.Column(c).FillWidth().MaxWidth(520).Height(293).Center(). + Radius(c.Theme().Metrics.RadiusSurface).Background(c.Theme().Muted).Children(func() { + ui.Text(c, "16:9 release preview").Muted() +})`, PageSnippetZh: `ui.Column(c).FillWidth().MaxWidth(520).Height(293).Center(). + Radius(c.Theme().Metrics.RadiusSurface).Background(c.Theme().Muted).Children(func() { + ui.Text(c, "16:9 发布预览").Muted() +})`}, {ID: "square", Title: "方形封面", Description: "同一 API 使用 1:1 比例。", Snippet: `width := min(size.Width-48, float32(250)) height := components.AspectRatio(gfx.Rect{Width: width}, 1).Height media := ui.Slot(c).Size(width, height) bounds := components.AspectRatio(media.Rect(), 1) -canvas.Rounded(bounds, theme.Metrics.RadiusSurface, theme.Muted)`}, +canvas.Rounded(bounds, theme.Metrics.RadiusSurface, theme.Muted)`, PageSnippet: `ui.Column(c).Size(250, 250).Center(). + Radius(c.Theme().Metrics.RadiusSurface).Background(c.Theme().Muted).Children(func() { + ui.Text(c, "1:1 cover").Muted() +})`, PageSnippetZh: `ui.Column(c).Size(250, 250).Center(). + Radius(c.Theme().Metrics.RadiusSurface).Background(c.Theme().Muted).Children(func() { + ui.Text(c, "1:1 封面").Muted() +})`}, }, } diff --git a/internal/componentdemo/attachment.go b/internal/componentdemo/attachment.go index 54fa35cc..6300e0ac 100644 --- a/internal/componentdemo/attachment.go +++ b/internal/componentdemo/attachment.go @@ -1,14 +1,14 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/attachmentview" ) var attachmentComponent = Component{ ID: "attachment", Title: "Attachment", Category: "Data Display", Summary: "文件和图片附件的尺寸、方向与传输状态。", - paint: (*State).paintAttachment, + paint: (*State).paintAttachment, initialize: (*State).initializeAttachment, Examples: []Example{ {ID: "default", Title: "文件状态", Description: "点击附件依次查看完成、上传、处理和错误状态。", Snippet: `file := tree.ID(page, "file") card := components.BeginAttachment(canvas, theme, file, bounds, @@ -19,7 +19,33 @@ card := components.BeginAttachment(canvas, theme, file, bounds, card.Paint() if canvas.Clicked(file) { index = (index + 1) % len(states) -}`}, +}`, PageSnippet: `// m.attachment* were made with attachmentview.New() in the model. +card := m.attachment +states := [...]string{"2.4 MB · Complete", "Uploading · 64%", "Generating preview", "Upload failed · Click to retry"} +card.Reset().ID(m.fileID).Title("product-demo.mov").Meta(states[m.fileState]).File() +switch m.fileState { +case 1: + card.Uploading(0.64) +case 2: + card.Processing() +case 3: + card.Failed() +} +card.OnClick(m.nextState) +card.View(c, "product-demo.mov").FillWidth()`, PageSnippetZh: `// m.attachment* 在 model 中用 attachmentview.New() 创建。 +card := m.attachment +states := [...]string{"2.4 MB · 已完成", "正在上传 · 64%", "正在生成预览", "上传失败 · 点击重试"} +card.Reset().ID(m.fileID).Title("product-demo.mov").Meta(states[m.fileState]).File() +switch m.fileState { +case 1: + card.Uploading(0.64) +case 2: + card.Processing() +case 3: + card.Failed() +} +card.OnClick(m.nextState) +card.View(c, "product-demo.mov").FillWidth()`}, {ID: "variants", Title: "尺寸与方向", Description: "展示小型文件与竖向图片附件。", Snippet: `components.BeginAttachment(canvas, theme, tree.ID(page, "notes"), bounds, components.AttachmentData{ Name: "release-notes.md", Description: "18 KB · Markdown", @@ -30,7 +56,19 @@ components.BeginAttachment(canvas, theme, tree.ID(page, "cover"), cover, components.AttachmentData{ Name: "cover.png", Description: "1200 × 1200", Kind: components.AttachmentImage, Orientation: components.AttachmentVertical, - }).Paint()`}, + }).Paint()`, PageSnippet: `// m.attachment* were made with attachmentview.New() in the model. +file := m.smallAttachment +file.Reset().ID(m.notesID).Title("release-notes.md").Meta("18 KB · Markdown").File().Small() +file.View(c, "release-notes.md") +cover := m.coverAttachment +cover.Reset().ID(m.coverID).Title("cover.png").Meta("1200 × 1200").Image().Idle().Vertical() +cover.View(c, "cover.png")`, PageSnippetZh: `// m.attachment* 在 model 中用 attachmentview.New() 创建。 +file := m.smallAttachment +file.Reset().ID(m.notesID).Title("release-notes.md").Meta("18 KB · Markdown").File().Small() +file.View(c, "release-notes.md") +cover := m.coverAttachment +cover.Reset().ID(m.coverID).Title("cover.png").Meta("1200 × 1200").Image().Idle().Vertical() +cover.View(c, "cover.png")`}, {ID: "actions", Title: "操作与分组", Description: "附件上的删除、重试按钮,以及一行并排的附件组。", Snippet: `group := components.BeginAttachmentGroup(theme, bounds) for index, data := range attachments { card := components.BeginAttachment(canvas, theme, items.At(index), gfx.Rect{}, data) @@ -42,7 +80,35 @@ for index, data := range attachments { } } failedCard := components.BeginAttachment(canvas, theme, failedID, cover, failed) -failedCard.Action(components.AttachmentAction{ID: retryID, Label: "Retry"}).Paint()`}, +failedCard.Action(components.AttachmentAction{ID: retryID, Label: "Retry"}).Paint()`, PageSnippet: `group := m.attachmentGroup +group.Reset().Gap(12) +for index, name := range [...]string{"release-notes.md", "cover.png", "report.pdf"} { + if m.removed(index) { + continue + } + group.Add().ID(m.itemIDs[index]).ExtraSmall().Title(name).Meta("18 KB"). + Action(m.removeIDs[index], "Remove "+name, m.crossIcon, func() { m.remove(index) }) +} +group.View(c, "Attachments") +failed := m.failedAttachment +failed.Reset().ID(m.failedID).Title("cover.png").Meta("Upload failed"). + Image().Failed().Vertical(). + Action(m.retryID, "Retry", m.retryIcon, m.retry) +failed.View(c, "cover.png")`, PageSnippetZh: `group := m.attachmentGroup +group.Reset().Gap(12) +for index, name := range [...]string{"release-notes.md", "cover.png", "report.pdf"} { + if m.removed(index) { + continue + } + group.Add().ID(m.itemIDs[index]).ExtraSmall().Title(name).Meta("18 KB"). + Action(m.removeIDs[index], "删除 "+name, m.crossIcon, func() { m.remove(index) }) +} +group.View(c, "附件") +failed := m.failedAttachment +failed.Reset().ID(m.failedID).Title("cover.png").Meta("上传失败"). + Image().Failed().Vertical(). + Action(m.retryID, "重试", m.retryIcon, m.retry) +failed.View(c, "cover.png")`}, }, } @@ -72,79 +138,100 @@ var ( }} ) +// attachmentDemo is one attachment example's page controls and the callbacks +// they run. They are kept beside the State rather than rebuilt in each paint, +// so their handlers and draw functions are stable and a warm paint allocates +// nothing. +type attachmentDemo struct { + card, small, cover, failed *attachmentview.Attachment + group *attachmentview.Group + next func() + remove [3]func() + retry func() + removeLabels [3]string + retryLabel string +} + +// attachmentDemos is keyed by State because the constrained demo model has no +// field for these controls; a State is painted on one thread at a time. +var attachmentDemos = map[*State]*attachmentDemo{} + +var attachmentNames = [...]string{"release-notes.md", "cover.png", "report.pdf"} + +func (state *State) initializeAttachment() { attachmentDemoFor(state) } + +func attachmentDemoFor(state *State) *attachmentDemo { + if demo := attachmentDemos[state]; demo != nil { + return demo + } + demo := &attachmentDemo{ + card: attachmentview.New(), + small: attachmentview.New(), + cover: attachmentview.New(), + failed: attachmentview.New(), + group: attachmentview.NewGroup(), + } + demo.next = func() { state.values[0] = (state.values[0] + 1) % 4 } + for index := range demo.remove { + value := index + demo.remove[index] = func() { state.flags |= 1 << value } + prefix := state.Text("删除 ", "Remove ") + demo.removeLabels[index] = prefix + attachmentNames[index] + } + demo.retry = func() { state.flags = 0 } + demo.retryLabel = state.Text("重试", "Retry") + attachmentDemos[state] = demo + return demo +} + func (state *State) paintAttachment(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var first, second ui.Box - variants := state.exampleID == "variants" + demo := attachmentDemoFor(state) state.drawPage(canvas, theme, size, 560, state.Text("Attachment · 生产资源摘要", "Attachment · Production resource summary"), func(c ui.C) { switch state.exampleID { case "variants": - first = ui.Slot(c).FillWidth().Height(62) - second = ui.Slot(c).Size(120, 170) + demo.small.Reset().ID(attachmentItem.At(0)).Title("release-notes.md").Meta("18 KB · Markdown").File().Small() + demo.cover.Reset().ID(attachmentItem.At(1)).Title("cover.png").Meta("1200 × 1200").Image().Idle().Vertical() + ui.Row(c).Gap(12).Items(ui.Start).Children(func() { + demo.small.View(c, "release-notes.md") + demo.cover.View(c, "cover.png") + }) case "actions": - first = ui.Slot(c).FillWidth().Height(66) - second = ui.Slot(c).FillWidth().Height(170) - default: - first = ui.Slot(c).FillWidth().Height(92) - ui.Text(c, state.Text("点击附件切换状态。", "Click the attachment to cycle its state.")).FontSize(theme.Metrics.FontSizeS).Muted() - } - }) - if variants { - components.BeginAttachment(canvas, theme, attachmentItem.At(0), first.Rect(), components.AttachmentData{ - Name: "release-notes.md", Description: "18 KB · Markdown", Kind: components.AttachmentFile, - State: components.AttachmentDone, Size: components.AttachmentSizeSmall, - }).Paint() - components.BeginAttachment(canvas, theme, attachmentItem.At(1), second.Rect(), components.AttachmentData{ - Name: "cover.png", Description: "1200 × 1200", Kind: components.AttachmentImage, - State: components.AttachmentIdle, Size: components.AttachmentSizeDefault, Orientation: components.AttachmentVertical, - }).Paint() - return - } - if state.exampleID == "actions" { - // A row of natural-sized attachments, each with its own remove button, and - // an upload that failed with a retry button. - group := components.BeginAttachmentGroup(theme, first.Rect()) - names := [...]string{"release-notes.md", "cover.png", "report.pdf"} - removeLabels := [...]string{"Remove release-notes.md", "Remove cover.png", "Remove report.pdf"} - for index, name := range names { - if state.flags&(1< 0 { state.carousel-- } else if canvas.Clicked(next) && state.carousel < 2 { state.carousel++ +}`, PageSnippet: `slides := []string{"Retained scene", "Localized update", "Idle means idle"} +carousel := &carouselview.Carousel{ + ItemCount: 3, Index: m.slide, + PreviousID: m.previous, PreviousLabel: "Previous slide", + NextID: m.next, NextLabel: "Next slide", +} +carousel.Draw = func(d *ui.DrawContext, geometry carouselview.Geometry) { + for index := 0; index < carousel.ItemCount; index++ { + item := carousel.ItemBounds(geometry, index) + fill := d.Theme.Muted + if index == geometry.Index { + fill = d.Theme.Accent + } + d.Canvas.Rounded(item, d.Theme.Metrics.RadiusSurface, fill) + d.Canvas.LabelCenter(slides[index], item, gfx.TextStyle{ + Size: d.Theme.Metrics.FontSizeM + 2, Weight: gfx.WeightSemibold, + Color: d.Theme.Foreground, + }) + } +} +carouselview.View(c, "Product tour", carousel).FillWidth().Height(200).MarginX(32) +if carousel.Clicked(m.previous) && m.slide > 0 { + m.slide-- +} else if carousel.Clicked(m.next) && m.slide < 2 { + m.slide++ +}`, PageSnippetZh: `slides := []string{"保留场景", "本地化更新", "空闲即空闲"} +carousel := &carouselview.Carousel{ + ItemCount: 3, Index: m.slide, + PreviousID: m.previous, PreviousLabel: "上一张", + NextID: m.next, NextLabel: "下一张", +} +carousel.Draw = func(d *ui.DrawContext, geometry carouselview.Geometry) { + for index := 0; index < carousel.ItemCount; index++ { + item := carousel.ItemBounds(geometry, index) + fill := d.Theme.Muted + if index == geometry.Index { + fill = d.Theme.Accent + } + d.Canvas.Rounded(item, d.Theme.Metrics.RadiusSurface, fill) + d.Canvas.LabelCenter(slides[index], item, gfx.TextStyle{ + Size: d.Theme.Metrics.FontSizeM + 2, Weight: gfx.WeightSemibold, + Color: d.Theme.Foreground, + }) + } +} +carouselview.View(c, "产品导览", carousel).FillWidth().Height(200).MarginX(32) +if carousel.Clicked(m.previous) && m.slide > 0 { + m.slide-- +} else if carousel.Clicked(m.next) && m.slide < 2 { + m.slide++ }`}, {ID: "vertical", Title: "垂直轮播", Description: "相同几何模型切换为纵向内容轴。", Snippet: `previous, next := tree.ID(page, "previous"), tree.ID(page, "next") carousel := components.BeginCarousel(canvas, theme, bounds, 3, state.carousel). @@ -33,6 +83,58 @@ if canvas.Clicked(previous) && state.carousel > 0 { state.carousel-- } else if canvas.Clicked(next) && state.carousel < 2 { state.carousel++ +}`, PageSnippet: `slides := []string{"Retained scene", "Localized update", "Idle means idle"} +carousel := &carouselview.Carousel{ + ItemCount: 3, Index: m.slide, + Orientation: carouselview.Vertical, + PreviousID: m.previous, PreviousLabel: "Previous slide", + NextID: m.next, NextLabel: "Next slide", +} +carousel.Draw = func(d *ui.DrawContext, geometry carouselview.Geometry) { + for index := 0; index < carousel.ItemCount; index++ { + item := carousel.ItemBounds(geometry, index) + fill := d.Theme.Muted + if index == geometry.Index { + fill = d.Theme.Accent + } + d.Canvas.Rounded(item, d.Theme.Metrics.RadiusSurface, fill) + d.Canvas.LabelCenter(slides[index], item, gfx.TextStyle{ + Size: d.Theme.Metrics.FontSizeM + 2, Weight: gfx.WeightSemibold, + Color: d.Theme.Foreground, + }) + } +} +carouselview.View(c, "Product tour", carousel).FillWidth().Height(180).MarginY(44).MarginX(32) +if carousel.Clicked(m.previous) && m.slide > 0 { + m.slide-- +} else if carousel.Clicked(m.next) && m.slide < 2 { + m.slide++ +}`, PageSnippetZh: `slides := []string{"保留场景", "本地化更新", "空闲即空闲"} +carousel := &carouselview.Carousel{ + ItemCount: 3, Index: m.slide, + Orientation: carouselview.Vertical, + PreviousID: m.previous, PreviousLabel: "上一张", + NextID: m.next, NextLabel: "下一张", +} +carousel.Draw = func(d *ui.DrawContext, geometry carouselview.Geometry) { + for index := 0; index < carousel.ItemCount; index++ { + item := carousel.ItemBounds(geometry, index) + fill := d.Theme.Muted + if index == geometry.Index { + fill = d.Theme.Accent + } + d.Canvas.Rounded(item, d.Theme.Metrics.RadiusSurface, fill) + d.Canvas.LabelCenter(slides[index], item, gfx.TextStyle{ + Size: d.Theme.Metrics.FontSizeM + 2, Weight: gfx.WeightSemibold, + Color: d.Theme.Foreground, + }) + } +} +carouselview.View(c, "产品导览", carousel).FillWidth().Height(180).MarginY(44).MarginX(32) +if carousel.Clicked(m.previous) && m.slide > 0 { + m.slide-- +} else if carousel.Clicked(m.next) && m.slide < 2 { + m.slide++ }`}, }, } @@ -43,48 +145,79 @@ var ( carouselNext = tree.ID(carouselUI, "next") ) +// carouselDemo is one carousel example's page control. The wrapper's handlers +// are made once and point at this value, so it is kept beside the State rather +// than rebuilt in each paint. +type carouselDemo struct { + state *State + view carouselview.Carousel +} + +// carouselDemos is keyed by State because the constrained demo model has no +// field for this example; a State is painted on one thread at a time. +var carouselDemos = map[*State]*carouselDemo{} + +func (state *State) initializeCarousel() { + demo := &carouselDemo{state: state} + demo.view.Draw = demo.draw + carouselDemos[state] = demo +} + +func carouselDemoFor(state *State) *carouselDemo { + if demo := carouselDemos[state]; demo != nil { + return demo + } + demo := &carouselDemo{state: state} + demo.view.Draw = demo.draw + carouselDemos[state] = demo + return demo +} + func (state *State) paintCarousel(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { vertical := state.exampleID == "vertical" - // The previous and next buttons sit just outside the viewport, so the slot is + demo := carouselDemoFor(state) + demo.view.ItemCount = 3 + demo.view.Index = int(state.values[0]) + demo.view.Offset, demo.view.Extent = 0, 0 + demo.view.Orientation = carouselview.Horizontal + if vertical { + demo.view.Orientation = carouselview.Vertical + } + demo.view.PreviousID, demo.view.NextID = carouselPrevious, carouselNext + demo.view.PreviousLabel = state.Text("上一张", "Previous slide") + demo.view.NextLabel = state.Text("下一张", "Next slide") + // The previous and next buttons sit just outside the viewport, so the view is // kept clear of the page edge and of the title by a margin. - var slot ui.Box - state.drawPage(canvas, theme, size, 584, state.Text("Carousel · 产品导览", "Carousel · Product tour"), func(c ui.C) { + state.drawPage(canvas, theme, size, 584, state.Text("轮播 · 产品导览", "Carousel · Product tour"), func(c ui.C) { + view := carouselview.View(c, state.Text("轮播", "Carousel"), &demo.view).FillWidth() if vertical { - slot = ui.Slot(c).FillWidth().Height(180).MarginY(44).MarginX(32) + view.Height(180).MarginY(44).MarginX(32) } else { - slot = ui.Slot(c).FillWidth().Height(200).MarginX(32) + view.Height(200).MarginX(32) } }) - bounds := slot.Rect() - index := int(state.values[0]) - itemExtent := bounds.Width - if vertical { - itemExtent = bounds.Height - } - carousel := components.BeginCarousel(canvas, theme, bounds, 3, index). - Content(itemExtent*3, float32(index)*itemExtent). - Controls(carouselPrevious, state.Text("上一张", "Previous slide"), carouselNext, state.Text("下一张", "Next slide")) - if vertical { - carousel = carousel.Vertical() - } - carousel.BeginContent() - paintCarouselSlides(canvas, theme, &carousel, itemExtent, vertical) - carousel.EndContent() - if canvas.Clicked(carouselPrevious) && state.values[0] > 0 { + if demo.view.Clicked(carouselPrevious) && state.values[0] > 0 { state.values[0]-- - } else if canvas.Clicked(carouselNext) && state.values[0] < 2 { + } else if demo.view.Clicked(carouselNext) && state.values[0] < int32(demo.view.ItemCount-1) { state.values[0]++ } } -func paintCarouselSlides(canvas *gfx.Canvas, theme gfx.Theme, carousel *components.Carousel, itemExtent float32, vertical bool) { - labels := [...]string{"Retained scene", "Localized update", "Idle means idle"} +// draw paints each caller-owned slide into the clipped viewport. The wrapper +// hands it the complete geometry, so it maps an evenly divided content extent +// with ItemBounds. +func (d *carouselDemo) draw(ctx *ui.DrawContext, geometry carouselview.Geometry) { + labels := [3]string{ + d.state.Text("保留场景", "Retained scene"), + d.state.Text("本地化更新", "Localized update"), + d.state.Text("空闲即空闲", "Idle means idle"), + } + vertical := d.view.Orientation == carouselview.Vertical for index := range labels { - item := carousel.ItemGeometry(index, float32(index)*itemExtent, itemExtent) - if !item.Visible { + bounds := d.view.ItemBounds(geometry, index) + if !carouselSlideVisible(bounds, geometry.Viewport) { continue } - bounds := item.Bounds if vertical { bounds.Y += 6 bounds.Height -= 12 @@ -92,11 +225,19 @@ func paintCarouselSlides(canvas *gfx.Canvas, theme gfx.Theme, carousel *componen bounds.X += 6 bounds.Width -= 12 } - fill := theme.Muted - if item.Selected { - fill = theme.Accent + fill := ctx.Theme.Muted + if index == geometry.Index { + fill = ctx.Theme.Accent } - canvas.Rounded(bounds, theme.Metrics.RadiusSurface, fill) - canvas.LabelCenter(labels[index], bounds, gfx.TextStyle{Size: theme.Metrics.FontSizeM + 2, Weight: gfx.WeightSemibold, Color: theme.Foreground}) + ctx.Canvas.Rounded(bounds, ctx.Theme.Metrics.RadiusSurface, fill) + ctx.Canvas.LabelCenter(labels[index], bounds, gfx.TextStyle{ + Size: ctx.Theme.Metrics.FontSizeM + 2, Weight: gfx.WeightSemibold, Color: ctx.Theme.Foreground, + }) } } + +func carouselSlideVisible(bounds, viewport gfx.Rect) bool { + return bounds.Width > 0 && bounds.Height > 0 && + bounds.X < viewport.X+viewport.Width && bounds.X+bounds.Width > viewport.X && + bounds.Y < viewport.Y+viewport.Height && bounds.Y+bounds.Height > viewport.Y +} diff --git a/internal/componentdemo/chart.go b/internal/componentdemo/chart.go index d3e345cb..88ee7c68 100644 --- a/internal/componentdemo/chart.go +++ b/internal/componentdemo/chart.go @@ -4,21 +4,70 @@ import ( "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/chartview" ) var chartComponent = Component{ ID: "chart", Title: "Chart", Category: "Data Display", Summary: "生产图表容器、图例和提示框配合调用方数据几何。", - paint: (*State).paintChart, + paint: (*State).paintChart, initialize: (*State).initializeChart, Examples: []Example{ - {ID: "bars", Title: "提交次数", Description: "图表组件划分绘图区,柱形由调用方绘制。", Snippet: `layout := components.PaintChartContainer(canvas, theme, bounds, series, + {ID: "bars", Title: "提交次数", Description: "图表组件划分绘图区,柱形由调用方绘制。", + Snippet: `layout := components.PaintChartContainer(canvas, theme, bounds, series, components.ChartContainerOptions{Legend: components.ChartLegendBottom}) plot := layout.PlotBounds for i, scale := range []float32{0.42, 0.28, 0.60, 0.36, 0.72, 0.48, 0.88, 0.62} { y := plot.Y + plot.Height*(1-scale) bar := gfx.Rect{X: plot.X + float32(i)*44, Y: y, Width: 30, Height: plot.Height * scale} canvas.Rounded(bar, 3, series[i%2].Color) -}`}, - {ID: "tooltip", Title: "数据提示", Description: "在同一系列元数据上绘制生产 Tooltip。", Snippet: `layout := components.PaintChartContainer(canvas, theme, bounds, series, +}`, + PageSnippet: `palette := c.Theme() +series := []chartview.Series{ + {Key: "native", Label: "Native", Color: palette.Chart[0]}, + {Key: "web", Label: "Web", Color: palette.Chart[1]}, +} +heights := [...]float32{0.42, 0.28, 0.60, 0.36, 0.72, 0.48, 0.88, 0.62} +// Set once, when the model is created; ContainerView calls it every paint. +m.commits.Draw = func(d *ui.DrawContext, layout chartview.Layout) { + plot := layout.PlotBounds + baseline := plot.Y + plot.Height - 14 + barWidth := min(float32(30), (plot.Width-40)/8) + gap := (plot.Width - barWidth*8) / 9 + for index, scale := range heights { + x := plot.X + gap + float32(index)*(barWidth+gap) + height := (plot.Height - 34) * scale + d.Canvas.Rounded(gfx.Rect{X: x, Y: baseline - height, Width: barWidth, Height: height}, + 3, series[index%2].Color) + } + d.Canvas.Fill(gfx.Rect{X: plot.X, Y: baseline, Width: plot.Width, Height: 1}, d.Theme.Border) +} +m.commits.Series = series +m.commits.Options = chartview.ContainerOptions{Legend: chartview.LegendBottom} +chartview.ContainerView(c, "Commits", &m.commits).Height(244)`, + PageSnippetZh: `palette := c.Theme() +series := []chartview.Series{ + {Key: "native", Label: "原生", Color: palette.Chart[0]}, + {Key: "web", Label: "网页", Color: palette.Chart[1]}, +} +heights := [...]float32{0.42, 0.28, 0.60, 0.36, 0.72, 0.48, 0.88, 0.62} +// 创建模型时设置一次;ContainerView 在每次绘制时调用它。 +m.commits.Draw = func(d *ui.DrawContext, layout chartview.Layout) { + plot := layout.PlotBounds + baseline := plot.Y + plot.Height - 14 + barWidth := min(float32(30), (plot.Width-40)/8) + gap := (plot.Width - barWidth*8) / 9 + for index, scale := range heights { + x := plot.X + gap + float32(index)*(barWidth+gap) + height := (plot.Height - 34) * scale + d.Canvas.Rounded(gfx.Rect{X: x, Y: baseline - height, Width: barWidth, Height: height}, + 3, series[index%2].Color) + } + d.Canvas.Fill(gfx.Rect{X: plot.X, Y: baseline, Width: plot.Width, Height: 1}, d.Theme.Border) +} +m.commits.Series = series +m.commits.Options = chartview.ContainerOptions{Legend: chartview.LegendBottom} +chartview.ContainerView(c, "提交次数", &m.commits).Height(244)`}, + {ID: "tooltip", Title: "数据提示", Description: "在同一系列元数据上绘制生产 Tooltip。", + Snippet: `layout := components.PaintChartContainer(canvas, theme, bounds, series, components.ChartContainerOptions{Legend: components.ChartLegendBottom}) plot := layout.PlotBounds rows := []components.ChartTooltipRow{{Series: 0, Value: "42"}, {Series: 1, Value: "28"}} @@ -26,50 +75,64 @@ anchor := gfx.Rect{X: plot.X + plot.Width - 150, Y: plot.Y + 10} components.PaintChartTooltip(canvas, theme, anchor, series, rows, components.ChartTooltipOptions{ Label: "Week 4", Indicator: components.ChartTooltipDot, Layer: 4, - })`}, - }, + })`, + PageSnippet: `palette := c.Theme() +series := []chartview.Series{ + {Key: "native", Label: "Native", Color: palette.Chart[0]}, + {Key: "web", Label: "Web", Color: palette.Chart[1]}, } - -var chartDemoSeries = [...]components.ChartSeries{ - {Key: "native", Label: "Native", Color: gfx.Color{Red: 0.20, Green: 0.52, Blue: 0.96, Alpha: 1}}, - {Key: "web", Label: "Web", Color: gfx.Color{Red: 0.53, Green: 0.36, Blue: 0.92, Alpha: 1}}, +m.commits.Series = series +m.commits.Options = chartview.ContainerOptions{Legend: chartview.LegendBottom} +m.commitsTip = chartview.Tooltip{ + Rows: []chartview.TooltipRow{{Series: 0, Value: "42"}, {Series: 1, Value: "28"}}, + Options: chartview.TooltipOptions{Label: "Week 4", Indicator: chartview.TooltipDot}, } - -var chartDemoRows = [...]components.ChartTooltipRow{ - {Series: 0, Value: "42"}, - {Series: 1, Value: "28"}, +m.commits.Tooltip = &m.commitsTip +chartview.ContainerView(c, "Commits", &m.commits).Height(244)`, + PageSnippetZh: `palette := c.Theme() +series := []chartview.Series{ + {Key: "native", Label: "原生", Color: palette.Chart[0]}, + {Key: "web", Label: "网页", Color: palette.Chart[1]}, +} +m.commits.Series = series +m.commits.Options = chartview.ContainerOptions{Legend: chartview.LegendBottom} +m.commitsTip = chartview.Tooltip{ + Rows: []chartview.TooltipRow{{Series: 0, Value: "42"}, {Series: 1, Value: "28"}}, + Options: chartview.TooltipOptions{Label: "第 4 周", Indicator: chartview.TooltipDot}, +} +m.commits.Tooltip = &m.commitsTip +chartview.ContainerView(c, "提交次数", &m.commits).Height(244)`}, + }, } func (state *State) paintChart(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - // The card is a slot the page reserves; the plotting inside it is geometry - // the chart container and this function draw. - var card ui.Box - state.drawPage(canvas, theme, size, 600, state.Text("Chart · 最近四周提交", "Chart · Last four weeks"), func(c ui.C) { - card = ui.Slot(c).FillWidth().Height(244) - }) - bounds := card.Rect() - components.PaintCard(canvas, theme, bounds, components.CardOptions{Size: components.CardSizeSmall}) - inner := gfx.Rect{X: bounds.X + 16, Y: bounds.Y + 14, Width: bounds.Width - 32, Height: bounds.Height - 28} - layout := components.PaintChartContainer(canvas, theme, inner, chartDemoSeries[:], components.ChartContainerOptions{Legend: components.ChartLegendBottom}) - plot := layout.PlotBounds - baseline := plot.Y + plot.Height - 14 - barWidth := min(float32(30), (plot.Width-40)/8) - gap := (plot.Width - barWidth*8) / 9 - heights := [...]float32{0.42, 0.28, 0.60, 0.36, 0.72, 0.48, 0.88, 0.62} - for index, scale := range heights { - x := plot.X + gap + float32(index)*(barWidth+gap) - height := (plot.Height - 34) * scale - color := chartDemoSeries[index%2].Color - canvas.Rounded(gfx.Rect{X: x, Y: baseline - height, Width: barWidth, Height: height}, 3, color) + demo := state.chart + native, web := "原生", "网页" + title, label := "Chart · 最近四周提交", "提交次数" + if state.english { + native, web = "Native", "Web" + title, label = "Chart · Last four weeks", "Commits" + } + demo.series = [2]chartview.Series{ + {Key: "native", Label: native, Color: theme.Chart[0]}, + {Key: "web", Label: web, Color: theme.Chart[1]}, + } + demo.container.Series = demo.series[:] + demo.tooltip.Options = chartview.TooltipOptions{ + Label: state.Text("第 4 周", "Week 4"), Indicator: chartview.TooltipDot, } - canvas.Fill(gfx.Rect{X: plot.X, Y: baseline, Width: plot.Width, Height: 1}, theme.Border) if state.exampleID == "tooltip" { - originX := plot.X + plot.Width - 150 - if originX < plot.X { - originX = plot.X - } - components.PaintChartTooltip(canvas, theme, gfx.Rect{X: originX, Y: plot.Y + 10}, chartDemoSeries[:], chartDemoRows[:], components.ChartTooltipOptions{ - Label: state.Text("第 4 周", "Week 4"), Indicator: components.ChartTooltipDot, Layer: 4, - }) + demo.container.Tooltip = &demo.tooltip + } else { + demo.container.Tooltip = nil } + ring := theme.Foreground + ring.Alpha *= 0.10 + state.drawPage(canvas, theme, size, 600, title, func(c ui.C) { + ui.Column(c).FillWidth().Pad(components.CardSpacing(theme, components.CardSizeSmall)). + Background(theme.Card).Border(1, ring).Radius(theme.Metrics.RadiusSurface + 4).Shadow(gfx.ShadowXS). + Children(func() { + chartview.ContainerView(c, label, &demo.container).Height(244) + }) + }) } diff --git a/internal/componentdemo/chart_area.go b/internal/componentdemo/chart_area.go index 042f7911..cabc036f 100644 --- a/internal/componentdemo/chart_area.go +++ b/internal/componentdemo/chart_area.go @@ -6,6 +6,7 @@ import ( "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/chartview" ) var chartAreaComponent = Component{ @@ -13,7 +14,8 @@ var chartAreaComponent = Component{ paint: (*State).paintChartArea, pointer: (*State).pointerChart, key: (*State).keyChart, initialize: (*State).initializeChart, Examples: []Example{ - {ID: "area-style", Title: "自定义渐变填充", Description: "每个序列单独配置填充透明度和渐变端点,折线与图例颜色保持独立。", Height: 320, Snippet: `transparent := theme.Chart[0] + {ID: "area-style", Title: "自定义渐变填充", Description: "每个序列单独配置填充透明度和渐变端点,折线与图例颜色保持独立。", Height: 320, + Snippet: `transparent := theme.Chart[0] transparent.Alpha = 0 series[0].AreaStyle = &components.ChartAreaStyle{ Opacity: .24, @@ -27,16 +29,90 @@ chart := components.AreaChart{ Curve: components.ChartCurveMonotone, Fill: components.ChartFillGradient, } -components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`}, - {ID: "default", Title: "渐变面积", Description: "单序列、平滑曲线和从序列色渐隐的填充。", Height: 320, Snippet: `chart := components.AreaChart{ +components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`, + PageSnippet: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "Desktop", Color: palette.Chart[0]}, + {Key: "mobile", Label: "Mobile", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +transparent := palette.Chart[0] +transparent.Alpha = 0 +series[0].AreaStyle = &chartview.AreaStyle{ + Opacity: .24, + Gradient: &chartview.AreaGradient{From: palette.Chart[0], To: transparent}, +} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Curve: chartview.CurveMonotone, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Legend: chartview.LegendBottom, + Label: "Monthly visitors area chart", Version: 1, +} +chartview.View(c, "Monthly visitors area chart", &m.visitors).Height(280)`, + PageSnippetZh: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "桌面端", Color: palette.Chart[0]}, + {Key: "mobile", Label: "移动端", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +transparent := palette.Chart[0] +transparent.Alpha = 0 +series[0].AreaStyle = &chartview.AreaStyle{ + Opacity: .24, + Gradient: &chartview.AreaGradient{From: palette.Chart[0], To: transparent}, +} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Curve: chartview.CurveMonotone, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Legend: chartview.LegendBottom, + Label: "月访问量面积图", Version: 1, +} +chartview.View(c, "月访问量面积图", &m.visitors).Height(280)`}, + {ID: "default", Title: "渐变面积", Description: "单序列、平滑曲线和从序列色渐隐的填充。", Height: 320, + Snippet: `chart := components.AreaChart{ Series: []components.ChartSeries{{Key: "desktop", Label: "Desktop", Color: theme.Chart[0]}}, Values: [][]float32{desktop}, Curve: components.ChartCurveMonotone, XAxis: components.ChartAxis{Format: formatMonth}, Grid: components.ChartGridHorizontal, } -plot := components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`}, - {ID: "linear", Title: "折线与数据点", Description: "无填充的折线图,标出每个数据点。", Height: 320, Snippet: `chart := components.AreaChart{ +plot := components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`, + PageSnippet: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "Desktop", Color: palette.Chart[0]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: [][]float32{desktop}, + Curve: chartview.CurveMonotone, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Label: "Monthly visitors area chart", Version: 1, +} +chartview.View(c, "Monthly visitors area chart", &m.visitors).Height(280)`, + PageSnippetZh: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "桌面端", Color: palette.Chart[0]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: [][]float32{desktop}, + Curve: chartview.CurveMonotone, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Label: "月访问量面积图", Version: 1, +} +chartview.View(c, "月访问量面积图", &m.visitors).Height(280)`}, + {ID: "linear", Title: "折线与数据点", Description: "无填充的折线图,标出每个数据点。", Height: 320, + Snippet: `chart := components.AreaChart{ Series: series, Values: values, Fill: components.ChartFillNone, Dots: true, @@ -44,15 +120,83 @@ plot := components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state) Grid: components.ChartGridBoth, Legend: components.ChartLegendBottom, } -components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`}, - {ID: "step", Title: "阶梯曲线", Description: "每个值保持到相邻两点的中点。", Height: 320, Snippet: `chart := components.AreaChart{ +components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`, + PageSnippet: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "Desktop", Color: palette.Chart[0]}, + {Key: "mobile", Label: "Mobile", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Fill: chartview.FillNone, Dots: true, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridBoth, + Legend: chartview.LegendBottom, + Label: "Monthly visitors line chart", Version: 1, +} +chartview.View(c, "Monthly visitors line chart", &m.visitors).Height(280)`, + PageSnippetZh: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "桌面端", Color: palette.Chart[0]}, + {Key: "mobile", Label: "移动端", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Fill: chartview.FillNone, Dots: true, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridBoth, + Legend: chartview.LegendBottom, + Label: "月访问量折线图", Version: 1, +} +chartview.View(c, "月访问量折线图", &m.visitors).Height(280)`}, + {ID: "step", Title: "阶梯曲线", Description: "每个值保持到相邻两点的中点。", Height: 320, + Snippet: `chart := components.AreaChart{ Series: series, Values: values, Curve: components.ChartCurveStep, Fill: components.ChartFillSolid, XAxis: components.ChartAxis{Format: formatMonth}, } -components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`}, - {ID: "stacked", Title: "堆叠", Description: "按序列顺序自下而上堆叠,纵轴随总量缩放。", Height: 320, Snippet: `chart := components.AreaChart{ +components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`, + PageSnippet: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "Desktop", Color: palette.Chart[0]}, + {Key: "mobile", Label: "Mobile", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Curve: chartview.CurveStep, Fill: chartview.FillSolid, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Label: "Monthly visitors step chart", Version: 1, +} +chartview.View(c, "Monthly visitors step chart", &m.visitors).Height(280)`, + PageSnippetZh: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "桌面端", Color: palette.Chart[0]}, + {Key: "mobile", Label: "移动端", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Curve: chartview.CurveStep, Fill: chartview.FillSolid, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Label: "月访问量阶梯图", Version: 1, +} +chartview.View(c, "月访问量阶梯图", &m.visitors).Height(280)`}, + {ID: "stacked", Title: "堆叠", Description: "按序列顺序自下而上堆叠,纵轴随总量缩放。", Height: 320, + Snippet: `chart := components.AreaChart{ Series: series, Values: values, Curve: components.ChartCurveNatural, Stack: components.ChartStackStacked, @@ -60,20 +204,136 @@ components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`}, Grid: components.ChartGridHorizontal, Legend: components.ChartLegendBottom, } -components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`}, - {ID: "expanded", Title: "百分比堆叠", Description: "每个横坐标归一到 100%,纵轴以百分比标注。", Height: 320, Snippet: `chart := components.AreaChart{ +components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`, + PageSnippet: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "Desktop", Color: palette.Chart[0]}, + {Key: "mobile", Label: "Mobile", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Curve: chartview.CurveNatural, Stack: chartview.StackStacked, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Legend: chartview.LegendBottom, + Label: "Stacked monthly visitors", Version: 1, +} +chartview.View(c, "Stacked monthly visitors", &m.visitors).Height(280)`, + PageSnippetZh: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "桌面端", Color: palette.Chart[0]}, + {Key: "mobile", Label: "移动端", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Curve: chartview.CurveNatural, Stack: chartview.StackStacked, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Legend: chartview.LegendBottom, + Label: "堆叠月访问量", Version: 1, +} +chartview.View(c, "堆叠月访问量", &m.visitors).Height(280)`}, + {ID: "expanded", Title: "百分比堆叠", Description: "每个横坐标归一到 100%,纵轴以百分比标注。", Height: 320, + Snippet: `chart := components.AreaChart{ Series: series, Values: values, Stack: components.ChartStackExpand, XAxis: components.ChartAxis{Format: formatMonth}, Grid: components.ChartGridHorizontal, } -components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`}, - {ID: "interactive", Title: "悬停与键盘", Description: "指针或方向键移动悬停点,提示框按边缘自动翻转。", Height: 320, Snippet: `plot := components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state) +components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`, + PageSnippet: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "Desktop", Color: palette.Chart[0]}, + {Key: "mobile", Label: "Mobile", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Stack: chartview.StackExpand, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Label: "Monthly visitors share", Version: 1, +} +chartview.View(c, "Monthly visitors share", &m.visitors).Height(280)`, + PageSnippetZh: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "桌面端", Color: palette.Chart[0]}, + {Key: "mobile", Label: "移动端", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Stack: chartview.StackExpand, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Label: "月访问量占比", Version: 1, +} +chartview.View(c, "月访问量占比", &m.visitors).Height(280)`}, + {ID: "interactive", Title: "悬停与键盘", Description: "指针或方向键移动悬停点,提示框按边缘自动翻转。", Height: 320, + Snippet: `plot := components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state) // From the pointer: state.Hover(plot.IndexAt(event.X)), and state.Clear() on exit. // From the keyboard: if index, ok := components.ChartStepForKey(event.Key, current, plot.Count()); ok { state.Hover(index) -}`}, +}`, + PageSnippet: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "Desktop", Color: palette.Chart[0]}, + {Key: "mobile", Label: "Mobile", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Curve: chartview.CurveMonotone, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Legend: chartview.LegendBottom, + Label: "Monthly visitors area chart", Version: 1, +} +// The view turns the pointer and the arrow keys into the hovered point. +m.visitors.OnHover = func(index int, active bool) { + m.inspected = index + if !active { + m.inspected = -1 + } +} +chartview.View(c, "Monthly visitors area chart", &m.visitors).Height(280)`, + PageSnippetZh: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "桌面端", Color: palette.Chart[0]}, + {Key: "mobile", Label: "移动端", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.visitors.Chart = chartview.AreaChart{ + Series: series, Values: values, + Curve: chartview.CurveMonotone, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Legend: chartview.LegendBottom, + Label: "月访问量面积图", Version: 1, +} +// 视图把指针和方向键映射为悬停点。 +m.visitors.OnHover = func(index int, active bool) { + m.inspected = index + if !active { + m.inspected = -1 + } +} +chartview.View(c, "月访问量面积图", &m.visitors).Height(280)`}, }, } @@ -82,20 +342,88 @@ var chartBarComponent = Component{ paint: (*State).paintChartBar, pointer: (*State).pointerChart, key: (*State).keyChart, initialize: (*State).initializeChart, Examples: []Example{ - {ID: "default", Title: "分组柱状图", Description: "同一类别的序列并排排列,顶端圆角。", Height: 320, Snippet: `chart := components.BarChart{ + {ID: "default", Title: "分组柱状图", Description: "同一类别的序列并排排列,顶端圆角。", Height: 320, + Snippet: `chart := components.BarChart{ Series: series, Values: values, XAxis: components.ChartAxis{Format: formatMonth}, Grid: components.ChartGridHorizontal, Legend: components.ChartLegendBottom, } -plot := components.PaintBarChart(canvas, theme, bounds, chartID, chart, &state)`}, - {ID: "stacked", Title: "堆叠柱状图", Description: "同一类别的序列叠成一根柱,只有最上端圆角。", Height: 320, Snippet: `chart := components.BarChart{ +plot := components.PaintBarChart(canvas, theme, bounds, chartID, chart, &state)`, + PageSnippet: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "Desktop", Color: palette.Chart[0]}, + {Key: "mobile", Label: "Mobile", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.bars.Chart = chartview.BarChart{ + Series: series, Values: values, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Legend: chartview.LegendBottom, + Label: "Monthly visitors bar chart", Version: 1, +} +chartview.Bar(c, "Monthly visitors bar chart", &m.bars).Height(280)`, + PageSnippetZh: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "桌面端", Color: palette.Chart[0]}, + {Key: "mobile", Label: "移动端", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.bars.Chart = chartview.BarChart{ + Series: series, Values: values, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Legend: chartview.LegendBottom, + Label: "月访问量柱状图", Version: 1, +} +chartview.Bar(c, "月访问量柱状图", &m.bars).Height(280)`}, + {ID: "stacked", Title: "堆叠柱状图", Description: "同一类别的序列叠成一根柱,只有最上端圆角。", Height: 320, + Snippet: `chart := components.BarChart{ Series: series, Values: values, Stack: components.ChartStackStacked, XAxis: components.ChartAxis{Format: formatMonth}, Legend: components.ChartLegendBottom, } -components.PaintBarChart(canvas, theme, bounds, chartID, chart, &state)`}, +components.PaintBarChart(canvas, theme, bounds, chartID, chart, &state)`, + PageSnippet: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "Desktop", Color: palette.Chart[0]}, + {Key: "mobile", Label: "Mobile", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.bars.Chart = chartview.BarChart{ + Series: series, Values: values, + Stack: chartview.StackStacked, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Legend: chartview.LegendBottom, + Label: "Stacked monthly visitors", Version: 1, +} +chartview.Bar(c, "Stacked monthly visitors", &m.bars).Height(280)`, + PageSnippetZh: `palette := c.Theme() +series := []chartview.Series{ + {Key: "desktop", Label: "桌面端", Color: palette.Chart[0]}, + {Key: "mobile", Label: "移动端", Color: palette.Chart[1]}, +} +desktop := []float32{186, 305, 237, 73, 209, 214} +mobile := []float32{80, 200, 120, 190, 130, 140} +values := [][]float32{desktop, mobile} +m.bars.Chart = chartview.BarChart{ + Series: series, Values: values, + Stack: chartview.StackStacked, + XAxis: chartview.Axis{Format: m.formatMonth}, + Grid: chartview.GridHorizontal, + Legend: chartview.LegendBottom, + Label: "堆叠月访问量", Version: 1, +} +chartview.Bar(c, "堆叠月访问量", &m.bars).Height(280)`}, }, } @@ -104,14 +432,65 @@ var chartDownsampleComponent = Component{ paint: (*State).paintChartDownsample, pointer: (*State).pointerChart, key: (*State).keyChart, initialize: (*State).initializeChart, Examples: []Example{ - {ID: "default", Title: "最大三角形降采样", Description: "保留首尾和每个桶中形状最突出的点,毛刺不会被抹平。", Height: 320, Snippet: `// Reduce once when the data changes, then draw the reduced series every frame. + {ID: "default", Title: "最大三角形降采样", Description: "保留首尾和每个桶中形状最突出的点,毛刺不会被抹平。", Height: 320, + Snippet: `// Reduce once when the data changes, then draw the reduced series every frame. keep = components.ChartDownsample(keep[:0], nil, samples, 400) for i, index := range keep { reduced[i] = samples[index] x[i] = float32(index) } chart := components.AreaChart{Series: series, X: x[:len(keep)], Values: [][]float32{reduced[:len(keep)]}} -components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`}, +components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state)`, + PageSnippet: `palette := c.Theme() +samples := make([]float32, 100_000) +for i := range samples { + t := float64(i) + samples[i] = float32(40*math.Sin(t/9000) + 15*math.Sin(t/700) + 4*math.Sin(t/37)) +} +for _, spike := range [...]int{23_000, 61_500, 88_800} { + samples[spike] += 60 +} +keep := chartview.Downsample(nil, nil, samples, 400) +x := make([]float32, len(keep)) +reduced := make([]float32, len(keep)) +for i, index := range keep { + x[i] = float32(index) + reduced[i] = samples[index] +} +m.cpu.Chart = chartview.AreaChart{ + Series: []chartview.Series{{Key: "cpu", Label: "CPU samples", Color: palette.Chart[2]}}, + X: x, Values: [][]float32{reduced}, + Fill: chartview.FillSolid, Curve: chartview.CurveLinear, StrokeWidth: 1.5, + XAxis: chartview.Axis{Linear: true, Ticks: 6}, + Grid: chartview.GridHorizontal, + Label: "CPU samples", Version: 1, +} +chartview.View(c, "CPU samples", &m.cpu).Height(280)`, + PageSnippetZh: `palette := c.Theme() +samples := make([]float32, 100_000) +for i := range samples { + t := float64(i) + samples[i] = float32(40*math.Sin(t/9000) + 15*math.Sin(t/700) + 4*math.Sin(t/37)) +} +for _, spike := range [...]int{23_000, 61_500, 88_800} { + samples[spike] += 60 +} +keep := chartview.Downsample(nil, nil, samples, 400) +x := make([]float32, len(keep)) +reduced := make([]float32, len(keep)) +for i, index := range keep { + x[i] = float32(index) + reduced[i] = samples[index] +} +m.cpu.Chart = chartview.AreaChart{ + Series: []chartview.Series{{Key: "cpu", Label: "CPU 采样", Color: palette.Chart[2]}}, + X: x, Values: [][]float32{reduced}, + Fill: chartview.FillSolid, Curve: chartview.CurveLinear, StrokeWidth: 1.5, + XAxis: chartview.Axis{Linear: true, Ticks: 6}, + Grid: chartview.GridHorizontal, + Label: "CPU 采样", Version: 1, +} +chartview.View(c, "CPU 采样", &m.cpu).Height(280)`}, }, } @@ -122,9 +501,10 @@ var ( // The months and visitor counts of shadcn's area chart examples. var ( - chartDemoMonths = [...]string{"January", "February", "March", "April", "May", "June"} - chartDemoDesktop = []float32{186, 305, 237, 73, 209, 214} - chartDemoMobile = []float32{80, 200, 120, 190, 130, 140} + chartDemoMonths = [...]string{"January", "February", "March", "April", "May", "June"} + chartDemoMonthsZh = [...]string{"1月", "2月", "3月", "4月", "5月", "6月"} + chartDemoDesktop = []float32{186, 305, 237, 73, 209, 214} + chartDemoMobile = []float32{80, 200, 120, 190, 130, 140} ) // chartDemoState holds what a chart needs between paints: the hovered point, the @@ -142,11 +522,25 @@ type chartDemoState struct { // itself allocates nothing. series [2]components.ChartSeries values [2][]float32 + // The generic Chart example's container and its caller-owned geometry. + container chartview.Container + tooltip chartview.Tooltip + rows [2]chartview.TooltipRow + heights [8]float32 } func (state *State) initializeChart() { demo := &chartDemoState{} - if state.componentID == "chart-downsample" { + switch state.componentID { + case "chart": + demo.heights = [...]float32{0.42, 0.28, 0.60, 0.36, 0.72, 0.48, 0.88, 0.62} + demo.rows = [2]chartview.TooltipRow{{Series: 0, Value: "42"}, {Series: 1, Value: "28"}} + demo.tooltip.Rows = demo.rows[:] + demo.container.Options = chartview.ContainerOptions{Legend: chartview.LegendBottom} + // The draw function is made once, with the model, so a warm paint does + // not allocate it again. + demo.container.Draw = demo.drawChartBars + case "chart-downsample": const count = 100_000 demo.samples = make([]float32, count) for i := range demo.samples { @@ -167,6 +561,21 @@ func (state *State) initializeChart() { state.chart = demo } +// drawChartBars paints the generic Chart example's custom commit bars inside the +// container's plot. +func (demo *chartDemoState) drawChartBars(d *ui.DrawContext, layout chartview.Layout) { + plot := layout.PlotBounds + baseline := plot.Y + plot.Height - 14 + barWidth := min(float32(30), (plot.Width-40)/8) + gap := (plot.Width - barWidth*8) / 9 + for index, scale := range demo.heights { + x := plot.X + gap + float32(index)*(barWidth+gap) + height := (plot.Height - 34) * scale + d.Canvas.Rounded(gfx.Rect{X: x, Y: baseline - height, Width: barWidth, Height: height}, 3, demo.series[index%2].Color) + } + d.Canvas.Fill(gfx.Rect{X: plot.X, Y: baseline, Width: plot.Width, Height: 1}, d.Theme.Border) +} + func chartDemoMonth(dst []byte, v float32) []byte { if index := int(v); index >= 0 && index < len(chartDemoMonths) { return append(dst, chartDemoMonths[index][:3]...) @@ -174,6 +583,21 @@ func chartDemoMonth(dst []byte, v float32) []byte { return dst } +func chartDemoMonthZh(dst []byte, v float32) []byte { + if index := int(v); index >= 0 && index < len(chartDemoMonthsZh) { + return append(dst, chartDemoMonthsZh[index]...) + } + return dst +} + +// chartMonthFormat names the month axis in the preview's language. +func (state *State) chartMonthFormat() func([]byte, float32) []byte { + if state.english { + return chartDemoMonth + } + return chartDemoMonthZh +} + // fill points the demo's series and values at the month data in the theme's colors. func (demo *chartDemoState) fill(theme gfx.Theme, english bool) { desktop, mobile := "桌面端", "移动端" @@ -203,7 +627,7 @@ func (state *State) paintChartArea(canvas *gfx.Canvas, theme gfx.Theme, size gfx series := demo.series[:] chart := components.AreaChart{ Series: series, Values: demo.values[:], - XAxis: components.ChartAxis{Format: chartDemoMonth}, Grid: components.ChartGridHorizontal, + XAxis: components.ChartAxis{Format: state.chartMonthFormat()}, Grid: components.ChartGridHorizontal, Label: state.Text("月访问量面积图", "Monthly visitors area chart"), Version: 1, } @@ -239,7 +663,7 @@ func (state *State) paintChartBar(canvas *gfx.Canvas, theme gfx.Theme, size gfx. demo.fill(theme, state.english) chart := components.BarChart{ Series: demo.series[:], Values: demo.values[:], - XAxis: components.ChartAxis{Format: chartDemoMonth}, Grid: components.ChartGridHorizontal, + XAxis: components.ChartAxis{Format: state.chartMonthFormat()}, Grid: components.ChartGridHorizontal, Legend: components.ChartLegendBottom, Label: state.Text("月访问量柱状图", "Monthly visitors bar chart"), Version: 1, } diff --git a/internal/componentdemo/code_diff.go b/internal/componentdemo/code_diff.go index e4e43168..a0a916b8 100644 --- a/internal/componentdemo/code_diff.go +++ b/internal/componentdemo/code_diff.go @@ -72,6 +72,50 @@ var codeDiffComponent = Component{ VerticalScrollbarID: vertical, HorizontalScrollbarID: horizontal, })`, + PageSnippet: `server := "server: production\n" + + "replicas: 2\n" + + "logLevel: info\n" + + "timeout: 20s\n" + + "healthCheck:\n" + + " enabled: true\n" + + " interval: 10s\n" +local := "server: production\n" + + "replicas: 4\n" + + "logLevel: warning\n" + + "timeout: 30s\n" + + "healthCheck:\n" + + " enabled: true\n" + + " interval: 10s\n" + + " path: /ready\n" +m.diff.Snapshot.Result = m.align(server, local) // the caller aligns both sides by row +m.diff.Snapshot.Value = local +m.diff.Snapshot.Language = "yaml" +m.diff.Snapshot.Hint = "Edit the right pane; the left pane remains the server baseline." +m.diff.Snapshot.VerticalScrollbarID = codeeditor.Shown +m.diff.Snapshot.HorizontalScrollbarID = codeeditor.Shown +codeeditor.DiffView(c, "Local edited version", &m.diff).Fill()`, + PageSnippetZh: `server := "server: production\n" + + "replicas: 2\n" + + "logLevel: info\n" + + "timeout: 20s\n" + + "healthCheck:\n" + + " enabled: true\n" + + " interval: 10s\n" +local := "server: production\n" + + "replicas: 4\n" + + "logLevel: warning\n" + + "timeout: 30s\n" + + "healthCheck:\n" + + " enabled: true\n" + + " interval: 10s\n" + + " path: /ready\n" +m.diff.Snapshot.Result = m.align(server, local) // 调用方按行对齐左右两栏 +m.diff.Snapshot.Value = local +m.diff.Snapshot.Language = "yaml" +m.diff.Snapshot.Hint = "编辑右侧文本,左侧保持为服务器基准版本。" +m.diff.Snapshot.VerticalScrollbarID = codeeditor.Shown +m.diff.Snapshot.HorizontalScrollbarID = codeeditor.Shown +codeeditor.DiffView(c, "本地编辑版本", &m.diff).Fill()`, }}, } diff --git a/internal/componentdemo/code_editor.go b/internal/componentdemo/code_editor.go index 45c5d404..1ff40ac1 100644 --- a/internal/componentdemo/code_editor.go +++ b/internal/componentdemo/code_editor.go @@ -97,10 +97,10 @@ editor.SetCode(text.CodeOptions{TabWidth: 4, HardTabs: true, AutoIndent: true, A view.Paint(canvas, theme, bounds, components.CodeEditorSnapshot{ ID: field, Value: editor.String(), LineNumbers: true, CurrentLine: true, MatchBrackets: true, Caret: editor.ByteOffset(editor.Caret()), Highlight: highlight, ScrollbarID: bar, -})`}, +})`, PageSnippet: "// m is the page model; m.editor was made with codeeditor.New.\nsource := `package main\n\nimport \"fmt\"\n\n// greet prints one line for every name it is given.\nfunc greet(names []string) {\n\tfor index, name := range names {\n\t\tif name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%d: hello, %s\\n\", index+1, name)\n\t}\n}\n\nfunc main() {\n\tgreet([]string{\"Viva\", \"wide\", \"Motty\"})\n}\n`\n\ndocument := text.NewEditor(source)\ndocument.SetCode(text.CodeOptions{TabWidth: 4, HardTabs: true, AutoIndent: true, AutoClose: true,\n IndentAfter: \"{[(\", LineComment: \"//\"})\nm.editor.Document = document\nm.editor.Snapshot.Language = \"go\"\nm.editor.Snapshot.Highlight = m.highlight\ncodeeditor.View(c, \"Source\", &m.editor).Fill()", PageSnippetZh: "// m is the page model; m.editor was made with codeeditor.New.\nsource := `package main\n\nimport \"fmt\"\n\n// greet prints one line for every name it is given.\nfunc greet(names []string) {\n\tfor index, name := range names {\n\t\tif name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%d: hello, %s\\n\", index+1, name)\n\t}\n}\n\nfunc main() {\n\tgreet([]string{\"Viva\", \"中文\", \"Motty\"})\n}\n`\n\ndocument := text.NewEditor(source)\ndocument.SetCode(text.CodeOptions{TabWidth: 4, HardTabs: true, AutoIndent: true, AutoClose: true,\n IndentAfter: \"{[(\", LineComment: \"//\"})\nm.editor.Document = document\nm.editor.Snapshot.Language = \"go\"\nm.editor.Snapshot.Highlight = m.highlight\ncodeeditor.View(c, \"源码\", &m.editor).Fill()"}, {ID: "wrap", Title: "软换行", Description: "Wrap 让长行在单词处折到下一行,行号只标在每行的第一行;不换行时视图横向滚动并跟随插入点。", Snippet: `view.Paint(canvas, theme, bounds, components.CodeEditorSnapshot{ ID: field, Value: value, Wrap: true, LineNumbers: true, -})`}, +})`, PageSnippet: "// m is the page model; m.editor was made with codeeditor.New.\nsource := `package main\n\nimport \"fmt\"\n\n// greet prints one line for every name it is given.\nfunc greet(names []string) {\n\tfor index, name := range names {\n\t\tif name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%d: hello, %s\\n\", index+1, name)\n\t}\n}\n\nfunc main() {\n\tgreet([]string{\"Viva\", \"wide\", \"Motty\"})\n}\n`\n\ndocument := text.NewEditor(source)\ndocument.SetCode(text.CodeOptions{TabWidth: 4, HardTabs: true, AutoIndent: true, AutoClose: true,\n IndentAfter: \"{[(\", LineComment: \"//\"})\nm.editor.Document = document\nm.editor.Snapshot.Language = \"go\"\nm.editor.Snapshot.Highlight = m.highlight\nm.editor.Snapshot.Wrap = true\ncodeeditor.View(c, \"Source\", &m.editor).Fill()", PageSnippetZh: "// m is the page model; m.editor was made with codeeditor.New.\nsource := `package main\n\nimport \"fmt\"\n\n// greet prints one line for every name it is given.\nfunc greet(names []string) {\n\tfor index, name := range names {\n\t\tif name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%d: hello, %s\\n\", index+1, name)\n\t}\n}\n\nfunc main() {\n\tgreet([]string{\"Viva\", \"中文\", \"Motty\"})\n}\n`\n\ndocument := text.NewEditor(source)\ndocument.SetCode(text.CodeOptions{TabWidth: 4, HardTabs: true, AutoIndent: true, AutoClose: true,\n IndentAfter: \"{[(\", LineComment: \"//\"})\nm.editor.Document = document\nm.editor.Snapshot.Language = \"go\"\nm.editor.Snapshot.Highlight = m.highlight\nm.editor.Snapshot.Wrap = true\ncodeeditor.View(c, \"源码\", &m.editor).Fill()"}, {ID: "find", Title: "查找与替换", Description: "PaintFindBar 只画条和声明命中:查询、选项、计数、上一个/下一个、替换都由应用用 text/find.Session 驱动;匹配通过 Marks 画在编辑器里,当前匹配更亮。", Snippet: `session.Update(editor.String()) layout := components.PaintFindBar(canvas, theme, bar, components.FindBarSnapshot{ Find: findInput, Replacement: replaceInput, Replacing: true, @@ -108,12 +108,12 @@ layout := components.PaintFindBar(canvas, theme, bar, components.FindBarSnapshot MatchCaseID: matchCase, WholeWordID: wholeWord, RegexpID: regexp, ReplaceOneID: replaceOne, ReplaceAllID: replaceAll, Status: "2 of 4", -})`}, +})`, PageSnippet: "// m is the page model; m.editor was made with codeeditor.New.\nsource := `package main\n\nimport \"fmt\"\n\n// greet prints one line for every name it is given.\nfunc greet(names []string) {\n\tfor index, name := range names {\n\t\tif name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%d: hello, %s\\n\", index+1, name)\n\t}\n}\n\nfunc main() {\n\tgreet([]string{\"Viva\", \"wide\", \"Motty\"})\n}\n`\n\ndocument := text.NewEditor(source)\ndocument.SetCode(text.CodeOptions{TabWidth: 4, HardTabs: true, AutoIndent: true, AutoClose: true,\n IndentAfter: \"{[(\", LineComment: \"//\"})\nm.editor.Document = document\nm.editor.Snapshot.Language = \"go\"\nm.editor.Snapshot.Highlight = m.highlight\nm.find.Snapshot.Find.Value = \"name\"\nm.find.Snapshot.Find.Label = \"Find\"\nm.find.Snapshot.Find.Placeholder = \"Find\"\nm.find.Snapshot.Replacement.Value = \"title\"\nm.find.Snapshot.Replacement.Label = \"Replace\"\nm.find.Snapshot.Replacement.Placeholder = \"Replace\"\nm.find.Snapshot.Replacing = true\nm.find.Snapshot.MatchCase = true\nm.find.Snapshot.Status = \"2 of 4\"\nm.find.Snapshot.Labels = m.findLabels // Previous, Next, Close, …\nm.find.Snapshot.Find.ID = codeeditor.Shown\nm.find.Snapshot.Replacement.ID = codeeditor.Shown\nm.find.Snapshot.PreviousID = codeeditor.Shown\nm.find.Snapshot.NextID = codeeditor.Shown\nm.find.Snapshot.CloseID = codeeditor.Shown\nm.find.Snapshot.MatchCaseID = codeeditor.Shown\nm.find.Snapshot.WholeWordID = codeeditor.Shown\nm.find.Snapshot.RegexpID = codeeditor.Shown\nm.find.Snapshot.ToggleReplaceID = codeeditor.Shown\nm.find.Snapshot.ReplaceOneID = codeeditor.Shown\nm.find.Snapshot.ReplaceAllID = codeeditor.Shown\nm.editor.Snapshot.Marks = m.marks\nm.editor.Snapshot.CurrentMark = m.current\ncodeeditor.View(c, \"Source\", &m.editor).Fill()\ncodeeditor.FindBarView(c, \"Find\", &m.find).FillWidth()", PageSnippetZh: "// m is the page model; m.editor was made with codeeditor.New.\nsource := `package main\n\nimport \"fmt\"\n\n// greet prints one line for every name it is given.\nfunc greet(names []string) {\n\tfor index, name := range names {\n\t\tif name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%d: hello, %s\\n\", index+1, name)\n\t}\n}\n\nfunc main() {\n\tgreet([]string{\"Viva\", \"中文\", \"Motty\"})\n}\n`\n\ndocument := text.NewEditor(source)\ndocument.SetCode(text.CodeOptions{TabWidth: 4, HardTabs: true, AutoIndent: true, AutoClose: true,\n IndentAfter: \"{[(\", LineComment: \"//\"})\nm.editor.Document = document\nm.editor.Snapshot.Language = \"go\"\nm.editor.Snapshot.Highlight = m.highlight\nm.find.Snapshot.Find.Value = \"name\"\nm.find.Snapshot.Find.Label = \"查找\"\nm.find.Snapshot.Find.Placeholder = \"查找\"\nm.find.Snapshot.Replacement.Value = \"title\"\nm.find.Snapshot.Replacement.Label = \"替换\"\nm.find.Snapshot.Replacement.Placeholder = \"替换\"\nm.find.Snapshot.Replacing = true\nm.find.Snapshot.MatchCase = true\nm.find.Snapshot.Status = \"2 / 4\"\nm.find.Snapshot.Labels = m.findLabels // 上一个、下一个、关闭……\nm.find.Snapshot.Find.ID = codeeditor.Shown\nm.find.Snapshot.Replacement.ID = codeeditor.Shown\nm.find.Snapshot.PreviousID = codeeditor.Shown\nm.find.Snapshot.NextID = codeeditor.Shown\nm.find.Snapshot.CloseID = codeeditor.Shown\nm.find.Snapshot.MatchCaseID = codeeditor.Shown\nm.find.Snapshot.WholeWordID = codeeditor.Shown\nm.find.Snapshot.RegexpID = codeeditor.Shown\nm.find.Snapshot.ToggleReplaceID = codeeditor.Shown\nm.find.Snapshot.ReplaceOneID = codeeditor.Shown\nm.find.Snapshot.ReplaceAllID = codeeditor.Shown\nm.editor.Snapshot.Marks = m.marks\nm.editor.Snapshot.CurrentMark = m.current\ncodeeditor.View(c, \"源码\", &m.editor).Fill()\ncodeeditor.FindBarView(c, \"查找\", &m.find).FillWidth()"}, {ID: "marks", Title: "查找标记与选区", Description: "Marks 在文本后面画查找匹配,当前匹配更亮;选区跨行时行尾多画半格表示换行也被选中。", Snippet: `view.Paint(canvas, theme, bounds, components.CodeEditorSnapshot{ ID: field, Value: value, Marks: session.Matches(), CurrentMark: current, // []text.Span of the find session SelectionStart: 0, SelectionEnd: 20, -})`}, +})`, PageSnippet: "// m is the page model; m.editor was made with codeeditor.New.\nsource := `package main\n\nimport \"fmt\"\n\n// greet prints one line for every name it is given.\nfunc greet(names []string) {\n\tfor index, name := range names {\n\t\tif name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%d: hello, %s\\n\", index+1, name)\n\t}\n}\n\nfunc main() {\n\tgreet([]string{\"Viva\", \"wide\", \"Motty\"})\n}\n`\n\ndocument := text.NewEditor(source)\ndocument.SetCode(text.CodeOptions{TabWidth: 4, HardTabs: true, AutoIndent: true, AutoClose: true,\n IndentAfter: \"{[(\", LineComment: \"//\"})\nm.editor.Document = document\nm.editor.Snapshot.Language = \"go\"\nm.editor.Snapshot.Highlight = m.highlight\nm.editor.Snapshot.Marks = m.marks\nm.editor.Snapshot.CurrentMark = m.current\ndocument.SetSelection(text.Range{Start: document.RuneIndex(m.selectionStart), End: document.RuneIndex(m.selectionEnd)})\nm.editor.Snapshot.ShowCaret = true\ncodeeditor.View(c, \"Source\", &m.editor).Fill()", PageSnippetZh: "// m is the page model; m.editor was made with codeeditor.New.\nsource := `package main\n\nimport \"fmt\"\n\n// greet prints one line for every name it is given.\nfunc greet(names []string) {\n\tfor index, name := range names {\n\t\tif name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%d: hello, %s\\n\", index+1, name)\n\t}\n}\n\nfunc main() {\n\tgreet([]string{\"Viva\", \"中文\", \"Motty\"})\n}\n`\n\ndocument := text.NewEditor(source)\ndocument.SetCode(text.CodeOptions{TabWidth: 4, HardTabs: true, AutoIndent: true, AutoClose: true,\n IndentAfter: \"{[(\", LineComment: \"//\"})\nm.editor.Document = document\nm.editor.Snapshot.Language = \"go\"\nm.editor.Snapshot.Highlight = m.highlight\nm.editor.Snapshot.Marks = m.marks\nm.editor.Snapshot.CurrentMark = m.current\ndocument.SetSelection(text.Range{Start: document.RuneIndex(m.selectionStart), End: document.RuneIndex(m.selectionEnd)})\nm.editor.Snapshot.ShowCaret = true\ncodeeditor.View(c, \"源码\", &m.editor).Fill()"}, }, } diff --git a/internal/componentdemo/code_merge.go b/internal/componentdemo/code_merge.go index 1a0e69ab..1e55c6c5 100644 --- a/internal/componentdemo/code_merge.go +++ b/internal/componentdemo/code_merge.go @@ -62,6 +62,58 @@ var codeMergeComponent = Component{ Editor: components.CodeDiffSnapshot{ID: resultID, Value: result}, Actions: []components.CodeMergeAction{{Row: 1, Incoming: true, ID: acceptID, Label: "Accept"}}, })`, + PageSnippet: `current := []string{"head", "local", "tail"} +incoming := []string{"head", "remote", "tail"} +result := "head\nchoice\ntail" +type mergeRow struct { + CurrentLine, ResultLine, IncomingLine int + CurrentChanged, IncomingChanged bool +} +rows := []mergeRow{ + {CurrentLine: 0, ResultLine: 0, IncomingLine: 0}, + {CurrentLine: 1, ResultLine: 1, IncomingLine: 1, CurrentChanged: true, IncomingChanged: true}, + {CurrentLine: 2, ResultLine: 2, IncomingLine: 2}, +} +type mergeAction struct { + Row int + Incoming bool + ID gfx.ID + Label string +} +m.merge.Snapshot.Current = current +m.merge.Snapshot.Incoming = incoming +m.merge.Snapshot.Rows = rows +m.merge.Snapshot.Editor.Value = result +m.merge.Snapshot.Editor.VerticalScrollbarID = codeeditor.Shown +// m.acceptID is the caller's stable hit ID for the Accept action. +m.merge.Snapshot.Actions = []mergeAction{{Row: 1, Incoming: true, ID: m.acceptID, Label: "Accept"}} +codeeditor.MergeView(c, "Merge result", &m.merge).Fill()`, + PageSnippetZh: `current := []string{"head", "local", "tail"} +incoming := []string{"head", "remote", "tail"} +result := "head\nchoice\ntail" +type mergeRow struct { + CurrentLine, ResultLine, IncomingLine int + CurrentChanged, IncomingChanged bool +} +rows := []mergeRow{ + {CurrentLine: 0, ResultLine: 0, IncomingLine: 0}, + {CurrentLine: 1, ResultLine: 1, IncomingLine: 1, CurrentChanged: true, IncomingChanged: true}, + {CurrentLine: 2, ResultLine: 2, IncomingLine: 2}, +} +type mergeAction struct { + Row int + Incoming bool + ID gfx.ID + Label string +} +m.merge.Snapshot.Current = current +m.merge.Snapshot.Incoming = incoming +m.merge.Snapshot.Rows = rows +m.merge.Snapshot.Editor.Value = result +m.merge.Snapshot.Editor.VerticalScrollbarID = codeeditor.Shown +// m.acceptID 是调用方为“接受”操作分配的稳定命中 ID。 +m.merge.Snapshot.Actions = []mergeAction{{Row: 1, Incoming: true, ID: m.acceptID, Label: "接受"}} +codeeditor.MergeView(c, "合并结果", &m.merge).Fill()`, }}, } diff --git a/internal/componentdemo/collapsible.go b/internal/componentdemo/collapsible.go index aa422979..beb07117 100644 --- a/internal/componentdemo/collapsible.go +++ b/internal/componentdemo/collapsible.go @@ -16,13 +16,47 @@ content := collapsible.Paint("3 build artifacts", open, 112) if canvas.Clicked(trigger) { open = !open } -canvas.Rounded(content, theme.Metrics.RadiusSurface, theme.Muted)`}, +canvas.Rounded(content, theme.Metrics.RadiusSurface, theme.Muted)`, PageSnippet: `ui.Collapsible(c, &m.builds, "3 build artifacts", func() { + for _, line := range []string{ + "viva-darwin-arm64 3.8 MiB", + "viva-windows-amd64 4.1 MiB", + "viva-linux-amd64 3.9 MiB", + } { + ui.Text(c, line).Mono().Muted() + } +})`, PageSnippetZh: `ui.Collapsible(c, &m.builds, "3 个构建产物", func() { + for _, line := range []string{ + "viva-darwin-arm64 3.8 MiB", + "viva-windows-amd64 4.1 MiB", + "viva-linux-amd64 3.9 MiB", + } { + ui.Text(c, line).Mono().Muted() + } +})`}, {ID: "disabled", Title: "禁用状态", Description: "保持展开快照但禁止触发。", Snippet: `trigger := tree.ID(page, "trigger") collapsible := components.BeginCollapsible(canvas, theme, trigger, bounds).Disabled() content := collapsible.Paint("3 build artifacts", open, 112) if content.Height > 0 { canvas.Rounded(content, theme.Metrics.RadiusSurface, theme.Muted) -}`}, +}`, PageSnippet: `m.builds.Disabled = true +ui.Collapsible(c, &m.builds, "3 build artifacts", func() { + for _, line := range []string{ + "viva-darwin-arm64 3.8 MiB", + "viva-windows-amd64 4.1 MiB", + "viva-linux-amd64 3.9 MiB", + } { + ui.Text(c, line).Mono().Muted() + } +})`, PageSnippetZh: `m.builds.Disabled = true +ui.Collapsible(c, &m.builds, "3 个构建产物", func() { + for _, line := range []string{ + "viva-darwin-arm64 3.8 MiB", + "viva-windows-amd64 4.1 MiB", + "viva-linux-amd64 3.9 MiB", + } { + ui.Text(c, line).Mono().Muted() + } +})`}, }, } diff --git a/internal/componentdemo/color_picker.go b/internal/componentdemo/color_picker.go index a6ce0606..322f96e6 100644 --- a/internal/componentdemo/color_picker.go +++ b/internal/componentdemo/color_picker.go @@ -37,7 +37,15 @@ if m.picker.Applied() { // Use #RRGGBBAA in the caller-owned text editor. color, valid := components.ParseColorHex(hex, true) if valid { draft = draft.WithColor(color) } -layout := components.BeginColorPicker(canvas, theme, bounds, options).Paint()`}}, +layout := components.BeginColorPicker(canvas, theme, bounds, options).Paint()`, PageSnippet: `// m.color starts as #3B82F6. +ui.ColorPicker(c, &m.picker, &m.color, "Custom color") +if m.picker.Applied() { + m.saved = m.color +}`, PageSnippetZh: `// m.color 初始为 #3B82F6。 +ui.ColorPicker(c, &m.picker, &m.color, "自定义颜色") +if m.picker.Applied() { + m.saved = m.color +}`}}, } var demoPickerFeature = tree.Feature("color-picker") diff --git a/internal/componentdemo/column_resize.go b/internal/componentdemo/column_resize.go index 68258201..1d53bb5e 100644 --- a/internal/componentdemo/column_resize.go +++ b/internal/componentdemo/column_resize.go @@ -21,9 +21,12 @@ layout := components.BeginColumnResize(canvas, theme, stage.Rect(), widths). Fits([]float32{180, 64, 100}).Gap(8). Paint(columns, dividers, hits, []string{"Resize name", "Resize size"}) edit, ok := components.BeginColumnResize(nil, theme, stage.Rect(), widths). - Gap(8).Edit(0, pointer.X)`, - }}, -} + Gap(8).Edit(0, pointer.X)`, PageSnippet: `m.columns.Widths = m.columnWidths +columnresizeview.View(c, "File list", &m.columns).FillWidth().Height(180) +ui.Text(c, "Drag a divider to resize two columns; double-click it to fit the left one.").Muted()`, PageSnippetZh: `m.columns.Widths = m.columnWidths +columnresizeview.View(c, "文件列表", &m.columns).FillWidth().Height(180) +ui.Text(c, "拖动分隔线调整两列宽度;双击按内容自适应。").Muted()`}, + }} var ( columnResizeDemoUI = tree.Feature("column-resize") diff --git a/internal/componentdemo/combobox.go b/internal/componentdemo/combobox.go index 3f5fed5c..4ba736e7 100644 --- a/internal/componentdemo/combobox.go +++ b/internal/componentdemo/combobox.go @@ -60,7 +60,9 @@ combo.AddItem(components.ComboboxItem{ID: opt.At(1), Label: "WebGPU", Selected: combo.AddItem(components.ComboboxItem{ ID: opt.At(2), Label: "Headless tests", Selected: selected == 3, }) -combo.End()`}, +combo.End()`, PageSnippet: `frameworks := []string{"Viva Native", "WebGPU", "Headless tests"} +ui.Combobox(c, &m.framework, frameworks, nil, "Framework").Clearable()`, PageSnippetZh: `frameworks := []string{"Viva Native", "WebGPU", "Headless tests"} +ui.Combobox(c, &m.framework, frameworks, nil, "框架").Clearable()`}, {ID: "chips", Title: "多选标签", Description: "标签与查询输入按宽度换行,容器随内容增高。", Snippet: `// chips is the caller-owned []components.ComboboxChip, one RemoveID each. var rects [5]gfx.Rect components.PaintComboboxChips(canvas, theme, bounds, chips, components.ComboboxChipsOptions{ @@ -69,7 +71,9 @@ components.PaintComboboxChips(canvas, theme, bounds, chips, components.ComboboxC }, rects[:0]) if index, ok := canvas.ClickedIn(remove); ok { chips = append(chips[:index], chips[index+1:]...) -}`}, +}`, PageSnippet: `frameworks := []string{"Viva Native", "WebGPU", "Headless tests", "Windows", "Linux"} +ui.Combobox(c, &m.framework, frameworks, nil, "Framework").Clearable()`, PageSnippetZh: `frameworks := []string{"Viva Native", "WebGPU", "Headless tests", "Windows", "Linux"} +ui.Combobox(c, &m.framework, frameworks, nil, "框架").Clearable()`}, }, } diff --git a/internal/componentdemo/command.go b/internal/componentdemo/command.go index 8aaff244..711597e4 100644 --- a/internal/componentdemo/command.go +++ b/internal/componentdemo/command.go @@ -1,14 +1,29 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/commandview" ) var commandComponent = Component{ ID: "command", Title: "Command", Category: "Overlays", Summary: "受控查询、分组结果与键盘提示的命令面板。", - paint: (*State).paintCommand, + paint: (*State).paintCommand, initialize: (*State).initializeCommand, + editable: func(exampleID string) (editableField, bool) { + initial := "" + if exampleID == "dialog" { + initial = "open" + } + return editableField{ID: commandInput, Initial: initial}, true + }, + editor: func(state *State) *text.Editor { + initial := "" + if state.exampleID == "dialog" { + initial = "open" + } + return text.NewEditor(initial) + }, Examples: []Example{ {ID: "default", Title: "命令搜索", Description: "生产 Command 组合输入快照与调用方筛选的结果。", Height: 270, Snippet: `results := tree.Sub(page, tree.Name("item")) command := components.BeginCommand(canvas, theme, bounds, components.CommandOptions{ @@ -29,7 +44,39 @@ if hovered := canvas.Hovered(); !hovered.IsZero() { } if index, ok := canvas.ClickedIn(results); ok { selected = int(index) -}`}, +}`, + PageSnippet: `m.command.Filter = func(query string) { + // Re-filter m.results and rebuild m.command.Results here. +} +m.command.Select = func(index int) { + m.selected = index +} +m.command.Choose = func(index int) { + m.chosen = index +} +m.command.Clear() +m.command.Group("Suggestions") +m.command.Item("Open workspace", "⌘O") +m.command.Item("Create window", "⌘N") +m.command.Separator() +m.command.Item("Pin current view", "") +commandview.View(c, "Command", &m.command).FillWidth().Height(180)`, + PageSnippetZh: `m.command.Filter = func(query string) { + // 在这里按 query 重新过滤 m.results,并重建 m.command.Results。 +} +m.command.Select = func(index int) { + m.selected = index +} +m.command.Choose = func(index int) { + m.chosen = index +} +m.command.Clear() +m.command.Group("建议") +m.command.Item("打开工作区", "⌘O") +m.command.Item("新建窗口", "⌘N") +m.command.Separator() +m.command.Item("固定当前视图", "") +commandview.View(c, "命令", &m.command).FillWidth().Height(180)`}, {ID: "dialog", Title: "对话框尺寸", Description: "更宽松的命令面板行高和已选状态。", Height: 320, Snippet: `results := tree.Sub(page, tree.Name("item")) command := components.BeginCommand(canvas, theme, bounds, components.CommandOptions{ InputID: inputID, Query: "open", Placeholder: "Type a command…", @@ -41,58 +88,127 @@ command.AddItem(components.CommandItem{ command.AddSeparator() command.AddItem(components.CommandItem{ ID: results.At(2), Label: "Pin current view", Checked: checked, Disabled: true, -})`}, +})`, + PageSnippet: `m.command.Options = m.command.Options.Dialog() +m.command.Query = "open" +m.command.Selected = 0 +m.command.Clear() +m.command.Group("Suggestions") +m.command.Item("Open workspace", "⌘O") +m.command.Item("Create window", "⌘N") +m.command.Separator() +m.command.Item("Pin current view", "") +// A Result appended with Disabled: true is painted inert. +commandview.View(c, "Command", &m.command).FillWidth().Height(220)`, + PageSnippetZh: `m.command.Options = m.command.Options.Dialog() +m.command.Query = "open" +m.command.Selected = 0 +m.command.Clear() +m.command.Group("建议") +m.command.Item("打开工作区", "⌘O") +m.command.Item("新建窗口", "⌘N") +m.command.Separator() +m.command.Item("固定当前视图", "") +// 追加 Disabled: true 的 Result 会绘制为不可用行。 +commandview.View(c, "命令", &m.command).FillWidth().Height(220)`}, {ID: "empty", Title: "空结果", Description: "使用生产空结果行而不伪造列表。", Height: 210, Snippet: `command := components.BeginCommand(canvas, theme, bounds, components.CommandOptions{ InputID: inputID, Query: query, Placeholder: "Type a command…", Layer: 1, }) command.AddEmpty("No commands found") -command.End()`}, +command.End()`, + PageSnippet: `m.command.Query = "" +m.command.Selected = 0 +m.command.Clear() +m.command.Empty("No commands found") +commandview.View(c, "Command", &m.command).FillWidth().Height(112)`, + PageSnippetZh: `m.command.Query = "" +m.command.Selected = 0 +m.command.Clear() +m.command.Empty("没有找到命令") +commandview.View(c, "命令", &m.command).FillWidth().Height(112)`}, }, } var ( - commandUI = tree.Feature("command") + commandUI = tree.Feature("command") + // commandInput is the demo's native text hit before the first paint; the + // page control's own identity replaces it once View declares the control. commandInput = tree.ID(commandUI, "query") // commandItem's item i is the i-th result. commandItem = tree.Sub(commandUI, tree.Name("item")) ) +// commandDemo is one command example's page control. The wrapper's handlers +// and draw function point at this value, so it is kept beside the State rather +// than rebuilt in each paint. +type commandDemo struct { + command commandview.Command +} + +// commandDemos is keyed by State because the constrained demo model has no +// field for this example; a State is painted on one thread at a time. +var commandDemos = map[*State]*commandDemo{} + +func (state *State) initializeCommand() { + demo := &commandDemo{} + if state.exampleID == "dialog" { + demo.command.Query = "open" + demo.command.Options = demo.command.Options.Dialog() + } + // The selection is the wrapper's; the test reads it back through the demo's + // shared value slot. + demo.command.Select = func(index int) { state.values[0] = int32(index) } + commandDemos[state] = demo +} + +func commandDemoFor(state *State) *commandDemo { + if demo := commandDemos[state]; demo != nil { + return demo + } + demo := &commandDemo{} + commandDemos[state] = demo + return demo +} + func (state *State) paintCommand(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - variant := components.CommandDefault + demo := commandDemoFor(state) // Input row, group label, three result rows, separator, and bottom padding. height := float32(36 + 28 + 3*32 + 9 + 4) - query := "" switch state.exampleID { case "dialog": - variant = components.CommandDialog height = 48 + 28 + 3*44 + 9 + 4 - query = "open" case "empty": height = 36 + 68 + 4 } - var panel ui.Box state.drawPage(canvas, theme, size, 520, state.Text("Command · 快速操作", "Command · Quick actions"), func(c ui.C) { - panel = ui.Slot(c).FillWidth().Height(min(height, max(size.Height-84, 120))) - }) - command := components.BeginCommand(canvas, theme, panel.Rect(), components.CommandOptions{InputID: commandInput, Label: "Command query", Query: query, Placeholder: "Type a command…", Hint: "Search commands", Variant: variant, Layer: 1}) - if state.exampleID == "empty" { - command.AddEmpty("No commands found") - return - } - // Selected is the row Enter runs (cmdk's data-selected): the pointer moves it - // here, and a real panel also moves it from its arrow keys. - current := int(state.values[0]) - for i := 0; i < 3; i++ { - if canvas.Hovered() == commandItem.At(i) { - current = i + command := &demo.command + command.Clear() + if state.exampleID == "empty" { + command.Empty(state.Text("没有找到命令", "No commands found")) + } else { + command.Group(state.Text("建议", "Suggestions")) + command.Results = append(command.Results, commandview.Result{ + ID: commandItem.At(0), Label: state.Text("打开工作区", "Open workspace"), Shortcut: "⌘O", + }) + command.Results = append(command.Results, commandview.Result{ + ID: commandItem.At(1), Label: state.Text("新建窗口", "Create window"), Shortcut: "⌘N", + }) + command.Results = append(command.Results, commandview.Result{Kind: commandview.ResultSeparator}) + command.Results = append(command.Results, commandview.Result{ + ID: commandItem.At(2), + Label: state.Text("固定当前视图", "Pin current view"), + Checked: command.Selected == 2, + Disabled: state.exampleID == "dialog", + }) } - } - command.AddGroup("Suggestions") - command.AddItem(components.CommandItem{ID: commandItem.At(0), Label: "Open workspace", Shortcut: "⌘O", Selected: current == 0}) - command.AddItem(components.CommandItem{ID: commandItem.At(1), Label: "Create window", Shortcut: "⌘N", Selected: current == 1}) - command.AddSeparator() - command.AddItem(components.CommandItem{ID: commandItem.At(2), Label: "Pin current view", Checked: current == 2, Selected: current == 2, Disabled: state.exampleID == "dialog"}) - if index, ok := canvas.ClickedIn(commandItem); ok { - state.values[0] = int32(index) - } + commandview.View(c, state.Text("命令", "Command"), command). + FillWidth().Height(min(height, max(size.Height-84, 120))) + if state.editing { + // The query row is a part of the control; the demo's fixed-field text + // service edits the page control's own editor, so typing reaches Query + // and Filter exactly as it does for a page that calls Page.TextInput. + state.fieldID = command.InputID() + state.editor = command.Editor() + } + }) } diff --git a/internal/componentdemo/dialog.go b/internal/componentdemo/dialog.go index 25f9bcb9..43d23fb6 100644 --- a/internal/componentdemo/dialog.go +++ b/internal/componentdemo/dialog.go @@ -12,7 +12,7 @@ var dialogComponent = Component{ {ID: "default", Title: "打开弹窗", Description: "从按钮打开;确认、取消、关闭与 Escape 均可结束弹窗。", Snippet: `if open { d := ui.Dialog(c, ui.DialogSpec{ Title: "Save changes?", Description: "This updates the local example state.", - Width: 440, Scope: scope, CloseID: closeID, + Width: 440, Scope: m.scope, CloseID: m.closeID, }) d.Footer(func() { if ui.Button(c, "Cancel").Hit(cancelID, "Cancel").Outline().Clicked() { open = false } @@ -29,7 +29,7 @@ if open { d := ui.Dialog(c, ui.DialogSpec{ Title: "Save changes?", Description: "Confirm to update the local example state.", - Width: 440, Scope: scope, CloseID: closeID, + Width: 440, Scope: m.scope, CloseID: m.closeID, }) d.Footer(func() { if ui.Button(c, "Cancel").Outline().Clicked() { @@ -52,7 +52,7 @@ if open { d := ui.Dialog(c, ui.DialogSpec{ Title: "保存更改?", Description: "确认后更新本地示例状态。", - Width: 440, Scope: scope, CloseID: closeID, + Width: 440, Scope: m.scope, CloseID: m.closeID, }) d.Footer(func() { if ui.Button(c, "Cancel").Outline().Clicked() { @@ -69,7 +69,7 @@ if open { {ID: "confirm", Title: "确认操作", Description: "初始打开的确认弹窗;Tab 限于弹窗,关闭后可重新打开。", Snippet: `if open { d := ui.Dialog(c, ui.DialogSpec{ Title: "Discard changes?", Description: "Unsaved edits will be lost.", - Scope: scope, CloseID: closeID, + Scope: m.scope, CloseID: m.closeID, }) d.Footer(func() { if ui.Button(c, "Cancel").Hit(cancelID, "Cancel").Outline().Clicked() { open = false } @@ -81,7 +81,7 @@ if open { d := ui.Dialog(c, ui.DialogSpec{ Title: "Save changes?", Description: "Confirm to update the local example state.", - Width: 440, Scope: scope, CloseID: closeID, + Width: 440, Scope: m.scope, CloseID: m.closeID, }) d.Footer(func() { if ui.Button(c, "Cancel").Outline().Clicked() { @@ -99,7 +99,7 @@ if open { d := ui.Dialog(c, ui.DialogSpec{ Title: "保存更改?", Description: "确认后更新本地示例状态。", - Width: 440, Scope: scope, CloseID: closeID, + Width: 440, Scope: m.scope, CloseID: m.closeID, }) d.Footer(func() { if ui.Button(c, "Cancel").Outline().Clicked() { @@ -116,7 +116,7 @@ if open { {ID: "destructive", Title: "危险操作", Description: "危险按钮仅改变本地示例结果,不删除任何数据。", Snippet: `if open { d := ui.Dialog(c, ui.DialogSpec{ Title: "Remove draft?", Description: "Demo only; no data is deleted.", - Scope: scope, CloseID: closeID, + Scope: m.scope, CloseID: m.closeID, }) d.Footer(func() { if ui.Button(c, "Cancel").Hit(cancelID, "Cancel").Outline().Clicked() { open = false } @@ -128,7 +128,7 @@ if open { d := ui.Dialog(c, ui.DialogSpec{ Title: "Remove draft?", Description: "Demo only; no data is deleted.", - Width: 440, Scope: scope, CloseID: closeID, + Width: 440, Scope: m.scope, CloseID: m.closeID, }) d.Footer(func() { if ui.Button(c, "Cancel").Outline().Clicked() { @@ -146,7 +146,7 @@ if open { d := ui.Dialog(c, ui.DialogSpec{ Title: "移除草稿?", Description: "仅作演示,不会删除数据。", - Width: 440, Scope: scope, CloseID: closeID, + Width: 440, Scope: m.scope, CloseID: m.closeID, }) d.Footer(func() { if ui.Button(c, "Cancel").Outline().Clicked() { diff --git a/internal/componentdemo/drawer.go b/internal/componentdemo/drawer.go index 4addd2e9..58654dd3 100644 --- a/internal/componentdemo/drawer.go +++ b/internal/componentdemo/drawer.go @@ -50,7 +50,7 @@ drawer.End() if canvas.Clicked(saveID) || canvas.Clicked(closeID) { open = false }`, PageSnippet: `open := true ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ Side: ui.DrawerRight, Size: 300, - Description: "Applies immediately.", + Description: "Same modal contract on the right edge.", }, func() { ui.Text(c, "Native settings.") }, func() { @@ -60,7 +60,7 @@ ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ })`, PageSnippetZh: `open := true ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ Side: ui.DrawerRight, Size: 300, - Description: "Applies immediately.", + Description: "Same modal contract on the right edge.", }, func() { ui.Text(c, "Native settings.") }, func() { @@ -73,7 +73,23 @@ ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ }).WithHandle().Disabled() layout := drawer.Begin("Workspace settings", "Structure remains visible; interaction is off.") drawer.Actions(layout, components.ButtonAction{ID: saveID, Label: "Save changes"}) -drawer.End()`, PageSnippet: ""}, +drawer.End()`, PageSnippet: `open := true +ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ + Side: ui.DrawerBottom, Disabled: true, + Description: "Structure remains visible; interaction is off.", +}, func() { + ui.Text(c, "Native settings.") +}, func() { + ui.Button(c, "Save changes").Disabled(true) +})`, PageSnippetZh: `open := true +ui.Drawer(c, &open, "工作区设置", ui.DrawerSpec{ + Side: ui.DrawerBottom, Disabled: true, + Description: "结构保持可见,交互已关闭。", +}, func() { + ui.Text(c, "原生设置。") +}, func() { + ui.Button(c, "保存更改").Disabled(true) +})`}, }, } diff --git a/internal/componentdemo/empty.go b/internal/componentdemo/empty.go index f6d6cf0f..453a17bb 100644 --- a/internal/componentdemo/empty.go +++ b/internal/componentdemo/empty.go @@ -19,12 +19,12 @@ var emptyComponent = Component{ content := components.Empty(canvas, theme, bounds, data) components.BeginButton(canvas, theme, tree.ID(page, "create"), gfx.Rect{Height: content.Height}). SizeToFit("Create project").CenterIn(content).Default("Create project")`, PageSnippet: `ui.Column(c).Fill().Center().Gap(6).Children(func() { - ui.Icon(c, folderIcon).Size(40, 40).Color(theme.MutedForeground) + ui.Icon(c, m.folderIcon).Size(40, 40).Muted() ui.Text(c, "No projects yet").FontSize(18).Bold() ui.Text(c, "Create a project to get started.").FontSize(13).Muted() ui.Button(c, "Create project").Self(ui.Start) })`, PageSnippetZh: `ui.Column(c).Fill().Center().Gap(6).Children(func() { - ui.Icon(c, folderIcon).Size(40, 40).Color(theme.MutedForeground) + ui.Icon(c, m.folderIcon).Size(40, 40).Muted() ui.Text(c, "No projects yet").FontSize(18).Bold() ui.Text(c, "Create a project to get started.").FontSize(13).Muted() ui.Button(c, "Create project").Self(ui.Start) @@ -37,15 +37,15 @@ components.BeginButton(canvas, theme, tree.ID(page, "create"), gfx.Rect{Height: content := components.Empty(canvas, theme, bounds, data) components.BeginButton(canvas, theme, tree.ID(page, "create"), gfx.Rect{Height: content.Height}). SizeToFit("Create project").CenterIn(content).Default("Create project")`, PageSnippet: `ui.Column(c).Fill().Center().Gap(6).Children(func() { - ui.Column(c).Size(56, 56).Center().Radius(28).Background(theme.Muted).Children(func() { - ui.Icon(c, folderIcon).Size(24, 24).Color(theme.MutedForeground) + ui.Column(c).Size(56, 56).Center().Radius(28).Background(c.Theme().Muted).Children(func() { + ui.Icon(c, m.folderIcon).Size(24, 24).Muted() }) ui.Text(c, "No projects yet").FontSize(18).Bold() ui.Text(c, "Create a project to get started.").FontSize(13).Muted() ui.Button(c, "Create project").Self(ui.Start) })`, PageSnippetZh: `ui.Column(c).Fill().Center().Gap(6).Children(func() { - ui.Column(c).Size(56, 56).Center().Radius(28).Background(theme.Muted).Children(func() { - ui.Icon(c, folderIcon).Size(24, 24).Color(theme.MutedForeground) + ui.Column(c).Size(56, 56).Center().Radius(28).Background(c.Theme().Muted).Children(func() { + ui.Icon(c, m.folderIcon).Size(24, 24).Muted() }) ui.Text(c, "No projects yet").FontSize(18).Bold() ui.Text(c, "Create a project to get started.").FontSize(13).Muted() diff --git a/internal/componentdemo/field.go b/internal/componentdemo/field.go index 60f9170f..a8e9175d 100644 --- a/internal/componentdemo/field.go +++ b/internal/componentdemo/field.go @@ -35,6 +35,14 @@ field := components.BeginField(canvas, theme, bounds).For(email). control := field.Paint("Work email", "Used only for release notifications.", "") components.PaintInput(canvas, theme, control, components.InputSnapshot{ ID: email, Label: "Work email", Value: value, +})`, PageSnippet: `m.field.Description = "Used only for release notifications." +// m.email starts as "team@viva.dev". +ui.FormField(c, &m.field, "Work email").Children(func() { + ui.TextField(c, &m.email, "Work email", "") +})`, PageSnippetZh: `m.field.Description = "Used only for release notifications." +// m.email starts as "team@viva.dev". +ui.FormField(c, &m.field, "Work email").Children(func() { + ui.TextField(c, &m.email, "Work email", "") })`}, {ID: "invalid", Title: "错误状态", Description: "必填、无效元数据与无效输入保持一致。", Snippet: `email := tree.ID(page, "email") invalid := !strings.Contains(value, "@") diff --git a/internal/componentdemo/form.go b/internal/componentdemo/form.go index cff39de0..d6ea36a1 100644 --- a/internal/componentdemo/form.go +++ b/internal/componentdemo/form.go @@ -45,6 +45,14 @@ field := components.PaintFormField(canvas, theme, bounds, components.FormFieldSn components.PaintInput(canvas, theme, field.Control, components.InputSnapshot{ ID: username, Label: field.Semantics.Label, Value: value, Hint: field.Semantics.AssistiveText(), +})`, PageSnippet: `m.field.Description = "This name is visible to collaborators." +// m.username starts as "gopher". +ui.FormField(c, &m.field, "Username").Children(func() { + ui.TextField(c, &m.username, "Username", "") +})`, PageSnippetZh: `m.field.Description = "This name is visible to collaborators." +// m.username starts as "gopher". +ui.FormField(c, &m.field, "Username").Children(func() { + ui.TextField(c, &m.username, "Username", "") })`}, {ID: "invalid", Title: "验证错误", Description: "错误覆盖普通消息并同步到控件语义。", Snippet: `username := tree.ID(page, "username") snapshot := components.FormFieldSnapshot{ diff --git a/internal/componentdemo/hover_card.go b/internal/componentdemo/hover_card.go index a6b41e21..28364ff7 100644 --- a/internal/componentdemo/hover_card.go +++ b/internal/componentdemo/hover_card.go @@ -1,36 +1,91 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/hovercardview" ) var hoverCardComponent = Component{ - ID: "hover-card", Title: "Hover Card", Category: "Overlays", Summary: "无计时器的同步锚点预览卡。", + ID: "hover-card", Title: "Hover Card", Category: "Overlays", Summary: "带延迟、可进入内容的页面锚点悬停预览卡。", paint: (*State).paintHoverCard, pointer: (*State).pointerHoverCard, Examples: []Example{ - {ID: "default", Title: "个人资料", Description: "生产 HoverCard 根据锚点和视口放置预览。", Snippet: `trigger := ui.Button(c, "@viva-framework").Outline().Width(180).Hit(anchorID, "@viva-framework") -if canvas.Hovered() == anchorID { - card := components.BeginHoverCard(canvas, theme, viewport, trigger.Rect(), components.HoverCardOptions{ - Layer: 1, Side: components.HoverCardBottom, BodyHeight: 24, - }) - layout := card.Begin("Viva Framework", "Go-first, GPU-native desktop UI.") - canvas.Label("Native • Retained", layout.Body, labelStyle) - card.End() -}`}, - {ID: "sides", Title: "侧边放置", Description: "右侧放置在窄视口会自动限制到边缘。", Snippet: `trigger := ui.Button(c, "@viva-framework").Outline().Width(180).Hit(anchorID, "@viva-framework") -card := components.BeginHoverCard(canvas, theme, viewport, trigger.Rect(), components.HoverCardOptions{ - Layer: 1, Side: components.HoverCardRight, Align: components.HoverCardAlignCenter, - ContentSize: gfx.Size{Width: min(280, size.Width-32)}, BodyHeight: 24, -}) -layout := card.Begin("Viva Framework", "Placed right and clamped to the viewport.") -canvas.Label("@viva-framework", layout.Body, labelStyle) -card.End()`}, - {ID: "disabled", Title: "禁用触发器", Description: "禁用声明不绘制预览表面。", Snippet: `trigger := ui.Button(c, "@viva-framework").Outline().Width(180).Hit(anchorID, "@viva-framework") -card := components.BeginHoverCard(canvas, theme, viewport, trigger.Rect(), - components.HoverCardOptions{Layer: 1, Side: components.HoverCardBottom}).Disabled() -card.Paint("Viva Framework", "A disabled trigger shows no preview.")`}, + {ID: "default", Title: "个人资料", Description: "页面 HoverCard 使用锚点几何,在指针停留后打开,并允许指针进入卡片。", Snippet: `anchor := ui.Button(c, "@viva-framework").Outline().Width(180) +hovercardview.View(c, "@viva-framework", &hovercardview.HoverCard{ + Anchor: anchor, + Title: "Viva Framework", + Description: "Go-first, GPU-native desktop UI.", + Body: func() { + ui.Text(c, "Native • Retained • Allocation-aware").Muted() + }, +})`, PageSnippet: `anchor := ui.Button(c, "@viva-framework").Outline().Width(180) +hovercardview.View(c, "@viva-framework", &hovercardview.HoverCard{ + Anchor: anchor, + Title: "Viva Framework", + Description: "Go-first, GPU-native desktop UI.", + Body: func() { + ui.Text(c, "Native • Retained • Allocation-aware").Muted() + }, + Open: &m.hoverOpen, +})`, PageSnippetZh: `anchor := ui.Button(c, "@viva-framework").Outline().Width(180) +hovercardview.View(c, "@viva-framework", &hovercardview.HoverCard{ + Anchor: anchor, + Title: "Viva Framework", + Description: "Go 优先、GPU 原生的桌面 UI。", + Body: func() { + ui.Text(c, "原生 • 保留式 • 关注分配").Muted() + }, + Open: &m.hoverOpen, +})`}, + {ID: "sides", Title: "侧边放置", Description: "右侧放置并在窄视口内由页面弹层收进边缘。", Snippet: `anchor := ui.Button(c, "@viva-framework").Outline().Width(180) +card := &hovercardview.HoverCard{ + Anchor: anchor, + Title: "Viva Framework", + Description: "Placed right and clamped to the viewport.", + Body: func() { + ui.Text(c, "@viva-framework").Muted() + }, +} +card.Side(hovercardview.Right).Align(hovercardview.Center) +hovercardview.View(c, "@viva-framework", card)`, PageSnippet: `anchor := ui.Button(c, "@viva-framework").Outline().Width(180) +card := &hovercardview.HoverCard{ + Anchor: anchor, + Title: "Viva Framework", + Description: "Placed right and clamped to the viewport.", + Body: func() { + ui.Text(c, "@viva-framework").Muted() + }, + Open: &m.hoverOpen, +} +card.Side(hovercardview.Right).Align(hovercardview.Center) +hovercardview.View(c, "@viva-framework", card)`, PageSnippetZh: `anchor := ui.Button(c, "@viva-framework").Outline().Width(180) +card := &hovercardview.HoverCard{ + Anchor: anchor, + Title: "Viva Framework", + Description: "放在右侧,并在视口边缘内收。", + Body: func() { + ui.Text(c, "@viva-framework").Muted() + }, + Open: &m.hoverOpen, +} +card.Side(hovercardview.Right).Align(hovercardview.Center) +hovercardview.View(c, "@viva-framework", card)`}, + {ID: "disabled", Title: "禁用触发器", Description: "禁用声明不打开预览卡。", Snippet: `anchor := ui.Button(c, "@viva-framework").Outline().Width(180) +hovercardview.View(c, "@viva-framework", (&hovercardview.HoverCard{ + Anchor: anchor, + Title: "Viva Framework", + Description: "A disabled trigger shows no preview.", +}).Disabled())`, PageSnippet: `anchor := ui.Button(c, "@viva-framework").Outline().Width(180) +hovercardview.View(c, "@viva-framework", (&hovercardview.HoverCard{ + Anchor: anchor, + Title: "Viva Framework", + Description: "A disabled trigger shows no preview.", +}).Disabled())`, PageSnippetZh: `anchor := ui.Button(c, "@viva-framework").Outline().Width(180) +hovercardview.View(c, "@viva-framework", (&hovercardview.HoverCard{ + Anchor: anchor, + Title: "Viva Framework", + Description: "禁用的触发器不显示预览。", +}).Disabled())`}, }, } @@ -39,6 +94,8 @@ var ( hoverCardAnchor = tree.ID(hoverCardUI, "anchor") ) +// pointerHoverCard keeps the example's typed pointer state for the demo's +// event tests. The card's hover timing is owned by hovercardview.View. func (state *State) pointerHoverCard(event gfx.PointerEvent) gfx.EventResult { if event.Kind != gfx.PointerMove && event.Kind != gfx.PointerExit { return gfx.EventResult{} @@ -53,29 +110,39 @@ func (state *State) pointerHoverCard(event gfx.PointerEvent) gfx.EventResult { return gfx.EventResult{Handled: open || wasOpen, Repaint: open != wasOpen} } +// hoverCardDemo is the demo's page-owned declaration: one card and one stable +// body function, so a warm paint reuses them instead of allocating a closure +// and a card every frame. +type hoverCardDemo struct { + card hovercardview.HoverCard + body func() + bodyC ui.C + bodyText string +} + +func (demo *hoverCardDemo) paintBody() { + ui.Text(demo.bodyC, demo.bodyText).Muted() +} + func (state *State) paintHoverCard(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var trigger ui.Box state.drawPage(canvas, theme, size, 760, state.Text("Hover Card · 悬停预览", "Hover Card · Hover preview"), func(c ui.C) { - trigger = ui.Button(c, "@viva-framework").Outline().Width(180).Self(ui.Start).Hit(hoverCardAnchor, "@viva-framework") + anchor := ui.Button(c, "@viva-framework").Outline().Width(180).Self(ui.Start).Hit(hoverCardAnchor, "@viva-framework") + demo := ui.State[hoverCardDemo](c, "hover-card-demo") + if demo.body == nil { + demo.body = demo.paintBody + demo.card.Body = demo.body + } + demo.bodyC = c + demo.bodyText = state.Text("原生 • 保留式 • 关注分配", "Native • Retained • Allocation-aware") + demo.card.Anchor = anchor + demo.card.Title = state.Text("Viva Framework", "Viva Framework") + demo.card.Description = state.Text("Go 优先、GPU 原生的桌面 UI。", "Go-first, GPU-native desktop UI.") + demo.card.Width(min(float32(280), size.Width-32)) + demo.card.Side(hovercardview.Bottom).Align(hovercardview.Center) + demo.card.Disabled(state.exampleID == "disabled") + if state.exampleID == "sides" { + demo.card.Side(hovercardview.Right) + } + hovercardview.View(c, "@viva-framework", &demo.card) }) - anchor := trigger.Rect() - viewport := gfx.Rect{Width: size.Width, Height: size.Height} - side := components.HoverCardBottom - align := components.HoverCardAlignStart - if state.exampleID == "sides" { - side = components.HoverCardRight - align = components.HoverCardAlignCenter - } - card := components.BeginHoverCard(canvas, theme, viewport, anchor, components.HoverCardOptions{Layer: 1, Side: side, Align: align, ContentSize: gfx.Size{Width: min(float32(280), size.Width-32)}, BodyHeight: 24}) - if state.exampleID == "disabled" { - card = card.Disabled() - } - if state.flags&1 == 0 && canvas.Hovered() != hoverCardAnchor { - return - } - layout := card.Begin("Viva Framework", "Go-first, GPU-native desktop UI.") - if layout.Body.Width > 0 { - canvas.Label("Native • Retained • Allocation-aware", layout.Body, gfx.TextStyle{Size: theme.Metrics.FontSizeS, Color: theme.MutedForeground}) - } - card.End() } diff --git a/internal/componentdemo/icon_hover.go b/internal/componentdemo/icon_hover.go index 7e57f81d..019c61c2 100644 --- a/internal/componentdemo/icon_hover.go +++ b/internal/componentdemo/icon_hover.go @@ -13,7 +13,21 @@ var iconHoverComponent = Component{ Examples: []Example{ {ID: "default", Title: "悬停手势", Description: "指针在图标上停留后上浮再归位;离开不会中断已经开始的播放。", Snippet: `icon := tree.ID(page, "icon") ui.Icon(c, menuIcon).Size(24, 24).Hit(icon, "Menu"). - BindIconHover(ui.BindIconHover(&hover, icon))`, Height: 200}, + BindIconHover(ui.BindIconHover(&hover, icon))`, Height: 200, PageSnippet: `icon := ui.ID(c) +ui.Row(c).Gap(12).Items(ui.Center).Children(func() { + ui.Icon(c, m.moreIcon).Size(24, 24). + Hit(icon, "More actions"). + BindIconHover(ui.BindIconHover(&m.iconHover, icon). + Dwell(130 * time.Millisecond).Span(180 * time.Millisecond)) + ui.Text(c, "Hover → lift → settle") +})`, PageSnippetZh: `icon := ui.ID(c) +ui.Row(c).Gap(12).Items(ui.Center).Children(func() { + ui.Icon(c, m.moreIcon).Size(24, 24). + Hit(icon, "更多操作"). + BindIconHover(ui.BindIconHover(&m.iconHover, icon). + Dwell(130 * time.Millisecond).Span(180 * time.Millisecond)) + ui.Text(c, "悬停 → 上浮 → 归位") +})`}, }, } diff --git a/internal/componentdemo/image_view.go b/internal/componentdemo/image_view.go index 83cfe774..58ab959a 100644 --- a/internal/componentdemo/image_view.go +++ b/internal/componentdemo/image_view.go @@ -29,7 +29,7 @@ var imageViewComponent = Component{ components.PaintImageView(canvas, theme, gfx.Rect{X: 24, Y: 24, Width: max(0, size.Width-48), Height: max(0, size.Height-48)}, components.ImageViewOptions{Bitmap: *state.imageBitmap, Zoom: zoom}) }, Examples: []Example{ - {ID: "fit", Title: "适配视口", Description: "应用提供已解码且有界的像素,组件只负责绘制。", Height: 260, Snippet: `components.PaintImageView(canvas, theme, bounds, components.ImageViewOptions{Bitmap: bitmap})`}, - {ID: "actual", Title: "一个图像像素对应一个设备像素", Description: "Zoom 1 在分数 DPI 缩放下保持实际像素尺寸。", Height: 260, Snippet: `components.PaintImageView(canvas, theme, bounds, components.ImageViewOptions{Bitmap: bitmap, Zoom: 1})`}, + {ID: "fit", Title: "适配视口", Description: "应用提供已解码且有界的像素,组件只负责绘制。", Height: 260, Snippet: `components.PaintImageView(canvas, theme, bounds, components.ImageViewOptions{Bitmap: bitmap})`, PageSnippet: `ui.Image(c, m.bitmap).Fill()`, PageSnippetZh: `ui.Image(c, m.bitmap).Fill()`}, + {ID: "actual", Title: "一个图像像素对应一个设备像素", Description: "Zoom 1 在分数 DPI 缩放下保持实际像素尺寸。", Height: 260, Snippet: `components.PaintImageView(canvas, theme, bounds, components.ImageViewOptions{Bitmap: bitmap, Zoom: 1})`, PageSnippet: `ui.Image(c, m.bitmap).Size(float32(m.bitmap.Width), float32(m.bitmap.Height))`, PageSnippetZh: `ui.Image(c, m.bitmap).Size(float32(m.bitmap.Width), float32(m.bitmap.Height))`}, }, } diff --git a/internal/componentdemo/input.go b/internal/componentdemo/input.go index df6ae9c1..9952538b 100644 --- a/internal/componentdemo/input.go +++ b/internal/componentdemo/input.go @@ -38,9 +38,9 @@ components.PaintInput(canvas, theme, field.Rect(), components.InputSnapshot{ Placeholder: "name@example.com", Invalid: invalid, })`, PageSnippet: `// m.email starts as "not-an-email". m.email.Invalid = !strings.Contains(m.email.Text(), "@") -ui.TextField(c, &m.email, "Email", "name@example.com")`, PageSnippetZh: `// m.email starts as "not-an-email". +ui.TextFieldID(c, ui.ID(c), &m.email, "Email", "name@example.com")`, PageSnippetZh: `// m.email 初始为 "not-an-email"。 m.email.Invalid = !strings.Contains(m.email.Text(), "@") -ui.TextField(c, &m.email, "Email", "name@example.com")`}, +ui.TextFieldID(c, ui.ID(c), &m.email, "Email", "name@example.com")`}, {ID: "states", Title: "禁用与只读", Description: "两个固定文本样本均不向平台 provider 暴露 Editor。", Snippet: `disabled := ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) components.PaintInput(canvas, theme, disabled.Rect(), components.InputSnapshot{ ID: disabledID, Label: "Disabled", @@ -50,7 +50,13 @@ readOnly := ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) components.PaintInput(canvas, theme, readOnly.Rect(), components.InputSnapshot{ ID: readOnlyID, Label: "Read-only", Value: "Viva · read-only text", ReadOnly: true, -})`}, +})`, PageSnippet: `// m.disabled starts as "Not editable"; m.readOnly as "Viva · read-only text". +m.disabled.Disabled = true +ui.TextFieldID(c, ui.ID(c), &m.disabled, "Disabled", "") +ui.TextFieldID(c, ui.ID(c), &m.readOnly, "Read-only", "")`, PageSnippetZh: `// m.disabled 初始为 "不可编辑";m.readOnly 初始为 "Viva · 只读文本"。 +m.disabled.Disabled = true +ui.TextFieldID(c, ui.ID(c), &m.disabled, "Disabled", "") +ui.TextFieldID(c, ui.ID(c), &m.readOnly, "Read-only", "")`}, {ID: "custom", Title: "圆角与字号", Description: "单个输入框用 Radius 和 FontSize 拥有自己的圆角与字号,光标、选区随字号缩放,旁边的输入框不受影响。", Snippet: `// A field's theme and text size belong to the call: the others keep theirs. field := ui.Slot(c).FillWidth().Height(40) components.PaintInput(canvas, theme.WithRadius(gfx.RadiusFull), field.Rect(), components.InputSnapshot{ diff --git a/internal/componentdemo/input_group.go b/internal/componentdemo/input_group.go index 7fea597a..71c532c2 100644 --- a/internal/componentdemo/input_group.go +++ b/internal/componentdemo/input_group.go @@ -25,7 +25,11 @@ var inputGroupComponent = Component{ Icon: clearIcon, ButtonSize: components.InputGroupButtonIconXS, Label: "Clear domain", }, -})`}, +})`, PageSnippet: `domain := "viva.dev" +ui.TextField(c, &domain, "Project domain", "project-name"). + Action(m.clearIcon, "Clear domain")`, PageSnippetZh: `domain := "viva.dev" +ui.TextField(c, &domain, "Project domain", "project-name"). + Action(m.clearIcon, "Clear domain")`}, {ID: "addons", Title: "块级附加项", Description: "块级说明、键帽和多行控制槽。", Snippet: `components.PaintInputGroup(canvas, theme, bounds, components.InputGroupSnapshot{ ID: tree.ID(page, "description"), Label: "Release description", Value: value, Multiline: true, @@ -36,7 +40,9 @@ var inputGroupComponent = Component{ BlockEnd: components.InputGroupSlot{ Kind: components.InputGroupSlotKbd, Text: "⌘↵", }, -})`}, +})`, PageSnippet: `description := "Ship the component gallery.\nAdd the keyboard shortcuts." +ui.TextArea(c, &description, "Release description", "").Height(128)`, PageSnippetZh: `description := "Ship the component gallery.\nAdd the keyboard shortcuts." +ui.TextArea(c, &description, "Release description", "").Height(128)`}, {ID: "buttons", Title: "图标按钮与加载", Description: "icon-xs / icon-sm 按钮切换密码可见,以及 Spinner 附加槽。", Snippet: `reveal := tree.ID(page, "reveal") components.PaintInputGroup(canvas, theme, bounds, components.InputGroupSnapshot{ ID: tree.ID(page, "password"), Label: "Password", Value: value, @@ -48,7 +54,21 @@ components.PaintInputGroup(canvas, theme, bounds, components.InputGroupSnapshot{ }) if canvas.Clicked(reveal) { revealed = !revealed -}`}, +}`, PageSnippet: `password := "viva.dev" +ui.TextField(c, &password, "Password", ""). + Secure().Action(m.eyeIcon, "Show password") +search := "viva" +ui.Row(c).Gap(8).Children(func() { + ui.TextField(c, &search, "Search", "").Grow(1) + ui.Spinner(c) +})`, PageSnippetZh: `password := "viva.dev" +ui.TextField(c, &password, "Password", ""). + Secure().Action(m.eyeIcon, "Show password") +search := "viva" +ui.Row(c).Gap(8).Children(func() { + ui.TextField(c, &search, "Search", "").Grow(1) + ui.Spinner(c) +})`}, {ID: "states", Title: "输入状态", Description: "无效与禁用快照保留完整语义。", Snippet: `invalid := components.InputGroupSnapshot{ ID: tree.ID(page, "email"), Label: "Project domain", Value: value, Invalid: true, @@ -65,7 +85,17 @@ locked := components.InputGroupSnapshot{ ID: tree.ID(page, "locked"), Label: "Project domain", Value: "locked", Disabled: true, } -components.PaintInputGroup(canvas, theme, lockedBounds, locked)`}, +components.PaintInputGroup(canvas, theme, lockedBounds, locked)`, PageSnippet: `// m.email starts as "viva.dev". +m.email.Invalid = true +ui.TextFieldID(c, ui.ID(c), &m.email, "Project domain", "") +// m.locked starts as "locked". +m.locked.Disabled = true +ui.TextFieldID(c, ui.ID(c), &m.locked, "Project domain", "")`, PageSnippetZh: `// m.email starts as "viva.dev". +m.email.Invalid = true +ui.TextFieldID(c, ui.ID(c), &m.email, "Project domain", "") +// m.locked starts as "locked". +m.locked.Disabled = true +ui.TextFieldID(c, ui.ID(c), &m.locked, "Project domain", "")`}, }, } diff --git a/internal/componentdemo/input_otp.go b/internal/componentdemo/input_otp.go index 7159fd42..ab911b8c 100644 --- a/internal/componentdemo/input_otp.go +++ b/internal/componentdemo/input_otp.go @@ -20,14 +20,20 @@ var inputOTPComponent = Component{ ID: tree.ID(page, "code"), Label: "Verification code", Value: code, Slots: 6, GroupSize: 3, HasActiveSlot: true, ActiveSlot: min(len(code), 5), ShowCaret: true, -})`}, +})`, PageSnippet: `code := "482" +ui.TextField(c, &code, "Verification code", "000000")`, PageSnippetZh: `code := "482" +ui.TextField(c, &code, "Verification code", "000000")`}, {ID: "states", Title: "验证码状态", Description: "选择、输入法组合与错误状态。", Snippet: `components.PaintInputOTP(canvas, theme, bounds, components.InputOTPSnapshot{ ID: tree.ID(page, "code"), Label: "Verification code", Value: "482901", Slots: 6, GroupSize: 3, Invalid: true, Focused: true, ShowCaret: true, HasSelection: true, SelectionStart: 1, SelectionEnd: 3, HasComposition: true, CompositionStart: 3, CompositionEnd: 5, ActiveSlot: 0, -})`}, +})`, PageSnippet: `// m.code starts as "482901". +m.code.Invalid = true +ui.TextFieldID(c, ui.ID(c), &m.code, "Verification code", "000000")`, PageSnippetZh: `// m.code 初始为 "482901"。 +m.code.Invalid = true +ui.TextFieldID(c, ui.ID(c), &m.code, "Verification code", "000000")`}, }, } diff --git a/internal/componentdemo/item.go b/internal/componentdemo/item.go index 946de069..727a9aab 100644 --- a/internal/componentdemo/item.go +++ b/internal/componentdemo/item.go @@ -21,13 +21,13 @@ layout := components.BeginItem(canvas, theme, id, bounds). canvas.Rounded(layout.Media, 6, theme.Primary) if canvas.Clicked(id) { selected = !selected -}`, PageSnippet: `theme := c.Theme() +}`, PageSnippet: `look := c.Theme() trailing := "Open" if m.selected { trailing = "Selected" } row := ui.Row(c).FillWidth().Pad(12).Gap(12).Items(ui.Center).Hit(ui.ID(c), "Release notes") -ui.Row(c).Size(24, 24).Radius(6).Background(theme.Primary) +ui.Row(c).Size(24, 24).Radius(6).Background(look.Primary) ui.Column(c).Grow(1).Gap(2).Children(func() { ui.Text(c, "Release notes").Bold() ui.Text(c, "Latest runtime changes.").Muted() @@ -35,13 +35,13 @@ ui.Column(c).Grow(1).Gap(2).Children(func() { ui.Text(c, trailing) if row.Clicked() { m.selected = !m.selected -}`, PageSnippetZh: `theme := c.Theme() +}`, PageSnippetZh: `look := c.Theme() trailing := "Open" if m.selected { trailing = "Selected" } row := ui.Row(c).FillWidth().Pad(12).Gap(12).Items(ui.Center).Hit(ui.ID(c), "Release notes") -ui.Row(c).Size(24, 24).Radius(6).Background(theme.Primary) +ui.Row(c).Size(24, 24).Radius(6).Background(look.Primary) ui.Column(c).Grow(1).Gap(2).Children(func() { ui.Text(c, "Release notes").Bold() ui.Text(c, "Latest runtime changes.").Muted() diff --git a/internal/componentdemo/list.go b/internal/componentdemo/list.go index dc73519b..d8e70544 100644 --- a/internal/componentdemo/list.go +++ b/internal/componentdemo/list.go @@ -186,9 +186,31 @@ var listComponent = Component{ m.files.Header = func(i int) bool { return m.files[i].Header } m.files.Selection = &m.chosen m.files.Reorder = m.move -m.files.RowWidth = 640`, PageSnippet: `theme := c.Theme() -m.files.Key = func(i int) int { return m.rows[i].ID } -m.files.Header = func(i int) bool { return m.rows[i].Header } +m.files.RowWidth = 640`, PageSnippet: `type file struct { + ID int + Name, Size, Date string + Header bool +} +files := []file{ + {ID: 1, Name: "Recent", Header: true}, + {ID: 2, Name: "Report.pdf", Size: "2.4 MB", Date: "2026-11-02 14:20"}, + {ID: 3, Name: "Notes.md", Size: "12 KB", Date: "2026-11-02 09:05"}, + {ID: 4, Name: "Budget.xlsx", Size: "88 KB", Date: "2026-11-01 18:44"}, + {ID: 5, Name: "Screenshot.png", Size: "1.1 MB", Date: "2026-11-01 11:30"}, + {ID: 6, Name: "Documents", Header: true}, + {ID: 7, Name: "Contract.pdf", Size: "640 KB", Date: "2026-10-31 16:12"}, + {ID: 8, Name: "Roadmap.md", Size: "8 KB", Date: "2026-10-30 10:02"}, + {ID: 9, Name: "Style guide.pdf", Size: "3.8 MB", Date: "2026-10-29 15:48"}, + {ID: 10, Name: "Meeting notes.md", Size: "24 KB", Date: "2026-10-28 08:19"}, + {ID: 11, Name: "Images", Header: true}, + {ID: 12, Name: "Logo.svg", Size: "36 KB", Date: "2026-10-27 13:07"}, + {ID: 13, Name: "Hero.jpg", Size: "4.2 MB", Date: "2026-10-26 19:26"}, + {ID: 14, Name: "Icon set.zip", Size: "2.9 MB", Date: "2026-10-25 07:41"}, + {ID: 15, Name: "Palette.png", Size: "310 KB", Date: "2026-10-24 12:55"}, +} +theme := c.Theme() +m.files.Key = func(i int) int { return files[i].ID } +m.files.Header = func(i int) bool { return files[i].Header } m.files.Selection = &m.selection m.files.Reorder = m.reorder m.files.RowWidth = 640 @@ -199,8 +221,8 @@ ui.Row(c).Clip().Height(24).Children(func() { ui.Text(c, "Modified").Width(150).TextEnd().Bold() }) }) -ui.List(c, &m.files, len(m.rows), func(row ui.ListRow) { - item := m.rows[row.Index] +ui.List(c, &m.files, len(files), func(row ui.ListRow) { + item := files[row.Index] if item.Header { row.Element.Height(32).PadX(8).Background(theme.Muted) ui.Text(row.C, item.Name).Bold() @@ -213,9 +235,31 @@ ui.List(c, &m.files, len(m.rows), func(row ui.ListRow) { ui.Text(row.C, item.Name).Grow(1).Ellipsis() ui.Text(row.C, item.Size).Width(90).TextEnd().Muted() ui.Text(row.C, item.Date).Width(150).TextEnd().Muted() -}).Label("Files").Grow(1)`, PageSnippetZh: `theme := c.Theme() -m.files.Key = func(i int) int { return m.rows[i].ID } -m.files.Header = func(i int) bool { return m.rows[i].Header } +}).Label("Files").Grow(1)`, PageSnippetZh: `type file struct { + ID int + Name, Size, Date string + Header bool +} +files := []file{ + {ID: 1, Name: "最近", Header: true}, + {ID: 2, Name: "Report.pdf", Size: "2.4 MB", Date: "2026-11-02 14:20"}, + {ID: 3, Name: "Notes.md", Size: "12 KB", Date: "2026-11-02 09:05"}, + {ID: 4, Name: "Budget.xlsx", Size: "88 KB", Date: "2026-11-01 18:44"}, + {ID: 5, Name: "Screenshot.png", Size: "1.1 MB", Date: "2026-11-01 11:30"}, + {ID: 6, Name: "文档", Header: true}, + {ID: 7, Name: "Contract.pdf", Size: "640 KB", Date: "2026-10-31 16:12"}, + {ID: 8, Name: "Roadmap.md", Size: "8 KB", Date: "2026-10-30 10:02"}, + {ID: 9, Name: "Style guide.pdf", Size: "3.8 MB", Date: "2026-10-29 15:48"}, + {ID: 10, Name: "Meeting notes.md", Size: "24 KB", Date: "2026-10-28 08:19"}, + {ID: 11, Name: "图片", Header: true}, + {ID: 12, Name: "Logo.svg", Size: "36 KB", Date: "2026-10-27 13:07"}, + {ID: 13, Name: "Hero.jpg", Size: "4.2 MB", Date: "2026-10-26 19:26"}, + {ID: 14, Name: "Icon set.zip", Size: "2.9 MB", Date: "2026-10-25 07:41"}, + {ID: 15, Name: "Palette.png", Size: "310 KB", Date: "2026-10-24 12:55"}, +} +theme := c.Theme() +m.files.Key = func(i int) int { return files[i].ID } +m.files.Header = func(i int) bool { return files[i].Header } m.files.Selection = &m.selection m.files.Reorder = m.reorder m.files.RowWidth = 640 @@ -226,8 +270,8 @@ ui.Row(c).Clip().Height(24).Children(func() { ui.Text(c, "修改时间").Width(150).TextEnd().Bold() }) }) -ui.List(c, &m.files, len(m.rows), func(row ui.ListRow) { - item := m.rows[row.Index] +ui.List(c, &m.files, len(files), func(row ui.ListRow) { + item := files[row.Index] if item.Header { row.Element.Height(32).PadX(8).Background(theme.Muted) ui.Text(row.C, item.Name).Bold() diff --git a/internal/componentdemo/markdown.go b/internal/componentdemo/markdown.go index c5f41871..6679b56f 100644 --- a/internal/componentdemo/markdown.go +++ b/internal/componentdemo/markdown.go @@ -1,10 +1,9 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/markdown" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/markdownview" ) var markdownComponent = Component{ @@ -16,7 +15,35 @@ doc.Parse(source) view.Layout(canvas, components.MarkdownStyle{Size: theme.Metrics.FontSizeM, LineHeight: 20}, &doc, width) view.Paint(canvas, components.MarkdownPaint{ Look: components.MarkdownLookFor(theme), X: x, Y: y, -})`}, +})`, + PageSnippet: "answer := \"## Restarting nginx\\n\" +\n" + + " \"Check the **config** first with `nginx -t`, then read the [docs](https://nginx.org/en/docs/) or the errors in the log.\\n\" +\n" + + " \"\\n\" +\n" + + " \"1. Check the status\\n\" +\n" + + " \" - run `systemctl status nginx`\\n\" +\n" + + " \" - read the last ~~20~~ 50 lines\\n\" +\n" + + " \"2. Restart it\\n\" +\n" + + " \"\\n\" +\n" + + " \"> Back up the config before you change it.\\n\"\n" + + "m.answerView.Source = answer\n" + + "m.answerView.Style = markdownview.Style{\n" + + " Size: c.Theme().Metrics.FontSizeM, LineHeight: 20,\n" + + "}\n" + + "markdownview.View(c, \"Assistant answer\", &m.answerView).FillWidth().Height(420)", + PageSnippetZh: "answer := \"## 重启 nginx\\n\" +\n" + + " \"先用 `nginx -t` 检查 **配置**,再阅读 [文档](https://nginx.org/en/docs/) 或日志里的错误。\\n\" +\n" + + " \"\\n\" +\n" + + " \"1. 检查状态\\n\" +\n" + + " \" - 运行 `systemctl status nginx`\\n\" +\n" + + " \" - 查看最后 ~~20~~ 50 行\\n\" +\n" + + " \"2. 重启服务\\n\" +\n" + + " \"\\n\" +\n" + + " \"> 修改配置前先备份。\\n\"\n" + + "m.answerView.Source = answer\n" + + "m.answerView.Style = markdownview.Style{\n" + + " Size: c.Theme().Metrics.FontSizeM, LineHeight: 20,\n" + + "}\n" + + "markdownview.View(c, \"助手回答\", &m.answerView).FillWidth().Height(420)"}, {ID: "blocks", Title: "代码块与表格", Description: "代码块按单元格换行并预留按钮位置;表格列宽随内容或可用宽度分配。", Snippet: `view.Layout(canvas, components.MarkdownStyle{Size: theme.Metrics.FontSizeM, CodeInset: 28}, &doc, width) view.Paint(canvas, components.MarkdownPaint{ Look: components.MarkdownLookFor(theme), X: x, Y: y, @@ -27,25 +54,60 @@ for _, code := range view.Codes() { canvas.Rounded(button, 4, theme.Muted) style := gfx.TextStyle{Size: theme.Metrics.FontSizeS, Color: theme.MutedForeground} canvas.LabelCenter("Copy", button, style) -}`}, +}`, + PageSnippet: "blocks := \"```sh\\nsudo systemctl restart nginx\\njournalctl -u nginx --since \\\"10 min ago\\\" | tail -n 50\\n```\\n\" +\n" + + " \"\\n\" +\n" + + " \"| Port | Service | Note |\\n|:--|:-:|--:|\\n| 22 | ssh | remote login |\\n| 443 | https | encrypted web traffic and reverse proxy |\\n\"\n" + + "m.blocksView.Source = blocks\n" + + "m.blocksView.Style = markdownview.Style{\n" + + " Size: c.Theme().Metrics.FontSizeM, CodeInset: 28,\n" + + "}\n" + + "markdownview.View(c, \"Code and table\", &m.blocksView).FillWidth().Height(420)", + PageSnippetZh: "blocks := \"```sh\\nsudo systemctl restart nginx\\njournalctl -u nginx --since \\\"10 min ago\\\" | tail -n 50\\n```\\n\" +\n" + + " \"\\n\" +\n" + + " \"| 端口 | 服务 | 说明 |\\n|:--|:-:|--:|\\n| 22 | ssh | 远程登录 |\\n| 443 | https | 加密网络流量与反向代理 |\\n\"\n" + + "m.blocksView.Source = blocks\n" + + "m.blocksView.Style = markdownview.Style{\n" + + " Size: c.Theme().Metrics.FontSizeM, CodeInset: 28,\n" + + "}\n" + + "markdownview.View(c, \"代码与表格\", &m.blocksView).FillWidth().Height(420)"}, {ID: "unclosed", Title: "尚未写完", Description: "流式到达的文字中,未闭合的标记与围栏保持原样。", Snippet: `// A partial stream still lays out; unclosed markers stay literal. doc.Parse(chunk) view.Layout(canvas, components.MarkdownStyle{Size: theme.Metrics.FontSizeM}, &doc, width) view.Paint(canvas, components.MarkdownPaint{ Look: components.MarkdownLookFor(theme), X: x, Y: y, -})`}, +})`, + PageSnippet: "partial := \"A **bold phrase that is still arriving, and `a code span\\n\" +\n" + + " \"```go\\nfmt.Println(\\\"the fence is not closed yet\"\n" + + "m.partialView.Source = partial\n" + + "m.partialView.Style = markdownview.Style{Size: c.Theme().Metrics.FontSizeM}\n" + + "markdownview.View(c, \"Incoming answer\", &m.partialView).FillWidth().Height(420)", + PageSnippetZh: "partial := \"一个仍在到达的**粗体短语,以及 `一段行内代码\\n\" +\n" + + " \"```go\\nfmt.Println(\\\"围栏还没有闭合\"\n" + + "m.partialView.Source = partial\n" + + "m.partialView.Style = markdownview.Style{Size: c.Theme().Metrics.FontSizeM}\n" + + "markdownview.View(c, \"正在到达的回答\", &m.partialView).FillWidth().Height(420)"}, }, } // markdownScratch is what the example keeps between paints. type markdownScratch struct { - doc markdown.Document - view components.MarkdownView + view markdownview.Markdown } -// markdownAnswer is the assistant's reply; only the sentence about the log -// differs between the Chinese preview and the English one. -const markdownAnswerRest = "\n" + +const markdownAnswerZh = "## 重启 nginx\n" + + "先用 `nginx -t` 检查 **配置**,再阅读 [文档](https://nginx.org/en/docs/) 或日志里的错误。\n" + + "\n" + + "1. 检查状态\n" + + " - 运行 `systemctl status nginx`\n" + + " - 查看最后 ~~20~~ 50 行\n" + + "2. 重启服务\n" + + "\n" + + "> 修改配置前先备份。\n" + +const markdownAnswerEnglish = "## Restarting nginx\n" + + "Check the **config** first with `nginx -t`, then read the [docs](https://nginx.org/en/docs/) or the errors in the log.\n" + + "\n" + "1. Check the status\n" + " - run `systemctl status nginx`\n" + " - read the last ~~20~~ 50 lines\n" + @@ -53,38 +115,33 @@ const markdownAnswerRest = "\n" + "\n" + "> Back up the config before you change it.\n" -const markdownAnswer = "## Restarting nginx\n" + - "Check the **config** first with `nginx -t`, then read the [docs](https://nginx.org/en/docs/) or the 日志 里的错误。\n" + - markdownAnswerRest - -const markdownAnswerEnglish = "## Restarting nginx\n" + - "Check the **config** first with `nginx -t`, then read the [docs](https://nginx.org/en/docs/) or the errors in the log.\n" + - markdownAnswerRest +const markdownBlocksZh = "```sh\nsudo systemctl restart nginx\njournalctl -u nginx --since \"10 min ago\" | tail -n 50\n```\n" + + "\n" + + "| 端口 | 服务 | 说明 |\n|:--|:-:|--:|\n| 22 | ssh | 远程登录 |\n| 443 | https | 加密网络流量与反向代理 |\n" -const markdownBlocks = "```sh\nsudo systemctl restart nginx\njournalctl -u nginx --since \"10 min ago\" | tail -n 50\n```\n" + +const markdownBlocksEnglish = "```sh\nsudo systemctl restart nginx\njournalctl -u nginx --since \"10 min ago\" | tail -n 50\n```\n" + "\n" + "| Port | Service | Note |\n|:--|:-:|--:|\n| 22 | ssh | remote login |\n| 443 | https | encrypted web traffic and reverse proxy |\n" -const markdownUnclosed = "A **bold phrase that is still arriving, and `a code span\n" + +const markdownUnclosedZh = "一个仍在到达的**粗体短语,以及 `一段行内代码\n" + + "```go\nfmt.Println(\"围栏还没有闭合" + +const markdownUnclosedEnglish = "A **bold phrase that is still arriving, and `a code span\n" + "```go\nfmt.Println(\"the fence is not closed yet" func (state *State) paintMarkdown(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var stage ui.Box - state.drawPage(canvas, theme, size, 560, state.Text("Markdown · 排版", "Markdown · Typesetting"), func(c ui.C) { - // The document paints itself into the rest of the stage; its height follows its text. - stage = ui.Slot(c).FillWidth().Height(max(size.Height-100, 120)) - }) - source := state.Text(markdownAnswer, markdownAnswerEnglish) + source := state.Text(markdownAnswerZh, markdownAnswerEnglish) switch state.exampleID { case "blocks": - source = markdownBlocks + source = state.Text(markdownBlocksZh, markdownBlocksEnglish) case "unclosed": - source = markdownUnclosed + source = state.Text(markdownUnclosedZh, markdownUnclosedEnglish) } - bounds := stage.Rect() - doc := &state.markdown.doc - doc.Parse(source) view := &state.markdown.view - view.Layout(canvas, components.MarkdownStyle{Size: theme.Metrics.FontSizeM, LineHeight: 20, CodeInset: 28}, doc, bounds.Width) - view.Paint(canvas, components.MarkdownPaint{Look: components.MarkdownLookFor(theme), X: bounds.X, Y: bounds.Y, Clip: gfx.Rect{Y: 0, Width: size.Width, Height: size.Height}}) + view.Source = source + view.Style = markdownview.Style{Size: theme.Metrics.FontSizeM, LineHeight: 20, CodeInset: 28} + label := state.Text("Markdown 文档", "Markdown document") + state.drawPage(canvas, theme, size, 560, state.Text("Markdown · 排版", "Markdown · Typesetting"), func(c ui.C) { + markdownview.View(c, label, view).FillWidth().Height(max(size.Height-100, 120)) + }) } diff --git a/internal/componentdemo/marker.go b/internal/componentdemo/marker.go index d0511b8e..2654595b 100644 --- a/internal/componentdemo/marker.go +++ b/internal/componentdemo/marker.go @@ -10,19 +10,61 @@ var markerComponent = Component{ ID: "marker", Title: "Marker", Category: "Display", Summary: "用于分组和时间线的轻量元数据标记。", paint: (*State).paintMarker, Examples: []Example{ - {ID: "default", Title: "元数据", Description: "图标与文本组成的标准标记。", Snippet: `// clockIcon is a caller-owned gfx.Icon; a nil icon paints none. + {ID: "default", Title: "元数据", Description: "图标与文本组成的标准标记。", Snippet: `// m.clockIcon is a caller-owned gfx.Icon; a nil icon paints none. components.Marker(canvas, theme, bounds, components.MarkerDefault, - &clockIcon, "Updated 2 minutes ago")`}, + &m.clockIcon, "Updated 2 minutes ago")`, PageSnippet: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { + ui.Icon(c, m.clockIcon).Size(16, 16).Muted() + ui.Text(c, "Updated 2 minutes ago").Muted() +})`, PageSnippetZh: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { + ui.Icon(c, m.clockIcon).Size(16, 16).Muted() + ui.Text(c, "Updated 2 minutes ago").Muted() +})`}, {ID: "variants", Title: "三种形式", Description: "普通、居中分隔和底部边框形式。", Snippet: `// The separator centers its content between rules; the border draws one below. components.Marker(canvas, theme, bounds[0], components.MarkerDefault, - &checkIcon, "Default") + &m.checkIcon, "Default") components.Marker(canvas, theme, bounds[1], components.MarkerSeparator, nil, "October 2026") components.Marker(canvas, theme, bounds[2], components.MarkerBorder, - &clockIcon, "Release channel")`}, + &m.clockIcon, "Release channel")`, PageSnippet: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { + ui.Icon(c, m.checkIcon).Size(16, 16).Muted() + ui.Text(c, "Default").Muted() +}) +ui.Row(c).Gap(10).Items(ui.Center).Children(func() { + ui.Column(c).Grow(1).Height(1).Background(c.Theme().Border) + ui.Text(c, "October 2026").Muted() + ui.Column(c).Grow(1).Height(1).Background(c.Theme().Border) +}) +ui.Column(c).Gap(6).Children(func() { + ui.Row(c).Gap(6).Items(ui.Center).Children(func() { + ui.Icon(c, m.clockIcon).Size(16, 16).Muted() + ui.Text(c, "Release channel").Muted() + }) + ui.Divider(c) +})`, PageSnippetZh: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { + ui.Icon(c, m.checkIcon).Size(16, 16).Muted() + ui.Text(c, "Default").Muted() +}) +ui.Row(c).Gap(10).Items(ui.Center).Children(func() { + ui.Column(c).Grow(1).Height(1).Background(c.Theme().Border) + ui.Text(c, "October 2026").Muted() + ui.Column(c).Grow(1).Height(1).Background(c.Theme().Border) +}) +ui.Column(c).Gap(6).Children(func() { + ui.Row(c).Gap(6).Items(ui.Center).Children(func() { + ui.Icon(c, m.clockIcon).Size(16, 16).Muted() + ui.Text(c, "Release channel").Muted() + }) + ui.Divider(c) +})`}, {ID: "progress", Title: "进行中", Description: "用 Spinner 代替图标表示正在进行的工作。", Snippet: `// Advance the phase from an animation frame and request the next paint. phase = (phase + 1) % 8 -components.MarkerProgress(canvas, theme, bounds, components.MarkerDefault, phase, "Thinking")`}, +components.MarkerProgress(canvas, theme, bounds, components.MarkerDefault, phase, "Thinking")`, PageSnippet: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { + ui.Spinner(c) + ui.Text(c, "Thinking").Muted() +})`, PageSnippetZh: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { + ui.Spinner(c) + ui.Text(c, "Thinking").Muted() +})`}, }, } diff --git a/internal/componentdemo/menubar.go b/internal/componentdemo/menubar.go index b3d311d1..92f0bb1e 100644 --- a/internal/componentdemo/menubar.go +++ b/internal/componentdemo/menubar.go @@ -1,9 +1,9 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/menubarview" ) var menubarComponent = Component{ @@ -22,7 +22,41 @@ if open { } if canvas.Clicked(file) { open = !open -}`}, +}`, + PageSnippet: `// m.menubar.Selected holds the row chosen during the last paint. +file, view, help := ui.ID(c), ui.ID(c), ui.ID(c) +newWindow, showGrid, deleteItem, reload := ui.ID(c), ui.ID(c), ui.ID(c), ui.ID(c) +bar := &m.menubar +if bar.Selected == showGrid { + m.grid = !m.grid + bar.Selected = gfx.ID{} +} +bar.Reset() +bar.Trigger(file, "File"). + Item(newWindow, "New window").Shortcut("⌘N"). + Item(showGrid, "Show grid").Checkbox(m.grid). + Separator(). + Item(deleteItem, "Delete workspace").Destructive() +bar.Trigger(view, "View").Item(reload, "Reload") +bar.Trigger(help, "Help") +menubarview.View(c, "Menubar", bar).FillWidth().Height(c.Theme().Metrics.ControlHeight)`, + PageSnippetZh: `// m.menubar.Selected 保存上一次绘制中选中的行。 +file, view, help := ui.ID(c), ui.ID(c), ui.ID(c) +newWindow, showGrid, deleteItem, reload := ui.ID(c), ui.ID(c), ui.ID(c), ui.ID(c) +bar := &m.menubar +if bar.Selected == showGrid { + m.grid = !m.grid + bar.Selected = gfx.ID{} +} +bar.Reset() +bar.Trigger(file, "File"). + Item(newWindow, "New window").Shortcut("⌘N"). + Item(showGrid, "Show grid").Checkbox(m.grid). + Separator(). + Item(deleteItem, "Delete workspace").Destructive() +bar.Trigger(view, "View").Item(reload, "Reload") +bar.Trigger(help, "Help") +menubarview.View(c, "Menubar", bar).FillWidth().Height(c.Theme().Metrics.ControlHeight)`}, {ID: "states", Title: "菜单项状态", Description: "复选、禁用和危险菜单项。", Snippet: `options := components.MenubarOverlayOptions{ Layer: 2, DismissID: tree.ID(page, "file"), } @@ -36,7 +70,41 @@ content.AddItem(components.MenubarItem{ ID: tree.ID(page, "delete"), Label: "Delete workspace", Variant: components.MenubarItemDestructive, Disabled: true, }) -content.End()`}, +content.End()`, + PageSnippet: `file, view, help := ui.ID(c), ui.ID(c), ui.ID(c) +newWindow, showGrid, deleteItem, reload := ui.ID(c), ui.ID(c), ui.ID(c), ui.ID(c) +bar := &m.menubar +if bar.Selected == showGrid { + m.grid = !m.grid + bar.Selected = gfx.ID{} +} +bar.Reset() +bar.Open = file +bar.Trigger(file, "File"). + Item(newWindow, "New window").Shortcut("⌘N"). + Item(showGrid, "Show grid").Checkbox(m.grid). + Separator(). + Item(deleteItem, "Delete workspace").Destructive().Disabled() +bar.Trigger(view, "View").Item(reload, "Reload") +bar.Trigger(help, "Help").Disabled() +menubarview.View(c, "Menubar", bar).FillWidth().Height(c.Theme().Metrics.ControlHeight)`, + PageSnippetZh: `file, view, help := ui.ID(c), ui.ID(c), ui.ID(c) +newWindow, showGrid, deleteItem, reload := ui.ID(c), ui.ID(c), ui.ID(c), ui.ID(c) +bar := &m.menubar +if bar.Selected == showGrid { + m.grid = !m.grid + bar.Selected = gfx.ID{} +} +bar.Reset() +bar.Open = file +bar.Trigger(file, "File"). + Item(newWindow, "New window").Shortcut("⌘N"). + Item(showGrid, "Show grid").Checkbox(m.grid). + Separator(). + Item(deleteItem, "Delete workspace").Destructive().Disabled() +bar.Trigger(view, "View").Item(reload, "Reload") +bar.Trigger(help, "Help").Disabled() +menubarview.View(c, "Menubar", bar).FillWidth().Height(c.Theme().Metrics.ControlHeight)`}, }, } @@ -47,39 +115,63 @@ var ( menubarHelp = tree.ID(menubarUI, "help") menubarGrid = tree.ID(menubarUI, "grid") menubarFocus = tree.ID(menubarUI, "focus") + menubarDrop = tree.ID(menubarUI, "dismiss") // menubarItem's item i is the i-th plain item of the menu. menubarItem = tree.Sub(menubarUI, tree.Name("item")) + + // menubarDemo is the preview's page control. The preview has one menubar. + menubarDemo menubarview.Menubar + menubarDemoState *State ) func (state *State) paintMenubar(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - open := state.flags&1 != 0 || state.exampleID == "states" - var strip ui.Box + bar := &menubarDemo + if menubarDemoState != state { + menubarDemoState = state + bar.Open, bar.Selected = gfx.ID{}, gfx.ID{} + } + open := state.flags&3 != 0 || state.exampleID == "states" + bar.Scope = menubarFocus + bar.DismissID = menubarDrop + bar.Layer = 2 + if state.exampleID == "states" { + bar.Open = menubarFile + } + bar.Reset() + bar.Trigger(menubarFile, "File"). + Item(menubarItem.At(0), "New window").Shortcut("⌘N"). + Item(menubarGrid, "Show grid").Checkbox(state.flags&4 != 0). + Separator(). + Item(menubarItem.At(1), "Delete workspace").Destructive() + if state.exampleID == "states" { + bar.Disabled() + } + bar.Trigger(menubarView, "View").Item(menubarItem.At(2), "Reload") + bar.Trigger(menubarHelp, "Help") + if state.exampleID == "states" { + bar.Disabled() + } + state.drawPage(canvas, theme, size, 560, state.Text("Menubar · 桌面菜单", "Menubar · Desktop menu"), func(c ui.C) { - strip = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) if !open { ui.Text(c, state.Text("点击 File 查看弹出菜单。", "Click File to open the popup menu.")).FontSize(theme.Metrics.FontSizeS).Muted() } + menubarview.View(c, "Menubar", bar).FillWidth().Height(theme.Metrics.ControlHeight) }) - bounds := strip.Rect() - bar := components.BeginMenubar(canvas, theme, bounds) - bar.AddTrigger(components.MenubarTrigger{ID: menubarFile, Label: "File", Open: open}) - bar.AddTrigger(components.MenubarTrigger{ID: menubarView, Label: "View"}) - bar.AddTrigger(components.MenubarTrigger{ID: menubarHelp, Label: "Help", Disabled: state.exampleID == "states"}) - if open { - // Three 32px rows, a separator, and the surface's 4px top and bottom padding. - popup := gfx.Rect{X: bounds.X, Y: bounds.Y + bounds.Height + 8, Width: min(bounds.Width, float32(260)), Height: 3*32 + 9 + 2*4} - content := components.BeginMenubarContent(canvas, theme, popup, components.MenubarOverlayOptions{Layer: 2, Scope: menubarFocus, DismissID: menubarFile}) - content.AddItem(components.MenubarItem{ID: menubarItem.At(0), Label: "New window", Shortcut: "⌘N"}) - content.AddItem(components.MenubarItem{ID: menubarGrid, Label: "Show grid", Kind: components.MenubarCheckbox, Checked: state.flags&2 != 0}) - content.AddSeparator() - content.AddItem(components.MenubarItem{ID: menubarItem.At(1), Label: "Delete workspace", Variant: components.MenubarItemDestructive, Disabled: state.exampleID == "states"}) - content.End() - } - // File opens and closes the menu; so does a press outside it (its DismissID). - if canvas.Clicked(menubarFile) { - state.flags ^= 1 + + // Mirror the control's caller-owned state into the demo's flags, which the + // tests and the caption read. + state.flags &^= 3 + switch bar.Open { + case menubarFile: + state.flags |= 1 + case menubarView: + state.flags |= 2 } - if canvas.Clicked(menubarGrid) { - state.flags ^= 2 + if selected := bar.Selected; !selected.IsZero() { + if selected == menubarGrid { + state.flags ^= 4 + } + bar.Selected = gfx.ID{} } } diff --git a/internal/componentdemo/message.go b/internal/componentdemo/message.go index a84addfe..5b7f0e4d 100644 --- a/internal/componentdemo/message.go +++ b/internal/componentdemo/message.go @@ -1,75 +1,151 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/messageview" ) var messageComponent = Component{ ID: "message", Title: "Message", Category: "Communication", Summary: "带头像、元数据与可组合正文槽的消息行。", - paint: (*State).paintMessage, + paint: (*State).paintMessage, initialize: (*State).initializeMessage, Examples: []Example{ - {ID: "default", Title: "收到的消息", Description: "生产 Message 负责头像和元数据,调用方填充正文槽。", Snippet: `regions := components.Message(canvas, theme, bounds, components.MessageData{ - Header: "Ari · Design", Footer: "09:42", Initials: "AR", ShowAvatar: true, -}) -components.Bubble(canvas, theme, regions.Content, - components.BubbleStart, components.BubbleSecondary, "Native preview ready.")`}, - {ID: "alignment", Title: "双向消息", Description: "起始与结束方向并列展示,结束方向的页眉页脚靠右。", Snippet: `ari := components.Message(canvas, theme, first, components.MessageData{ - Header: "Ari · Design", Footer: "09:42", Initials: "AR", ShowAvatar: true, -}) -components.Bubble(canvas, theme, ari.Content, components.BubbleStart, - components.BubbleSecondary, "Native preview ready.") -you := components.Message(canvas, theme, second, components.MessageData{ - Header: "You", Footer: "Delivered", Initials: "YO", - Alignment: components.MessageEnd, ShowAvatar: true, -}) -components.Bubble(canvas, theme, you.Content, components.BubbleEnd, - components.BubbleDefault, "Ship the compact variant.")`}, - {ID: "group", Title: "连续消息", Description: "同一发送者的连续消息只在最后一条显示头像,其余预留头像位。", Snippet: `group := components.BeginMessageGroup(theme, bounds) -first := components.Message(canvas, theme, group.Row(44), - components.MessageData{ReserveAvatar: true}) -components.Bubble(canvas, theme, first.Content, - components.BubbleStart, components.BubbleSecondary, "Native preview is ready.") -last := components.Message(canvas, theme, group.Row(64), - components.MessageData{Initials: "AR", ShowAvatar: true, Footer: "09:42"}) -components.Bubble(canvas, theme, last.Content, - components.BubbleStart, components.BubbleSecondary, "Ship it when the gate is green.")`}, + {ID: "default", Title: "收到的消息", Description: "页面视图组合头像、名称、时间、正文与操作,正文使用 ui.Bubble。", Snippet: `messageview.View(c, "Ari", messageview.New(). + Name("Ari · Design").Time("09:42").Avatar("AR"). + Body("Native preview ready."). + Actions(func(c ui.C) { + if ui.Button(c, "Copy").Ghost().Small().Clicked() { + state.copied = true + } + }))`, PageSnippet: `messageview.View(c, "Ari", messageview.New(). + Name("Ari · Design").Time("09:42").Avatar("AR"). + Body("Native preview ready."). + Actions(func(c ui.C) { + label := "Copy" + if m.copied { + label = "Copied" + } + if ui.Button(c, label).Ghost().Small().Clicked() { + m.copied = true + } + }))`, PageSnippetZh: `messageview.View(c, "Ari", messageview.New(). + Name("Ari · 设计").Time("09:42").Avatar("AR"). + Body("原生预览已就绪。"). + Actions(func(c ui.C) { + label := "复制" + if m.copied { + label = "已复制" + } + if ui.Button(c, label).Ghost().Small().Clicked() { + m.copied = true + } + }))`}, + {ID: "alignment", Title: "双向消息", Description: "Start 与 End 互为镜像:结束方向的头像在末尾,气泡与元数据靠右。", Snippet: `messageview.View(c, "Ari", messageview.New(). + Name("Ari · Design").Time("09:42").Avatar("AR"). + Body("Native preview ready.")) +messageview.View(c, "You", messageview.New().End(). + Name("You").Time("Delivered").Avatar("YO"). + Surface(ui.BubblePrimary).Body("Ship the compact variant."))`, PageSnippet: `messageview.View(c, "Ari", messageview.New(). + Name("Ari · Design").Time("09:42").Avatar("AR"). + Body("Native preview ready.")) +messageview.View(c, "You", messageview.New().End(). + Name("You").Time("Delivered").Avatar("YO"). + Surface(ui.BubblePrimary).Body("Ship the compact variant."))`, PageSnippetZh: `messageview.View(c, "Ari", messageview.New(). + Name("Ari · 设计").Time("09:42").Avatar("AR"). + Body("原生预览已就绪。")) +messageview.View(c, "我", messageview.New().End(). + Name("我").Time("已送达").Avatar("YO"). + Surface(ui.BubblePrimary).Body("发布紧凑变体。"))`}, + {ID: "group", Title: "连续消息", Description: "同一发送者的连续行只预留头像位,最后一行显示头像与时间。", Snippet: `messageview.Group(c, "Ari", + messageview.New().ReserveAvatar(). + Body("Native preview is ready."), + messageview.New().ReserveAvatar(). + Body("I checked the narrow window too."), + messageview.New().Avatar("AR").Time("09:42"). + Body("Ship it when the gate is green."), +)`, PageSnippet: `messageview.Group(c, "Ari", + messageview.New().ReserveAvatar(). + Body("Native preview is ready."), + messageview.New().ReserveAvatar(). + Body("I checked the narrow window too."), + messageview.New().Avatar("AR").Time("09:42"). + Body("Ship it when the gate is green."), +)`, PageSnippetZh: `messageview.Group(c, "Ari", + messageview.New().ReserveAvatar(). + Body("原生预览已就绪。"), + messageview.New().ReserveAvatar(). + Body("我也检查了窄窗口。"), + messageview.New().Avatar("AR").Time("09:42"). + Body("门禁通过后就发布。"), +)`}, }, } func (state *State) paintMessage(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var rows [3]ui.Box + demo := messageDemoFor(state) state.drawPage(canvas, theme, size, 600, state.Text("Message · 对话组合", "Message · Conversation"), func(c ui.C) { switch state.exampleID { - case "group": - // The rows of one group are stacked by BeginMessageGroup below. - rows[0] = ui.Slot(c).FillWidth().Height(210) case "alignment": - rows[0] = ui.Slot(c).FillWidth().Height(118) - rows[1] = ui.Slot(c).FillWidth().Height(118) + messageview.View(c, state.Text("收到的消息", "Incoming message"), messageview.New(). + Name(state.Text("Ari · 设计", "Ari · Design")). + Time("09:42").Avatar("AR"). + Body(state.Text("原生预览已就绪。", "Native preview ready."))).FillWidth() + messageview.View(c, state.Text("发送的消息", "Outgoing message"), messageview.New().End(). + Name(state.Text("我", "You")). + Time(state.Text("已送达", "Delivered")).Avatar("YO"). + Surface(ui.BubblePrimary). + Body(state.Text("发布紧凑变体。", "Ship the compact variant."))).FillWidth() + case "group": + messageview.Group(c, state.Text("连续消息", "Consecutive messages"), + messageview.New().ReserveAvatar(). + Body(state.Text("原生预览已就绪。", "Native preview is ready.")), + messageview.New().ReserveAvatar(). + Body(state.Text("我也检查了窄窗口。", "I checked the narrow window too.")), + messageview.New().Avatar("AR").Time("09:42"). + Body(state.Text("门禁通过后就发布。", "Ship it when the gate is green.")), + ).FillWidth() default: - rows[0] = ui.Slot(c).FillWidth().Height(118) + messageview.View(c, state.Text("消息", "Message"), messageview.New(). + Name(state.Text("Ari · 设计", "Ari · Design")). + Time("09:42").Avatar("AR"). + Body(state.Text("原生预览已就绪。", "Native preview ready.")). + Actions(demo.action)).FillWidth() } }) - paint := func(bounds gfx.Rect, data components.MessageData, variant components.BubbleVariant, body string) { - regions := components.Message(canvas, theme, bounds, data) - alignment := components.BubbleStart - if data.Alignment == components.MessageEnd { - alignment = components.BubbleEnd - } - components.Bubble(canvas, theme, regions.Content, alignment, variant, body) +} + +// messageDemo is the mutable state and stable callback of the message example. +// It is kept beside the State rather than rebuilt in each paint. +type messageDemo struct { + state *State + action func(ui.C) +} + +// messageDemos is keyed by State because the constrained demo model has no +// field for this example; a State is painted on one thread at a time. +var messageDemos = map[*State]*messageDemo{} + +func (state *State) initializeMessage() { + messageDemoFor(state) +} + +func messageDemoFor(state *State) *messageDemo { + if demo := messageDemos[state]; demo != nil { + return demo + } + demo := &messageDemo{state: state} + demo.action = demo.actions + messageDemos[state] = demo + return demo +} + +// actions declares the copy control; the click changes the caller-owned state. +func (d *messageDemo) actions(c ui.C) { + label := d.state.Text("复制", "Copy") + if d.state.values[0] != 0 { + label = d.state.Text("已复制", "Copied") } - switch state.exampleID { - case "group": - group := components.BeginMessageGroup(theme, rows[0].Rect()) - paint(group.Row(44), components.MessageData{ReserveAvatar: true}, components.BubbleSecondary, "Native preview is ready.") - paint(group.Row(44), components.MessageData{ReserveAvatar: true}, components.BubbleSecondary, "I checked the narrow window too.") - paint(group.Row(64), components.MessageData{Initials: "AR", ShowAvatar: true, Footer: "09:42"}, components.BubbleSecondary, "Ship it when the gate is green.") - case "alignment": - paint(rows[0].Rect(), components.MessageData{Header: "Ari · Design", Footer: "09:42", Initials: "AR", ShowAvatar: true}, components.BubbleSecondary, "Native preview ready.") - paint(rows[1].Rect(), components.MessageData{Header: "You", Footer: "Delivered", Initials: "YO", Alignment: components.MessageEnd, ShowAvatar: true}, components.BubbleDefault, "Ship the compact variant.") - default: - paint(rows[0].Rect(), components.MessageData{Header: "Ari · Design", Footer: "09:42", Initials: "AR", ShowAvatar: true}, components.BubbleSecondary, "Native preview ready.") + if ui.Button(c, label).Ghost().Small().Clicked() { + d.state.values[0] = 1 } } diff --git a/internal/componentdemo/message_scroller.go b/internal/componentdemo/message_scroller.go index 1383f3bf..3d1472c9 100644 --- a/internal/componentdemo/message_scroller.go +++ b/internal/componentdemo/message_scroller.go @@ -1,63 +1,131 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/messagescrollerview" ) var messageScrollerComponent = Component{ ID: "message-scroller", Title: "Message Scroller", Category: "Communication", Summary: "外部控制偏移的消息视口、滚动条与跳转按钮。", - paint: (*State).paintMessageScroller, + paint: (*State).paintMessageScroller, + initialize: (*State).initializeMessageScroller, + scroll: (*State).scrollMessageScroller, Examples: []Example{ - {ID: "default", Title: "消息流", Description: "点击上下按钮改变调用方持有的滚动偏移。", Snippet: `earlier, later := tree.ID(page, "earlier"), tree.ID(page, "later") -scroller := components.BeginMessageScroller(canvas, theme, viewport, 380, offset) -scroller = scroller.Buttons(earlier, "Earlier messages", later, "Later messages") -scroller.BeginContent() -for index := range 5 { - item := scroller.ItemGeometry(index, float32(index)*74, 62) - if item.Visible { canvas.Fill(item.Bounds, theme.Muted) } -} -scroller.EndContent() -if canvas.Clicked(earlier) { offset = max(0, offset-72) } -if canvas.Clicked(later) { offset = min(144, offset+72) }`, PageSnippet: `ui.Control(c, "Messages", &m.messages).FillWidth().Height(238).Draw(m.paintMessages) -if ui.Button(c, "Earlier messages").Clicked() { - m.offset = max(0, m.offset-72) -} -if ui.Button(c, "Later messages").Clicked() { - m.offset = min(144, m.offset+72) -}`, PageSnippetZh: `ui.Control(c, "Messages", &m.messages).FillWidth().Height(238).Draw(m.paintMessages) -if ui.Button(c, "Earlier messages").Clicked() { - m.offset = max(0, m.offset-72) -} -if ui.Button(c, "Later messages").Clicked() { - m.offset = min(144, m.offset+72) -}`}, - {ID: "end", Title: "接近末尾", Description: "展示偏移、滑块和可用方向变化。", Snippet: `bar := tree.ID(page, "scrollbar") -earlier, later := tree.ID(page, "earlier"), tree.ID(page, "later") -scroller := components.BeginMessageScroller(canvas, theme, viewport, 380, offset) -scroller = scroller.Scrollbar(bar, "Message position", "Conversation") -scroller = scroller.Buttons(earlier, "Earlier messages", later, "Later messages") -geometry := scroller.BeginContent() -item := scroller.ItemGeometry(4, 296, 62) -if item.Visible { canvas.Fill(item.Bounds, theme.Muted) } -scroller.EndContent() -if geometry.CanStart && canvas.Clicked(earlier) { offset = max(0, offset-72) } -if geometry.CanEnd && canvas.Clicked(later) { offset = min(144, offset+72) }`, PageSnippet: `// m.offset starts at 132, near the end of its 144 range. -ui.Control(c, "Messages", &m.messages).FillWidth().Height(238).Draw(m.paintMessages) -if ui.Button(c, "Earlier messages").Clicked() { - m.offset = max(0, m.offset-72) -} -if ui.Button(c, "Later messages").Clicked() { - m.offset = min(144, m.offset+72) -}`, PageSnippetZh: `// m.offset starts at 132, near the end of its 144 range. -ui.Control(c, "Messages", &m.messages).FillWidth().Height(238).Draw(m.paintMessages) -if ui.Button(c, "Earlier messages").Clicked() { - m.offset = max(0, m.offset-72) -} -if ui.Button(c, "Later messages").Clicked() { - m.offset = min(144, m.offset+72) -}`}, + {ID: "default", Title: "消息流", Description: "点击较早/较晚按钮或滚动滚轮,视图把新偏移交给调用方。", Snippet: `stream := &messagescrollerview.Scroller{ + Offset: m.offset, + EarlierLabel: "Earlier messages", LaterLabel: "Later messages", + Content: func(c ui.C) { + for _, label := range [...]string{ + "Project started", "Build complete", "Review requested", + "Changes approved", "Release ready", + } { + ui.Row(c).Height(62).PadX(12).Items(ui.Center). + Radius(c.Theme().Metrics.RadiusSurface). + Background(c.Theme().Muted).Children(func() { + ui.Text(c, label).FontSize(c.Theme().Metrics.FontSizeM) + }) + } + }, +} +stream.OnScroll = func(offset float32) { m.offset = offset } +stream.OnJump = func(direction messagescrollerview.Direction, end float32) { + if direction == messagescrollerview.Earlier { + m.offset = max(float32(0), m.offset-72) + } else { + m.offset = min(end, m.offset+72) + } +} +messagescrollerview.View(c, "Message stream", stream).FillWidth().Height(278)`, PageSnippet: `stream := &m.scroller +stream.Offset = m.offset +stream.EarlierLabel = "Earlier messages" +stream.LaterLabel = "Later messages" +stream.Content = func(c ui.C) { + ui.Column(c).Gap(12).Children(func() { + for _, label := range [...]string{ + "Project started", "Build complete", "Review requested", + "Changes approved", "Release ready", + } { + ui.Row(c).Height(62).PadX(12).Items(ui.Center). + Radius(c.Theme().Metrics.RadiusSurface). + Background(c.Theme().Muted).Children(func() { + ui.Text(c, label).FontSize(c.Theme().Metrics.FontSizeM) + }) + } + }) +} +stream.OnScroll = func(offset float32) { m.offset = offset } +stream.OnJump = func(direction messagescrollerview.Direction, end float32) { + if direction == messagescrollerview.Earlier { + m.offset = max(float32(0), m.offset-72) + } else { + m.offset = min(end, m.offset+72) + } +} +messagescrollerview.View(c, "Message stream", stream).FillWidth().Height(278)`, PageSnippetZh: `stream := &m.scroller +stream.Offset = m.offset +stream.EarlierLabel = "更早的消息" +stream.LaterLabel = "更晚的消息" +stream.Content = func(c ui.C) { + ui.Column(c).Gap(12).Children(func() { + for _, label := range [...]string{ + "项目已启动", "构建完成", "请求审查", "更改已批准", "准备发布", + } { + ui.Row(c).Height(62).PadX(12).Items(ui.Center). + Radius(c.Theme().Metrics.RadiusSurface). + Background(c.Theme().Muted).Children(func() { + ui.Text(c, label).FontSize(c.Theme().Metrics.FontSizeM) + }) + } + }) +} +stream.OnScroll = func(offset float32) { m.offset = offset } +stream.OnJump = func(direction messagescrollerview.Direction, end float32) { + if direction == messagescrollerview.Earlier { + m.offset = max(float32(0), m.offset-72) + } else { + m.offset = min(end, m.offset+72) + } +} +messagescrollerview.View(c, "消息流", stream).FillWidth().Height(278)`}, + {ID: "end", Title: "接近末尾", Description: "初始偏移为 72;较早/较晚按钮都可用,每次把调用方持有的偏移移动 72 像素。", Snippet: `stream := &messagescrollerview.Scroller{ + Offset: 72, // near the end of the content + EarlierLabel: "Earlier messages", LaterLabel: "Later messages", + Content: func(c ui.C) { /* the same five rows */ }, +} +stream.OnScroll = func(offset float32) { m.offset = offset } +stream.OnJump = func(direction messagescrollerview.Direction, end float32) { + if direction == messagescrollerview.Earlier { + m.offset = max(float32(0), m.offset-72) + } else { + m.offset = min(end, m.offset+72) + } +} +messagescrollerview.View(c, "Message stream", stream).FillWidth().Height(278)`, PageSnippet: `stream := &m.scroller +stream.Offset = 72 // near the end of the content +stream.EarlierLabel = "Earlier messages" +stream.LaterLabel = "Later messages" +stream.OnScroll = func(offset float32) { m.offset = offset } +stream.OnJump = func(direction messagescrollerview.Direction, end float32) { + if direction == messagescrollerview.Earlier { + m.offset = max(float32(0), m.offset-72) + } else { + m.offset = min(end, m.offset+72) + } +} +messagescrollerview.View(c, "Message stream", stream).FillWidth().Height(278)`, PageSnippetZh: `stream := &m.scroller +stream.Offset = 72 // 接近内容末尾 +stream.EarlierLabel = "更早的消息" +stream.LaterLabel = "更晚的消息" +stream.OnScroll = func(offset float32) { m.offset = offset } +stream.OnJump = func(direction messagescrollerview.Direction, end float32) { + if direction == messagescrollerview.Earlier { + m.offset = max(float32(0), m.offset-72) + } else { + m.offset = min(end, m.offset+72) + } +} +messagescrollerview.View(c, "消息流", stream).FillWidth().Height(278)`}, }, } @@ -68,30 +136,98 @@ var ( messageScrollerEnd = tree.ID(messageScrollerUI, "later") ) +// messageScrollerDemo is one stream example's page control. Its callbacks are +// made once and point at this value, so it is kept beside the State rather than +// rebuilt in each paint. +type messageScrollerDemo struct { + state *State + view messagescrollerview.Scroller +} + +// messageScrollerDemos is keyed by State because the constrained demo model has +// no field for this example; a State is painted on one thread at a time. +var messageScrollerDemos = map[*State]*messageScrollerDemo{} + +func (state *State) initializeMessageScroller() { + messageScrollerDemoFor(state) + if state.exampleID == "end" { + // Open near the end of the five rows; the earlier control is available and + // the later one steps the rest of the way. + state.values[0] = 72 + } +} + +func messageScrollerDemoFor(state *State) *messageScrollerDemo { + if demo := messageScrollerDemos[state]; demo != nil { + return demo + } + demo := &messageScrollerDemo{state: state} + demo.view.Content = demo.content + demo.view.OnScroll = demo.scroll + demo.view.OnJump = demo.jump + messageScrollerDemos[state] = demo + return demo +} + func (state *State) paintMessageScroller(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var viewport ui.Box + demo := messageScrollerDemoFor(state) + demo.view.Offset = float32(state.values[0]) + demo.view.EarlierLabel = state.Text("更早的消息", "Earlier messages") + demo.view.LaterLabel = state.Text("更晚的消息", "Later messages") + demo.view.EarlierID = messageScrollerStart + demo.view.LaterID = messageScrollerEnd + demo.view.ScrollbarID = messageScrollerBar + demo.view.ScrollbarLabel = state.Text("消息位置", "Message position") + demo.view.ScrollbarValue = state.Text("会话", "Conversation") state.drawPage(canvas, theme, size, 560, state.Text("Message Scroller · 受控偏移", "Message Scroller · Controlled offset"), func(c ui.C) { - viewport = ui.Slot(c).FillWidth().Height(min(238, max(size.Height-84, 120))) + messagescrollerview.View(c, state.Text("消息流", "Message stream"), &demo.view). + FillWidth().Height(min(278, max(size.Height-84, 180))) }) - offset := float32(state.values[0]) - if state.exampleID == "end" && state.values[0] == 0 { - offset = 132 +} + +// content paints the caller-owned rows inside the scroll area. +func (d *messageScrollerDemo) content(c ui.C) { + look := c.Theme() + labels := [...]string{ + d.state.Text("项目已启动", "Project started"), + d.state.Text("构建完成", "Build complete"), + d.state.Text("请求审查", "Review requested"), + d.state.Text("更改已批准", "Changes approved"), + d.state.Text("准备发布", "Release ready"), } - scroller := components.BeginMessageScroller(canvas, theme, viewport.Rect(), 380, offset).Scrollbar(messageScrollerBar, "Message position", "Conversation").Buttons(messageScrollerStart, "Earlier messages", messageScrollerEnd, "Later messages") - geometry := scroller.BeginContent() - for index := range 5 { - item := scroller.ItemGeometry(index, float32(index)*74, 62) - if !item.Visible || item.Bounds.Y < geometry.Viewport.Y || item.Bounds.Y+item.Bounds.Height > geometry.Viewport.Y+geometry.Viewport.Height { - continue + ui.Column(c).Gap(look.Metrics.GapItem).Children(func() { + for _, label := range labels { + ui.Row(c).Height(62).PadX(12).Items(ui.Center). + Radius(look.Metrics.RadiusSurface).Background(look.Muted).Children(func() { + ui.Text(c, label).FontSize(look.Metrics.FontSizeM) + }) } - canvas.Rounded(item.Bounds, theme.Metrics.RadiusSurface, theme.Muted) - canvas.Label([...]string{"Project started", "Build complete", "Review requested", "Changes approved", "Release ready"}[index], gfx.Rect{X: item.Bounds.X + 12, Y: item.Bounds.Y, Width: max(0, item.Bounds.Width-24), Height: item.Bounds.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.Foreground}) - } - scroller.EndContent() - if canvas.Clicked(messageScrollerStart) { - state.values[0] = max(0, state.values[0]-72) + }) +} + +// scroll stores the offset the reader moved to. +func (d *messageScrollerDemo) scroll(offset float32) { + d.state.values[0] = int32(offset + 0.5) +} + +// jump steps toward the end an earlier/later control asked for; the view hands +// it the target offset, which caps a later step at the end of the content. +func (d *messageScrollerDemo) jump(direction messagescrollerview.Direction, target float32) { + offset := d.state.values[0] + switch direction { + case messagescrollerview.Earlier: + offset = max(0, offset-72) + case messagescrollerview.Later: + offset = min(int32(target), offset+72) } - if canvas.Clicked(messageScrollerEnd) { - state.values[0] = min(144, state.values[0]+72) + d.state.values[0] = offset +} + +// scrollMessageScroller routes the wheel over the stream to its ScrollState. +func (state *State) scrollMessageScroller(event gfx.ScrollEvent) gfx.EventResult { + demo := messageScrollerDemoFor(state) + if !demo.view.Contains(event.X, event.Y) { + return gfx.EventResult{} } + return demo.view.Wheel(event) } diff --git a/internal/componentdemo/metric_card.go b/internal/componentdemo/metric_card.go index 26feecfb..d7624b0f 100644 --- a/internal/componentdemo/metric_card.go +++ b/internal/componentdemo/metric_card.go @@ -12,11 +12,71 @@ var metricCardComponent = Component{ Examples: []Example{ {ID: "default", Title: "单项指标", Description: "生产 MetricCard 展示当前值与正向趋势。", Snippet: `// bounds is the dashboard slot reserved for the card. components.MetricCard(canvas, theme, bounds, "Active sessions", - "12,840", "+18.2% from last week", true)`}, + "12,840", "+18.2% from last week", true)`, PageSnippet: `ui.Column(c).FillWidth().Pad(c.Theme().Metrics.PadSurface).Gap(6). + Background(c.Theme().Card).Border(1, c.Theme().Border). + Radius(c.Theme().Metrics.RadiusSurface).Children(func() { + ui.Text(c, "Active sessions"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() + ui.Text(c, "12,840"). + FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) + ui.Text(c, "+18.2% from last week"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Success) +})`, PageSnippetZh: `ui.Column(c).FillWidth().Pad(c.Theme().Metrics.PadSurface).Gap(6). + Background(c.Theme().Card).Border(1, c.Theme().Border). + Radius(c.Theme().Metrics.RadiusSurface).Children(func() { + ui.Text(c, "Active sessions"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() + ui.Text(c, "12,840"). + FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) + ui.Text(c, "+18.2% from last week"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Success) +})`}, {ID: "trends", Title: "趋势对比", Description: "正向和负向趋势并列展示。", Snippet: `// left and right are equal-width slots in the page's row. // true paints the trend in Success; false paints it in Danger. components.MetricCard(canvas, theme, left, "Revenue", "$48.2K", "+12.4%", true) -components.MetricCard(canvas, theme, right, "Refunds", "$1.3K", "+4.1%", false)`}, +components.MetricCard(canvas, theme, right, "Refunds", "$1.3K", "+4.1%", false)`, PageSnippet: `ui.Row(c).FillWidth().Gap(16).Children(func() { + ui.Column(c).Grow(1).Pad(c.Theme().Metrics.PadSurface).Gap(6). + Background(c.Theme().Card).Border(1, c.Theme().Border). + Radius(c.Theme().Metrics.RadiusSurface).Children(func() { + ui.Text(c, "Revenue"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() + ui.Text(c, "$48.2K"). + FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) + ui.Text(c, "+12.4%"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Success) + }) + ui.Column(c).Grow(1).Pad(c.Theme().Metrics.PadSurface).Gap(6). + Background(c.Theme().Card).Border(1, c.Theme().Border). + Radius(c.Theme().Metrics.RadiusSurface).Children(func() { + ui.Text(c, "Refunds"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() + ui.Text(c, "$1.3K"). + FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) + ui.Text(c, "+4.1%"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Danger) + }) +})`, PageSnippetZh: `ui.Row(c).FillWidth().Gap(16).Children(func() { + ui.Column(c).Grow(1).Pad(c.Theme().Metrics.PadSurface).Gap(6). + Background(c.Theme().Card).Border(1, c.Theme().Border). + Radius(c.Theme().Metrics.RadiusSurface).Children(func() { + ui.Text(c, "Revenue"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() + ui.Text(c, "$48.2K"). + FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) + ui.Text(c, "+12.4%"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Success) + }) + ui.Column(c).Grow(1).Pad(c.Theme().Metrics.PadSurface).Gap(6). + Background(c.Theme().Card).Border(1, c.Theme().Border). + Radius(c.Theme().Metrics.RadiusSurface).Children(func() { + ui.Text(c, "Refunds"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() + ui.Text(c, "$1.3K"). + FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) + ui.Text(c, "+4.1%"). + FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Danger) + }) +})`}, }, } diff --git a/internal/componentdemo/native_select.go b/internal/componentdemo/native_select.go index bb02bcca..38d495f6 100644 --- a/internal/componentdemo/native_select.go +++ b/internal/componentdemo/native_select.go @@ -33,7 +33,21 @@ components.PaintNativeSelect(canvas, theme, invalidBounds, components.NativeSele components.PaintNativeSelect(canvas, theme, disabledBounds, components.NativeSelectSnapshot{ ID: tree.ID(page, "plan"), Label: "Plan", Value: "enterprise", Display: "Enterprise", Disabled: true, -})`, PageSnippet: ""}, +})`, PageSnippet: `regions := []string{"us-east", "eu-west", "ap-south"} +teams := []string{"No team"} +plans := []string{"Enterprise"} +ui.Select(c, &m.region, regions, nil).Placeholder("Select a region").Small() +ui.FormField(c, &m.teamField, "Team").Children(func() { + ui.Select(c, &m.team, teams, nil).Placeholder("No team") +}) +ui.Select(c, &m.plan, plans, nil).Disabled(true)`, PageSnippetZh: `regions := []string{"us-east", "eu-west", "ap-south"} +teams := []string{"No team"} +plans := []string{"Enterprise"} +ui.Select(c, &m.region, regions, nil).Placeholder("Select a region").Small() +ui.FormField(c, &m.teamField, "Team").Children(func() { + ui.Select(c, &m.team, teams, nil).Placeholder("No team") +}) +ui.Select(c, &m.plan, plans, nil).Disabled(true)`}, }, } diff --git a/internal/componentdemo/navigation_menu.go b/internal/componentdemo/navigation_menu.go index 8aec1171..aa1aab32 100644 --- a/internal/componentdemo/navigation_menu.go +++ b/internal/componentdemo/navigation_menu.go @@ -1,9 +1,9 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/navigationmenuview" ) var navigationMenuComponent = Component{ @@ -23,7 +23,51 @@ content.AddLink(components.NavigationMenuLink{ ID: tree.ID(page, "guide"), Label: "Getting started", Description: "Build a native window and retained scene.", Value: "/guide", }) -if canvas.Clicked(tree.ID(page, "products")) { open = !open }`, Height: 310}, +if canvas.Clicked(tree.ID(page, "products")) { open = !open }`, + PageSnippet: `// m.navigation.Selected holds the link chosen during the last paint. +products, docs, guide, api := ui.ID(c), ui.ID(c), ui.ID(c), ui.ID(c) +nav := m.navigation +switch nav.Selected { +case docs: + m.page = "docs" +case guide: + m.page = "guide" +case api: + m.page = "components" +} +nav.Selected = gfx.ID{} +nav.Reset() +nav.Trigger(products, "Products").Hint("Open product navigation") +nav.Link(docs, "Docs").Value("/docs").Active(m.page == "docs") +nav.ContentLink(guide, "Getting started"). + Description("Build a native window and retained scene."). + Value("/guide").Active(m.page == "guide") +nav.ContentLink(api, "Component API"). + Description("Read the source-owned recipes."). + Value("/components").Active(m.page == "components") +navigationmenuview.View(c, "Navigation menu", nav).FillWidth().Height(36)`, + PageSnippetZh: `// m.navigation.Selected 保存上一次绘制中选中的链接。 +products, docs, guide, api := ui.ID(c), ui.ID(c), ui.ID(c), ui.ID(c) +nav := m.navigation +switch nav.Selected { +case docs: + m.page = "docs" +case guide: + m.page = "guide" +case api: + m.page = "components" +} +nav.Selected = gfx.ID{} +nav.Reset() +nav.Trigger(products, "Products").Hint("Open product navigation") +nav.Link(docs, "Docs").Value("/docs").Active(m.page == "docs") +nav.ContentLink(guide, "Getting started"). + Description("Build a native window and retained scene."). + Value("/guide").Active(m.page == "guide") +nav.ContentLink(api, "Component API"). + Description("Read the source-owned recipes."). + Value("/components").Active(m.page == "components") +navigationmenuview.View(c, "Navigation menu", nav).FillWidth().Height(36)`}, {ID: "direct-content", Title: "直接内容", Description: "以直接内容模式展示无触发器指示的菜单面板。", Snippet: `trigger := tree.ID(page, "products") options := components.NavigationMenuOptions{ Open: true, DirectContent: true, Content: panel, Layer: 2, @@ -37,7 +81,53 @@ content := menu.BeginContent() content.AddLink(components.NavigationMenuLink{ ID: tree.ID(page, "guide"), Label: "Getting started", Description: "Build a native window and retained scene.", Value: "/guide", -})`, Height: 310}, +})`, + PageSnippet: `products, docs, guide, api := ui.ID(c), ui.ID(c), ui.ID(c), ui.ID(c) +nav := m.navigation +switch nav.Selected { +case docs: + m.page = "docs" +case guide: + m.page = "guide" +case api: + m.page = "components" +} +nav.Selected = gfx.ID{} +nav.Reset() +nav.DirectContent = true +nav.Open = products +nav.Trigger(products, "Products").Hint("Open product navigation") +nav.Link(docs, "Docs").Value("/docs").Active(m.page == "docs") +nav.ContentLink(guide, "Getting started"). + Description("Build a native window and retained scene."). + Value("/guide").Active(m.page == "guide") +nav.ContentLink(api, "Component API"). + Description("Read the source-owned recipes."). + Value("/components").Active(m.page == "components") +navigationmenuview.View(c, "Navigation menu", nav).FillWidth().Height(36)`, + PageSnippetZh: `products, docs, guide, api := ui.ID(c), ui.ID(c), ui.ID(c), ui.ID(c) +nav := m.navigation +switch nav.Selected { +case docs: + m.page = "docs" +case guide: + m.page = "guide" +case api: + m.page = "components" +} +nav.Selected = gfx.ID{} +nav.Reset() +nav.DirectContent = true +nav.Open = products +nav.Trigger(products, "Products").Hint("Open product navigation") +nav.Link(docs, "Docs").Value("/docs").Active(m.page == "docs") +nav.ContentLink(guide, "Getting started"). + Description("Build a native window and retained scene."). + Value("/guide").Active(m.page == "guide") +nav.ContentLink(api, "Component API"). + Description("Read the source-owned recipes."). + Value("/components").Active(m.page == "components") +navigationmenuview.View(c, "Navigation menu", nav).FillWidth().Height(36)`}, }, } @@ -49,66 +139,67 @@ var ( navigationMenuAPI = tree.ID(navigationMenuUI, "api") navigationMenuDismiss = tree.ID(navigationMenuUI, "dismiss") navigationMenuScope = tree.ID(navigationMenuUI, "content") + + // navigationMenuDemo is the preview's page control. The preview has one + // navigation menu. + navigationMenuDemo navigationmenuview.NavigationMenu + navigationMenuDemoState *State ) func (state *State) paintNavigationMenu(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - open := state.flags&1 != 0 || state.exampleID == "direct-content" + nav := &navigationMenuDemo + if navigationMenuDemoState != state { + navigationMenuDemoState = state + nav.Open, nav.Selected = gfx.ID{}, gfx.ID{} + nav.DirectContent = false + } + direct := state.exampleID == "direct-content" + nav.DirectContent = direct + if direct { + nav.Open = navigationMenuTrigger + } + open := direct || !nav.Open.IsZero() status := state.Text("Products 已关闭", "Products closed") if open { status = state.Text("Products 已打开;Escape 使用稳定 dismiss ID", "Products open; Escape dismisses through a stable ID") } - var brand, bar ui.Box + + nav.Scope = navigationMenuScope + nav.DismissID = navigationMenuDismiss + nav.Layer = 2 + nav.Content = gfx.Rect{Width: min(float32(420), size.Width-32)} + nav.Reset() + nav.Trigger(navigationMenuTrigger, "Products").Hint(state.Text("打开产品导航", "Open product navigation")) + nav.Link(navigationMenuDocs, "Docs").Value("/docs").Active(state.values[0] == 1) + nav.ContentLink(navigationMenuGuide, "Getting started"). + Description("Build a native window and retained scene."). + Value("/guide").Active(state.values[0] == 2) + nav.ContentLink(navigationMenuAPI, "Component API"). + Description("Read the source-owned recipes."). + Value("/components").Active(state.values[0] == 3) + state.drawPage(canvas, theme, size, 620, "Navigation Menu", func(c ui.C) { caption(c, status) ui.Row(c).Gap(12).Items(ui.Center).Children(func() { - brand = ui.Text(c, "Viva").FontSize(theme.Metrics.FontSizeM + 2).Weight(gfx.WeightSemibold) - bar = ui.Slot(c).Grow(1).Height(theme.Metrics.ControlHeight) + ui.Text(c, "Viva").FontSize(theme.Metrics.FontSizeM + 2).Weight(gfx.WeightSemibold) + navigationmenuview.View(c, "Navigation menu", nav).Grow(1).Height(36) }) }) - // The panel drops from the bar, over the blank part of the page below it. - bounds := bar.Rect() - // The panel hangs from the menu when it fits there, and from the page's edge - // when the stage is too narrow for that. - contentX, contentWidth := bounds.X, float32(420) - if right := bounds.X + bounds.Width; contentX+contentWidth > right { - contentX = brand.Rect().X - contentWidth = min(right-contentX, contentWidth) - } - options := components.NavigationMenuOptions{ - Open: open, DirectContent: state.exampleID == "direct-content", - // Two description rows (56 + 4 gap each) inside the content's 8px padding. - Content: gfx.Rect{X: contentX, Y: bounds.Y + bounds.Height + 8, Width: contentWidth, Height: 8 + 2*(56+4) + 8}, - Layer: 2, Scope: navigationMenuScope, DismissID: navigationMenuDismiss, + // Mirror the control's caller-owned state into the demo's flags and + // values, which the tests and the caption read. + state.flags &^= 1 + if !nav.Open.IsZero() { + state.flags |= 1 } - menu := components.BeginNavigationMenu(canvas, theme, bounds, options) - menu.AddTrigger(components.NavigationMenuTrigger{ - ID: navigationMenuTrigger, Label: "Products", Hint: "Open product navigation", Open: open, - }) - menu.AddLink(components.NavigationMenuLink{ - ID: navigationMenuDocs, Label: "Docs", Value: "/docs", Active: state.values[0] == 1, - }) - - content := menu.BeginContent() - content.AddLink(components.NavigationMenuLink{ - ID: navigationMenuGuide, Label: "Getting started", Description: "Build a native window and retained scene.", Value: "/guide", - Active: state.values[0] == 2, - }) - content.AddLink(components.NavigationMenuLink{ - ID: navigationMenuAPI, Label: "Component API", Description: "Read the source-owned recipes.", Value: "/components", - Active: state.values[0] == 3, - }) - - switch { - case canvas.Clicked(navigationMenuTrigger): - state.flags ^= 1 - case canvas.Clicked(navigationMenuDocs): - state.values[0], state.flags = 1, state.flags&^1 - case canvas.Clicked(navigationMenuGuide): - state.values[0], state.flags = 2, state.flags&^1 - case canvas.Clicked(navigationMenuAPI): - state.values[0], state.flags = 3, state.flags&^1 - case canvas.Clicked(navigationMenuDismiss): - state.flags &^= 1 + state.values[0] = 0 + switch nav.Selected { + case navigationMenuDocs: + state.values[0] = 1 + case navigationMenuGuide: + state.values[0] = 2 + case navigationMenuAPI: + state.values[0] = 3 } + nav.Selected = gfx.ID{} } diff --git a/internal/componentdemo/page_source.go b/internal/componentdemo/page_source.go index 0a627b41..0509075d 100644 --- a/internal/componentdemo/page_source.go +++ b/internal/componentdemo/page_source.go @@ -4,50 +4,91 @@ package componentdemo // documentation site links "Page API source" here when PageUsage exists; a // component without a page API links its own source instead. var pageSource = map[string]string{ - "toggle-group": "base/page_bases.go", - "button": "base/controls.go", - "badge": "base/badge.go", - "checkbox": "base/controls.go", - "switch": "base/controls.go", - "input": "base/field.go", - "textarea": "base/textarea.go", - "select": "base/select.go", - "combobox": "base/combobox.go", - "slider": "base/slider.go", - "tabs": "base/tabs.go", - "dialog": "base/dialog.go", - "alert-dialog": "base/alert_dialog.go", - "drawer": "base/drawer.go", - "sheet": "base/drawer.go", - "popover": "base/popover.go", - "dropdown-menu": "base/menu.go", - "context-menu": "base/menu.go", - "table": "base/table.go", - "list": "base/list.go", - "tree": "base/tree.go", - "tree-navigation": "base/tree_navigation.go", - "color-picker": "base/color.go", - "color-swatch": "base/color.go", - "progress": "base/leaves.go", - "spinner": "base/leaves.go", - "split-button": "base/split_button.go", - "pagination": "base/pagination.go", - "radio-group": "base/controls.go", - "choice": "base/elements.go", - "toggle": "base/controls.go", - "native-select": "base/select.go", - "single-select": "base/select.go", - "scroll-area": "base/scroll.go", - "resizable": "base/splitter.go", - "separator": "base/frame.go", - "typography": "base/frame.go", - "form": "base/form_field.go", - "field": "base/form_field.go", - "multi-select": "multiselect/multiselect.go", - "tooltip": "base/tooltip.go", - "kbd": "base/leaves.go", - "label": "base/elements.go", - "card": "base/box.go", - "item": "base/box.go", - "empty": "base/box.go", + "toggle-group": "base/page_bases.go", + "button": "base/controls.go", + "badge": "base/badge.go", + "checkbox": "base/controls.go", + "switch": "base/controls.go", + "input": "base/field.go", + "textarea": "base/textarea.go", + "select": "base/select.go", + "combobox": "base/combobox.go", + "slider": "base/slider.go", + "tabs": "base/tabs.go", + "dialog": "base/dialog.go", + "alert-dialog": "base/alert_dialog.go", + "drawer": "base/drawer.go", + "sheet": "base/drawer.go", + "popover": "base/popover.go", + "dropdown-menu": "base/menu.go", + "context-menu": "base/menu.go", + "table": "base/table.go", + "list": "base/list.go", + "tree": "base/tree.go", + "tree-navigation": "base/tree_navigation.go", + "color-picker": "base/color.go", + "color-swatch": "base/color.go", + "progress": "base/leaves.go", + "spinner": "base/leaves.go", + "split-button": "base/split_button.go", + "pagination": "base/pagination.go", + "radio-group": "base/controls.go", + "choice": "base/elements.go", + "toggle": "base/controls.go", + "native-select": "base/select.go", + "single-select": "base/select.go", + "scroll-area": "base/scroll.go", + "resizable": "base/splitter.go", + "separator": "base/frame.go", + "typography": "base/frame.go", + "form": "base/form_field.go", + "field": "base/form_field.go", + "multi-select": "ui/multiselect/multiselect.go", + "tooltip": "base/tooltip.go", + "kbd": "base/leaves.go", + "label": "base/elements.go", + "card": "base/box.go", + "item": "base/box.go", + "empty": "base/box.go", + "bubble": "ui/bubble.go", + "accordion": "ui/disclosure.go", + "collapsible": "ui/disclosure.go", + "code-editor": "ui/codeeditor/codeeditor.go", + "code-diff": "ui/codeeditor/diff.go", + "code-merge": "ui/codeeditor/merge.go", + "chart-area": "ui/chartview/chartview.go", + "chart-bar": "ui/chartview/bar.go", + "calendar": "ui/calendarview/calendarview.go", + "carousel": "ui/carouselview/carouselview.go", + "markdown": "ui/markdownview/markdownview.go", + "column-resize": "ui/columnresizeview/columnresizeview.go", + "chart": "ui/chartview/container.go", + "chart-downsample": "ui/chartview/chartview.go", + "toast": "base/toast.go", + "sonner": "base/toast.go", + "hover-card": "ui/hovercardview/hovercardview.go", + "avatar-editor": "ui/avatareditorview/avatareditorview.go", + "reorder-grid": "ui/reordergridview/reordergridview.go", + "alert": "base/box.go", + "aspect-ratio": "base/box.go", + "attachment": "ui/attachmentview/attachmentview.go", + "avatar": "ui/avatarview/avatarview.go", + "breadcrumb": "base/elements.go", + "button-group": "base/controls.go", + "command": "ui/commandview/commandview.go", + "icon-hover": "base/icon_motion.go", + "image-view": "base/elements.go", + "input-group": "base/field.go", + "input-otp": "base/field.go", + "marker": "base/elements.go", + "menubar": "ui/menubarview/menubarview.go", + "message": "ui/messageview/messageview.go", + "message-scroller": "ui/messagescrollerview/messagescrollerview.go", + "metric-card": "base/box.go", + "navigation-menu": "ui/navigationmenuview/navigationmenuview.go", + "questionnaire": "base/radio.go", + "reorder-list": "base/list_reorder.go", + "segmented-control": "base/elements.go", + "sidebar": "base/list.go", + "skeleton": "base/box.go", } diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index 833f92ae..d5dd2f93 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -38,26 +38,66 @@ ui.Table(c, &m.table, ui.TableSpec{ Headers: []string{"项目", "状态", "金额"}, Source: &bills, })`, - "list": `ui.List(c, &m.list, len(rows), func(row ui.ListRow) { _ = row })`, - "tree": `ui.Tree(c, &m.tree, len(rows), func(i int) string { return rows[i] }, func(i int) {})`, - "tree-navigation": `next, action, handled := ui.NavigateTree(items, current, key, pageRows)`, - "color-picker": `ui.ColorPicker(c, &m.picker, &m.color, "Accent")`, - "color-swatch": `ui.ColorSwatch(c, color, selected, "Accent")`, - "progress": `ui.Progress(c, 0.6)`, - "spinner": `ui.Spinner(c)`, - "split-button": `ui.SplitButton(c, ui.SplitButtonSpec{PrimaryID: primary, Label: "Run"})`, - "pagination": `ui.Pagination(c, items)`, - "radio-group": `ui.RadioGroup(c)`, - "choice": `ui.Choice(c, &m.choice, choices, nameOf)`, - "toggle": `ui.Toggle(c, &m.on, "Bold").Outline()`, - "native-select": `ui.Select(c, &m.choice, choices, nameOf)`, - "single-select": `ui.Select(c, &m.choice, choices, nameOf)`, - "scroll-area": `ui.Scroll(c).Grow(1).Scrollbars()`, - "resizable": `ui.Splitter(c, &m.splitter)`, - "separator": `ui.Divider(c)`, - "typography": `ui.Paragraph(c, text, 0)`, - "form": `ui.FormField(c, &m.field, "Name").Children(func() { ui.TextField(c, &m.name, "Name", "") })`, - "field": `ui.FormField(c, &m.field, "Name").Children(func() { ui.TextField(c, &m.name, "Name", "") })`, - "multi-select": `picker := multiselect.New(&m.tags)` + "\n" + `picker.View(c, multiselect.Spec{Label: "Tags"}).FillWidth()`, - "message-scroller": `ui.Control(c, "Messages", &m.handlers).Draw(paintMessages)`, + "list": `ui.List(c, &m.list, len(rows), func(row ui.ListRow) { _ = row })`, + "tree": `ui.Tree(c, &m.tree, len(rows), func(i int) string { return rows[i] }, func(i int) {})`, + "tree-navigation": `next, action, handled := ui.NavigateTree(items, current, key, pageRows)`, + "color-picker": `ui.ColorPicker(c, &m.picker, &m.color, "Accent")`, + "color-swatch": `ui.ColorSwatch(c, color, selected, "Accent")`, + "progress": `ui.Progress(c, 0.6)`, + "spinner": `ui.Spinner(c)`, + "split-button": `ui.SplitButton(c, ui.SplitButtonSpec{PrimaryID: primary, Label: "Run"})`, + "pagination": `ui.Pagination(c, items)`, + "radio-group": `ui.RadioGroup(c)`, + "choice": `ui.Choice(c, &m.choice, choices, nameOf)`, + "toggle": `ui.Toggle(c, &m.on, "Bold").Outline()`, + "native-select": `ui.Select(c, &m.choice, choices, nameOf)`, + "single-select": `ui.Select(c, &m.choice, choices, nameOf)`, + "scroll-area": `ui.Scroll(c).Grow(1).Scrollbars()`, + "resizable": `ui.Splitter(c, &m.splitter)`, + "separator": `ui.Divider(c)`, + "typography": `ui.Paragraph(c, text, 0)`, + "form": `ui.FormField(c, &m.field, "Name").Children(func() { ui.TextField(c, &m.name, "Name", "") })`, + "field": `ui.FormField(c, &m.field, "Name").Children(func() { ui.TextField(c, &m.name, "Name", "") })`, + "multi-select": `picker := multiselect.New(&m.tags)` + "\n" + `picker.View(c, multiselect.Spec{Label: "Tags"}).FillWidth()`, + "message-scroller": `messagescrollerview.View(c, "Conversation", &m.scroller).FillWidth().Height(278)`, + "bubble": `ui.Bubble(c, "Ready when you are", ui.BubbleMuted).Self(ui.Start)`, + "accordion": `ui.Accordion(c, m.faq, []ui.AccordionItem{{Title: "Shipping", Content: func() { ui.Text(c, "Ships in two days") }}})`, + "collapsible": `ui.Collapsible(c, &m.builds, "3 build artifacts", func() { ui.Text(c, "viva-darwin-arm64 3.8 MiB").Mono() })`, + "code-editor": `codeeditor.View(c, "Source", &m.editor).Fill()`, + "code-diff": `codeeditor.DiffView(c, "Changes", &m.diff).Fill()`, + "code-merge": `codeeditor.MergeView(c, "Merge", &m.merge).Fill()`, + "chart-area": `chartview.View(c, "Monthly visitors", &m.visitors).Height(280)`, + "chart-bar": `chartview.Bar(c, "Weekly orders", &m.orders).Height(280)`, + "calendar": `calendarview.View(c, "Calendar", &m.calendar).FillWidth().MaxWidth(360)`, + "carousel": `carouselview.View(c, "Product tour", &m.tour).FillWidth().Height(220)`, + "markdown": `markdownview.View(c, "Answer", &m.answer).Fill()`, + "column-resize": `columnresizeview.View(c, "File list", &m.columns).FillWidth().Height(180)`, + "chart": `chartview.ContainerView(c, "Weekly commits", &m.commits).Height(244)`, + "chart-downsample": `chartview.View(c, "History", &m.history).Height(280)`, + "toast": `ui.Toasts(c, &m.toaster)`, + "sonner": `ui.Toasts(c, &m.toaster)`, + "hover-card": `hovercardview.View(c, "@viva-framework", &m.hoverCard)`, + "avatar-editor": `m.avatarEditor.View(c, "Image crop").FillWidth().MaxWidth(440)`, + "reorder-grid": `m.reorderGrid.View(c, "Host order").FillWidth().Height(220)`, + "alert": `ui.Row(c).FillWidth().Pad(14).Gap(10).Background(c.Theme().Card).Border(1, c.Theme().Border).Children(func() { ui.Text(c, "Sync complete").Bold() })`, + "aspect-ratio": `ui.Column(c).FillWidth().MaxWidth(520).Height(293).Center().Radius(c.Theme().Metrics.RadiusSurface).Background(c.Theme().Muted)`, + "attachment": `m.attachment.View(c, "product-demo.mov").FillWidth()`, + "avatar": `m.avatar.View(c, "Skyler").Size(64, 64)`, + "breadcrumb": `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { ui.Text(c, "Workspace").Muted(); ui.Text(c, "›").Muted(); ui.Text(c, "Preview") })`, + "button-group": `ui.Row(c).Children(func() { ui.Button(c, "Left").Outline(); ui.Button(c, "Center").Outline(); ui.Button(c, "Right").Outline() })`, + "command": `commandview.View(c, "Command", &m.command).FillWidth().Height(220)`, + "icon-hover": `id := ui.ID(c); ui.Icon(c, m.moreIcon).Size(24, 24).Hit(id, "More actions").BindIconHover(ui.BindIconHover(&m.iconHover, id))`, + "image-view": `ui.Image(c, m.bitmap).Fill()`, + "input-group": `ui.TextField(c, &m.domain, "Project domain", "project-name").Action(m.clearIcon, "Clear domain")`, + "input-otp": `ui.TextField(c, &m.code, "Verification code", "000000")`, + "marker": `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { ui.Icon(c, m.clockIcon).Size(16, 16).Muted(); ui.Text(c, "Updated 2 minutes ago").Muted() })`, + "menubar": `menubarview.View(c, "File", &m.menubar)`, + "message": `messageview.View(c, "Ari", messageview.New().Name("Ari").Body("Native preview ready."))`, + "metric-card": `ui.Column(c).FillWidth().Pad(c.Theme().Metrics.PadSurface).Gap(6).Background(c.Theme().Card).Border(1, c.Theme().Border).Children(func() { ui.Text(c, "Active sessions").Muted(); ui.Text(c, "12,840").Bold() })`, + "navigation-menu": `navigationmenuview.View(c, "Site", &m.menu)`, + "questionnaire": `ui.Column(c).Gap(12).Children(func() { ui.Text(c, "Question 2 of 5").Muted(); ui.RadioGroup(c).Children(func() { ui.Radio(c, &m.answer, "Low memory", "Low memory") }); ui.Button(c, "Continue") })`, + "reorder-list": `items := []string{"Editor", "Terminal", "Explorer"}; m.list.Key = func(i int) int { return i }; ui.List(c, &m.list, len(items), func(row ui.ListRow) { ui.Text(row.C, items[row.Index]).Grow(1) })`, + "segmented-control": `ui.Choice(c, &m.view, []string{"List", "Board", "Timeline"}, nil)`, + "sidebar": `items := []string{"Overview", "Components", "Benchmarks"}; ui.Column(c).Width(240).FillHeight().Gap(8).Children(func() { ui.Text(c, "Viva Studio").Bold(); ui.List(c, &m.nav, len(items), func(row ui.ListRow) { ui.Text(row.C, items[row.Index]) }) })`, + "skeleton": `ui.Column(c).FillWidth().Height(14).Radius(4).Background(c.Theme().Muted)`, } diff --git a/internal/componentdemo/popover.go b/internal/componentdemo/popover.go index c89bc699..b0139eb0 100644 --- a/internal/componentdemo/popover.go +++ b/internal/componentdemo/popover.go @@ -16,11 +16,11 @@ if trigger.Clicked() { } if open { components.BeginPopover(canvas, theme, viewport, trigger.Rect(), components.PopoverOptions{ - Layer: 3, Scope: scope, DismissID: dismissID, Side: components.PopoverBottom, + Layer: 3, Scope: m.scope, DismissID: m.dismissID, Side: components.PopoverBottom, Align: components.PopoverAlignStart, SideOffset: 8, AnchorDismiss: true, }).Paint("Native surface", "Clamped to the viewport without timers.") } -if canvas.Clicked(dismissID) { open = false }`, PageSnippet: `open := false +if canvas.Clicked(m.dismissID) { open = false }`, PageSnippet: `open := false trigger := ui.Button(c, "Open details").Outline().Self(ui.Start) if trigger.Clicked() { open = !open @@ -28,7 +28,7 @@ if trigger.Clicked() { ui.PopoverWith(c, trigger, ui.PopoverSpec{ Title: "Native surface", Description: "Clamped to the current viewport without timers.", - Scope: scope, DismissID: dismissID, + Scope: m.scope, DismissID: m.dismissID, }, &open, func() {})`, PageSnippetZh: `open := false trigger := ui.Button(c, "Open details").Outline().Self(ui.Start) if trigger.Clicked() { @@ -37,14 +37,14 @@ if trigger.Clicked() { ui.PopoverWith(c, trigger, ui.PopoverSpec{ Title: "Native surface", Description: "Clamped to the current viewport without timers.", - Scope: scope, DismissID: dismissID, + Scope: m.scope, DismissID: m.dismissID, }, &open, func() {})`}, {ID: "custom-body", Title: "自定义内容", Description: "使用 Begin/End 槽位在浮层正文中追加状态。", Snippet: `label := "Diagnostics disabled" if enabled { label = "Diagnostics enabled" } popover := components.BeginPopover(canvas, theme, viewport, anchor, components.PopoverOptions{ - Layer: 3, Scope: scope, DismissID: dismissID, ContentSize: gfx.Size{Width: 288}, BodyHeight: 34, + Layer: 3, Scope: m.scope, DismissID: m.dismissID, ContentSize: gfx.Size{Width: 288}, BodyHeight: 34, }) layout := popover.Begin("Build status", "The stable host owns this overlay state.") if components.BeginButton(canvas, theme, actionID, layout.Body).Secondary(label).Clicked() { @@ -59,7 +59,7 @@ enabled := false ui.PopoverWith(c, trigger, ui.PopoverSpec{ Title: "Build status", Description: "The stable host owns this overlay state.", - Scope: scope, DismissID: dismissID, + Scope: m.scope, DismissID: m.dismissID, }, &open, func() { label := "Diagnostics disabled" if enabled { @@ -77,7 +77,7 @@ enabled := false ui.PopoverWith(c, trigger, ui.PopoverSpec{ Title: "Build status", Description: "The stable host owns this overlay state.", - Scope: scope, DismissID: dismissID, + Scope: m.scope, DismissID: m.dismissID, }, &open, func() { label := "Diagnostics disabled" if enabled { diff --git a/internal/componentdemo/progress.go b/internal/componentdemo/progress.go index b1ca6909..62176da0 100644 --- a/internal/componentdemo/progress.go +++ b/internal/componentdemo/progress.go @@ -10,34 +10,34 @@ var progressComponent = Component{ paint: (*State).paintProgress, Examples: []Example{ {ID: "default", Title: "上传进度", Description: "生产进度条展示一个调用方提供的确定值。", Snippet: `ui.Column(c).Gap(8).Children(func() { - ui.Text(c, "Uploading assets · 64%").FontSize(theme.Metrics.FontSizeM) + ui.Text(c, "Uploading assets · 64%").FontSize(c.Theme().Metrics.FontSizeM) ui.Progress(c, 0.64) })`, PageSnippet: `ui.Column(c).Gap(8).Children(func() { - ui.Text(c, "Uploading assets · 64%").FontSize(theme.Metrics.FontSizeM) + ui.Text(c, "Uploading assets · 64%") ui.Progress(c, 0.64) })`, PageSnippetZh: `ui.Column(c).Gap(8).Children(func() { - ui.Text(c, "Uploading assets · 64%").FontSize(theme.Metrics.FontSizeM) + ui.Text(c, "Uploading assets · 64%") ui.Progress(c, 0.64) })`}, {ID: "states", Title: "进度状态", Description: "同时展示空、进行中与完成状态。", Snippet: `labels := [...]string{"Queued", "Compiling", "Complete"} values := [...]float32{0, 0.42, 1} for index, label := range labels { ui.Column(c).Gap(8).Children(func() { - ui.Text(c, label).FontSize(theme.Metrics.FontSizeM) + ui.Text(c, label).FontSize(c.Theme().Metrics.FontSizeM) ui.Progress(c, values[index]) }) }`, PageSnippet: `labels := [...]string{"Queued", "Compiling", "Complete"} values := [...]float32{0, 0.42, 1} for index, label := range labels { ui.Column(c).Gap(8).Children(func() { - ui.Text(c, label).FontSize(theme.Metrics.FontSizeM) + ui.Text(c, label) ui.Progress(c, values[index]) }) }`, PageSnippetZh: `labels := [...]string{"Queued", "Compiling", "Complete"} values := [...]float32{0, 0.42, 1} for index, label := range labels { ui.Column(c).Gap(8).Children(func() { - ui.Text(c, label).FontSize(theme.Metrics.FontSizeM) + ui.Text(c, label) ui.Progress(c, values[index]) }) }`}, diff --git a/internal/componentdemo/questionnaire.go b/internal/componentdemo/questionnaire.go index 0a2fd634..3f731c6b 100644 --- a/internal/componentdemo/questionnaire.go +++ b/internal/componentdemo/questionnaire.go @@ -27,7 +27,31 @@ q.PaintActions(components.QuestionnaireActions{ }) if index, ok := canvas.ClickedIn(choice); ok { selected = index -}`}, +}`, PageSnippet: `ui.Text(c, "Question 2 of 5").Muted() +ui.Text(c, "What should Viva optimize first?") +ui.Text(c, "Answers stay in application state.").Muted() +ui.RadioGroup(c).Children(func() { + ui.Radio(c, &m.answer, "Low memory", "Low memory") + ui.Radio(c, &m.answer, "Fast startup", "Fast startup") + ui.Radio(c, &m.answer, "Small binaries", "Small binaries") +}) +ui.Row(c).Gap(8).Children(func() { + ui.Button(c, "Back").Outline() + ui.Button(c, "Skip").Outline() + ui.Button(c, "Continue") +})`, PageSnippetZh: `ui.Text(c, "Question 2 of 5").Muted() +ui.Text(c, "What should Viva optimize first?") +ui.Text(c, "Answers stay in application state.").Muted() +ui.RadioGroup(c).Children(func() { + ui.Radio(c, &m.answer, "Low memory", "Low memory") + ui.Radio(c, &m.answer, "Fast startup", "Fast startup") + ui.Radio(c, &m.answer, "Small binaries", "Small binaries") +}) +ui.Row(c).Gap(8).Children(func() { + ui.Button(c, "Back").Outline() + ui.Button(c, "Skip").Outline() + ui.Button(c, "Continue") +})`}, {ID: "multiple-choice", Title: "多选题", Description: "切换多个性能目标,组件不隐藏答案状态。", Snippet: `choice := tree.Sub(page, tree.Name("choice")) q := components.BeginQuestionnaire(canvas, theme, bounds, components.QuestionnaireData{ Progress: "Question 2 of 5", Title: "Which performance goals matter?", @@ -41,7 +65,29 @@ for index, label := range []string{"Low memory", "Fast startup", "Small binaries } if index, ok := canvas.ClickedIn(choice); ok { checked[index] = !checked[index] -}`}, +}`, PageSnippet: `ui.Text(c, "Question 2 of 5").Muted() +ui.Text(c, "Which performance goals matter?") +ui.Text(c, "Answers stay in application state.").Muted() +memory, startup, binaries := false, false, false +ui.Checkbox(c, &memory, "Low memory") +ui.Checkbox(c, &startup, "Fast startup") +ui.Checkbox(c, &binaries, "Small binaries") +ui.Row(c).Gap(8).Children(func() { + ui.Button(c, "Back").Outline() + ui.Button(c, "Skip").Outline() + ui.Button(c, "Continue") +})`, PageSnippetZh: `ui.Text(c, "Question 2 of 5").Muted() +ui.Text(c, "Which performance goals matter?") +ui.Text(c, "Answers stay in application state.").Muted() +memory, startup, binaries := false, false, false +ui.Checkbox(c, &memory, "Low memory") +ui.Checkbox(c, &startup, "Fast startup") +ui.Checkbox(c, &binaries, "Small binaries") +ui.Row(c).Gap(8).Children(func() { + ui.Button(c, "Back").Outline() + ui.Button(c, "Skip").Outline() + ui.Button(c, "Continue") +})`}, }, } diff --git a/internal/componentdemo/radio_group.go b/internal/componentdemo/radio_group.go index 35de0a02..bf64178b 100644 --- a/internal/componentdemo/radio_group.go +++ b/internal/componentdemo/radio_group.go @@ -59,7 +59,17 @@ options := []components.RadioOption{ group := components.BeginRadioGroup(canvas, theme, bounds, options, selected) if id, ok := group.Paint().Clicked(); ok { selected = id -}`, PageSnippet: ""}, +}`, PageSnippet: `plan := "Team" +ui.RadioGroup(c).Children(func() { + ui.Radio(c, &plan, "Personal", "Personal") + ui.Radio(c, &plan, "Team", "Team") + ui.Radio(c, &plan, "Enterprise", "Enterprise").Disabled(true) +})`, PageSnippetZh: `plan := "Team" +ui.RadioGroup(c).Children(func() { + ui.Radio(c, &plan, "Personal", "Personal") + ui.Radio(c, &plan, "Team", "Team") + ui.Radio(c, &plan, "Enterprise", "Enterprise").Disabled(true) +})`}, }, } diff --git a/internal/componentdemo/reorder_grid.go b/internal/componentdemo/reorder_grid.go index 8f8d2270..bd386d15 100644 --- a/internal/componentdemo/reorder_grid.go +++ b/internal/componentdemo/reorder_grid.go @@ -1,94 +1,42 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/reordergridview" ) var reorderGridDemoHandles = tree.Sub(tree.Feature("reorder-grid"), tree.Name("handle")) type reorderGridDemoState struct { - grid components.ReorderGridState + state *State + view reordergridview.Grid order [6]int } -func (state *reorderGridDemoState) move(move components.ReorderGridMove) { - if !move.Valid() || move.From < 0 || move.From >= len(state.order) || move.To < 0 || move.To >= len(state.order) { +func (demo *reorderGridDemoState) move(move reordergridview.Move) { + if !move.Valid() || move.From < 0 || move.From >= len(demo.order) || move.To < 0 || move.To >= len(demo.order) { return } - value := state.order[move.From] + value := demo.order[move.From] if move.From < move.To { - copy(state.order[move.From:move.To], state.order[move.From+1:move.To+1]) + copy(demo.order[move.From:move.To], demo.order[move.From+1:move.To+1]) } else { - copy(state.order[move.To+1:move.From+1], state.order[move.To:move.From]) + copy(demo.order[move.To+1:move.From+1], demo.order[move.To:move.From]) } - state.order[move.To] = value + demo.order[move.To] = value } var reorderGridComponent = Component{ ID: "reorder-grid", Title: "Reorder Grid", Category: "Layout", Summary: "在调用方定位的卡片或行中,用拖动手柄和键盘调整顺序。", initialize: func(state *State) { - state.reorderGrid = &reorderGridDemoState{order: [6]int{0, 1, 2, 3, 4, 5}} - }, - paint: func(state *State, canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var slot ui.Box - state.drawPage(canvas, theme, size, 620, state.Text("Reorder Grid · 卡片顺序", "Reorder Grid · Card order"), func(c ui.C) { - slot = ui.Slot(c).FillWidth().Height(220) - }) - bounds := slot.Rect() - const ( - columns = 3 - gap = float32(10) - height = float32(92) - ) - width := max((bounds.Width-gap*(columns-1))/columns, 0) - grid := components.BeginReorderGrid(canvas, theme, bounds, &state.reorderGrid.grid).HandleHitSlop(8) - labels := [6]string{ - state.Text("主机一", "Host one"), - state.Text("主机二", "Host two"), - state.Text("主机三", "Host three"), - state.Text("主机四", "Host four"), - state.Text("主机五", "Host five"), - state.Text("主机六", "Host six"), - } - for order, index := range state.reorderGrid.order { - grid.Order(reorderGridDemoHandles.At(index), 0, order, false) - } - for order, index := range state.reorderGrid.order { - id := reorderGridDemoHandles.At(index) - column, row := order%columns, order/columns - card := gfx.Rect{ - X: bounds.X + float32(column)*(width+gap), - Y: bounds.Y + float32(row)*(height+gap), - Width: width, Height: height, - } - edge := theme.Border - if state.reorderGrid.grid.Target() == id && state.reorderGrid.grid.Active() != id { - edge = theme.Primary - } - if state.reorderGrid.grid.Dragging() && state.reorderGrid.grid.Active() == id { - canvas.Elevate(card, theme.Metrics.RadiusControl, gfx.ShadowMD) - edge = theme.Primary - } - canvas.RoundedBorder(card, theme.Metrics.RadiusControl, 1, edge, theme.Background) - handle := gfx.Rect{X: card.X + 8, Y: card.Y + 12, Width: 28, Height: card.Height - 24} - content := gfx.Rect{X: card.X + 44, Y: card.Y, Width: max(card.Width-52, 0), Height: card.Height} - grid.Item(id, labels[index], 0, order, card, handle, false) - canvas.Label(labels[index], content, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.Foreground}) - } - grid.End() - }, - pointer: func(state *State, event gfx.PointerEvent) gfx.EventResult { - move, result := state.reorderGrid.grid.Pointer(event) - state.reorderGrid.move(move) - return result - }, - key: func(state *State, event gfx.KeyEvent) gfx.EventResult { - move, result := state.reorderGrid.grid.Key(event) - state.reorderGrid.move(move) - return result + demo := &reorderGridDemoState{state: state, order: [6]int{0, 1, 2, 3, 4, 5}} + demo.view.HandleHitSlop = 8 + demo.view.Draw = demo.draw + demo.view.Move = demo.move + state.reorderGrid = demo }, + paint: (*State).paintReorderGrid, Examples: []Example{{ ID: "default", Title: "卡片排序", Description: "调用方提供每个项目的位置与逻辑顺序;手柄负责拖动,方向键、Home / End 也可排序。", @@ -108,5 +56,65 @@ var reorderGridComponent = Component{ "}\n" + "// Keyboard events use dragState.Key(event) in the same way.\n" + "_ = result", + PageSnippet: `// m.reorderGrid is a reordergridview.Grid. +grid := m.reorderGrid +grid.HandleHitSlop = 8 +grid.Draw = m.drawReorderGrid +grid.Move = m.applyReorderMove +grid.View(c, "Host order").FillWidth().Height(220) +// Pointer, key and wheel callbacks are optional observers; the wrapper routes +// reorder input to State either way.`, + PageSnippetZh: `// m.reorderGrid 是 reordergridview.Grid。 +grid := m.reorderGrid +grid.HandleHitSlop = 8 +grid.Draw = m.drawReorderGrid +grid.Move = m.applyReorderMove +grid.View(c, "主机排序").FillWidth().Height(220) +// Pointer、按键和滚轮回调是可选的观察者;重排输入始终由包装路由到 State。`, }}, } + +func (state *State) paintReorderGrid(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := state.reorderGrid + state.drawPage(canvas, theme, size, 620, state.Text("Reorder Grid · 卡片顺序", "Reorder Grid · Card order"), func(c ui.C) { + reordergridview.View(c, state.Text("主机排序", "Host order"), &demo.view).FillWidth().Height(220) + }) +} + +// draw paints the caller's cards and declares each one through the layout. The +// layout reports the dragged and target items with the caller's own identities. +func (demo *reorderGridDemoState) draw(ctx *ui.DrawContext, layout reordergridview.Layout) { + labels := [6]string{ + demo.state.Text("主机一", "Host one"), + demo.state.Text("主机二", "Host two"), + demo.state.Text("主机三", "Host three"), + demo.state.Text("主机四", "Host four"), + demo.state.Text("主机五", "Host five"), + demo.state.Text("主机六", "Host six"), + } + const ( + columns = 3 + gap = float32(10) + height = float32(92) + ) + for order, index := range demo.order { + layout.Order(reorderGridDemoHandles.At(index), 0, order, false) + } + for order, index := range demo.order { + id := reorderGridDemoHandles.At(index) + card := layout.ItemBounds(columns, order, gap, height) + edge := ctx.Theme.Border + if layout.Target() == id && layout.Active() != id { + edge = ctx.Theme.Primary + } + if layout.Dragging() && layout.Active() == id { + ctx.Canvas.Elevate(card, ctx.Theme.Metrics.RadiusControl, gfx.ShadowMD) + edge = ctx.Theme.Primary + } + ctx.Canvas.RoundedBorder(card, ctx.Theme.Metrics.RadiusControl, 1, edge, ctx.Theme.Background) + handle := gfx.Rect{X: card.X + 8, Y: card.Y + 12, Width: 28, Height: card.Height - 24} + content := gfx.Rect{X: card.X + 44, Y: card.Y, Width: max(card.Width-52, 0), Height: card.Height} + layout.Item(id, labels[index], 0, order, card, handle, false) + ctx.Canvas.Label(labels[index], content, gfx.TextStyle{Size: ctx.Theme.Metrics.FontSizeM, Color: ctx.Theme.Foreground}) + } +} diff --git a/internal/componentdemo/reorder_list.go b/internal/componentdemo/reorder_list.go index a114b3ff..39d3eb5b 100644 --- a/internal/componentdemo/reorder_list.go +++ b/internal/componentdemo/reorder_list.go @@ -65,5 +65,25 @@ if move.Valid() { applyMove(move.From, move.To) } // Keyboard events can use dragState.Key(event) in the same way. -_ = result`}}, +_ = result`, PageSnippet: `m.list.Key = func(i int) int { return i } +m.list.Label = func(i int) string { return m.items[i] } +m.list.Reorder = m.move +m.list.Handle = m.handles +ui.List(c, &m.list, len(m.items), func(row ui.ListRow) { + row.Element.Height(48).PadX(12).Gap(12).Items(ui.Center).Children(func() { + ui.Icon(row.C, m.gripIcon).Size(16, 16). + Hit(m.handles.At(row.Index), "Reorder "+m.items[row.Index]) + ui.Text(row.C, m.items[row.Index]).Grow(1) + }) +}).Label("Shortcuts")`, PageSnippetZh: `m.list.Key = func(i int) int { return i } +m.list.Label = func(i int) string { return m.items[i] } +m.list.Reorder = m.move +m.list.Handle = m.handles +ui.List(c, &m.list, len(m.items), func(row ui.ListRow) { + row.Element.Height(48).PadX(12).Gap(12).Items(ui.Center).Children(func() { + ui.Icon(row.C, m.gripIcon).Size(16, 16). + Hit(m.handles.At(row.Index), "重新排序 "+m.items[row.Index]) + ui.Text(row.C, m.items[row.Index]).Grow(1) + }) +}).Label("快捷入口")`}}, } diff --git a/internal/componentdemo/resizable.go b/internal/componentdemo/resizable.go index 2f48f291..73a40656 100644 --- a/internal/componentdemo/resizable.go +++ b/internal/componentdemo/resizable.go @@ -66,7 +66,25 @@ layout := components.BeginResizable(canvas, theme, handle, bounds, fraction). Limits(0.2, 0.8).HandleSize(12).WithHandle().Disabled(). Paint("Resize editor panels") canvas.Rounded(layout.First.Inset(gfx.All(8)), 6, theme.Muted) -canvas.Rounded(layout.Second.Inset(gfx.All(8)), 6, theme.CardElevated)`, PageSnippet: ""}, +canvas.Rounded(layout.Second.Inset(gfx.All(8)), 6, theme.CardElevated)`, PageSnippet: `split := ui.SplitterState{Pos: 260} +ui.Row(c).Height(200).Children(func() { + ui.Column(c).Width(split.Pos).Background(c.Theme().Muted).Children(func() { + ui.Text(c, "Navigator") + }) + ui.Splitter(c, &split).Mins(120, 200).Label("Resize editor panels").Disabled(true) + ui.Column(c).Grow(1).Basis(0).Background(c.Theme().CardElevated).Children(func() { + ui.Text(c, "Preview") + }) +})`, PageSnippetZh: `split := ui.SplitterState{Pos: 260} +ui.Row(c).Height(200).Children(func() { + ui.Column(c).Width(split.Pos).Background(c.Theme().Muted).Children(func() { + ui.Text(c, "Navigator") + }) + ui.Splitter(c, &split).Mins(120, 200).Label("Resize editor panels").Disabled(true) + ui.Column(c).Grow(1).Basis(0).Background(c.Theme().CardElevated).Children(func() { + ui.Text(c, "Preview") + }) +})`}, }, } diff --git a/internal/componentdemo/segmented_control.go b/internal/componentdemo/segmented_control.go index 6e772296..74968037 100644 --- a/internal/componentdemo/segmented_control.go +++ b/internal/componentdemo/segmented_control.go @@ -19,7 +19,11 @@ options := []components.SegmentOption{ control := components.BeginSegmentedControl(canvas, theme, bounds, options, selected) if id, ok := control.Paint().Clicked(); ok { selected = id -}`}, +}`, PageSnippet: `// m.view starts as "List". +views := []string{"List", "Board", "Timeline"} +ui.Choice(c, &m.view, views, nil)`, PageSnippetZh: `// m.view 初始为 "List"。 +views := []string{"List", "Board", "Timeline"} +ui.Choice(c, &m.view, views, nil)`}, {ID: "states", Title: "局部禁用", Description: "展示一个不可用选项与完整控件禁用状态。", Snippet: `view := tree.Sub(page, tree.Name("view")) control := components.BeginSegmentedControl(canvas, theme, bounds, []components.SegmentOption{ {ID: view.At(0), Label: "List"}, {ID: view.At(1), Label: "Board"}, @@ -32,7 +36,13 @@ locked := tree.Sub(page, tree.Name("locked")) components.BeginSegmentedControl(canvas, theme, lockedBounds, []components.SegmentOption{ {ID: locked.At(0), Label: "List"}, {ID: locked.At(1), Label: "Board"}, {ID: locked.At(2), Label: "Timeline"}, -}, locked.At(1)).Disabled().Paint()`}, +}, locked.At(1)).Disabled().Paint()`, PageSnippet: `// m.view starts as "Board"; Timeline is unavailable here. +views := []string{"List", "Board", "Timeline"} +ui.Choice(c, &m.view, views, nil) +ui.Choice(c, &m.lockedView, views, nil).Disabled(true)`, PageSnippetZh: `// m.view 初始为 "Board";这里的 Timeline 不可用。 +views := []string{"List", "Board", "Timeline"} +ui.Choice(c, &m.view, views, nil) +ui.Choice(c, &m.lockedView, views, nil).Disabled(true)`}, }, } diff --git a/internal/componentdemo/select.go b/internal/componentdemo/select.go index bc122196..9f633b62 100644 --- a/internal/componentdemo/select.go +++ b/internal/componentdemo/select.go @@ -37,7 +37,21 @@ components.BeginSelect(canvas, theme, disabledBounds, components.SelectOptions{ TriggerID: tree.ID(page, "disabled"), Label: "Unavailable", Placeholder: "Backend unavailable", Disabled: true, Size: components.SelectSizeSmall, -})`, PageSnippet: ""}, +})`, PageSnippet: `backends := []string{"Metal", "Direct3D", "Vulkan"} +var backend string +ui.Select(c, &backend, backends, nil). + Label("Renderer").Placeholder("Select a backend") +var unavailable string +ui.Select(c, &unavailable, backends, nil). + Label("Unavailable").Placeholder("Backend unavailable"). + Disabled(true).Small()`, PageSnippetZh: `backends := []string{"Metal", "Direct3D", "Vulkan"} +var backend string +ui.Select(c, &backend, backends, nil). + Label("Renderer").Placeholder("Select a backend") +var unavailable string +ui.Select(c, &unavailable, backends, nil). + Label("Unavailable").Placeholder("Backend unavailable"). + Disabled(true).Small()`}, }, } diff --git a/internal/componentdemo/sheet.go b/internal/componentdemo/sheet.go index 92b82d13..e3a9a92a 100644 --- a/internal/componentdemo/sheet.go +++ b/internal/componentdemo/sheet.go @@ -23,8 +23,7 @@ ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ Side: ui.DrawerRight, Size: 360, Description: "Changes remain caller-owned until Save.", }, func() { - ui.Text(c, "Rendering backend") - ui.Text(c, "Native GPU") + ui.TextField(c, &m.backend, "Rendering backend", "") }, func() { if ui.Button(c, "Save changes").Clicked() { open = false @@ -34,8 +33,7 @@ ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ Side: ui.DrawerRight, Size: 360, Description: "Changes remain caller-owned until Save.", }, func() { - ui.Text(c, "Rendering backend") - ui.Text(c, "Native GPU") + ui.TextField(c, &m.backend, "Rendering backend", "") }, func() { if ui.Button(c, "Save changes").Clicked() { open = false @@ -52,10 +50,9 @@ sheet.End() if canvas.Clicked(saveID) || canvas.Clicked(closeID) || canvas.Clicked(dismissID) { open = false }`, PageSnippet: `open := true ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ Side: ui.DrawerBottom, Size: 230, - Description: "Changes remain caller-owned until Save.", + Description: "Same API, bottom edge.", }, func() { - ui.Text(c, "Rendering backend") - ui.Text(c, "Native GPU") + ui.TextField(c, &m.backend, "Rendering backend", "") }, func() { if ui.Button(c, "Save changes").Clicked() { open = false @@ -63,10 +60,9 @@ ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ })`, PageSnippetZh: `open := true ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ Side: ui.DrawerBottom, Size: 230, - Description: "Changes remain caller-owned until Save.", + Description: "Same API, bottom edge.", }, func() { - ui.Text(c, "Rendering backend") - ui.Text(c, "Native GPU") + ui.TextField(c, &m.backend, "Rendering backend", "") }, func() { if ui.Button(c, "Save changes").Clicked() { open = false diff --git a/internal/componentdemo/sidebar.go b/internal/componentdemo/sidebar.go index c3b99800..814d0d45 100644 --- a/internal/componentdemo/sidebar.go +++ b/internal/componentdemo/sidebar.go @@ -20,7 +20,87 @@ sidebar.AddMenuItem(components.SidebarMenuItem{ sidebar.AddMenuItem(components.SidebarMenuItem{ ID: items.At(1), Label: "Components", Icon: "C", Active: selected == 1, }) -if index, ok := canvas.ClickedIn(items); ok { selected = int(index) }`}, +if index, ok := canvas.ClickedIn(items); ok { selected = int(index) }`, + PageSnippet: `type navItem struct { + Icon, Label, Trailing string +} +navItems := []navItem{ + {Icon: "O", Label: "Overview", Trailing: "12"}, + {Icon: "C", Label: "Components"}, + {Icon: "B", Label: "Benchmarks"}, +} +ui.Row(c).Gap(20).Children(func() { + ui.Column(c).Width(240).FillHeight().Gap(8).Children(func() { + ui.Text(c, "Viva Studio").Bold() + ui.Text(c, "Workspace").Muted() + ui.List(c, &m.nav, len(navItems), func(row ui.ListRow) { + item := navItems[row.Index] + row.Element.PadX(8).Gap(8).Items(ui.Center).Children(func() { + ui.Text(row.C, item.Icon) + ui.Text(row.C, item.Label).Grow(1) + ui.Text(row.C, item.Trailing).Muted() + }) + }).Grow(1) + ui.Column(c).Gap(2).PadLeft(24).Children(func() { + if ui.Button(c, "Buttons").Ghost().Small().Self(ui.Start).Clicked() { + m.section = "buttons" + } + if ui.Button(c, "Inputs").Ghost().Small().Self(ui.Start).Clicked() { + m.section = "inputs" + } + }) + ui.Divider(c) + if ui.Button(c, "Settings").Ghost().Small().Self(ui.Start).Clicked() { + m.section = "settings" + } + if ui.Button(c, "Skyler").Ghost().Self(ui.Start).Clicked() { + m.account = true + } + }) + ui.Column(c).Grow(1).Basis(0).Gap(16).Children(func() { + ui.Text(c, m.selection).Bold() + }) +})`, + PageSnippetZh: `type navItem struct { + Icon, Label, Trailing string +} +navItems := []navItem{ + {Icon: "O", Label: "Overview", Trailing: "12"}, + {Icon: "C", Label: "Components"}, + {Icon: "B", Label: "Benchmarks"}, +} +ui.Row(c).Gap(20).Children(func() { + ui.Column(c).Width(240).FillHeight().Gap(8).Children(func() { + ui.Text(c, "Viva Studio").Bold() + ui.Text(c, "Workspace").Muted() + ui.List(c, &m.nav, len(navItems), func(row ui.ListRow) { + item := navItems[row.Index] + row.Element.PadX(8).Gap(8).Items(ui.Center).Children(func() { + ui.Text(row.C, item.Icon) + ui.Text(row.C, item.Label).Grow(1) + ui.Text(row.C, item.Trailing).Muted() + }) + }).Grow(1) + ui.Column(c).Gap(2).PadLeft(24).Children(func() { + if ui.Button(c, "Buttons").Ghost().Small().Self(ui.Start).Clicked() { + m.section = "buttons" + } + if ui.Button(c, "Inputs").Ghost().Small().Self(ui.Start).Clicked() { + m.section = "inputs" + } + }) + ui.Divider(c) + if ui.Button(c, "Settings").Ghost().Small().Self(ui.Start).Clicked() { + m.section = "settings" + } + if ui.Button(c, "Skyler").Ghost().Self(ui.Start).Clicked() { + m.account = true + } + }) + ui.Column(c).Grow(1).Basis(0).Gap(16).Children(func() { + ui.Text(c, m.selection).Bold() + }) +})`}, {ID: "floating", Title: "浮动变体", Description: "使用官方 Floating 表面与描边菜单项。", Snippet: `rail := ui.Slot(c).WidthPercent(42).MaxWidth(260).FillHeight() items := tree.Sub(page, tree.Name("item")) sidebar := components.BeginSidebarWithOptions(canvas, theme, rail.Rect(), "Viva Studio", @@ -30,7 +110,65 @@ sidebar.AddMenuItem(components.SidebarMenuItem{ID: items.At(0), Label: "Overview sidebar.AddMenuItem(components.SidebarMenuItem{ ID: items.At(1), Label: "Components", Icon: "C", Variant: components.SidebarMenuOutline, -})`}, +})`, + PageSnippet: `type navItem struct { + Icon, Label string + Outline bool +} +navItems := []navItem{ + {Icon: "O", Label: "Overview"}, + {Icon: "C", Label: "Components", Outline: true}, + {Icon: "B", Label: "Benchmarks"}, +} +ui.Column(c).Width(240).FillHeight().Pad(c.Theme().Metrics.PadSurface). + Background(c.Theme().Card).Border(1, c.Theme().Border). + Radius(c.Theme().Metrics.RadiusSurface).Gap(8).Children(func() { + ui.Text(c, "Viva Studio").Bold() + ui.Text(c, "Workspace").Muted() + ui.List(c, &m.nav, len(navItems), func(row ui.ListRow) { + item := navItems[row.Index] + if item.Outline { + ui.Button(row.C, item.Icon+" "+item.Label).Outline().Small().Self(ui.Start) + return + } + row.Element.PadX(8).Gap(8).Items(ui.Center).Children(func() { + ui.Text(row.C, item.Icon) + ui.Text(row.C, item.Label).Grow(1) + }) + }).Grow(1) + if ui.Button(c, "Settings").Ghost().Small().Self(ui.Start).Clicked() { + m.section = "settings" + } + })`, + PageSnippetZh: `type navItem struct { + Icon, Label string + Outline bool +} +navItems := []navItem{ + {Icon: "O", Label: "Overview"}, + {Icon: "C", Label: "Components", Outline: true}, + {Icon: "B", Label: "Benchmarks"}, +} +ui.Column(c).Width(240).FillHeight().Pad(c.Theme().Metrics.PadSurface). + Background(c.Theme().Card).Border(1, c.Theme().Border). + Radius(c.Theme().Metrics.RadiusSurface).Gap(8).Children(func() { + ui.Text(c, "Viva Studio").Bold() + ui.Text(c, "Workspace").Muted() + ui.List(c, &m.nav, len(navItems), func(row ui.ListRow) { + item := navItems[row.Index] + if item.Outline { + ui.Button(row.C, item.Icon+" "+item.Label).Outline().Small().Self(ui.Start) + return + } + row.Element.PadX(8).Gap(8).Items(ui.Center).Children(func() { + ui.Text(row.C, item.Icon) + ui.Text(row.C, item.Label).Grow(1) + }) + }).Grow(1) + if ui.Button(c, "Settings").Ghost().Small().Self(ui.Start).Clicked() { + m.section = "settings" + } + })`}, {ID: "collapsed", Title: "图标折叠", Description: "切换完整导航和桌面图标栏。", Snippet: `rail := ui.Slot(c).FillHeight() if collapsed { rail.Width(theme.Metrics.ControlHeight + theme.Metrics.GapItem*2) @@ -42,7 +180,67 @@ sidebar := components.BeginSidebarWithOptions(canvas, theme, rail.Rect(), "Viva if ui.Button(c, "Toggle sidebar").Outline().Hit(collapseID, "Toggle sidebar").Clicked() { collapsed = !collapsed } -sidebar.AddMenuItem(components.SidebarMenuItem{ID: tree.ID(page, "overview"), Label: "Overview", Icon: "O"})`}, +sidebar.AddMenuItem(components.SidebarMenuItem{ID: tree.ID(page, "overview"), Label: "Overview", Icon: "O"})`, + PageSnippet: `type navItem struct { + Icon, Label string +} +navItems := []navItem{ + {Icon: "O", Label: "Overview"}, + {Icon: "C", Label: "Components"}, + {Icon: "B", Label: "Benchmarks"}, +} +ui.Column(c).FillHeight().Gap(6).Children(func() { + if m.collapsed { + for _, item := range navItems { + if ui.Button(c, item.Icon).Ghost().IconOnly().Clicked() { + m.selection = item.Label + } + } + if ui.Button(c, "»").Ghost().IconOnly().Clicked() { + m.collapsed = false + } + return + } + ui.Text(c, "Viva Studio").Bold() + for _, item := range navItems { + if ui.Button(c, item.Icon+" "+item.Label).Ghost().Self(ui.Start).Clicked() { + m.selection = item.Label + } + } + if ui.Button(c, "Collapse sidebar").Ghost().Self(ui.Start).Clicked() { + m.collapsed = true + } +})`, + PageSnippetZh: `type navItem struct { + Icon, Label string +} +navItems := []navItem{ + {Icon: "O", Label: "Overview"}, + {Icon: "C", Label: "Components"}, + {Icon: "B", Label: "Benchmarks"}, +} +ui.Column(c).FillHeight().Gap(6).Children(func() { + if m.collapsed { + for _, item := range navItems { + if ui.Button(c, item.Icon).Ghost().IconOnly().Clicked() { + m.selection = item.Label + } + } + if ui.Button(c, "»").Ghost().IconOnly().Clicked() { + m.collapsed = false + } + return + } + ui.Text(c, "Viva Studio").Bold() + for _, item := range navItems { + if ui.Button(c, item.Icon+" "+item.Label).Ghost().Self(ui.Start).Clicked() { + m.selection = item.Label + } + } + if ui.Button(c, "Collapse sidebar").Ghost().Self(ui.Start).Clicked() { + m.collapsed = true + } +})`}, }, } diff --git a/internal/componentdemo/skeleton.go b/internal/componentdemo/skeleton.go index 68beaa31..6f743b85 100644 --- a/internal/componentdemo/skeleton.go +++ b/internal/componentdemo/skeleton.go @@ -17,7 +17,19 @@ line3 := ui.Slot(c).WidthPercent(64).Height(14) components.BeginSkeleton(canvas, theme, title.Rect()).Paint() components.BeginSkeleton(canvas, theme, line1.Rect()).Radius(4).Paint() components.BeginSkeleton(canvas, theme, line2.Rect()).Radius(4).Paint() -components.BeginSkeleton(canvas, theme, line3.Rect()).Radius(4).Paint()`}, +components.BeginSkeleton(canvas, theme, line3.Rect()).Radius(4).Paint()`, PageSnippet: `ui.Column(c).FillWidth().MaxWidth(236).Height(22). + Radius(c.Theme().Metrics.RadiusControl).Background(c.Theme().Muted) +ui.Column(c).Gap(12).Children(func() { + ui.Column(c).FillWidth().Height(14).Radius(4).Background(c.Theme().Muted) + ui.Column(c).WidthPercent(82).Height(14).Radius(4).Background(c.Theme().Muted) + ui.Column(c).WidthPercent(64).Height(14).Radius(4).Background(c.Theme().Muted) +})`, PageSnippetZh: `ui.Column(c).FillWidth().MaxWidth(236).Height(22). + Radius(c.Theme().Metrics.RadiusControl).Background(c.Theme().Muted) +ui.Column(c).Gap(12).Children(func() { + ui.Column(c).FillWidth().Height(14).Radius(4).Background(c.Theme().Muted) + ui.Column(c).WidthPercent(82).Height(14).Radius(4).Background(c.Theme().Muted) + ui.Column(c).WidthPercent(64).Height(14).Radius(4).Background(c.Theme().Muted) +})`}, {ID: "profile", Title: "资料卡", Description: "圆形头像与多行资料占位组合。", Snippet: `avatar := ui.Slot(c).Size(56, 56) name := ui.Slot(c).Size(172, 16) handle := ui.Slot(c).Size(118, 12) @@ -25,14 +37,50 @@ body := ui.Slot(c).Height(92) components.BeginSkeleton(canvas, theme, avatar.Rect()).Circle().Paint() components.BeginSkeleton(canvas, theme, name.Rect()).Paint() components.BeginSkeleton(canvas, theme, handle.Rect()).Radius(4).Paint() -components.BeginSkeleton(canvas, theme, body.Rect()).Paint()`}, +components.BeginSkeleton(canvas, theme, body.Rect()).Paint()`, PageSnippet: `ui.Row(c).Gap(16).Children(func() { + ui.Column(c).Size(56, 56).Radius(28).Background(c.Theme().Muted) + ui.Column(c).Gap(10).Children(func() { + ui.Column(c).Size(172, 16). + Radius(c.Theme().Metrics.RadiusControl).Background(c.Theme().Muted) + ui.Column(c).Size(118, 12).Radius(4).Background(c.Theme().Muted) + }) +}) +ui.Column(c).FillWidth().Height(92). + Radius(c.Theme().Metrics.RadiusControl).Background(c.Theme().Muted)`, PageSnippetZh: `ui.Row(c).Gap(16).Children(func() { + ui.Column(c).Size(56, 56).Radius(28).Background(c.Theme().Muted) + ui.Column(c).Gap(10).Children(func() { + ui.Column(c).Size(172, 16). + Radius(c.Theme().Metrics.RadiusControl).Background(c.Theme().Muted) + ui.Column(c).Size(118, 12).Radius(4).Background(c.Theme().Muted) + }) +}) +ui.Column(c).FillWidth().Height(92). + Radius(c.Theme().Metrics.RadiusControl).Background(c.Theme().Muted)`}, {ID: "phases", Title: "显式相位", Description: "由调用方提供固定动画相位;组件自身不启动计时器。", Snippet: `rows := [4]ui.Box{} for index := range rows { rows[index] = ui.Slot(c).Height(20) } for index, phase := range [...]float32{0, 0.25, 0.50, 0.75} { components.BeginSkeleton(canvas, theme, rows[index].Rect()).Radius(5).Phase(phase).Paint() -}`}, +}`, PageSnippet: `ui.Column(c).Gap(22).Children(func() { + ui.Column(c).FillWidth().Height(20).Radius(5). + Background(c.Theme().Muted).Opacity(1) + ui.Column(c).FillWidth().Height(20).Radius(5). + Background(c.Theme().Muted).Opacity(0.75) + ui.Column(c).FillWidth().Height(20).Radius(5). + Background(c.Theme().Muted).Opacity(0.5) + ui.Column(c).FillWidth().Height(20).Radius(5). + Background(c.Theme().Muted).Opacity(0.75) +})`, PageSnippetZh: `ui.Column(c).Gap(22).Children(func() { + ui.Column(c).FillWidth().Height(20).Radius(5). + Background(c.Theme().Muted).Opacity(1) + ui.Column(c).FillWidth().Height(20).Radius(5). + Background(c.Theme().Muted).Opacity(0.75) + ui.Column(c).FillWidth().Height(20).Radius(5). + Background(c.Theme().Muted).Opacity(0.5) + ui.Column(c).FillWidth().Height(20).Radius(5). + Background(c.Theme().Muted).Opacity(0.75) +})`}, }, } diff --git a/internal/componentdemo/slider.go b/internal/componentdemo/slider.go index 1e3b3b87..b8a049c9 100644 --- a/internal/componentdemo/slider.go +++ b/internal/componentdemo/slider.go @@ -21,7 +21,13 @@ ui.Slider(c, &volume).Range(0, 100).Step(10).Label("音量")`}, {ID: tree.ID(page, "lower"), Label: "Minimum price", ValueText: "25", Value: 25}, {ID: tree.ID(page, "upper"), Label: "Maximum price", ValueText: "75", Value: 75}, } -components.BeginRangeSlider(canvas, theme, bounds, thumbs).Step(5).Paint("Price range")`, PageSnippet: ""}, +components.BeginRangeSlider(canvas, theme, bounds, thumbs).Step(5).Paint("Price range")`, PageSnippet: `// m.price starts at 25–75. +price := ui.NewRangeSliderState(25, 75) +price.Step = 5 +ui.RangeSlider(c, &price)`, PageSnippetZh: `// m.price 初始为 25–75。 +price := ui.NewRangeSliderState(25, 75) +price.Step = 5 +ui.RangeSlider(c, &price)`}, {ID: "states", Title: "方向与禁用", Description: "同时展示竖向滑块与禁用状态。", Snippet: `components.BeginSlider(canvas, theme, tree.ID(page, "volume"), volumeBounds, float32(volume)).Vertical().Step(10).Paint("Volume") components.BeginSlider(canvas, theme, tree.ID(page, "disabled"), disabledBounds, 64). diff --git a/internal/componentdemo/sonner.go b/internal/componentdemo/sonner.go index 426a5b37..d76c6cd2 100644 --- a/internal/componentdemo/sonner.go +++ b/internal/componentdemo/sonner.go @@ -18,7 +18,13 @@ toasts := [...]components.SonnerToast{{ Scope: toast, DismissID: tree.ID(page, "dismiss"), ActionID: tree.ID(page, "action"), ActionLabel: "View", }} -components.PaintSonner(canvas, theme, viewport, toasts[:], components.SonnerOptions{Layer: 40})`}, +components.PaintSonner(canvas, theme, viewport, toasts[:], components.SonnerOptions{Layer: 40})`, PageSnippet: `if ui.Button(c, "Save project").Clicked() { + m.toaster.ShowAction("Project saved", "All local changes are written.", ui.ToastSuccess, "View") +} +ui.Toasts(c, &m.toaster)`, PageSnippetZh: `if ui.Button(c, "保存项目").Clicked() { + m.toaster.ShowAction("项目已保存", "所有本地更改均已写入。", ui.ToastSuccess, "查看") +} +ui.Toasts(c, &m.toaster)`}, {ID: "stack", Title: "折叠堆栈", Description: "最新通知在前,使用小间距叠放。", Snippet: `toast := tree.Sub(page, tree.Name("toast")) toasts := [...]components.SonnerToast{ {Snapshot: components.ToastSnapshot{Title: "Project saved", Type: components.ToastSuccess}, @@ -28,7 +34,19 @@ toasts := [...]components.SonnerToast{ {Snapshot: components.ToastSnapshot{Title: "Connection lost", Type: components.ToastError}, Scope: toast.At(2)}, } -components.PaintSonner(canvas, theme, viewport, toasts[:], components.SonnerOptions{Layer: 40})`}, +components.PaintSonner(canvas, theme, viewport, toasts[:], components.SonnerOptions{Layer: 40})`, PageSnippet: `if !m.notified { + m.toaster.Show("Project saved", "", ui.ToastSuccess) + m.toaster.Show("Update available", "", ui.ToastInfo) + m.toaster.Show("Connection lost", "", ui.ToastError) + m.notified = true +} +ui.Toasts(c, &m.toaster)`, PageSnippetZh: `if !m.notified { + m.toaster.Show("项目已保存", "", ui.ToastSuccess) + m.toaster.Show("有可用更新", "", ui.ToastInfo) + m.toaster.Show("连接已中断", "", ui.ToastError) + m.notified = true +} +ui.Toasts(c, &m.toaster)`}, {ID: "expanded", Title: "展开堆栈", Description: "显式展开多条不同语义通知。", Snippet: `toast := tree.Sub(page, tree.Name("toast")) action := tree.Sub(page, tree.Name("action")) toasts := [...]components.SonnerToast{ @@ -41,7 +59,21 @@ toasts := [...]components.SonnerToast{ } components.PaintSonner(canvas, theme, viewport, toasts[:], components.SonnerOptions{ Layer: 40, Expanded: true, -})`}, +})`, PageSnippet: `// The stack expands while the pointer rests on it or focus is inside it. +if !m.notified { + m.toaster.ShowAction("Project saved", "", ui.ToastSuccess, "View") + m.toaster.ShowAction("Update available", "", ui.ToastInfo, "Later") + m.toaster.Show("Connection lost", "", ui.ToastError) + m.notified = true +} +ui.Toasts(c, &m.toaster)`, PageSnippetZh: `// 指针停留或焦点在通知堆栈内时,堆栈会展开。 +if !m.notified { + m.toaster.ShowAction("项目已保存", "", ui.ToastSuccess, "查看") + m.toaster.ShowAction("有可用更新", "", ui.ToastInfo, "稍后") + m.toaster.Show("连接已中断", "", ui.ToastError) + m.notified = true +} +ui.Toasts(c, &m.toaster)`}, }, } diff --git a/internal/componentdemo/spinner.go b/internal/componentdemo/spinner.go index 58ee53ac..3406b13d 100644 --- a/internal/componentdemo/spinner.go +++ b/internal/componentdemo/spinner.go @@ -15,20 +15,50 @@ icon := ui.Slot(c).Size(24, 24) components.PaintSpinner(canvas, theme, icon.Rect(), 2) ui.Text(c, "Syncing workspace…").FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium)`, PageSnippet: `ui.Row(c).Gap(14).Items(ui.Center).Children(func() { ui.Spinner(c) - ui.Text(c, "Syncing workspace…").FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium) + ui.Text(c, "Syncing workspace…").Weight(gfx.WeightMedium) })`, PageSnippetZh: `ui.Row(c).Gap(14).Items(ui.Center).Children(func() { ui.Spinner(c) - ui.Text(c, "正在同步工作区…").FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium) + ui.Text(c, "正在同步工作区…").Weight(gfx.WeightMedium) })`}, {ID: "phases", Title: "八个相位", Description: "同屏展示全部确定性相位,不启动动画循环。", Snippet: `for index := range 8 { cell := ui.Slot(c).Size(32, 32) components.PaintSpinner(canvas, theme, cell.Rect(), components.SpinnerPhase(index)) +}`, PageSnippet: `for range 2 { + ui.Row(c).Gap(24).Children(func() { + for range 4 { + ui.Column(c).Size(32, 32).Center().Children(func() { + ui.Spinner(c) + }) + } + }) +}`, PageSnippetZh: `for range 2 { + ui.Row(c).Gap(24).Children(func() { + for range 4 { + ui.Column(c).Size(32, 32).Center().Children(func() { + ui.Spinner(c) + }) + } + }) }`}, {ID: "sizes", Title: "约束尺寸", Description: "指示器在不同边界中居中并保持比例。", Snippet: `for index, side := range [...]float32{16, 32, 48} { box := ui.Slot(c).Size(side, side) canvas.RoundedBorder(box.Rect(), 5, 1, theme.Border, theme.Background) components.PaintSpinner(canvas, theme, box.Rect(), components.SpinnerPhase(index*2)) -}`}, +}`, PageSnippet: `ui.Row(c).Gap(40).Items(ui.Center).Children(func() { + for _, side := range [...]float32{16, 32, 48} { + ui.Column(c).Size(side, side).Center().Border(1, c.Theme().Border). + Radius(5).Children(func() { + ui.Spinner(c) + }) + } +})`, PageSnippetZh: `ui.Row(c).Gap(40).Items(ui.Center).Children(func() { + for _, side := range [...]float32{16, 32, 48} { + ui.Column(c).Size(side, side).Center().Border(1, c.Theme().Border). + Radius(5).Children(func() { + ui.Spinner(c) + }) + } +})`}, }, } diff --git a/internal/componentdemo/split_button.go b/internal/componentdemo/split_button.go index 27f4c6d3..a6126aac 100644 --- a/internal/componentdemo/split_button.go +++ b/internal/componentdemo/split_button.go @@ -25,15 +25,15 @@ var splitButtonComponent = Component{ }).Paint() primary, menu := result.Clicked()`, PageSnippet: `d := ui.SplitButton(c, ui.SplitButtonSpec{ - PrimaryID: saveID, MenuID: moreID, + PrimaryID: m.saveID, MenuID: m.moreID, Label: "Save", MenuLabel: "More save actions", Open: m.menuOpen, }) if id, ok := d.Chosen(); ok { switch id { - case saveID: + case m.saveID: m.saved++ - case moreID: + case m.moreID: m.menuOpen = !m.menuOpen } } @@ -46,15 +46,15 @@ if m.menuOpen { } ui.Text(c, status).Muted() ui.Wrap(c, "The primary and menu targets have separate keyboard focus and accessible names.").Muted()`, PageSnippetZh: `d := ui.SplitButton(c, ui.SplitButtonSpec{ - PrimaryID: saveID, MenuID: moreID, + PrimaryID: m.saveID, MenuID: m.moreID, Label: "保存", MenuLabel: "更多保存操作", Open: m.menuOpen, }) if id, ok := d.Chosen(); ok { switch id { - case saveID: + case m.saveID: m.saved++ - case moreID: + case m.moreID: m.menuOpen = !m.menuOpen } } diff --git a/internal/componentdemo/table.go b/internal/componentdemo/table.go index bd10cc57..6b34dfe1 100644 --- a/internal/componentdemo/table.go +++ b/internal/componentdemo/table.go @@ -22,6 +22,11 @@ table.Caption("Click any data row to see its interactive feedback.")`, PageSnipp {"Desktop build", "Processing", "¥ 860"}, {"Performance audit", "Unpaid", "¥ 1,280"}, } +columns := []style.TableColumn{ + {Width: 112, Alignment: style.TableAlignLeft}, + {Width: 88, Alignment: style.TableAlignCenter}, + {Width: 0, Alignment: style.TableAlignRight}, +} ui.Table(c, &m.table, ui.TableSpec{ Columns: columns, Headers: []string{"Item", "Status", "Amount"}, @@ -33,6 +38,11 @@ ui.Text(c, "Click any data row to see its interactive feedback.").Muted()`, Page {"桌面构建", "处理中", "¥ 860"}, {"性能审计", "待付款", "¥ 1,280"}, } +columns := []style.TableColumn{ + {Width: 112, Alignment: style.TableAlignLeft}, + {Width: 88, Alignment: style.TableAlignCenter}, + {Width: 0, Alignment: style.TableAlignRight}, +} ui.Table(c, &m.table, ui.TableSpec{ Columns: columns, Headers: []string{"项目", "状态", "金额"}, @@ -54,6 +64,11 @@ table.Footer([]string{"Total", "3 items", "¥ 4,540"})`, PageSnippet: `bills := {"Desktop build", "Processing", "¥ 860"}, {"Performance audit", "Unpaid", "¥ 1,280"}, } +columns := []style.TableColumn{ + {Width: 112, Alignment: style.TableAlignLeft}, + {Width: 88, Alignment: style.TableAlignCenter}, + {Width: 0, Alignment: style.TableAlignRight}, +} table := ui.Table(c, &m.table, ui.TableSpec{ Columns: columns, Headers: []string{"Item", "Status", "Amount"}, @@ -69,6 +84,11 @@ if row := m.table.Selected(); row >= 0 { {"桌面构建", "处理中", "¥ 860"}, {"性能审计", "待付款", "¥ 1,280"}, } +columns := []style.TableColumn{ + {Width: 112, Alignment: style.TableAlignLeft}, + {Width: 88, Alignment: style.TableAlignCenter}, + {Width: 0, Alignment: style.TableAlignRight}, +} table := ui.Table(c, &m.table, ui.TableSpec{ Columns: columns, Headers: []string{"项目", "状态", "金额"}, diff --git a/internal/componentdemo/tabs.go b/internal/componentdemo/tabs.go index f858bdbc..d0cad576 100644 --- a/internal/componentdemo/tabs.go +++ b/internal/componentdemo/tabs.go @@ -16,14 +16,50 @@ options := []components.TabOption{ {ID: tabs.At(1), Label: "Activity", Icon: activityIcon}, {ID: tabs.At(2), Label: "Settings", Icon: settingsIcon}, } -components.BeginTabs(canvas, theme, bounds, options, options[selected].ID).Paint()`, PageSnippet: ""}, +components.BeginTabs(canvas, theme, bounds, options, options[selected].ID).Paint()`, PageSnippet: `// The strip shares its width between the three tabs. +labels := []string{"Overview", "Activity", "Settings"} +stroke := func(commands ...gfx.PathCommand) gfx.Icon { + return gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: commands} +} +circle := []gfx.PathCommand{ + gfx.MoveTo(22, 12), gfx.CubicTo(22, 17.52, 17.52, 22, 12, 22), + gfx.CubicTo(6.48, 22, 2, 17.52, 2, 12), gfx.CubicTo(2, 6.48, 6.48, 2, 12, 2), + gfx.CubicTo(17.52, 2, 22, 6.48, 22, 12), gfx.ClosePath(), +} +info := stroke(append(circle, gfx.MoveTo(12, 16), gfx.LineTo(12, 12), gfx.MoveTo(12, 8), gfx.LineTo(12.01, 8))...) +activity := stroke(append(circle, gfx.MoveTo(12, 8), gfx.LineTo(12, 12), gfx.MoveTo(12, 16), gfx.LineTo(12.01, 16))...) +folder := stroke( + gfx.MoveTo(4, 20), gfx.LineTo(20, 20), gfx.CubicTo(21.1, 20, 22, 19.1, 22, 18), gfx.LineTo(22, 8), + gfx.CubicTo(22, 6.9, 21.1, 6, 20, 6), gfx.LineTo(12.1, 6), gfx.LineTo(10.5, 3.9), + gfx.CubicTo(10.1, 3.4, 9.6, 3.1, 9, 3.1), gfx.LineTo(4, 3.1), + gfx.CubicTo(2.9, 3.1, 2, 4, 2, 5.1), gfx.LineTo(2, 18), gfx.CubicTo(2, 19.1, 2.9, 20, 4, 20), gfx.ClosePath(), +) +icons := []gfx.Icon{info, activity, folder} +ui.Tabs(c, &m.tab, labels, nil).TabIcons(func(i int) gfx.Icon { return icons[i] })`, PageSnippetZh: `// 标签条在三个标签之间均分宽度。 +labels := []string{"概览", "活动", "设置"} +stroke := func(commands ...gfx.PathCommand) gfx.Icon { + return gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: commands} +} +circle := []gfx.PathCommand{ + gfx.MoveTo(22, 12), gfx.CubicTo(22, 17.52, 17.52, 22, 12, 22), + gfx.CubicTo(6.48, 22, 2, 17.52, 2, 12), gfx.CubicTo(2, 6.48, 6.48, 2, 12, 2), + gfx.CubicTo(17.52, 2, 22, 6.48, 22, 12), gfx.ClosePath(), +} +info := stroke(append(circle, gfx.MoveTo(12, 16), gfx.LineTo(12, 12), gfx.MoveTo(12, 8), gfx.LineTo(12.01, 8))...) +activity := stroke(append(circle, gfx.MoveTo(12, 8), gfx.LineTo(12, 12), gfx.MoveTo(12, 16), gfx.LineTo(12.01, 16))...) +folder := stroke( + gfx.MoveTo(4, 20), gfx.LineTo(20, 20), gfx.CubicTo(21.1, 20, 22, 19.1, 22, 18), gfx.LineTo(22, 8), + gfx.CubicTo(22, 6.9, 21.1, 6, 20, 6), gfx.LineTo(12.1, 6), gfx.LineTo(10.5, 3.9), + gfx.CubicTo(10.1, 3.4, 9.6, 3.1, 9, 3.1), gfx.LineTo(4, 3.1), + gfx.CubicTo(2.9, 3.1, 2, 4, 2, 5.1), gfx.LineTo(2, 18), gfx.CubicTo(2, 19.1, 2.9, 20, 4, 20), gfx.ClosePath(), +) +icons := []gfx.Icon{info, activity, folder} +ui.Tabs(c, &m.tab, labels, nil).TabIcons(func(i int) gfx.Icon { return icons[i] })`}, {ID: "default", Title: "分段标签", Description: "三个稳定 tab ID 驱动关联内容。", Snippet: `labels := []string{"Overview", "Activity", "Settings"} -tab := labels[0] -ui.Tabs(c, &tab, labels, nil) -ui.Text(c, tab).FontSize(c.Theme().Metrics.FontSizeM)`, PageSnippet: `labels := []string{"Overview", "Activity", "Settings"} -tab := labels[0] -ui.Tabs(c, &tab, labels, nil) -switch tab { +ui.Tabs(c, &m.tab, labels, nil) +ui.Text(c, m.tab).FontSize(c.Theme().Metrics.FontSizeM)`, PageSnippet: `labels := []string{"Overview", "Activity", "Settings"} +ui.Tabs(c, &m.tab, labels, nil) +switch m.tab { case "Overview": ui.Column(c).Gap(8).Children(func() { ui.Text(c, "Project overview") @@ -40,9 +76,8 @@ case "Settings": ui.Wrap(c, "Configure display and local runtime options.") }) }`, PageSnippetZh: `labels := []string{"概览", "活动", "设置"} -tab := labels[0] -ui.Tabs(c, &tab, labels, nil) -switch tab { +ui.Tabs(c, &m.tab, labels, nil) +switch m.tab { case "概览": ui.Column(c).Gap(8).Children(func() { ui.Text(c, "项目概览") @@ -60,16 +95,13 @@ case "设置": }) }`}, {ID: "line", Title: "线形标签", Description: "透明列表与两像素活动指示条。", Snippet: `labels := []string{"Overview", "Activity", "Settings"} -tab := labels[0] -ui.Tabs(c, &tab, labels, nil).Line()`, PageSnippet: `labels := []string{"Overview", "Activity", "Settings"} -tab := labels[0] -ui.Tabs(c, &tab, labels, nil).Line() +ui.Tabs(c, &m.tab, labels, nil).Line()`, PageSnippet: `labels := []string{"Overview", "Activity", "Settings"} +ui.Tabs(c, &m.tab, labels, nil).Line() ui.Column(c).Gap(8).Children(func() { ui.Text(c, "Project overview") ui.Wrap(c, "See recent status and key highlights.") })`, PageSnippetZh: `labels := []string{"概览", "活动", "设置"} -tab := labels[0] -ui.Tabs(c, &tab, labels, nil).Line() +ui.Tabs(c, &m.tab, labels, nil).Line() ui.Column(c).Gap(8).Children(func() { ui.Text(c, "项目概览") ui.Wrap(c, "查看近期状态与关键摘要。") @@ -78,7 +110,7 @@ ui.Column(c).Gap(8).Children(func() { tab := labels[0] ui.Row(c).Gap(20).Children(func() { ui.Tabs(c, &tab, labels, nil).Line().Vertical().Self(ui.Start) - ui.Text(c, tab).Grow(1).Basis(0) + ui.Text(c, m.tab).Grow(1).Basis(0) })`, PageSnippet: `labels := []string{"Overview", "Activity", "Settings"} tab := labels[0] ui.Row(c).Gap(20).Children(func() { @@ -146,29 +178,18 @@ func (state *State) keyTabs(event gfx.KeyEvent) gfx.EventResult { } func (state *State) paintTabs(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - labels := state.tabsLabels() - selected := int(state.values[0]) - if selected < 0 || selected >= len(labels) { - selected = 0 - } if state.exampleID == "icons" { - var slot ui.Box state.drawPage(canvas, theme, size, 540, state.Text("Tabs · 图标标签", "Tabs · Icon labels"), func(c ui.C) { - slot = ui.Slot(c).FillWidth().Height(36) - state.tabsPanel(c, theme, selected) + ui.Tabs(c, &state.values[0], tabsChoices[:], state.tabLabel).TabIcons(tabIcon) + state.tabsPanel(c, theme, int(state.values[0])) }) - options := [...]components.TabOption{{ID: tabsItem.At(0), Label: labels[0], Icon: infoIcon}, {ID: tabsItem.At(1), Label: labels[1], Icon: alertIcon}, {ID: tabsItem.At(2), Label: labels[2], Icon: folderIcon}} - components.BeginTabs(canvas, theme, slot.Rect(), options[:], options[selected].ID).Paint() - if index, ok := canvas.ClickedIn(tabsItem); ok { - state.values[0] = int32(index) - } return } state.drawPage(canvas, theme, size, 540, state.Text("Tabs · 内容切换", "Tabs · Content switching"), func(c ui.C) { if state.exampleID == "vertical" { ui.Row(c).Gap(20).Children(func() { ui.Tabs(c, &state.values[0], tabsChoices[:], state.tabLabel).Line().Vertical().Self(ui.Start) - state.tabsPanel(c, theme, selected).Grow(1).Basis(0) + state.tabsPanel(c, theme, int(state.values[0])).Grow(1).Basis(0) }) return } @@ -176,10 +197,20 @@ func (state *State) paintTabs(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size if state.exampleID == "line" { strip.Line() } - state.tabsPanel(c, theme, selected) + state.tabsPanel(c, theme, int(state.values[0])) }) } +func tabIcon(index int) gfx.Icon { + switch index { + case 1: + return alertIcon + case 2: + return folderIcon + } + return infoIcon +} + // tabsChoices are the tab indices ui.Tabs chooses among. var tabsChoices = [...]int32{0, 1, 2} diff --git a/internal/componentdemo/textarea.go b/internal/componentdemo/textarea.go index dc922122..e6864ad0 100644 --- a/internal/componentdemo/textarea.go +++ b/internal/componentdemo/textarea.go @@ -45,7 +45,9 @@ field := ui.Slot(c).Height(height) components.PaintTextarea(canvas, theme, field.Rect(), components.TextareaSnapshot{ ID: tree.ID(page, "notes"), Label: "Project description", Value: value, DisplayValue: value, Layout: layout, -})`, PageSnippet: ""}, +})`, PageSnippet: `notes := "Type more text and the box grows with it, then scrolls after five rows." +ui.TextArea(c, ¬es, "Project description", "").Height(120)`, PageSnippetZh: `notes := "输入更多文字,框会随内容长高,到五行时开始滚动。" +ui.TextArea(c, ¬es, "项目说明", "").Height(120)`}, {ID: "selection", Title: "选择与输入法", Description: "确定性展示选择区、插入点与组合文本下划线。", Snippet: `value := "Select this text\nComposition text" field := ui.Slot(c).Height(142) components.PaintTextarea(canvas, theme, field.Rect(), components.TextareaSnapshot{ @@ -53,7 +55,9 @@ components.PaintTextarea(canvas, theme, field.Rect(), components.TextareaSnapsho ReadOnly: true, Focused: true, ShowCaret: true, Caret: 16, SelectionStart: 0, SelectionEnd: 6, CompositionStart: 17, CompositionEnd: len(value), -})`, PageSnippet: ""}, +})`, PageSnippet: `text := "Select this text\nComposition text" +ui.TextArea(c, &text, "", "").Height(142)`, PageSnippetZh: `text := "选择这段文字\n输入法组合文本" +ui.TextArea(c, &text, "", "").Height(142)`}, {ID: "states", Title: "校验与禁用", Description: "错误、只读与禁用状态并列展示。", Snippet: `var invalid, readOnly ui.Box ui.Row(c).Gap(12).Children(func() { invalid = ui.Slot(c).Grow(1).Basis(0).Height(104) @@ -72,7 +76,21 @@ components.PaintTextarea(canvas, theme, readOnly.Rect(), components.TextareaSnap components.PaintTextarea(canvas, theme, disabled.Rect(), components.TextareaSnapshot{ ID: tree.ID(page, "disabled"), Label: "Disabled field", Disabled: true, Placeholder: "Currently unavailable", -})`, PageSnippet: ""}, +})`, PageSnippet: `tooShort := "Too short" +generated := "Generated by the system\nNot editable" +ui.Row(c).Gap(12).Children(func() { + ui.TextArea(c, &tooShort, "Invalid field", "").Height(104) + ui.TextArea(c, &generated, "Read-only field", "").Height(104) +}) +unavailable := "" +ui.TextArea(c, &unavailable, "Disabled field", "Currently unavailable").Height(72).Disabled(true)`, PageSnippetZh: `tooShort := "内容过短" +generated := "由系统生成\n不可编辑" +ui.Row(c).Gap(12).Children(func() { + ui.TextArea(c, &tooShort, "错误说明", "").Height(104) + ui.TextArea(c, &generated, "只读说明", "").Height(104) +}) +unavailable := "" +ui.TextArea(c, &unavailable, "禁用说明", "当前不可填写").Height(72).Disabled(true)`}, }, } diff --git a/internal/componentdemo/toast.go b/internal/componentdemo/toast.go index ad2fa0b8..7968b74a 100644 --- a/internal/componentdemo/toast.go +++ b/internal/componentdemo/toast.go @@ -20,6 +20,18 @@ if open { ActionLabel: "View", }) if canvas.Clicked(tree.ID(page, "dismiss")) { open = false } +}`, PageSnippet: `if ui.Button(c, "Save project").Clicked() { + m.toaster.ShowAction("Project saved", "Changes are safely written locally.", ui.ToastSuccess, "View") +} +ui.Toasts(c, &m.toaster) +if _, ok := m.toaster.Acted(); ok { + m.openSaved() +}`, PageSnippetZh: `if ui.Button(c, "保存项目").Clicked() { + m.toaster.ShowAction("项目已保存", "更改已安全写入本地。", ui.ToastSuccess, "查看") +} +ui.Toasts(c, &m.toaster) +if _, ok := m.toaster.Acted(); ok { + m.openSaved() }`}, {ID: "types", Title: "语义类型", Description: "通过点击操作在信息、警告和错误样式间切换。", Snippet: `types := [...]components.ToastType{ components.ToastInfo, components.ToastWarning, components.ToastError, @@ -33,7 +45,29 @@ components.PaintToast(canvas, theme, viewport, snapshot, components.ToastOptions Layer: 52, Scope: tree.ID(page, "toast"), DismissID: tree.ID(page, "dismiss"), ActionID: tree.ID(page, "action"), ActionLabel: "Switch", }) -if canvas.Clicked(tree.ID(page, "action")) { selected = (selected + 1) % len(types) }`}, +if canvas.Clicked(tree.ID(page, "action")) { selected = (selected + 1) % len(types) }`, PageSnippet: `if ui.Button(c, "Switch type").Clicked() { + switch m.toastType { + case 0: + m.toaster.Show("Update available", "Activate the action button to see the next semantic type.", ui.ToastInfo) + case 1: + m.toaster.Show("Low disk space", "Activate the action button to see the next semantic type.", ui.ToastWarning) + default: + m.toaster.Show("Build failed", "Activate the action button to see the next semantic type.", ui.ToastError) + } + m.toastType = (m.toastType + 1) % 3 +} +ui.Toasts(c, &m.toaster)`, PageSnippetZh: `if ui.Button(c, "切换类型").Clicked() { + switch m.toastType { + case 0: + m.toaster.Show("有可用更新", "激活操作按钮查看下一个语义类型。", ui.ToastInfo) + case 1: + m.toaster.Show("磁盘空间不足", "激活操作按钮查看下一个语义类型。", ui.ToastWarning) + default: + m.toaster.Show("构建失败", "激活操作按钮查看下一个语义类型。", ui.ToastError) + } + m.toastType = (m.toastType + 1) % 3 +} +ui.Toasts(c, &m.toaster)`}, {ID: "swipe", Title: "手势快照", Description: "仅展示调用方提供的横向位移;组件不解释手势。", Snippet: `snapshot := components.ToastSnapshot{ Title: "Download almost complete", Description: "The horizontal offset comes from the caller's snapshot.", Type: components.ToastInfo, SwipeX: -8, @@ -41,7 +75,9 @@ if canvas.Clicked(tree.ID(page, "action")) { selected = (selected + 1) % len(typ components.PaintToast(canvas, theme, viewport, snapshot, components.ToastOptions{ Layer: 52, Scope: tree.ID(page, "toast"), DismissID: tree.ID(page, "dismiss"), ActionID: tree.ID(page, "action"), ActionLabel: "Continue", -})`}, +})`, PageSnippet: `m.toaster.Show("Download almost complete", "The horizontal offset comes from the caller's snapshot.", ui.ToastInfo) +ui.Toasts(c, &m.toaster)`, PageSnippetZh: `m.toaster.Show("下载即将完成", "横向位移来自调用方提供的快照。", ui.ToastInfo) +ui.Toasts(c, &m.toaster)`}, }, } diff --git a/internal/componentdemo/toggle_group.go b/internal/componentdemo/toggle_group.go index 128d4b72..256d14f1 100644 --- a/internal/componentdemo/toggle_group.go +++ b/internal/componentdemo/toggle_group.go @@ -61,11 +61,11 @@ if id, ok := group.Paint().Clicked(); ok { }`, PageSnippet: `ui.Column(c).Gap(0).Children(func() { ui.Toggle(c, &m.left, "Left").Outline() ui.Toggle(c, &m.center, "Center").Outline() - ui.Toggle(c, &m.right, "Right").Outline() + ui.Toggle(c, &m.right, "Right").Outline().Disabled(true) })`, PageSnippetZh: `ui.Column(c).Gap(0).Children(func() { ui.Toggle(c, &m.left, "左对齐").Outline() ui.Toggle(c, &m.center, "居中").Outline() - ui.Toggle(c, &m.right, "右对齐").Outline() + ui.Toggle(c, &m.right, "右对齐").Outline().Disabled(true) })`}, }, } diff --git a/internal/componentdemo/tooltip.go b/internal/componentdemo/tooltip.go index 2f3dd36a..fea95c45 100644 --- a/internal/componentdemo/tooltip.go +++ b/internal/componentdemo/tooltip.go @@ -24,7 +24,7 @@ if open || canvas.Hovered() == trigger { TooltipOn(ui.TooltipTop)`, PageSnippetZh: `ui.Button(c, "悬停或点击"). Tooltip("原生同步提示,无后台延时器"). TooltipOn(ui.TooltipTop)`}, - {ID: "sides", Title: "四个方向", Description: "同屏展示上、右、下、左四种放置方向。", Snippet: `labels := [...]string{"Top", "Right", "Bottom", "Left"} + {ID: "sides", Title: "四个方向", Description: "同屏展示上、右、下、左四种放置方向。", Height: 340, Snippet: `labels := [...]string{"Top", "Right", "Bottom", "Left"} sides := [...]components.TooltipSide{ components.TooltipTop, components.TooltipRight, components.TooltipBottom, components.TooltipLeft, @@ -76,14 +76,15 @@ func (state *State) paintTooltip(canvas *gfx.Canvas, theme gfx.Theme, size gfx.S var anchors [4]ui.Box state.drawPage(canvas, theme, size, 520, state.Text("Tooltip · 同步浮层", "Tooltip · Synchronous overlay"), func(c ui.C) { if state.exampleID == "sides" { - // A cross: the anchor whose tip hangs below on top, the others in a row. - ui.Column(c).Gap(36).Items(ui.Center).Children(func() { - anchors[2] = ui.Slot(c).Size(56, theme.Metrics.ControlHeight) - ui.Row(c).Gap(48).Children(func() { - anchors[1] = ui.Slot(c).Size(56, theme.Metrics.ControlHeight) - anchors[0] = ui.Slot(c).Size(56, theme.Metrics.ControlHeight) - anchors[3] = ui.Slot(c).Size(56, theme.Metrics.ControlHeight) + // A cross with room between the anchors: each tooltip points away + // from the cross instead of over a neighbouring button. + ui.Column(c).Gap(44).Items(ui.Center).Children(func() { + anchors[0] = ui.Slot(c).Size(64, theme.Metrics.ControlHeight) + ui.Row(c).Gap(180).Children(func() { + anchors[3] = ui.Slot(c).Size(64, theme.Metrics.ControlHeight) + anchors[1] = ui.Slot(c).Size(64, theme.Metrics.ControlHeight) }) + anchors[2] = ui.Slot(c).Size(64, theme.Metrics.ControlHeight) }) return } @@ -104,8 +105,10 @@ func (state *State) paintTooltip(canvas *gfx.Canvas, theme gfx.Theme, size gfx.S } anchor := anchors[0].Rect() if state.exampleID == "clamped" { - // The point of this example is an anchor at the window's edge. - anchor.X, anchor.Width = size.Width-76, 60 + // The point of this example is an anchor at the window's edge; keep the + // trigger wide enough for its label and let the tooltip clamp itself. + anchor.Width = 128 + anchor.X = size.Width - anchor.Width - 12 } canvas.RoundedBorder(anchor, theme.Metrics.RadiusControl, 1, theme.Border, theme.Background) canvas.LabelCenter(state.Text("悬停或点击", "Hover or click"), anchor, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.Foreground}) diff --git a/internal/componentdemo/tree_navigation.go b/internal/componentdemo/tree_navigation.go index 9da9c5ad..cf279762 100644 --- a/internal/componentdemo/tree_navigation.go +++ b/internal/componentdemo/tree_navigation.go @@ -11,7 +11,7 @@ var treeNavigationComponent = Component{ Summary: "为应用管理的可见树行和展开状态提供键盘导航。", paint: (*State).paintTreeNavigation, key: (*State).keyTreeNavigation, Examples: []Example{ - {ID: "default", Title: "键盘导航", Description: "聚焦 Production 行。按 → 展开或进入第一个子项,按 ← 返回父项或收起当前分支。", Snippet: `next, action, handled := ui.NavigateTree(visible, current, event.Key, pageRows) + {ID: "default", Title: "键盘导航", Description: "聚焦 Production 行。按 → 展开或进入第一个子项,按 ← 返回父项或收起当前分支。", Snippet: `next, action, handled := ui.NavigateTree(visible, current, m.key, pageRows) if handled { switch action { case ui.TreeNavigationExpand: @@ -30,7 +30,7 @@ visible := items[:1] if m.expanded { visible = items[:] } -next, action, handled := ui.NavigateTree(visible, m.selected, event.Key, len(rows)) +next, action, handled := ui.NavigateTree(visible, m.selected, m.key, len(rows)) if handled { switch action { case ui.TreeNavigationExpand: @@ -49,7 +49,7 @@ visible := items[:1] if m.expanded { visible = items[:] } -next, action, handled := ui.NavigateTree(visible, m.selected, event.Key, len(rows)) +next, action, handled := ui.NavigateTree(visible, m.selected, m.key, len(rows)) if handled { switch action { case ui.TreeNavigationExpand: diff --git a/internal/componentdemo/typography.go b/internal/componentdemo/typography.go index 05cb040b..d88b59b4 100644 --- a/internal/componentdemo/typography.go +++ b/internal/componentdemo/typography.go @@ -18,15 +18,15 @@ components.Typography(canvas, theme, h1.Rect(), components.TypographyH1, "Headin components.Typography(canvas, theme, h2.Rect(), components.TypographyH2, "Heading 2") components.Typography(canvas, theme, h3.Rect(), components.TypographyH3, "Heading 3") components.Typography(canvas, theme, h4.Rect(), components.TypographyH4, "Heading 4")`, PageSnippet: `ui.Column(c).Gap(6).Children(func() { - ui.Text(c, "Heading 1").FontSize(theme.Metrics.FontSizeL * 1.5).Weight(gfx.WeightBold) - ui.Text(c, "Heading 2").FontSize(theme.Metrics.FontSizeL + 6).Weight(gfx.WeightSemibold) - ui.Text(c, "Heading 3").FontSize(theme.Metrics.FontSizeL).Weight(gfx.WeightSemibold) - ui.Text(c, "Heading 4").FontSize(theme.Metrics.FontSizeM + 7).Weight(gfx.WeightSemibold) + ui.Text(c, "Heading 1").FontSize(c.Theme().Metrics.FontSizeL * 1.5).Weight(gfx.WeightBold) + ui.Text(c, "Heading 2").FontSize(c.Theme().Metrics.FontSizeL + 6).Weight(gfx.WeightSemibold) + ui.Text(c, "Heading 3").FontSize(c.Theme().Metrics.FontSizeL).Weight(gfx.WeightSemibold) + ui.Text(c, "Heading 4").FontSize(c.Theme().Metrics.FontSizeM + 7).Weight(gfx.WeightSemibold) })`, PageSnippetZh: `ui.Column(c).Gap(6).Children(func() { - ui.Text(c, "一级标题").FontSize(theme.Metrics.FontSizeL * 1.5).Weight(gfx.WeightBold) - ui.Text(c, "二级标题").FontSize(theme.Metrics.FontSizeL + 6).Weight(gfx.WeightSemibold) - ui.Text(c, "三级标题").FontSize(theme.Metrics.FontSizeL).Weight(gfx.WeightSemibold) - ui.Text(c, "四级标题").FontSize(theme.Metrics.FontSizeM + 7).Weight(gfx.WeightSemibold) + ui.Text(c, "一级标题").FontSize(c.Theme().Metrics.FontSizeL * 1.5).Weight(gfx.WeightBold) + ui.Text(c, "二级标题").FontSize(c.Theme().Metrics.FontSizeL + 6).Weight(gfx.WeightSemibold) + ui.Text(c, "三级标题").FontSize(c.Theme().Metrics.FontSizeL).Weight(gfx.WeightSemibold) + ui.Text(c, "四级标题").FontSize(c.Theme().Metrics.FontSizeM + 7).Weight(gfx.WeightSemibold) })`}, {ID: "content", Title: "正文角色", Description: "段落、引导、大号与小号正文。", Snippet: `lead := ui.Slot(c).Height(32) body := ui.Slot(c).Height(28) @@ -41,22 +41,22 @@ components.Typography(canvas, theme, large.Rect(), components.Typography(canvas, theme, small.Rect(), components.TypographySmall, "Small · Compact labels and supporting copy")`, PageSnippet: `ui.Column(c).Gap(6).Children(func() { ui.Paragraph(c, "A complete type system for native desktop interfaces", 0). - FontSize(theme.Metrics.FontSizeM + 7).Muted() + FontSize(c.Theme().Metrics.FontSizeM + 7).Muted() ui.Paragraph(c, "Paragraph text uses the theme's font size and foreground color.", 0). - FontSize(theme.Metrics.FontSizeM + 3) + FontSize(c.Theme().Metrics.FontSizeM + 3) ui.Text(c, "Large · Key note"). - FontSize(theme.Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) + FontSize(c.Theme().Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) ui.Text(c, "Small · Compact labels and supporting copy"). - FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium) + FontSize(c.Theme().Metrics.FontSizeM).Weight(gfx.WeightMedium) })`, PageSnippetZh: `ui.Column(c).Gap(6).Children(func() { ui.Paragraph(c, "原生桌面界面的完整文字系统", 0). - FontSize(theme.Metrics.FontSizeM + 7).Muted() + FontSize(c.Theme().Metrics.FontSizeM + 7).Muted() ui.Paragraph(c, "段落文字使用主题字号与前景色。", 0). - FontSize(theme.Metrics.FontSizeM + 3) + FontSize(c.Theme().Metrics.FontSizeM + 3) ui.Text(c, "Large · 关键说明"). - FontSize(theme.Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) + FontSize(c.Theme().Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) ui.Text(c, "Small · 紧凑标签与辅助内容"). - FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium) + FontSize(c.Theme().Metrics.FontSizeM).Weight(gfx.WeightMedium) })`}, {ID: "muted", Title: "强调与弱化", Description: "正文、强调文字与弱化说明。", Snippet: `body := ui.Slot(c).Height(32) strong := ui.Slot(c).Height(30) @@ -68,18 +68,18 @@ components.Typography(canvas, theme, strong.Rect(), components.Typography(canvas, theme, note.Rect(), components.TypographyMuted, "Secondary notes use the theme's muted foreground.")`, PageSnippet: `ui.Column(c).Gap(6).Children(func() { ui.Paragraph(c, "Body copy stays clear, stable, and readable.", 0). - FontSize(theme.Metrics.FontSizeM + 3) + FontSize(c.Theme().Metrics.FontSizeM + 3) ui.Text(c, "Key results use a heavier weight."). - FontSize(theme.Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) + FontSize(c.Theme().Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) ui.Text(c, "Secondary notes use the theme's muted foreground."). - FontSize(theme.Metrics.FontSizeM).Muted() + FontSize(c.Theme().Metrics.FontSizeM).Muted() })`, PageSnippetZh: `ui.Column(c).Gap(6).Children(func() { ui.Paragraph(c, "正文保持清晰、稳定且可读。", 0). - FontSize(theme.Metrics.FontSizeM + 3) + FontSize(c.Theme().Metrics.FontSizeM + 3) ui.Text(c, "关键结果使用更高字重。"). - FontSize(theme.Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) + FontSize(c.Theme().Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) ui.Text(c, "次要说明使用主题的弱化前景色。"). - FontSize(theme.Metrics.FontSizeM).Muted() + FontSize(c.Theme().Metrics.FontSizeM).Muted() })`}, }, } diff --git a/internal/gallery/gallery_drive_test.go b/internal/gallery/gallery_drive_test.go index e96d8058..a3c0c737 100644 --- a/internal/gallery/gallery_drive_test.go +++ b/internal/gallery/gallery_drive_test.go @@ -96,6 +96,15 @@ func clickHit(t *testing.T, driver *app.Driver, hit gfx.Hit) { } } +// clickField clicks a text field near its top edge: a compound control may be +// as tall as its results, while its editable row sits at the top. +func clickField(t *testing.T, driver *app.Driver, hit gfx.Hit) { + t.Helper() + if err := driver.Click(hit.Bounds.X+hit.Bounds.Width/2, hit.Bounds.Y+min(hit.Bounds.Height/2, 8)); err != nil { + t.Fatalf("click %q: %v", hit.Label, err) + } +} + func countText(driver *app.Driver, value string) int { count := 0 for _, text := range driver.Snapshot().Texts { @@ -215,7 +224,7 @@ func TestEditingATextFieldGoesThroughTheNativeTextPath(t *testing.T) { if field.ID.IsZero() { t.Fatal("the input page has no editable field") } - clickHit(t, driver, field) + clickField(t, driver, field) if driver.Snapshot().Focused != field.ID { t.Fatalf("clicking the field focused %v, want %v", driver.Snapshot().Focused, field.ID) } @@ -429,7 +438,7 @@ func TestEveryEditableFieldAcceptsKeyboardInput(t *testing.T) { continue // below the fold; its siblings cover the component } editable[catalog[index].ID] = true - clickHit(t, driver, field) + clickField(t, driver, field) editor, ok := state.TextEditor(field.ID) if !ok { t.Fatalf("%s: %q looks editable but has no editor", catalog[index].ID, field.Label) @@ -615,7 +624,7 @@ func TestTextareaTakesMultilineInput(t *testing.T) { driver := newDriver(t, state) open(t, driver, "Textarea") field := fieldNamed(t, driver, "项目说明") - clickHit(t, driver, field) + clickField(t, driver, field) editor, _ := state.TextEditor(field.ID) if err := driver.Key(gfx.KeyEnter, 0); err != nil { t.Fatal(err) diff --git a/tools/docs/catalog_test.go b/tools/docs/catalog_test.go index f0015d7e..0b6a763e 100644 --- a/tools/docs/catalog_test.go +++ b/tools/docs/catalog_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "errors" + "go/ast" "go/parser" "go/token" "os" @@ -406,3 +407,233 @@ func TestPageSnippetsArePageLevel(t *testing.T) { } } } + +// TestEveryExampleCarriesLocalizedPageSnippet keeps the preview and the code +// under it in one language and one authoring model: a canvas-only snippet is +// not a page call, and an English snippet under a Chinese preview is not the +// same example. +func TestEveryExampleCarriesLocalizedPageSnippet(t *testing.T) { + for _, component := range componentdemo.Catalog() { + for _, example := range component.Examples { + if strings.TrimSpace(example.PageSnippet) == "" { + t.Errorf("%s/%s has no page snippet", component.ID, example.ID) + } + if strings.TrimSpace(example.PageSnippetZh) == "" { + t.Errorf("%s/%s has no Chinese page snippet", component.ID, example.ID) + } + } + } +} + +// TestPageUsageIsPageLevel parses every component-level PageUsage and rejects +// the canvas API, so the line above the examples is a real call site too. +func TestPageUsageIsPageLevel(t *testing.T) { + for _, component := range componentdemo.Catalog() { + usage := component.PageUsage + if usage == "" { + continue + } + if strings.Contains(usage, "components.") || strings.Contains(usage, "Begin") || strings.Contains(usage, "Paint(") { + t.Errorf("%s PageUsage uses the canvas API: %q", component.ID, usage) + } + source := "package snippet\nfunc example(c ui.C, m model) {\n" + usage + "\n}\n" + if _, err := parser.ParseFile(token.NewFileSet(), "usage.go", source, 0); err != nil { + t.Errorf("%s PageUsage does not parse: %v\n%s", component.ID, err, usage) + } + } +} + +// TestPageSnippetsHaveNoUndeclaredNames rejects a snippet that reads a name the +// page function does not declare. Model data must be written m.field, so the +// snippet shows where it comes from; a bare `highlight` or `desktop` is a +// canvas-side local that would not compile at a call site. +func TestPageSnippetsHaveNoUndeclaredNames(t *testing.T) { + packages := map[string]bool{ + "ui": true, "base": true, "gfx": true, "window": true, "text": true, + "style": true, "strings": true, "utf8": true, "time": true, "math": true, + "codeeditor": true, "chartview": true, "calendarview": true, + "carouselview": true, "multiselect": true, "hierarchypicker": true, + "markdownview": true, "columnresizeview": true, + "hovercardview": true, + "navigationmenuview": true, + "menubarview": true, + "commandview": true, + "messagescrollerview": true, + "messageview": true, + "attachmentview": true, + "avatarview": true, + "avatareditorview": true, "reordergridview": true, + } + builtin := map[string]bool{ + "bool": true, "byte": true, "complex64": true, "complex128": true, + "error": true, "float32": true, "float64": true, "int": true, "int8": true, + "int16": true, "int32": true, "int64": true, "rune": true, "string": true, + "uint": true, "uint8": true, "uint16": true, "uint32": true, "uint64": true, + "uintptr": true, "any": true, "comparable": true, + "true": true, "false": true, "nil": true, "iota": true, + "append": true, "cap": true, "clear": true, "close": true, "complex": true, + "copy": true, "delete": true, "imag": true, "len": true, "make": true, + "max": true, "min": true, "new": true, "panic": true, "print": true, + "println": true, "real": true, "recover": true, + } + for _, component := range componentdemo.Catalog() { + for _, example := range component.Examples { + for _, snippet := range []string{example.PageSnippet, example.PageSnippetZh} { + if snippet == "" { + continue + } + source := "package snippet\nfunc example(c ui.C, m model) {\n" + snippet + "\n}\n" + file, err := parser.ParseFile(token.NewFileSet(), "snippet.go", source, 0) + if err != nil { + continue // the parse test reports it + } + for _, ident := range file.Unresolved { + if packages[ident.Name] || builtin[ident.Name] || ident.Name == "model" { + continue + } + t.Errorf("%s/%s page snippet reads undeclared %q; write model data as m.%s", component.ID, example.ID, ident.Name, ident.Name) + } + } + } + } +} + +// TestPageSnippetsUseCallerNames rejects a snippet that reads a canvas-side +// local: the snippet is shown inside a page function, where `theme`, `canvas`, +// `bounds`, `stage`, `page` and `tree` are not defined. A page reads its theme +// through c.Theme(). +func TestPageSnippetsUseCallerNames(t *testing.T) { + forbidden := map[string]bool{"theme": true, "canvas": true, "bounds": true, "stage": true, "page": true, "tree": true} + for _, component := range componentdemo.Catalog() { + for _, example := range component.Examples { + for _, snippet := range []string{example.PageSnippet, example.PageSnippetZh} { + if snippet == "" { + continue + } + source := "package snippet\nfunc example() {\n" + snippet + "\n}\n" + file, err := parser.ParseFile(token.NewFileSet(), "snippet.go", source, 0) + if err != nil { + continue // the parse test reports it + } + for _, ident := range file.Unresolved { + if forbidden[ident.Name] { + t.Errorf("%s/%s page snippet uses the canvas-side name %q", component.ID, example.ID, ident.Name) + } + } + } + } + } +} + +// TestPageSnippetsNameRealAPIs rejects a snippet that calls a package function +// the package does not declare. It does not type-check arguments: a snippet +// leaves the application's model implicit, so its types are not known here. +func TestPageSnippetsNameRealAPIs(t *testing.T) { + root, err := findRoot() + if err != nil { + t.Fatal(err) + } + packages := map[string]map[string]bool{ + "ui": exports(t, filepath.Join(root, "ui")), + "base": exports(t, filepath.Join(root, "base")), + "components": exports(t, filepath.Join(root, "components")), + "gfx": exports(t, filepath.Join(root, "gfx")), + "window": exports(t, filepath.Join(root, "window")), + "text": exports(t, filepath.Join(root, "text")), + "codeeditor": exports(t, filepath.Join(root, "ui/codeeditor")), + "chartview": exports(t, filepath.Join(root, "ui/chartview")), + "calendarview": exports(t, filepath.Join(root, "ui/calendarview")), + "carouselview": exports(t, filepath.Join(root, "ui/carouselview")), + "multiselect": exports(t, filepath.Join(root, "ui/multiselect")), + "hierarchypicker": exports(t, filepath.Join(root, "ui/hierarchypicker")), + "markdownview": exports(t, filepath.Join(root, "ui/markdownview")), + "columnresizeview": exports(t, filepath.Join(root, "ui/columnresizeview")), + "avatareditorview": exports(t, filepath.Join(root, "ui/avatareditorview")), + "reordergridview": exports(t, filepath.Join(root, "ui/reordergridview")), + "avatarview": exports(t, filepath.Join(root, "ui/avatarview")), + "attachmentview": exports(t, filepath.Join(root, "ui/attachmentview")), + "messageview": exports(t, filepath.Join(root, "ui/messageview")), + "messagescrollerview": exports(t, filepath.Join(root, "ui/messagescrollerview")), + "commandview": exports(t, filepath.Join(root, "ui/commandview")), + "menubarview": exports(t, filepath.Join(root, "ui/menubarview")), + "navigationmenuview": exports(t, filepath.Join(root, "ui/navigationmenuview")), + "hovercardview": exports(t, filepath.Join(root, "ui/hovercardview")), + } + for _, component := range componentdemo.Catalog() { + for _, example := range component.Examples { + for _, snippet := range []string{example.PageSnippet, example.PageSnippetZh} { + if snippet == "" { + continue + } + source := "package snippet\nfunc example() {\n" + snippet + "\n}\n" + file, err := parser.ParseFile(token.NewFileSet(), "snippet.go", source, 0) + if err != nil { + continue // the parse test reports it + } + ast.Inspect(file, func(node ast.Node) bool { + selector, ok := node.(*ast.SelectorExpr) + if !ok { + return true + } + pkg, ok := selector.X.(*ast.Ident) + if !ok { + return true + } + names, ok := packages[pkg.Name] + if !ok { + return true // the model or a local value + } + if !names[selector.Sel.Name] { + t.Errorf("%s/%s page snippet calls %s.%s, which the package does not declare", component.ID, example.ID, pkg.Name, selector.Sel.Name) + } + return true + }) + } + } + } +} + +// exports is the exported top-level names of one package directory. +func exports(t *testing.T, dir string) map[string]bool { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + names := map[string]bool{} + set := token.NewFileSet() + for _, entry := range entries { + name := entry.Name() + if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + file, err := parser.ParseFile(set, filepath.Join(dir, name), nil, 0) + if err != nil { + t.Fatal(err) + } + for _, declaration := range file.Decls { + switch declaration := declaration.(type) { + case *ast.FuncDecl: + if declaration.Recv == nil && declaration.Name.IsExported() { + names[declaration.Name.Name] = true + } + case *ast.GenDecl: + for _, spec := range declaration.Specs { + switch spec := spec.(type) { + case *ast.TypeSpec: + if spec.Name.IsExported() { + names[spec.Name.Name] = true + } + case *ast.ValueSpec: + for _, ident := range spec.Names { + if ident.IsExported() { + names[ident.Name] = true + } + } + } + } + } + } + } + return names +} diff --git a/tools/docs/content.go b/tools/docs/content.go index ca71bf3f..5d714db2 100644 --- a/tools/docs/content.go +++ b/tools/docs/content.go @@ -7,13 +7,11 @@ func documentation() map[string]Page { for _, component := range componentdemo.Catalog() { pages[component.ID] = Page{Sections: []Section{ {ID: "usage", Title: "Source-owned usage", Text: "This preview calls the production Go component directly. Stable IDs, values and open state remain owned by the application; the component only paints and declares interaction semantics.", Items: []string{"Read the linked component source for every option and visual decision.", "Use the native command to verify system text, focus, accessibility and platform integration.", "The browser preview validates shared layout and scene behavior, not native performance."}}, - {ID: "verification", Title: "Verification boundary", Text: "The examples cover representative states supported by the current API. They do not imply that every desktop backend has completed hardware validation."}, }} } overrides := map[string]Page{ "list": {Sections: []Section{ {ID: "usage", Title: "Page-layer list", Text: "The examples call ui.List, the page layer's virtualized list: the application declares each row as an element, and the list owns virtualization, selection, the keyboard, typeahead, pinned section headings, drag-to-reorder and sideways scrolling. The model keeps the ListState, the selection and the rows' data. This control is not a component of the components package; its source is ui/list.go.", Items: []string{"Names, sizes and dates lie side by side; rows wider than the list scroll sideways with the horizontal wheel or the wheel with Shift.", "ListState.Header pins the heading of the section at the top until the next heading pushes it away.", "ListState.Selection adds Primary-click and Shift ranges to the choice, and ListState.Reorder reports rows dropped in a new place for the application to move."}}, - {ID: "verification", Title: "Verification boundary", Text: "The preview runs the same page in the browser's WebAssembly build. Native lists, text metrics and platform input must be checked with the native preview."}, }}, "button": {Sections: []Section{ {ID: "usage", Title: "Usage", Text: "ui.Button(c, label) declares a labeled hit region and paints a source-owned button. Clicked reports activation in the same declaration; key the row when it moves.", Items: []string{"Default, Secondary, Outline, Ghost, Destructive and Link share the same interaction model.", "Buttons measure their label by default; set Width to reserve a fixed size.", "XSmall, Small, Large and icon sizes are explicit options. Icon-only controls still need an accessible name."}}, diff --git a/tools/webcheck/fixture/main.go b/tools/webcheck/fixture/main.go index 3161a1a0..a09fc9c2 100644 --- a/tools/webcheck/fixture/main.go +++ b/tools/webcheck/fixture/main.go @@ -10,9 +10,9 @@ package main import ( "fmt" + "github.com/vivaui/viva/app" "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/internal/platform/web" "github.com/vivaui/viva/text" ) @@ -42,17 +42,20 @@ type fixture struct { func main() { page := &fixture{level: 20, editor: text.NewEditor("")} - _ = web.Run(web.Config{ - Title: "Viva web check", - Width: 640, - Height: 480, - Paint: page.paint, - OnPointer: page.pointer, - OnKey: page.key, - TextInput: web.EditorInputs(func(id gfx.ID) (*text.Editor, bool) { - return page.editor, id == editorID - }), - }) + var input app.TextInput + _ = app.RunCanvas(app.Config{ + Title: "Viva web check", + Width: 640, + Height: 480, + Paint: page.paint, OnPointer: page.pointer, OnKey: page.key, + TextInput: func(context app.TextInputContext) *app.TextInput { + if context.ID != editorID { + return nil + } + input = app.TextInput{Editor: page.editor} + return &input + }, + }, nil) } func (f *fixture) paint(canvas *gfx.Canvas, size gfx.Size) { diff --git a/ui/attachmentview/attachmentview.go b/ui/attachmentview/attachmentview.go new file mode 100644 index 00000000..bbd39d9a --- /dev/null +++ b/ui/attachmentview/attachmentview.go @@ -0,0 +1,396 @@ +// Package attachmentview is the opt-in page control for attachment cards and +// attachment groups of package components. A page declares a card with typed +// configuration methods and views it as a ui.Control: +// +// card := attachmentview.New() +// ... +// card.Reset().ID(m.fileID).Title("product-demo.mov").Meta(states[m.state]). +// File().Uploading(0.64) +// card.OnClick(m.nextState) +// card.View(c, "product-demo.mov").FillWidth() +// if card.Clicked() { +// m.state = (m.state + 1) % len(states) +// } +// +// group := attachmentview.NewGroup() +// group.Reset() +// group.Add().ID(m.removeIDs[0]).Title("release-notes.md").Meta("18 KB"). +// Small().Action(m.removeID, "Remove release-notes.md", icon, m.remove) +// group.View(c, "Attachments") +// +// The caller owns the title, meta line, kind, icon, state, progress, action +// identities and callbacks; the wrapper owns the control's handlers and draw +// function. A card or action with a zero identity stays inert, as in the +// component. Clicked and ClickedAction report a click after View, and OnClick +// and an action's callback run for it, so a page can either read the click or +// be called back. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an Attachment or Group in the model beside its data: its +// handlers and draw function are made once, and Reset keeps the action storage, +// so a warm paint allocates nothing. Do not copy one after it has been painted. +package attachmentview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Kind, State, Size and Orientation are the component's typed variants, named +// here so a page that declares an attachment reads through this package alone. +type ( + Kind = components.AttachmentKind + State = components.AttachmentState + Size = components.AttachmentSize + Orientation = components.AttachmentOrientation +) + +const ( + File Kind = components.AttachmentFile + Image Kind = components.AttachmentImage + + Done State = components.AttachmentDone + Idle State = components.AttachmentIdle + Uploading State = components.AttachmentUploading + Processing State = components.AttachmentProcessing + Error State = components.AttachmentError + + SizeDefault Size = components.AttachmentSizeDefault + SizeSmall Size = components.AttachmentSizeSmall + SizeExtraSmall Size = components.AttachmentSizeExtraSmall + + Horizontal Orientation = components.AttachmentHorizontal + Vertical Orientation = components.AttachmentVertical +) + +// maxActions is how many actions one attachment paints, the component's limit. +const maxActions = 3 + +// Action is one icon button of an attachment. An action with a zero ID is +// painted but inert, as in the component. +type Action struct { + ID gfx.ID + Label string + Icon gfx.Icon + OnClick func() +} + +// Attachment is one attachment's caller-owned data and its page control. +// Configure it with the chainable methods. Reset clears the values and actions +// so a page that reconfigures the card every paint starts from a clean card; +// the action storage is kept. +type Attachment struct { + id gfx.ID + title string + meta string + kind Kind + icon gfx.Icon + state State + progress float32 + size Size + orientation Orientation + disabled bool + actions []Action + onClick func() + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + clicked gfx.ID + hadClick bool +} + +// New returns an attachment with the default size, done state and no content. +func New() *Attachment { return new(Attachment) } + +// Reset clears the identity, content, state, progress, size, orientation and +// actions, returning the card to the default horizontal, done, full-size card. +// The action storage is kept so a reset followed by the same actions does not +// allocate. +func (a *Attachment) Reset() *Attachment { + a.resetValues() + return a +} + +func (a *Attachment) resetValues() { + a.id = gfx.ID{} + a.title = "" + a.meta = "" + a.kind = File + a.icon = gfx.Icon{} + a.state = Done + a.progress = 0 + a.size = SizeDefault + a.orientation = Horizontal + a.disabled = false + a.actions = a.actions[:0] + a.onClick = nil +} + +// ID is the caller's identity for the card's trigger. A zero ID paints static +// content; give the card an ID if it should be clickable or read with Clicked. +func (a *Attachment) ID(id gfx.ID) *Attachment { a.id = id; return a } + +// Title is the attachment's first line, truncated with an ellipsis when needed. +func (a *Attachment) Title(value string) *Attachment { a.title = value; return a } + +// Meta is the attachment's muted second line, such as a size or state summary. +func (a *Attachment) Meta(value string) *Attachment { a.meta = value; return a } + +// File selects the generic file media glyph. +func (a *Attachment) File() *Attachment { a.kind = File; return a } + +// Image selects the image media glyph. +func (a *Attachment) Image() *Attachment { a.kind = Image; return a } + +// Icon sets a caller-owned glyph painted instead of the kind's placeholder. +func (a *Attachment) Icon(icon gfx.Icon) *Attachment { a.icon = icon; return a } + +// State sets the typed transfer state. +func (a *Attachment) State(state State) *Attachment { a.state = state; return a } + +// Progress sets the fraction, 0 to 1, shown along an Uploading card's bottom +// edge. The zero value draws no bar. +func (a *Attachment) Progress(progress float32) *Attachment { a.progress = progress; return a } + +// Done marks the attachment complete. +func (a *Attachment) Done() *Attachment { a.state, a.progress = Done, 0; return a } + +// Idle marks the attachment idle, with its dashed outline. +func (a *Attachment) Idle() *Attachment { a.state, a.progress = Idle, 0; return a } + +// Uploading marks the attachment as uploading and sets its progress fraction. +func (a *Attachment) Uploading(progress float32) *Attachment { + a.state, a.progress = Uploading, progress + return a +} + +// Processing marks the attachment as processing, with no determinate progress. +func (a *Attachment) Processing() *Attachment { a.state, a.progress = Processing, 0; return a } + +// Failed marks the attachment as failed. +func (a *Attachment) Failed() *Attachment { a.state, a.progress = Error, 0; return a } + +// Small selects the small attachment size. +func (a *Attachment) Small() *Attachment { a.size = SizeSmall; return a } + +// ExtraSmall selects the extra-small attachment size. +func (a *Attachment) ExtraSmall() *Attachment { a.size = SizeExtraSmall; return a } + +// Vertical stacks the media above the text. The default is horizontal. +func (a *Attachment) Vertical() *Attachment { a.orientation = Vertical; return a } + +// Disabled paints the card inert without changing its transfer state. +func (a *Attachment) Disabled() *Attachment { a.disabled = true; return a } + +// Action adds an icon button. The component paints at most three per card; a +// zero id is painted but inert. The callback runs after the click is read. +func (a *Attachment) Action(id gfx.ID, label string, icon gfx.Icon, onClick func()) *Attachment { + a.actions = append(a.actions, Action{ID: id, Label: label, Icon: icon, OnClick: onClick}) + return a +} + +// OnClick sets the callback run when the card's own trigger is clicked. +func (a *Attachment) OnClick(fn func()) *Attachment { a.onClick = fn; return a } + +// View declares the attachment at c. label names the card for assistive +// technology. The box is the card's natural size; give it a wider box to let +// the card fill it. +// +// Declare the view on its own, not inside a Memo. +func (a *Attachment) View(c ui.C, label string) ui.Box { + if a == nil { + panic("attachmentview: View needs its Attachment") + } + a.prepare() + size := a.naturalSize(c.Canvas(), *c.Theme()) + return ui.Control(c, label, &a.handlers).Size(size.Width, size.Height).Draw(a.drawFn) +} + +// Clicked reports whether the paint just made delivered a click on the card's +// trigger. It is false in ordinary paints. Ask it after View. +func (a *Attachment) Clicked() bool { + return a.hadClick && !a.id.IsZero() && a.clicked == a.id +} + +// ClickedAction reports whether the paint just made delivered a click on the +// action with id. It is false in ordinary paints or when id is zero. +func (a *Attachment) ClickedAction(id gfx.ID) bool { + return a.hadClick && !id.IsZero() && a.clicked == id +} + +func (a *Attachment) prepare() { + if a.prepared { + return + } + a.prepared = true + a.handlers.Role = gfx.RoleGroup + a.drawFn = a.draw +} + +func (a *Attachment) draw(d *ui.DrawContext) { + a.clicked, a.hadClick = d.Canvas.ClickTarget() + a.component(d.Canvas, *d.Theme, a.id, d.Rect).Paint() + a.notify(a.clicked, a.hadClick) +} + +// naturalSize measures the card the component will paint, including its text, +// media and actions. +func (a *Attachment) naturalSize(canvas *gfx.Canvas, theme gfx.Theme) gfx.Size { + return a.component(canvas, theme, gfx.ID{}, gfx.Rect{}).Size() +} + +// component builds the component's declaration from the typed configuration. +func (a *Attachment) component(canvas *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx.Rect) components.Attachment { + card := components.BeginAttachment(canvas, theme, id, bounds, components.AttachmentData{ + Name: a.title, Description: a.meta, Kind: a.kind, Icon: a.icon, + State: a.state, Size: a.size, Orientation: a.orientation, Progress: a.progress, + }) + if a.disabled { + card = card.Disabled() + } + for index := 0; index < len(a.actions) && index < maxActions; index++ { + action := a.actions[index] + card = card.Action(components.AttachmentAction{ID: action.ID, Label: action.Label, Icon: action.Icon}) + } + return card +} + +// notify runs the callback of the card or action that was clicked. +func (a *Attachment) notify(clicked gfx.ID, hadClick bool) { + if !hadClick || clicked.IsZero() { + return + } + if clicked == a.id { + if a.onClick != nil { + a.onClick() + } + return + } + for index := range a.actions { + if a.actions[index].ID == clicked { + if a.actions[index].OnClick != nil { + a.actions[index].OnClick() + } + return + } + } +} + +// Group is one row of attachments and its page control. Configure the gap, +// Reset it, then Add the cards that apply now. +type Group struct { + gap float32 + gapSet bool + items []Attachment + clicked gfx.ID + hadClick bool + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool +} + +// NewGroup returns an empty attachment group with the component's default gap. +func NewGroup() *Group { return new(Group) } + +// Reset removes every card, keeping the layout configuration, the card storage +// and each card's action storage so a warm re-declaration allocates nothing. +func (g *Group) Reset() *Group { g.items = g.items[:0]; return g } + +// Gap sets the spacing between cards in pixels. The default is the component's +// scaled 12 pixels. +func (g *Group) Gap(pixels float32) *Group { + if pixels < 0 { + pixels = 0 + } + g.gap, g.gapSet = pixels, true + return g +} + +// Add appends a card and returns it for configuration. A reused card is reset; +// a new card starts as an empty default card. +func (g *Group) Add() *Attachment { + if len(g.items) == cap(g.items) { + g.items = append(g.items, Attachment{}) + } else { + g.items = g.items[:len(g.items)+1] + g.items[len(g.items)-1].resetValues() + } + return &g.items[len(g.items)-1] +} + +// View declares the group at c. label names the row for assistive technology. +// The box is as wide as the cards and gaps, and as tall as the tallest card +// plus the component's vertical padding. Cards that do not fit the box are not +// painted, as in the component's group; wrap the group or drop cards instead of +// letting them overflow. +// +// Declare the view on its own, not inside a Memo. +func (g *Group) View(c ui.C, label string) ui.Box { + if g == nil { + panic("attachmentview: View needs its Group") + } + g.prepare() + width, height := g.naturalSize(c.Canvas(), *c.Theme()) + return ui.Control(c, label, &g.handlers).Size(width, height).Draw(g.drawFn) +} + +// Clicked reports whether the paint just made delivered a click on the card or +// action with id. It is false in ordinary paints or when id is zero. +func (g *Group) Clicked(id gfx.ID) bool { + return g.hadClick && !id.IsZero() && g.clicked == id +} + +func (g *Group) prepare() { + if g.prepared { + return + } + g.prepared = true + g.handlers.Role = gfx.RoleGroup + g.drawFn = g.draw +} + +func (g *Group) draw(d *ui.DrawContext) { + g.clicked, g.hadClick = d.Canvas.ClickTarget() + theme := *d.Theme + group := components.BeginAttachmentGroup(theme, d.Rect) + for index := range g.items { + item := &g.items[index] + card := item.component(d.Canvas, theme, item.id, gfx.Rect{}) + if !group.Fits(card.Size()) { + break + } + card.PaintIn(&group) + } + if g.hadClick && !g.clicked.IsZero() { + for index := range g.items { + g.items[index].notify(g.clicked, true) + } + } +} + +func (g *Group) naturalSize(canvas *gfx.Canvas, theme gfx.Theme) (width, height float32) { + if len(g.items) == 0 { + return 0, 0 + } + gap := g.gapFor(theme) + pad := 4 * theme.Metrics.ControlHeight / 32 + for index := range g.items { + size := g.items[index].naturalSize(canvas, theme) + if index > 0 { + width += gap + } + width += size.Width + height = max(height, size.Height) + } + return width, height + pad*2 +} + +func (g *Group) gapFor(theme gfx.Theme) float32 { + if g.gapSet { + return g.gap + } + return 12 * theme.Metrics.ControlHeight / 32 +} diff --git a/ui/attachmentview/attachmentview_test.go b/ui/attachmentview/attachmentview_test.go new file mode 100644 index 00000000..cf108f2e --- /dev/null +++ b/ui/attachmentview/attachmentview_test.go @@ -0,0 +1,217 @@ +package attachmentview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/attachmentview" +) + +var ( + cardID = gfx.Item(71) + actionID = gfx.Item(72) + secondID = gfx.Item(73) + linkID = gfx.Item(74) + thirdID = gfx.Item(75) +) + +var testIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{ + gfx.MoveTo(4, 4), gfx.LineTo(20, 20), +}} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 320}, view) + canvas.EndFrame() +} + +func drawClick(page *ui.Page, canvas *gfx.Canvas, view func(ui.C), id gfx.ID) { + canvas.BeginEventPass(id, gfx.ClickInfo{}) + draw(page, canvas, view) + canvas.EndEventPass() +} + +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + hits := canvas.Hits() + for index := len(hits) - 1; index >= 0; index-- { + if hits[index].Label == label { + return hits[index] + } + } + t.Fatalf("no hit labelled %q was painted", label) + return gfx.Hit{} +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := new(gfx.Canvas) + draw(page, canvas, view) + return page, canvas +} + +type model struct { + card attachmentview.Attachment + group attachmentview.Group + cardClicks int + actionHits int + cardHit int + onCard func() + onAction func() +} + +func (m *model) init() { + m.onCard = func() { m.cardClicks++ } + m.onAction = func() { m.actionHits++ } +} + +func (m *model) configureCard() { + m.card.Reset().ID(cardID).Title("product-demo.mov").Meta("2.4 MB · Complete").File(). + OnClick(m.onCard) +} + +func (m *model) viewCard(c ui.C) { + m.configureCard() + m.card.View(c, "product-demo.mov") +} + +// The page declares a card, and the component paints its title, meta and +// trigger with the caller's identity inside the control. +func TestViewPaintsCardAndReportsClick(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.viewCard) + + trigger := hit(t, canvas, "product-demo.mov") + if trigger.ID != cardID || trigger.Role != gfx.RoleButton { + t.Fatalf("trigger = %+v, want the caller's button identity", trigger) + } + if !hasText(canvas, "2.4 MB · Complete") { + t.Fatal("the card's meta line was not painted") + } + + drawClick(page, canvas, m.viewCard, cardID) + if !m.card.Clicked() { + t.Fatal("Clicked did not report the clicked card") + } + if m.cardClicks != 1 { + t.Fatalf("OnClick ran %d times, want 1", m.cardClicks) + } + draw(page, canvas, m.viewCard) + if m.card.Clicked() { + t.Fatal("Clicked reported a click in an ordinary paint") + } +} + +// An action is a button above the card trigger, and its callback and +// ClickedAction both report the caller's action identity. +func TestActionPaintsAndCallsBack(t *testing.T) { + m := new(model) + m.init() + view := func(c ui.C) { + m.configureCard() + m.card.Action(actionID, "Remove report.pdf", testIcon, m.onAction) + m.card.View(c, "product-demo.mov") + } + page, canvas := open(t, view) + + action := hit(t, canvas, "Remove report.pdf") + if action.ID != actionID || action.Role != gfx.RoleButton { + t.Fatalf("action = %+v, want the caller's action button", action) + } + + drawClick(page, canvas, view, actionID) + if m.actionHits != 1 { + t.Fatalf("action callback ran %d times, want 1", m.actionHits) + } + if !m.card.ClickedAction(actionID) || m.card.Clicked() { + t.Fatal("ClickedAction did not isolate the fired action from the card") + } +} + +// A group paints a row of cards and routes each card and action identity. +func TestGroupPaintsCardsAndCallsBack(t *testing.T) { + m := new(model) + m.init() + view := func(c ui.C) { + m.group.Reset().Gap(12) + m.group.Add().ID(cardID).ExtraSmall().Title("notes.md").Meta("18 KB").File(). + Action(actionID, "Remove notes.md", testIcon, m.onAction) + m.group.Add().ID(secondID).ExtraSmall().Title("cover.png").Meta("18 KB").Image(). + Action(linkID, "Remove cover.png", testIcon, m.onAction) + m.group.View(c, "Attachments") + } + page, canvas := open(t, view) + + if len(hit(t, canvas, "Attachments").Label) == 0 { + t.Fatal("group control has no label") + } + first := hit(t, canvas, "notes.md") + second := hit(t, canvas, "cover.png") + if first.ID != cardID || second.ID != secondID { + t.Fatalf("group cards = %v, %v, want the caller's identities", first.ID, second.ID) + } + + drawClick(page, canvas, view, linkID) + if m.actionHits != 1 { + t.Fatalf("group action callback ran %d times, want 1", m.actionHits) + } + if !m.group.Clicked(linkID) || m.group.Clicked(cardID) { + t.Fatal("Clicked did not isolate the fired group action") + } +} + +func hasText(canvas *gfx.Canvas, value string) bool { + for _, text := range canvas.Texts() { + if text.Value == value { + return true + } + } + return false +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.init() + var group attachmentview.Group + view := func(c ui.C) { + m.configureCard() + m.card.Action(actionID, "Remove product-demo.mov", testIcon, m.onAction) + m.card.View(c, "product-demo.mov") + group.Reset().Gap(12) + group.Add().ID(secondID).ExtraSmall().Title("notes.md").Meta("18 KB").File(). + Action(linkID, "Remove notes.md", testIcon, m.onAction) + group.Add().ID(thirdID).ExtraSmall().Title("cover.png").Meta("18 KB").Image() + group.View(c, "Attachments") + } + page, canvas := open(t, view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := new(model) + m.init() + var group attachmentview.Group + view := func(c ui.C) { + m.configureCard() + m.card.Action(actionID, "Remove product-demo.mov", testIcon, m.onAction) + m.card.View(c, "product-demo.mov") + group.Reset().Gap(12) + group.Add().ID(secondID).ExtraSmall().Title("notes.md").Meta("18 KB").File(). + Action(linkID, "Remove notes.md", testIcon, m.onAction) + group.Add().ID(thirdID).ExtraSmall().Title("cover.png").Meta("18 KB").Image() + group.View(c, "Attachments") + } + page, canvas := open(b, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/avatareditorview/avatareditorview.go b/ui/avatareditorview/avatareditorview.go new file mode 100644 index 00000000..be8a52b1 --- /dev/null +++ b/ui/avatareditorview/avatareditorview.go @@ -0,0 +1,217 @@ +// Package avatareditorview is the opt-in page control for the avatar crop +// surface of package components. It wraps components.BeginAvatarEditor in a +// ui.Control, so a page declares the editor without calling the component: +// +// editor := &avatareditorview.Editor{ +// Bitmap: m.avatar, IDs: m.avatarIDs, State: m.crop, +// AspectRatio: 1, Circular: true, MaxStageSize: 320, +// } +// ... +// avatareditorview.View(c, "Avatar crop", editor).FillWidth().MaxWidth(360) +// m.crop = editor.State +// if layout := editor.Layout(); layout.Ready { +// m.avatar = export(layout.Crop) +// } +// +// The caller owns the image, the crop state and the identities; the wrapper +// owns the control's identity and input routing. It paints through the +// component with identities inside the control, so pointer, key and wheel +// events aimed at the preview or its controls reach the wrapper and update +// State. Clicked translates a click on one of the caller's identities back, and +// the optional callbacks receive the caller's targets rather than the control's +// internal part identities. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an Editor in the model, beside its image: its handlers +// and draw function are made once, so a warm paint allocates nothing. Do not +// copy an Editor after it has been painted. +package avatareditorview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// IDs, Labels, State and Layout are the component's types, named here so a page +// that declares an editor reads through this package alone. +type ( + IDs = components.AvatarEditorIDs + Labels = components.AvatarEditorLabels + State = components.AvatarEditorState + Layout = components.AvatarEditorLayout +) + +// Editor is one avatar editor's caller-owned image and crop state and its page +// control. Fill the fields from the model every paint; State is updated in +// place by View, by input and by the zoom and reset controls. +type Editor struct { + // Bitmap is the caller-owned image. Its dimensions define Crop's coordinates. + Bitmap gfx.Bitmap + // IDs are the caller's identities for the preview and controls. A zero ID + // omits that control. + IDs IDs + // State is the current zoom and center. Use the zero value for a new image or + // a reset. View writes it back after every paint and input event. + State State + // Labels localizes the accessible names and empty states. + Labels Labels + + // AspectRatio is width / height, defaulting to 1. + AspectRatio float32 + // MinZoom defaults to 1. MaxZoom defaults to 8 (or MinZoom, if larger). + MinZoom, MaxZoom float32 + // MaxStageSize caps the preview's longest edge, defaulting to 320. + MaxStageSize float32 + // Circular masks a square preview. + Circular bool + // Backdrop must match the containing surface's solid color when Circular. + Backdrop gfx.Color + // Loading or Error disables editing. Error takes precedence. + Loading bool + Error string + + // Pointer receives every pointer event aimed at the control, with a target + // that is one of IDs when the event came from one of the editor's parts. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Key receives the keys pressed while the control has the focus. + Key func(gfx.KeyEvent) gfx.EventResult + // Scroll receives the wheel over the control. + Scroll func(gfx.ScrollEvent) gfx.EventResult + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + layout Layout + ids IDs + clicked gfx.ID + hadClick bool +} + +// View declares the editor at c. label names the control for assistive +// technology. Give it a size; it is a ui.Control painted through the component. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, editor *Editor) ui.Box { + if editor == nil { + panic("avatareditorview: View needs its Editor") + } + editor.prepare() + return ui.Control(c, label, &editor.handlers).Draw(editor.drawFn) +} + +// View declares the editor at c without naming it separately, for a page that +// keeps the Editor in its model. +func (e *Editor) View(c ui.C, label string) ui.Box { + return View(c, label, e) +} + +// Layout is the frame painted last: the stage and the selected crop in bitmap +// pixels. It is zero until View has painted at least once. +func (e *Editor) Layout() Layout { return e.layout } + +// Clicked reports whether the paint just made was an event pass delivering a +// click on id, one of the caller's own identities. It is false in ordinary +// paints. Ask it after View, where the component's clicks have always been +// read. +func (e *Editor) Clicked(id gfx.ID) bool { + return e.hadClick && !id.IsZero() && e.caller(e.clicked) == id +} + +func (e *Editor) prepare() { + if e.prepared { + return + } + e.prepared = true + e.handlers.Pointer = e.pointer + e.handlers.Key = e.key + e.handlers.Scroll = e.scroll + e.drawFn = e.draw +} + +func (e *Editor) draw(d *ui.DrawContext) { + e.clicked, e.hadClick = d.Canvas.ClickTarget() + e.ids = e.remap() + options := components.AvatarEditorOptions{ + IDs: e.ids, Labels: e.Labels, Bitmap: e.Bitmap, State: e.State, + AspectRatio: e.AspectRatio, MinZoom: e.MinZoom, MaxZoom: e.MaxZoom, + MaxStageSize: e.MaxStageSize, Circular: e.Circular, Backdrop: e.Backdrop, + Loading: e.Loading, Error: e.Error, + } + e.layout = components.BeginAvatarEditor(d.Canvas, *d.Theme, d.Rect, options).Paint() + e.State = e.layout.State +} + +// remap gives each caller identity a stable identity inside the control, so the +// page routes its events to this control's handlers. A zero caller ID stays +// zero, which keeps that control omitted as the component expects. +func (e *Editor) remap() IDs { + parts := e.handlers.Parts() + part := func(caller gfx.ID, index int) gfx.ID { + if caller.IsZero() { + return gfx.ID{} + } + return parts.At(index) + } + return IDs{ + Canvas: part(e.IDs.Canvas, 0), + Zoom: part(e.IDs.Zoom, 1), + ZoomOut: part(e.IDs.ZoomOut, 2), + ZoomIn: part(e.IDs.ZoomIn, 3), + Reset: part(e.IDs.Reset, 4), + } +} + +// caller translates an identity inside the control back to the caller's own. +func (e *Editor) caller(part gfx.ID) gfx.ID { + if part.IsZero() { + return part + } + parts := e.handlers.Parts() + callers := [...]gfx.ID{e.IDs.Canvas, e.IDs.Zoom, e.IDs.ZoomOut, e.IDs.ZoomIn, e.IDs.Reset} + for index, caller := range callers { + if !caller.IsZero() && part == parts.At(index) { + return caller + } + } + return part +} + +func (e *Editor) pointer(event gfx.PointerEvent) gfx.EventResult { + var result gfx.EventResult + e.State, result = e.layout.Pointer(event, e.State) + if e.Pointer != nil { + event.Target = e.caller(event.Target) + result = mergeResult(result, e.Pointer(event)) + } + return result +} + +func (e *Editor) key(event gfx.KeyEvent) gfx.EventResult { + var result gfx.EventResult + e.State, result = e.layout.Key(event, e.State) + if e.Key != nil { + event.Target = e.caller(event.Target) + result = mergeResult(result, e.Key(event)) + } + return result +} + +func (e *Editor) scroll(event gfx.ScrollEvent) gfx.EventResult { + var result gfx.EventResult + e.State, result = e.layout.Scroll(event, e.State) + if e.Scroll != nil { + event.Target = e.caller(event.Target) + result = mergeResult(result, e.Scroll(event)) + } + return result +} + +// mergeResult keeps the wrapper's handling and repaint requests and adds the +// caller callback's. Focus is the control's: it stays on the identity inside +// the control so the page can deliver later keys. +func mergeResult(wrapper, callback gfx.EventResult) gfx.EventResult { + wrapper.Handled = wrapper.Handled || callback.Handled + wrapper.Repaint = wrapper.Repaint || callback.Repaint + return wrapper +} diff --git a/ui/avatareditorview/avatareditorview_test.go b/ui/avatareditorview/avatareditorview_test.go new file mode 100644 index 00000000..40bfe609 --- /dev/null +++ b/ui/avatareditorview/avatareditorview_test.go @@ -0,0 +1,234 @@ +package avatareditorview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/avatareditorview" +) + +var ( + testCanvas = gfx.Item(4) + testZoom = gfx.Item(5) + testZoomOut = gfx.Item(6) + testZoomIn = gfx.Item(7) + testReset = gfx.Item(8) +) + +func testIDs() avatareditorview.IDs { + return avatareditorview.IDs{ + Canvas: testCanvas, Zoom: testZoom, ZoomOut: testZoomOut, ZoomIn: testZoomIn, + Reset: testReset, + } +} + +func testBitmap() gfx.Bitmap { + const width, height = 160, 100 + pixels := make([]byte, width*height*4) + for index := 3; index < len(pixels); index += 4 { + pixels[index] = 255 + } + return gfx.Bitmap{Pix: pixels, Width: width, Height: height, Stride: width * 4, ID: 1, Version: 1} +} + +type model struct { + view avatareditorview.Editor + page *ui.Page + canvas *gfx.Canvas + target gfx.ID + keys int + scrolls int +} + +func (m *model) wire() { + m.view.Bitmap = testBitmap() + m.view.IDs = testIDs() + m.view.AspectRatio = 1 + m.view.Circular = true + m.view.Labels = avatareditorview.Labels{ + Hint: "Drag and zoom", Canvas: "Avatar crop", Zoom: "Zoom", + ZoomOut: "Zoom out", ZoomIn: "Zoom in", Reset: "Reset", + } + m.view.Pointer = func(event gfx.PointerEvent) gfx.EventResult { + m.target = event.Target + return gfx.EventResult{Handled: true, Repaint: true} + } + m.view.Key = func(event gfx.KeyEvent) gfx.EventResult { + m.keys++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } + m.view.Scroll = func(event gfx.ScrollEvent) gfx.EventResult { + m.scrolls++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } +} + +func (m *model) viewPage(c ui.C) { + avatareditorview.View(c, "Editor", &m.view).Size(360, 260) +} + +func (m *model) open(t testing.TB) { + t.Helper() + theme := gfx.LightTheme() + m.page = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: &theme}) + m.canvas = new(gfx.Canvas) + draw(m.page, m.canvas, m.viewPage) +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 400, Height: 320}, view) + canvas.EndFrame() +} + +func drawClick(page *ui.Page, canvas *gfx.Canvas, view func(ui.C), id gfx.ID) { + canvas.BeginEventPass(id, gfx.ClickInfo{}) + draw(page, canvas, view) + canvas.EndEventPass() +} + +func hitLabelled(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + if hits[i].Label == label && !hits[i].ID.IsZero() { + return hits[i], true + } + } + return gfx.Hit{}, false +} + +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + got, ok := hitLabelled(canvas, label) + if !ok { + t.Fatalf("no hit labelled %q was painted", label) + } + return got +} + +// The page declares the view, the component paints the caller's image and crop +// state, and the wrapper gives every control an identity inside the page's +// control so pointer, key and wheel events reach it. +func TestViewPaintsAndRoutesInput(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + + if layout := m.view.Layout(); !layout.Ready || layout.Crop.Width <= 0 || layout.Stage.Width <= 0 { + t.Fatalf("layout = %+v, want a ready crop and stage", layout) + } + canvas := hit(t, m.canvas, "Avatar crop") + if canvas.Role != gfx.RoleGroup { + t.Fatalf("canvas role = %v, want a group", canvas.Role) + } + if zoomIn := hit(t, m.canvas, "Zoom in"); zoomIn.ID.IsZero() { + t.Fatal("zoom in was painted without an identity") + } + + x := canvas.Bounds.X + canvas.Bounds.Width/2 + y := canvas.Bounds.Y + canvas.Bounds.Height/2 + if result := m.page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: canvas.ID, X: x, Y: y, + }); !result.Handled || !result.Repaint || m.target != testCanvas { + t.Fatalf("pointer down Target = %v (result %+v), want the caller's %v", m.target, result, testCanvas) + } + if result := m.page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerMove, Captured: true, Target: canvas.ID, X: x + 40, Y: y - 25, + }); !result.Handled || m.target != testCanvas { + t.Fatalf("pointer move Target = %v (result %+v)", m.target, result) + } + if m.view.State.CenterX == .5 && m.view.State.CenterY == .5 { + t.Fatalf("drag did not update the crop: %+v", m.view.State) + } + if result := m.page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerUp, Captured: true, Target: canvas.ID, X: x + 40, Y: y - 25, + }); !result.Handled { + t.Fatalf("pointer up result = %+v", result) + } + + before := m.view.State.Zoom + if result := m.page.Wheel(gfx.ScrollEvent{Target: canvas.ID, X: x, Y: y, DeltaY: -1}); !result.Handled || m.scrolls != 1 { + t.Fatalf("wheel result = %+v after %d calls", result, m.scrolls) + } + if m.view.State.Zoom <= before || m.target != testCanvas { + t.Fatalf("wheel did not zoom around the pointer: %+v target %v", m.view.State, m.target) + } + + if result := m.page.Key(gfx.KeyEvent{Key: gfx.KeyHome, Target: canvas.ID}); !result.Handled || m.keys != 1 { + t.Fatalf("key result = %+v after %d calls", result, m.keys) + } + if m.view.State.Zoom != 1 || m.view.State.CenterX != .5 || m.view.State.CenterY != .5 { + t.Fatalf("Home did not reset the crop: %+v", m.view.State) + } +} + +// A click on a caller identity is read with Clicked after View, and the zoom +// control keeps working. +func TestClickedTranslatesCallerIdentities(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + zoomIn := hit(t, m.canvas, "Zoom in") + drawClick(m.page, m.canvas, m.viewPage, zoomIn.ID) + if !m.view.Clicked(testZoomIn) { + t.Fatal("Clicked did not report the clicked zoom control") + } + if m.view.Clicked(testZoomOut) || m.view.Clicked(testReset) { + t.Fatal("Clicked reported an identity that was not clicked") + } + if m.view.State.Zoom <= 1 { + t.Fatalf("zoom click did not update the crop: %+v", m.view.State) + } + draw(m.page, m.canvas, m.viewPage) + if m.view.Clicked(testZoomIn) { + t.Fatal("Clicked reported a click in an ordinary paint") + } +} + +// A zero identity stays omitted: the control is neither painted nor focusable, +// while the other controls keep their behavior. +func TestZeroIdentityIsOmitted(t *testing.T) { + var view avatareditorview.Editor + view.Bitmap = testBitmap() + view.IDs = avatareditorview.IDs{Canvas: testCanvas, ZoomIn: testZoomIn} + view.Labels = avatareditorview.Labels{Canvas: "Avatar crop", Reset: "Reset"} + viewPage := func(c ui.C) { avatareditorview.View(c, "Editor", &view).Size(360, 260) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: viewPage, Theme: &theme}) + canvas := new(gfx.Canvas) + draw(page, canvas, viewPage) + hit(t, canvas, "Avatar crop") + hit(t, canvas, "Zoom in") + if _, ok := hitLabelled(canvas, "Reset"); ok { + t.Fatal("a control with the zero identity was painted") + } + if _, ok := hitLabelled(canvas, "Zoom out"); ok { + t.Fatal("an omitted zoom control was painted") + } +} + +// A warm repaint allocates nothing: the wrapper keeps its handlers and draw +// function and the component keeps its own caches. +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + if allocations := testing.AllocsPerRun(100, func() { draw(m.page, m.canvas, m.viewPage) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := new(model) + m.wire() + m.open(b) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + draw(m.page, m.canvas, m.viewPage) + } +} diff --git a/ui/avatarview/avatarview.go b/ui/avatarview/avatarview.go new file mode 100644 index 00000000..1d1a7131 --- /dev/null +++ b/ui/avatarview/avatarview.go @@ -0,0 +1,384 @@ +// Package avatarview is the opt-in page control for avatars and overlapping +// avatar groups of package components. A page declares an avatar with typed +// configuration methods and views it as a ui.Control: +// +// avatar := avatarview.New() +// ... +// avatar.Initials("SK").Name("Skyler").Tint(theme.Primary).Diameter(64).Online() +// avatar.View(c, "Skyler").Size(64, 64) +// +// group := avatarview.NewGroup() +// group.Diameter(40).Overlap(8) +// group.Add().Initials("AD").Name("Ada").Tint(theme.Primary).Online() +// group.AddCount("+8") +// group.View(c, "Collaborators") +// +// The caller owns the image, initials, size, status and group overlap; the +// wrapper owns the control's handlers and draw function. It paints through the +// component with the caller's values. There is no hidden image loading: the +// picture is a bitmap the caller decoded, and an empty image falls back to +// initials or the component's geometric fallback. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an Avatar or Group in the model beside its data: its +// handlers and draw function are made once, so a warm paint allocates nothing. +// Do not copy one after it has been painted. +package avatarview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Size and Status are the component's typed variants, named here so a page +// that declares an avatar reads through this package alone. +type ( + Size = components.AvatarSize + Status = components.AvatarStatus +) + +const ( + SizeDefault Size = components.AvatarSizeDefault + SizeSmall Size = components.AvatarSizeSmall + SizeLarge Size = components.AvatarSizeLarge + + StatusNone Status = components.AvatarStatusNone + StatusOnline Status = components.AvatarStatusOnline + StatusBusy Status = components.AvatarStatusBusy + StatusOffline Status = components.AvatarStatusOffline +) + +// Avatar is one avatar's caller-owned values and page control. Configure it +// with the chainable methods, then view it. Reset clears the values so a page +// that reconfigures the avatar every paint does not keep a stale image or +// initials. +type Avatar struct { + bitmap gfx.Bitmap + initials string + name string + tint gfx.Color + size Size + diameter float32 + status Status + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool +} + +// New returns an avatar with the default size and no image, initials or status. +func New() *Avatar { return new(Avatar) } + +// Reset clears the image, initials, name, tint, status and explicit diameter, +// returning the avatar to the default size. Call it at the start of a paint that +// reconfigures the avatar, then set the values that apply now. +func (a *Avatar) Reset() *Avatar { + a.bitmap = gfx.Bitmap{} + a.initials = "" + a.name = "" + a.tint = gfx.Color{} + a.size = SizeDefault + a.diameter = 0 + a.status = StatusNone + return a +} + +// Image sets the caller-decoded picture, center-cropped to a circle. It takes +// precedence over initials when it has pixels. +func (a *Avatar) Image(bitmap gfx.Bitmap) *Avatar { a.bitmap = bitmap; return a } + +// Initials sets the fallback text painted when Image is empty. +func (a *Avatar) Initials(value string) *Avatar { a.initials = value; return a } + +// Name is the accessible name of the avatar; it is not painted. +func (a *Avatar) Name(value string) *Avatar { a.name = value; return a } + +// Tint fills an initials or geometric fallback. The zero value uses the theme's +// muted surface, like an untinted Avatar. +func (a *Avatar) Tint(color gfx.Color) *Avatar { a.tint = color; return a } + +// Size selects the component's small, default or large variant: 24, 32 or 40 +// pixels. It clears any explicit Diameter. +func (a *Avatar) Size(size Size) *Avatar { a.size, a.diameter = size, 0; return a } + +// Diameter sets an explicit circle diameter in pixels, overriding Size. The +// small or large text and status-dot variant is chosen from the diameter. +func (a *Avatar) Diameter(pixels float32) *Avatar { + if pixels < 0 { + pixels = 0 + } + a.diameter = pixels + return a +} + +// Status sets the typed status dot: online, busy, offline or none. +func (a *Avatar) Status(status Status) *Avatar { a.status = status; return a } + +// Online shows the success status dot. +func (a *Avatar) Online() *Avatar { a.status = StatusOnline; return a } + +// Busy shows the danger status dot. +func (a *Avatar) Busy() *Avatar { a.status = StatusBusy; return a } + +// Offline shows the muted status dot. +func (a *Avatar) Offline() *Avatar { a.status = StatusOffline; return a } + +// View declares the avatar at c. label names it for assistive technology. The +// box is exactly the avatar's diameter square. +// +// Declare the view on its own, not inside a Memo. +func (a *Avatar) View(c ui.C, label string) ui.Box { + if a == nil { + panic("avatarview: View needs its Avatar") + } + a.prepare() + side := a.dimension() + return ui.Control(c, label, &a.handlers).Size(side, side).Draw(a.drawFn) +} + +func (a *Avatar) prepare() { + if a.prepared { + return + } + a.prepared = true + a.handlers.Role = gfx.RoleGroup + a.drawFn = a.draw +} + +func (a *Avatar) draw(d *ui.DrawContext) { + components.Avatar(d.Canvas, *d.Theme, d.Rect, components.AvatarData{ + Name: a.name, Initials: a.initials, Image: a.bitmap, Tint: a.tint, + Status: a.status, Size: a.variant(), + }) +} + +func (a *Avatar) dimension() float32 { + if a.diameter > 0 { + return a.diameter + } + return sizePixels(a.size) +} + +func (a *Avatar) variant() Size { + if a.diameter > 0 { + return variantForPixels(a.diameter) + } + return a.size +} + +// Member is one avatar of a Group. Configure it with the chainable methods; the +// group paints it in the order it was added. +type Member struct { + bitmap gfx.Bitmap + initials string + name string + tint gfx.Color + status Status + label string + count bool +} + +// Image sets the member's picture. +func (m *Member) Image(bitmap gfx.Bitmap) *Member { m.bitmap = bitmap; return m } + +// Initials sets the member's fallback text. +func (m *Member) Initials(value string) *Member { m.initials = value; return m } + +// Name is the member's accessible name; it is not painted. +func (m *Member) Name(value string) *Member { m.name = value; return m } + +// Tint fills the member's fallback. +func (m *Member) Tint(color gfx.Color) *Member { m.tint = color; return m } + +// Status sets the member's status dot. +func (m *Member) Status(status Status) *Member { m.status = status; return m } + +// Online shows the member's success status dot. +func (m *Member) Online() *Member { m.status = StatusOnline; return m } + +// Busy shows the member's danger status dot. +func (m *Member) Busy() *Member { m.status = StatusBusy; return m } + +// Offline shows the member's muted status dot. +func (m *Member) Offline() *Member { m.status = StatusOffline; return m } + +// Group is one overlapping row of avatars and its page control. Configure the +// diameter and overlap, Reset it, then Add the members that apply now. +type Group struct { + size Size + diameter float32 + overlap float32 + overlapSet bool + members []Member + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool +} + +// NewGroup returns an empty avatar group with the default size and the official +// 8 pixel overlap. +func NewGroup() *Group { return new(Group) } + +// Reset removes every member, keeping the size and overlap configuration and +// the member storage so a warm re-declaration allocates nothing. +func (g *Group) Reset() *Group { g.members = g.members[:0]; return g } + +// Size selects the component's size variant for every member and clears any +// explicit Diameter. +func (g *Group) Size(size Size) *Group { g.size, g.diameter = size, 0; return g } + +// Diameter sets an explicit member diameter in pixels, overriding Size. +func (g *Group) Diameter(pixels float32) *Group { + if pixels < 0 { + pixels = 0 + } + g.diameter = pixels + return g +} + +// Overlap sets how many pixels each member overlaps the one before it. The +// default is the official 8 pixels; 0 spaces the members edge to edge. Values +// are clamped to the member diameter. +func (g *Group) Overlap(pixels float32) *Group { + if pixels < 0 { + pixels = 0 + } + g.overlap, g.overlapSet = pixels, true + return g +} + +// Add appends a member and returns it for configuration. +func (g *Group) Add() *Member { + if len(g.members) == cap(g.members) { + g.members = append(g.members, Member{}) + } else { + g.members = g.members[:len(g.members)+1] + g.members[len(g.members)-1] = Member{} + } + return &g.members[len(g.members)-1] +} + +// AddCount appends the muted group-count fallback, such as "+8". +func (g *Group) AddCount(label string) *Group { + if len(g.members) == cap(g.members) { + g.members = append(g.members, Member{}) + } else { + g.members = g.members[:len(g.members)+1] + g.members[len(g.members)-1] = Member{} + } + member := &g.members[len(g.members)-1] + member.label, member.count = label, true + return g +} + +// View declares the group at c. label names the row for assistive technology. +// The box is as wide as the overlapping members and as tall as one member. +// +// Declare the view on its own, not inside a Memo. +func (g *Group) View(c ui.C, label string) ui.Box { + if g == nil { + panic("avatarview: View needs its Group") + } + g.prepare() + side := g.dimension() + width := float32(0) + if len(g.members) > 0 { + width = side + float32(len(g.members)-1)*g.step() + } + return ui.Control(c, label, &g.handlers).Size(width, side).Draw(g.drawFn) +} + +func (g *Group) prepare() { + if g.prepared { + return + } + g.prepared = true + g.handlers.Role = gfx.RoleGroup + g.drawFn = g.draw +} + +func (g *Group) draw(d *ui.DrawContext) { + theme := *d.Theme + side := g.dimension() + step := g.step() + kind := g.variant() + x := d.Rect.X + for index := range g.members { + member := &g.members[index] + bounds := gfx.Rect{X: x, Y: d.Rect.Y, Width: side, Height: side} + ring := gfx.Rect{X: bounds.X - 2, Y: bounds.Y - 2, Width: side + 4, Height: side + 4} + d.Canvas.Rounded(ring, ring.Width/2, theme.Background) + if member.count { + d.Canvas.Rounded(bounds, side/2, theme.Muted) + d.Canvas.LabelCenter(member.label, bounds, gfx.TextStyle{ + Size: fontSize(theme.Metrics, kind), Color: theme.MutedForeground, + }) + } else { + components.Avatar(d.Canvas, theme, bounds, components.AvatarData{ + Name: member.name, Initials: member.initials, Image: member.bitmap, + Tint: member.tint, Status: member.status, Size: kind, + }) + } + x += step + } +} + +func (g *Group) dimension() float32 { + if g.diameter > 0 { + return g.diameter + } + return sizePixels(g.size) +} + +func (g *Group) variant() Size { + if g.diameter > 0 { + return variantForPixels(g.diameter) + } + return g.size +} + +// step is the horizontal advance from one member to the next. +func (g *Group) step() float32 { + side := g.dimension() + overlap := float32(8) + if g.overlapSet { + overlap = g.overlap + } + if overlap > side { + overlap = side + } + return side - overlap +} + +func sizePixels(size Size) float32 { + switch size { + case SizeSmall: + return 24 + case SizeLarge: + return 40 + default: + return 32 + } +} + +func variantForPixels(pixels float32) Size { + switch { + case pixels <= 24: + return SizeSmall + case pixels >= 40: + return SizeLarge + default: + return SizeDefault + } +} + +// fontSize is the component's text-sm for default and large avatars and +// text-xs for small ones, mapped onto the theme's body and caption sizes. +func fontSize(metrics gfx.Metrics, size Size) float32 { + if size == SizeSmall { + return metrics.FontSizeS + } + return metrics.FontSizeM +} diff --git a/ui/avatarview/avatarview_test.go b/ui/avatarview/avatarview_test.go new file mode 100644 index 00000000..40e94c9a --- /dev/null +++ b/ui/avatarview/avatarview_test.go @@ -0,0 +1,179 @@ +package avatarview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/avatarview" +) + +var testPhoto = func() gfx.Bitmap { + pix := make([]byte, 4*4*4) + for index := range pix { + pix[index] = byte(index * 7) + } + return gfx.Bitmap{Pix: pix, Width: 4, Height: 4, Stride: 16, ID: 1, Version: 1} +}() + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 260}, view) + canvas.EndFrame() +} + +// hit returns the front-most hit with the label. +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + hits := canvas.Hits() + for index := len(hits) - 1; index >= 0; index-- { + if hits[index].Label == label { + return hits[index] + } + } + t.Fatalf("no hit labelled %q was painted", label) + return gfx.Hit{} +} + +func hasText(canvas *gfx.Canvas, value string) bool { + for _, text := range canvas.Texts() { + if text.Value == value { + return true + } + } + return false +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := new(gfx.Canvas) + draw(page, canvas, view) + return page, canvas +} + +// The page declares an avatar, and the component paints the caller's initials, +// status and exact diameter inside the control's square. +func TestViewPaintsConfiguredAvatar(t *testing.T) { + var avatar avatarview.Avatar + theme := gfx.LightTheme() + view := func(c ui.C) { + avatar.Reset().Initials("SK").Name("Skyler").Tint(theme.Primary).Diameter(64).Online() + avatar.View(c, "Skyler").Size(64, 64) + } + _, canvas := open(t, view) + + control := hit(t, canvas, "Skyler") + if control.Role != gfx.RoleGroup { + t.Fatalf("control role = %v, want a group", control.Role) + } + if control.Bounds.Width != 64 || control.Bounds.Height != 64 { + t.Fatalf("control bounds = %v, want 64x64", control.Bounds) + } + if !hasText(canvas, "SK") { + t.Fatal("the avatar's initials were not painted") + } +} + +// An image avatar paints the caller's bitmap and does not paint the initials. +func TestImageAvatarPaintsBitmap(t *testing.T) { + var avatar avatarview.Avatar + view := func(c ui.C) { + avatar.Reset().Image(testPhoto).Initials("NO").Diameter(40) + avatar.View(c, "Photo").Size(40, 40) + } + _, canvas := open(t, view) + if len(canvas.Images()) == 0 { + t.Fatal("the image avatar painted no bitmap") + } + if hasText(canvas, "NO") { + t.Fatal("the image avatar painted its initials over the image") + } +} + +// A group advances by the caller's overlap and paints every member and the +// count fallback in the control's box. +func TestGroupPaintsMembersAtTheCallerOverlap(t *testing.T) { + var group avatarview.Group + theme := gfx.LightTheme() + view := func(c ui.C) { + group.Reset().Diameter(40).Overlap(8) + group.Add().Initials("AD").Name("Ada").Tint(theme.Primary).Online() + group.Add().Initials("BO").Name("Bo") + group.Add().Initials("CH").Name("Chen") + group.AddCount("+8") + group.View(c, "Collaborators") + } + _, canvas := open(t, view) + + control := hit(t, canvas, "Collaborators") + // Four members, each advancing 32 pixels after the first 40 pixel avatar. + if control.Bounds.Width != 40+3*32 || control.Bounds.Height != 40 { + t.Fatalf("group bounds = %v, want %v", control.Bounds, gfx.Rect{Width: 136, Height: 40}) + } + for _, label := range []string{"AD", "BO", "CH", "+8"} { + if !hasText(canvas, label) { + t.Fatalf("group did not paint %q", label) + } + } +} + +// Overlap is a caller choice: zero spaces the members edge to edge. +func TestGroupOverlapChangesTheExtent(t *testing.T) { + var group avatarview.Group + view := func(c ui.C) { + group.Reset().Diameter(40).Overlap(0) + group.Add().Initials("A") + group.Add().Initials("B") + group.Add().Initials("C") + group.View(c, "Collaborators") + } + _, canvas := open(t, view) + if control := hit(t, canvas, "Collaborators"); control.Bounds.Width != 120 { + t.Fatalf("group width = %v, want 120 at zero overlap", control.Bounds.Width) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + var avatar avatarview.Avatar + var group avatarview.Group + theme := gfx.LightTheme() + view := func(c ui.C) { + avatar.Reset().Initials("SK").Name("Skyler").Tint(theme.Primary).Diameter(64).Online() + avatar.View(c, "Skyler").Size(64, 64) + group.Reset().Diameter(40).Overlap(8) + group.Add().Initials("AD").Name("Ada").Online() + group.Add().Initials("BO").Name("Bo") + group.Add().Image(testPhoto).Name("Photo") + group.AddCount("+8") + group.View(c, "Collaborators") + } + page, canvas := open(t, view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + var avatar avatarview.Avatar + var group avatarview.Group + theme := gfx.LightTheme() + view := func(c ui.C) { + avatar.Reset().Initials("SK").Name("Skyler").Tint(theme.Primary).Diameter(64).Online() + avatar.View(c, "Skyler").Size(64, 64) + group.Reset().Diameter(40).Overlap(8) + group.Add().Initials("AD").Name("Ada").Online() + group.Add().Initials("BO").Name("Bo") + group.Add().Image(testPhoto).Name("Photo") + group.AddCount("+8") + group.View(c, "Collaborators") + } + page, canvas := open(b, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/base_parity_test.go b/ui/base_parity_test.go index c2c292ee..d7c70a8c 100644 --- a/ui/base_parity_test.go +++ b/ui/base_parity_test.go @@ -110,6 +110,26 @@ func TestStyledControlsDeclareWhatTheirBasesDeclare(t *testing.T) { } }) + for _, state := range []struct { + Name string + open bool + disabled bool + }{{"closed", false, false}, {"open", true, false}, {"disabled", false, true}} { + styled := ui.CollapsibleState{Open: state.open, Disabled: state.disabled} + base := ui.CollapsibleState{Open: state.open, Disabled: state.disabled} + t.Run("collapsible/"+state.Name, func(t *testing.T) { + styledHits := declared(t, page(func(c ui.C) { + ui.Collapsible(c, &styled, "Details", func() {}) + })) + baseHits := declared(t, page(func(c ui.C) { + ui.DisclosureBase(c, &base.Open, "Details").Disabled(base.Disabled).Size(120, 30) + })) + if fmt.Sprint(styledHits) != fmt.Sprint(baseHits) { + t.Fatalf("the collapsible and its Base declare different semantics\n styled: %+v\n base: %+v", styledHits, baseHits) + } + }) + } + t.Run("text field", func(t *testing.T) { var a, b string styled := declared(t, page(func(c ui.C) { ui.TextField(c, &a, "Name", "Ada") })) diff --git a/ui/base_scan_test.go b/ui/base_scan_test.go index eb4fdb06..052a9ab1 100644 --- a/ui/base_scan_test.go +++ b/ui/base_scan_test.go @@ -15,7 +15,7 @@ import ( // and its name here, or, when no styled control is built from it, to withoutStyledForm. var comparedWithTheirStyledForm = []string{ "ButtonBase", "CheckboxBase", "SwitchBase", "SelectBase", "SliderBase", - "TextFieldBase", "TabBase", "RadioBase", + "TextFieldBase", "TabBase", "RadioBase", "DisclosureBase", } // withoutStyledForm are the Bases that are not the Base of a control that ships with a look, diff --git a/ui/bubble.go b/ui/bubble.go new file mode 100644 index 00000000..6d76de7c --- /dev/null +++ b/ui/bubble.go @@ -0,0 +1,68 @@ +package ui + +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) + +// BubbleVariant is the surface of a Bubble, as shadcn's content variants. +type BubbleVariant uint8 + +const ( + // BubblePrimary is the primary surface with the primary foreground. + BubblePrimary BubbleVariant = iota + BubbleSecondary + BubbleMuted + BubbleTinted + BubbleOutline + BubbleGhost + BubbleDestructive +) + +// Bubble declares one message surface: its text wraps at 80% of the row and +// the box is as tall as its lines. Use Self(Start) or Self(End) for alignment; +// the page layer owns the conversation order. +// +// ui.Bubble(c, "Ready when you are", ui.BubbleMuted).Self(ui.Start) +func Bubble(c C, text string, variant BubbleVariant) Box { + theme := *c.Theme() + fill := theme.Primary + foreground := theme.PrimaryForeground + border := gfx.Color{} + bordered := false + padX, padY := theme.Metrics.PadControlX+1, theme.Metrics.GapItem+1 + switch variant { + case BubbleSecondary: + fill, foreground = theme.Secondary, theme.SecondaryForeground + case BubbleMuted: + fill, foreground = theme.Muted, theme.Foreground + case BubbleTinted: + fill, foreground = theme.Primary, theme.Foreground + fill.Alpha *= 0.12 + case BubbleOutline: + fill, foreground, border, bordered = theme.Background, theme.Foreground, theme.Border, true + case BubbleGhost: + fill, foreground = gfx.Color{}, theme.Foreground + padX, padY = 0, 0 + case BubbleDestructive: + fill, foreground = theme.Danger, theme.Danger + fill.Alpha *= 0.10 + if theme.Background.Red < 0.5 { + fill.Alpha *= 2 + } + } + bubble := base.Column(c).MaxWidthPercent(80).Radius(theme.Metrics.RadiusSurface + 4) + if variant != BubbleGhost { + bubble = bubble.PadSides(padY, padX, padY, padX).Background(fill) + } + if bordered { + bubble = bubble.Border(1, border) + } + bubble.Children(func() { + base.Wrap(c, text). + FontSize(theme.Metrics.FontSizeM). + LineHeight(theme.Metrics.FontSizeM * 1.625). + Color(foreground) + }) + return bubble +} diff --git a/ui/bubble_test.go b/ui/bubble_test.go new file mode 100644 index 00000000..43eb7d2e --- /dev/null +++ b/ui/bubble_test.go @@ -0,0 +1,36 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/ui" +) + +// A page Bubble is a row-sized surface: it measures its wrapped text, stays +// inside 80% of its row and carries a hit named by the caller. +func TestPageBubbleSizesToItsText(t *testing.T) { + d := openPage(t, func(c ui.C) { + ui.Column(c).FillWidth().Children(func() { + ui.Bubble(c, "A short message", ui.BubbleMuted). + Hit(ui.ID(c), "Short").Self(ui.Start) + ui.Bubble(c, "A much longer message that has to wrap onto more than one line in a narrow window", ui.BubbleTinted). + Hit(ui.ID(c), "Long").Self(ui.End) + }) + }) + short, long := d.hit("Short"), d.hit("Long") + if short.Bounds.Width >= long.Bounds.Width { + t.Fatalf("short bubble %g is not narrower than long %g", short.Bounds.Width, long.Bounds.Width) + } + if long.Bounds.Width > 480*0.8+1 { + t.Fatalf("long bubble width %g exceeds 80%% of the page", long.Bounds.Width) + } + if long.Bounds.Height <= short.Bounds.Height { + t.Fatalf("long bubble height %g is not taller than short %g", long.Bounds.Height, short.Bounds.Height) + } + if short.Bounds.X != 0 { + t.Fatalf("start bubble x = %g, want the row start", short.Bounds.X) + } + if long.Bounds.X+long.Bounds.Width < 479 { + t.Fatalf("end bubble ends at %g, want the row end", long.Bounds.X+long.Bounds.Width) + } +} diff --git a/ui/calendarview/calendarview.go b/ui/calendarview/calendarview.go new file mode 100644 index 00000000..da66f399 --- /dev/null +++ b/ui/calendarview/calendarview.go @@ -0,0 +1,123 @@ +// Package calendarview is the opt-in page control for the month grid of package +// components. It wraps components.BeginCalendar in a ui.Control, so a page +// declares a calendar without calling the component itself: +// +// month := &calendarview.Calendar{Options: calendarview.Options{ +// MonthTitle: title, Weekdays: weekdays, Days: days, +// PreviousID: previous, NextID: next, +// PreviousLabel: "Previous month", NextLabel: "Next month", +// }} +// ... +// calendarview.View(c, "Calendar", month).FillWidth().MaxWidth(360) +// if month.Clicked(previous) { +// m.month = -1 +// } else if month.Clicked(next) { +// m.month = 1 +// } +// +// The caller owns the month snapshot, the day identities and the navigation +// identities; the wrapper adds no date model and derives no dates. It paints +// through the component with exactly the identities the caller supplied, so a +// day or navigation click is read with Clicked after View, as for any canvas +// component. Pointer, keys and the wheel aimed at the control itself reach the +// optional callbacks. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Calendar in the model, beside the data it presents: +// its handlers and draw function are made once, so a warm paint allocates +// nothing. Do not copy a Calendar after it has been declared. +package calendarview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Options is the caller-owned month snapshot the view paints. It is +// components.CalendarOptions, named here so a page that declares a calendar +// reads through this package alone. +type Options = components.CalendarOptions + +// Day is one caller-owned cell of the month grid. +type Day = components.CalendarDay + +// Calendar is one calendar's month snapshot and page control. Fill Options from +// the caller's typed month data every paint; the callbacks stay as they are and +// are read when an event arrives. +type Calendar struct { + // Options is the complete application-owned month snapshot painted next. + // The wrapper does not modify it. + Options components.CalendarOptions + + // Pointer receives every pointer event aimed at the control itself. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Key receives the keys pressed while the control has the focus. + Key func(gfx.KeyEvent) gfx.EventResult + // Scroll receives the wheel over the control. A nil callback leaves it to + // the page. + Scroll func(gfx.ScrollEvent) gfx.EventResult + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + clicked gfx.ID + hadClick bool +} + +// View declares the calendar at c. label names the control for assistive +// technology. Give it a size; it is a ui.Control painted through the component. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, calendar *Calendar) ui.Box { + if calendar == nil { + panic("calendarview: View needs its Calendar") + } + calendar.prepare() + return ui.Control(c, label, &calendar.handlers).Draw(calendar.drawFn) +} + +// Clicked reports whether the paint just made was an event pass delivering a +// click on id, one of the caller's own day or navigation identities. It is +// false in ordinary paints. Ask it after View, where the component's clicks +// have always been read. +func (c *Calendar) Clicked(id gfx.ID) bool { + return c.hadClick && !id.IsZero() && c.clicked == id +} + +func (c *Calendar) prepare() { + if c.prepared { + return + } + c.prepared = true + c.handlers.Pointer = c.pointer + c.handlers.Key = c.key + c.handlers.Scroll = c.scroll + c.drawFn = c.draw +} + +func (c *Calendar) pointer(event gfx.PointerEvent) gfx.EventResult { + if c.Pointer == nil { + return gfx.EventResult{} + } + return c.Pointer(event) +} + +func (c *Calendar) key(event gfx.KeyEvent) gfx.EventResult { + if c.Key == nil { + return gfx.EventResult{} + } + return c.Key(event) +} + +func (c *Calendar) scroll(event gfx.ScrollEvent) gfx.EventResult { + if c.Scroll == nil { + return gfx.EventResult{} + } + return c.Scroll(event) +} + +func (c *Calendar) draw(d *ui.DrawContext) { + c.clicked, c.hadClick = d.Canvas.ClickTarget() + components.BeginCalendar(d.Canvas, *d.Theme, d.Rect, c.Options).Paint() +} diff --git a/ui/calendarview/calendarview_test.go b/ui/calendarview/calendarview_test.go new file mode 100644 index 00000000..5c880721 --- /dev/null +++ b/ui/calendarview/calendarview_test.go @@ -0,0 +1,203 @@ +package calendarview_test + +import ( + "testing" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/calendarview" +) + +var ( + testWeekdays = [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} + testPrevious = gfx.Item(91) + testNext = gfx.Item(92) + testDays = [...]components.CalendarDay{ + {ID: gfx.Item(101), Label: "29", AccessibilityLabel: "September 29", Outside: true}, + {ID: gfx.Item(102), Label: "30", AccessibilityLabel: "September 30", Disabled: true}, + {ID: gfx.Item(103), Label: "1", AccessibilityLabel: "October 1", Today: true}, + {ID: gfx.Item(104), Label: "2", AccessibilityLabel: "October 2", Selected: true}, + {ID: gfx.Item(105), Label: "3", AccessibilityLabel: "October 3"}, + } +) + +func testOptions() calendarview.Options { + return calendarview.Options{ + MonthTitle: "October 2026", Weekdays: testWeekdays, Days: testDays[:], + PreviousID: testPrevious, NextID: testNext, + PreviousLabel: "Previous month", NextLabel: "Next month", + } +} + +type model struct { + view calendarview.Calendar + page *ui.Page + canvas *gfx.Canvas + target gfx.ID + keys int + scrolls int +} + +func (m *model) wire() { + m.view.Options = testOptions() + m.view.Pointer = func(event gfx.PointerEvent) gfx.EventResult { + m.target = event.Target + return gfx.EventResult{Handled: true, Repaint: true} + } + m.view.Key = func(event gfx.KeyEvent) gfx.EventResult { + m.keys++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } + m.view.Scroll = func(event gfx.ScrollEvent) gfx.EventResult { + m.scrolls++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } +} + +func (m *model) viewPage(c ui.C) { + calendarview.View(c, "Calendar", &m.view).Size(300, 260) +} + +func (m *model) open(t testing.TB) { + t.Helper() + theme := gfx.LightTheme() + m.page = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: &theme}) + m.canvas = new(gfx.Canvas) + draw(m.page, m.canvas, m.viewPage) +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 360, Height: 320}, view) + canvas.EndFrame() +} + +func drawClick(page *ui.Page, canvas *gfx.Canvas, view func(ui.C), id gfx.ID) { + canvas.BeginEventPass(id, gfx.ClickInfo{}) + draw(page, canvas, view) + canvas.EndEventPass() +} + +// hitLabelled returns the front-most hit with the label and a non-zero identity. +func hitLabelled(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + if hits[i].Label == label && !hits[i].ID.IsZero() { + return hits[i], true + } + } + return gfx.Hit{}, false +} + +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + got, ok := hitLabelled(canvas, label) + if !ok { + t.Fatalf("no hit labelled %q was painted", label) + } + return got +} + +// The page declares the view, the component paints the caller's month snapshot +// with the caller's own identities, and the wrapper's callbacks take pointer, +// key and wheel input aimed at the control. +func TestViewPaintsCallerIdentitiesAndRoutesInput(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + + control := hit(t, m.canvas, "Calendar") + if control.Role != gfx.RoleGroup { + t.Fatalf("control role = %v, want a group", control.Role) + } + if previous := hit(t, m.canvas, "Previous month"); previous.ID != testPrevious { + t.Fatalf("previous hit = %v, want the caller's %v", previous.ID, testPrevious) + } + day := hit(t, m.canvas, "October 2") + if day.ID != testDays[3].ID || day.Role != gfx.RoleGridCell || !day.Selected { + t.Fatalf("day hit = %+v, want the caller's selected grid cell", day) + } + + if result := m.page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: control.ID, + X: control.Bounds.X + 4, Y: control.Bounds.Y + 4, + }); !result.Handled || !result.Repaint || m.target != control.ID { + t.Fatalf("pointer Target = %v (result %+v), want %v", m.target, result, control.ID) + } + if result := m.page.Key(gfx.KeyEvent{Key: gfx.KeyRight, Target: control.ID}); !result.Handled || m.keys != 1 || m.target != control.ID { + t.Fatalf("key Target = %v (result %+v after %d calls)", m.target, result, m.keys) + } + if result := m.page.Wheel(gfx.ScrollEvent{Target: control.ID, DeltaY: 1}); !result.Handled || m.scrolls != 1 || m.target != control.ID { + t.Fatalf("wheel Target = %v (result %+v after %d calls)", m.target, result, m.scrolls) + } +} + +// A click on a day or navigation control is read with Clicked after View, and a +// different identity is not reported. +func TestViewReportsClicksForCallerIdentities(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + + drawClick(m.page, m.canvas, m.viewPage, testNext) + if !m.view.Clicked(testNext) { + t.Fatal("Clicked did not report the clicked next control") + } + if m.view.Clicked(testPrevious) || m.view.Clicked(testDays[3].ID) { + t.Fatal("Clicked reported an identity that was not clicked") + } + // An ordinary paint is not an event pass and reports no click. + draw(m.page, m.canvas, m.viewPage) + if m.view.Clicked(testNext) { + t.Fatal("Clicked reported a click in an ordinary paint") + } +} + +// A zero day identity stays unpainted, so it is not focusable or clickable, +// while the other days keep their caller identities. +func TestViewLeavesZeroIdentitiesUnpainted(t *testing.T) { + options := testOptions() + options.Days = options.Days[:2] + options.Days[0].ID = gfx.ID{} + var view calendarview.Calendar + view.Options = options + viewPage := func(c ui.C) { calendarview.View(c, "Calendar", &view).Size(300, 260) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: viewPage, Theme: &theme}) + canvas := new(gfx.Canvas) + draw(page, canvas, viewPage) + + if _, ok := hitLabelled(canvas, "September 29"); ok { + t.Fatal("a day with the zero identity was painted") + } + disabled := hit(t, canvas, "September 30") + if disabled.ID != testDays[1].ID || !disabled.Disabled || disabled.Focusable { + t.Fatalf("disabled day hit = %+v, want inert with its caller identity", disabled) + } +} + +// A warm repaint allocates nothing: the wrapper keeps its handlers and draw +// function, and the component keeps its own caches. +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + if allocations := testing.AllocsPerRun(100, func() { draw(m.page, m.canvas, m.viewPage) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := new(model) + m.wire() + m.open(b) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + draw(m.page, m.canvas, m.viewPage) + } +} diff --git a/ui/carouselview/carouselview.go b/ui/carouselview/carouselview.go new file mode 100644 index 00000000..a614bc46 --- /dev/null +++ b/ui/carouselview/carouselview.go @@ -0,0 +1,214 @@ +// Package carouselview is the opt-in page control for the clipped carousel of +// package components. It wraps components.BeginCarousel in a ui.Control, so a +// page declares a carousel without calling the component itself: +// +// tour := &carouselview.Carousel{ +// ItemCount: 3, Index: m.slide, +// PreviousID: m.previous, PreviousLabel: "Previous slide", +// NextID: m.next, NextLabel: "Next slide", +// } +// tour.Draw = func(d *ui.DrawContext, geometry carouselview.Geometry) { +// for index := 0; index < tour.ItemCount; index++ { +// d.Canvas.Fill(tour.ItemBounds(geometry, index), d.Theme.Muted) +// } +// } +// ... +// carouselview.View(c, "Product tour", tour).FillWidth().Height(200) +// if tour.Clicked(m.previous) && m.slide > 0 { +// m.slide-- +// } else if tour.Clicked(m.next) && m.slide < 2 { +// m.slide++ +// } +// +// The caller owns the index, the offset, the content extent and the slide +// content; the wrapper paints through the component, clips the slide content to +// the viewport and routes pointer, keys and the wheel aimed at the control to +// the caller's callbacks. The navigation controls keep the caller's identities, +// so their clicks are read with Clicked after View. There is no autoplay, +// timer, animation, dragging or inertia: an idle carousel does no work. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Carousel in the model, beside its slides: its handlers +// and draw function are made once, so a warm paint allocates nothing. Do not +// copy a Carousel after it has been declared. +package carouselview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Orientation selects the content axis of a Carousel. +type Orientation = components.CarouselOrientation + +const ( + Horizontal = components.CarouselHorizontal + Vertical = components.CarouselVertical +) + +// Geometry is the complete carousel layout handed to Draw. +type Geometry = components.CarouselGeometry + +// Carousel is one carousel's state and page control. Fill the fields from the +// caller's model every paint; Draw and the callbacks stay as they are and are +// read when they are needed. +type Carousel struct { + // Orientation selects the content axis. The zero value is horizontal. + Orientation components.CarouselOrientation + // ItemCount is the number of caller-owned slides. + ItemCount int + // Index is the selected slide. It is clamped by the component. + Index int + // Offset is the caller-owned content offset. When Extent is zero and Offset + // is zero, the wrapper derives one viewport of each slide from Index. + Offset float32 + // Extent is the total content extent along the axis. When zero, it is + // ItemCount viewports, one slide per view. + Extent float32 + // PreviousID, NextID and their labels declare the navigation controls. + PreviousID gfx.ID + PreviousLabel string + NextID gfx.ID + NextLabel string + // Disabled paints both controls and keeps them inert. + Disabled bool + + // Draw paints the caller's slides. It runs inside the viewport clip, after + // the component has laid the content out; geometry is the complete carousel + // layout and ItemBounds maps a slide of an evenly divided content extent. + Draw func(*ui.DrawContext, components.CarouselGeometry) + + // Pointer receives every pointer event aimed at the control itself. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Key receives the keys pressed while the control has the focus. + Key func(gfx.KeyEvent) gfx.EventResult + // Scroll receives the wheel over the control. A nil callback leaves it to + // the page. + Scroll func(gfx.ScrollEvent) gfx.EventResult + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + label string + geometry components.CarouselGeometry + clicked gfx.ID + hadClick bool +} + +// View declares the carousel at c. label names the region for assistive +// technology. Give it a size; it is a ui.Control painted through the component. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, carousel *Carousel) ui.Box { + if carousel == nil { + panic("carouselview: View needs its Carousel") + } + carousel.prepare() + carousel.label = label + return ui.Control(c, label, &carousel.handlers).Draw(carousel.drawFn) +} + +// Clicked reports whether the paint just made was an event pass delivering a +// click on id, PreviousID or NextID. It is false in ordinary paints. Ask it +// after View, where a component's clicks have always been read. +func (c *Carousel) Clicked(id gfx.ID) bool { + return c.hadClick && !id.IsZero() && c.clicked == id +} + +func (c *Carousel) prepare() { + if c.prepared { + return + } + c.prepared = true + c.handlers.Pointer = c.pointer + c.handlers.Key = c.key + c.handlers.Scroll = c.scroll + c.drawFn = c.draw +} + +func (c *Carousel) pointer(event gfx.PointerEvent) gfx.EventResult { + if c.Pointer == nil { + return gfx.EventResult{} + } + return c.Pointer(event) +} + +func (c *Carousel) key(event gfx.KeyEvent) gfx.EventResult { + if c.Key == nil { + return gfx.EventResult{} + } + return c.Key(event) +} + +func (c *Carousel) scroll(event gfx.ScrollEvent) gfx.EventResult { + if c.Scroll == nil { + return gfx.EventResult{} + } + return c.Scroll(event) +} + +func (c *Carousel) draw(d *ui.DrawContext) { + c.clicked, c.hadClick = d.Canvas.ClickTarget() + + viewportExtent := d.Rect.Width + if c.Orientation == components.CarouselVertical { + viewportExtent = d.Rect.Height + } + extent, offset := c.Extent, c.Offset + if extent <= 0 { + extent = viewportExtent * float32(max(c.ItemCount, 0)) + if offset == 0 { + offset = viewportExtent * float32(c.Index) + } + } + + carousel := components.BeginCarousel(d.Canvas, *d.Theme, d.Rect, c.ItemCount, c.Index). + Content(extent, offset). + Controls(c.PreviousID, c.PreviousLabel, c.NextID, c.NextLabel). + Label(c.label) + if c.Orientation == components.CarouselVertical { + carousel = carousel.Vertical() + } + if c.Disabled { + carousel = carousel.Disabled() + } + geometry := carousel.BeginContent() + c.geometry = geometry + if c.Draw != nil { + c.Draw(d, geometry) + } + carousel.EndContent() +} + +// Geometry is the carousel layout painted last: viewport, translated content, +// both control bounds and the clamped index. It is zero until View has painted +// at least once. +func (c *Carousel) Geometry() components.CarouselGeometry { return c.geometry } + +// ItemBounds maps one slide of an evenly divided content extent to page +// coordinates: Index along the axis, the viewport extent across it. It returns +// an empty rectangle for an index outside the item count. Use it in Draw for +// the common one-slide-per-view layout; a caller with items of different +// extents maps them from Geometry.Content instead. +func (c *Carousel) ItemBounds(geometry components.CarouselGeometry, index int) gfx.Rect { + if index < 0 || index >= c.ItemCount || c.ItemCount <= 0 { + return gfx.Rect{} + } + content := geometry.Content + itemExtent := content.Width + if c.Orientation == components.CarouselVertical { + itemExtent = content.Height + } + itemExtent /= float32(c.ItemCount) + if c.Orientation == components.CarouselVertical { + return gfx.Rect{ + X: content.X, Y: content.Y + float32(index)*itemExtent, + Width: geometry.Viewport.Width, Height: itemExtent, + } + } + return gfx.Rect{ + X: content.X + float32(index)*itemExtent, Y: content.Y, + Width: itemExtent, Height: geometry.Viewport.Height, + } +} diff --git a/ui/carouselview/carouselview_test.go b/ui/carouselview/carouselview_test.go new file mode 100644 index 00000000..c056325a --- /dev/null +++ b/ui/carouselview/carouselview_test.go @@ -0,0 +1,221 @@ +package carouselview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/carouselview" +) + +var ( + testPrevious = gfx.Item(91) + testNext = gfx.Item(92) +) + +type model struct { + view carouselview.Carousel + page *ui.Page + canvas *gfx.Canvas + target gfx.ID + draws int + geometry carouselview.Geometry + keys int + scrolls int +} + +func (m *model) wire(orientation carouselview.Orientation) { + m.view.Orientation = orientation + m.view.ItemCount = 3 + m.view.Index = 1 + m.view.PreviousID, m.view.NextID = testPrevious, testNext + m.view.PreviousLabel, m.view.NextLabel = "Previous slide", "Next slide" + m.view.Draw = func(d *ui.DrawContext, geometry carouselview.Geometry) { + m.draws++ + m.geometry = geometry + d.Canvas.Fill(m.view.ItemBounds(geometry, geometry.Index), d.Theme.Accent) + } + m.view.Pointer = func(event gfx.PointerEvent) gfx.EventResult { + m.target = event.Target + return gfx.EventResult{Handled: true, Repaint: true} + } + m.view.Key = func(event gfx.KeyEvent) gfx.EventResult { + m.keys++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } + m.view.Scroll = func(event gfx.ScrollEvent) gfx.EventResult { + m.scrolls++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } +} + +func (m *model) viewPage(c ui.C) { + carouselview.View(c, "Tour", &m.view).Size(320, 200) +} + +func (m *model) open(t testing.TB, orientation carouselview.Orientation) { + t.Helper() + m.wire(orientation) + theme := gfx.LightTheme() + m.page = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: &theme}) + m.canvas = new(gfx.Canvas) + draw(m.page, m.canvas, m.viewPage) +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 400, Height: 300}, view) + canvas.EndFrame() +} + +func drawClick(page *ui.Page, canvas *gfx.Canvas, view func(ui.C), id gfx.ID) { + canvas.BeginEventPass(id, gfx.ClickInfo{}) + draw(page, canvas, view) + canvas.EndEventPass() +} + +// hitLabelled returns the front-most hit with the label and a non-zero identity. +func hitLabelled(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + if hits[i].Label == label && !hits[i].ID.IsZero() { + return hits[i], true + } + } + return gfx.Hit{}, false +} + +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + got, ok := hitLabelled(canvas, label) + if !ok { + t.Fatalf("no hit labelled %q was painted", label) + } + return got +} + +// The page declares the view, the component lays out the content, the Draw +// callback paints the selected slide inside the viewport, and the controls keep +// the caller's identities while the control routes input to its callbacks. +func TestViewPaintsGeometryAndRoutesInput(t *testing.T) { + m := new(model) + m.open(t, carouselview.Horizontal) + + geometry := m.view.Geometry() + if m.draws != 1 { + t.Fatalf("Draw called %d times, want 1", m.draws) + } + if geometry.Viewport.Width != 320 || geometry.Viewport.Height != 200 { + t.Fatalf("viewport = %+v, want 320x200", geometry.Viewport) + } + if geometry.Content.Width != 960 || geometry.Offset != 320 || geometry.Index != 1 { + t.Fatalf("content = %+v offset %g index %d, want 960, 320, 1", geometry.Content, geometry.Offset, geometry.Index) + } + if first := m.view.ItemBounds(geometry, 0); first.Width != 320 || first.X != geometry.Content.X { + t.Fatalf("first slide = %+v, want one 320-wide viewport at the content origin", first) + } + if second := m.view.ItemBounds(geometry, 1); second.X != geometry.Content.X+320 { + t.Fatalf("second slide = %+v, want it one viewport along", second) + } + + control := hit(t, m.canvas, "Tour") + previous := hit(t, m.canvas, "Previous slide") + next := hit(t, m.canvas, "Next slide") + if previous.ID != testPrevious || next.ID != testNext { + t.Fatalf("navigation hits = %v %v, want the caller's %v %v", previous.ID, next.ID, testPrevious, testNext) + } + if previous.Role != gfx.RoleButton || previous.Disabled || !previous.Focusable { + t.Fatalf("previous hit = %+v, want an enabled button", previous) + } + + if result := m.page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: control.ID, + X: control.Bounds.X + 4, Y: control.Bounds.Y + 4, + }); !result.Handled || m.target != control.ID { + t.Fatalf("pointer Target = %v (result %+v), want %v", m.target, result, control.ID) + } + if result := m.page.Key(gfx.KeyEvent{Key: gfx.KeyLeft, Target: control.ID}); !result.Handled || m.keys != 1 || m.target != control.ID { + t.Fatalf("key Target = %v (result %+v after %d calls)", m.target, result, m.keys) + } + if result := m.page.Wheel(gfx.ScrollEvent{Target: control.ID, DeltaY: 1}); !result.Handled || m.scrolls != 1 || m.target != control.ID { + t.Fatalf("wheel Target = %v (result %+v after %d calls)", m.target, result, m.scrolls) + } +} + +// A click on a navigation control is read with Clicked after View, and a +// different identity is not reported. +func TestViewReportsClicksForCallerIdentities(t *testing.T) { + m := new(model) + m.open(t, carouselview.Horizontal) + + drawClick(m.page, m.canvas, m.viewPage, testNext) + if !m.view.Clicked(testNext) { + t.Fatal("Clicked did not report the clicked next control") + } + if m.view.Clicked(testPrevious) { + t.Fatal("Clicked reported an identity that was not clicked") + } + draw(m.page, m.canvas, m.viewPage) + if m.view.Clicked(testNext) { + t.Fatal("Clicked reported a click in an ordinary paint") + } +} + +// The vertical orientation places the controls above and below the viewport and +// divides the content extent by height. +func TestVerticalOrientation(t *testing.T) { + m := new(model) + m.open(t, carouselview.Vertical) + m.view.Index = 0 + draw(m.page, m.canvas, m.viewPage) + geometry := m.view.Geometry() + if geometry.Viewport.Height != 200 || geometry.Content.Height != 600 { + t.Fatalf("vertical content = %+v viewport %+v, want 600 high", geometry.Content, geometry.Viewport) + } + if geometry.PreviousButton.Y >= geometry.Viewport.Y || geometry.NextButton.Y <= geometry.Viewport.Y+geometry.Viewport.Height { + t.Fatalf("vertical controls = %+v %+v, want them above and below", geometry.PreviousButton, geometry.NextButton) + } + if item := m.view.ItemBounds(geometry, 2); item.Height != 200 || item.Y != geometry.Content.Y+400 { + t.Fatalf("third vertical slide = %+v, want one viewport down the axis", item) + } +} + +// Disabled keeps both control bounds and semantics while making them inert. +func TestDisabledControls(t *testing.T) { + m := new(model) + m.open(t, carouselview.Horizontal) + m.view.Disabled = true + m.view.Index = 0 + draw(m.page, m.canvas, m.viewPage) + geometry := m.view.Geometry() + if geometry.CanPrevious || geometry.CanNext { + t.Fatalf("disabled geometry = %+v, want both directions off", geometry) + } + next := hit(t, m.canvas, "Next slide") + if next.ID != testNext || !next.Disabled || next.Focusable { + t.Fatalf("disabled next hit = %+v, want inert with its caller identity", next) + } +} + +// A warm repaint allocates nothing: the wrapper keeps its part scope and the +// component keeps its own layout caches. +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.open(t, carouselview.Horizontal) + if allocations := testing.AllocsPerRun(100, func() { draw(m.page, m.canvas, m.viewPage) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := new(model) + m.open(b, carouselview.Horizontal) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + draw(m.page, m.canvas, m.viewPage) + } +} diff --git a/ui/chartview/bar.go b/ui/chartview/bar.go new file mode 100644 index 00000000..8daa8144 --- /dev/null +++ b/ui/chartview/bar.go @@ -0,0 +1,107 @@ +package chartview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// BarChartView is one bar chart's data, state and page control. It is the bar +// counterpart of AreaChartView: fill Chart each paint and keep State with the +// view; the pointer, keys and callbacks behave the same way. +type BarChartView struct { + // Chart is the data and presentation the components painter draws. + Chart components.BarChart + // State is the hovered category and the caches that keep a steady chart + // from allocating. Keep it with the view. + State components.ChartState + + // OnHover is told whenever the hovered category changes, with -1 and false + // when the pointer leaves. + OnHover func(index int, active bool) + // OnPointer receives every pointer event the control gets, after the + // view's own hover work. Its result is combined with the view's. + OnPointer func(gfx.PointerEvent) gfx.EventResult + // OnKey receives every key event the control gets, after the view's own + // arrow, Home and End handling. Its result is combined with the view's. + OnKey func(gfx.KeyEvent) gfx.EventResult + // OnScroll receives the wheel over the control. + OnScroll func(gfx.ScrollEvent) gfx.EventResult + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + hover hoverState + label string + prepared bool +} + +// Bar declares a bar chart at c. The returned box is full width and 200 high +// unless a Width or Height follows it. label names the control for assistive +// technology; when Chart.Label is empty it also names the plot. +// +// Declare the view on its own, not inside a Memo. +func Bar(c ui.C, label string, chart *BarChartView) ui.Box { + if chart == nil { + panic("chartview: Bar needs its BarChartView") + } + chart.prepare() + chart.label = label + return ui.Control(c, label, &chart.handlers). + FillWidth().Height(chartDefaultHeight). + Draw(chart.drawFn) +} + +func (v *BarChartView) prepare() { + if v.prepared { + return + } + v.prepared = true + v.handlers.Pointer = v.pointer + v.handlers.Key = v.key + v.handlers.Scroll = v.scroll + v.drawFn = v.draw +} + +func (v *BarChartView) pointer(event gfx.PointerEvent) gfx.EventResult { + var result gfx.EventResult + switch event.Kind { + case gfx.PointerMove: + result = v.hover.pointerMove(&v.State, v.OnHover, event.X) + result.Handled = true + case gfx.PointerDown: + result = v.hover.pointerMove(&v.State, v.OnHover, event.X) + case gfx.PointerExit: + result = v.hover.clear(&v.State, v.OnHover, true) + result.Handled = true + } + if v.OnPointer != nil { + result = combine(result, v.OnPointer(event)) + } + return result +} + +func (v *BarChartView) key(event gfx.KeyEvent) gfx.EventResult { + result := v.hover.key(&v.State, v.OnHover, event) + if v.OnKey != nil { + result = combine(result, v.OnKey(event)) + } + return result +} + +func (v *BarChartView) scroll(event gfx.ScrollEvent) gfx.EventResult { + if v.OnScroll == nil { + return gfx.EventResult{} + } + return v.OnScroll(event) +} + +func (v *BarChartView) draw(d *ui.DrawContext) { + if v.hover.pointer && !d.State.Hovered && !d.State.Pressed { + v.hover.clear(&v.State, v.OnHover, true) + } + chart := v.Chart + if chart.Label == "" { + chart.Label = v.label + } + v.hover.plot = components.PaintBarChart(d.Canvas, *d.Theme, d.Rect, d.Node.ID, chart, &v.State) +} diff --git a/ui/chartview/chartview.go b/ui/chartview/chartview.go new file mode 100644 index 00000000..e24bb44b --- /dev/null +++ b/ui/chartview/chartview.go @@ -0,0 +1,251 @@ +// Package chartview is the opt-in page control for the area and bar charts of +// package components. It wraps PaintAreaChart and PaintBarChart in a +// ui.Control, so a page declares a chart without calling the painters itself: +// the view owns the chart data, its ChartState and the handlers that turn the +// pointer and the keyboard into a hovered point. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public gfx, components and ui +// packages: it neither reaches into the page engine nor changes it. +// +// visitors := &chartview.AreaChartView{ +// Chart: components.AreaChart{ +// Series: []components.ChartSeries{{Key: "visitors", Label: "Visitors", Color: theme.Chart[0]}}, +// Values: [][]float32{counts}, +// }, +// OnHover: func(index int, active bool) { m.inspect(index, active) }, +// } +// ... +// chartview.View(c, "Visitors", visitors).FillWidth().Height(240) +// +// A chart that is only a container and caller-drawn geometry uses Container: +// +// commits := &chartview.Container{ +// Series: series, +// Options: chartview.ContainerOptions{Legend: chartview.LegendBottom}, +// Draw: m.drawCommits, // fills layout.PlotBounds +// } +// ... +// chartview.ContainerView(c, "Commits", commits).Height(240) +// +// The package also names the components package's chart types and constants, so +// a page declares chart data with chartview.Series, chartview.Axis and +// chartview.CurveMonotone without importing components itself. +// +// A view belongs to one place on one page and is kept in the model. Its +// handlers and draw function are made once, so a warm paint allocates nothing; +// do not copy a view after it has been declared. +package chartview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// chartDefaultHeight is the height a view takes when the caller gives none, +// matching the chart components' own initial height. +const chartDefaultHeight float32 = 200 + +// AreaChartView is one area or line chart's data, state and page control. Fill +// its Chart from the caller's typed slices every paint; State and the handlers +// stay as they are, and the view keeps the last plot so the pointer can be +// mapped back to a data point. +// +// OnHover, OnPointer, OnKey and OnScroll are optional. They may be set once or +// changed between paints; the handlers read them when the event arrives. +type AreaChartView struct { + // Chart is the data and presentation the components painter draws. + Chart components.AreaChart + // State is the hovered point and the caches that keep a steady chart from + // allocating. Keep it with the view. + State components.ChartState + + // OnHover is told whenever the hovered point changes, with -1 and false + // when the pointer leaves. It is called from input handling, and from the + // paint that notices the pointer left without an exit event. + OnHover func(index int, active bool) + // OnPointer receives every pointer event the control gets, after the + // view's own hover work. Its result is combined with the view's. + OnPointer func(gfx.PointerEvent) gfx.EventResult + // OnKey receives every key event the control gets, after the view's own + // arrow, Home and End handling. Its result is combined with the view's. + OnKey func(gfx.KeyEvent) gfx.EventResult + // OnScroll receives the wheel over the control. Unlike the pointer and key + // callbacks it comes first: the chart has no scrolling of its own, so an + // unhandled return lets the page scroll what the chart is in. + OnScroll func(gfx.ScrollEvent) gfx.EventResult + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + hover hoverState + label string + prepared bool +} + +// View declares an area chart at c. The returned box is full width and 200 +// high unless a Width or Height follows it. label names the control for +// assistive technology; when Chart.Label is empty it also names the plot. +// +// Give the chart a size that suits its data. Declare the view on its own, not +// inside a Memo. +func View(c ui.C, label string, chart *AreaChartView) ui.Box { + if chart == nil { + panic("chartview: View needs its AreaChartView") + } + chart.prepare() + chart.label = label + return ui.Control(c, label, &chart.handlers). + FillWidth().Height(chartDefaultHeight). + Draw(chart.drawFn) +} + +func (v *AreaChartView) prepare() { + if v.prepared { + return + } + v.prepared = true + v.handlers.Pointer = v.pointer + v.handlers.Key = v.key + v.handlers.Scroll = v.scroll + v.drawFn = v.draw +} + +func (v *AreaChartView) pointer(event gfx.PointerEvent) gfx.EventResult { + var result gfx.EventResult + switch event.Kind { + case gfx.PointerMove: + result = v.hover.pointerMove(&v.State, v.OnHover, event.X) + result.Handled = true + case gfx.PointerDown: + // A tap without a preceding move still hovers the point it lands on. + // The press stays unhandled so a click on the chart reaches the page. + result = v.hover.pointerMove(&v.State, v.OnHover, event.X) + case gfx.PointerExit: + result = v.hover.clear(&v.State, v.OnHover, true) + result.Handled = true + } + if v.OnPointer != nil { + result = combine(result, v.OnPointer(event)) + } + return result +} + +func (v *AreaChartView) key(event gfx.KeyEvent) gfx.EventResult { + result := v.hover.key(&v.State, v.OnHover, event) + if v.OnKey != nil { + result = combine(result, v.OnKey(event)) + } + return result +} + +func (v *AreaChartView) scroll(event gfx.ScrollEvent) gfx.EventResult { + if v.OnScroll == nil { + return gfx.EventResult{} + } + return v.OnScroll(event) +} + +func (v *AreaChartView) draw(d *ui.DrawContext) { + // A pointer that leaves the window without a press gets no exit event: the + // repaint that clears the hover is where the chart sees it. A press keeps + // the pointer until it is released, even outside the window. + if v.hover.pointer && !d.State.Hovered && !d.State.Pressed { + v.hover.clear(&v.State, v.OnHover, true) + } + chart := v.Chart + if chart.Label == "" { + chart.Label = v.label + } + v.hover.plot = components.PaintAreaChart(d.Canvas, *d.Theme, d.Rect, d.Node.ID, chart, &v.State) +} + +// hoverState is what a view remembers between paints and input events to turn +// a pointer position or a key into a data point. pointer says the current hover +// came from the pointer, so leaving the chart clears it without clearing a +// keyboard hover. +type hoverState struct { + plot components.ChartPlot + pointer bool +} + +// pointerMove sets the point nearest x. It repaints only when the point changes. +func (h *hoverState) pointerMove(state *components.ChartState, notify func(int, bool), x float32) gfx.EventResult { + index := h.plot.IndexAt(x) + previous, active := state.Index() + h.pointer = true + if index < 0 { + if !active { + return gfx.EventResult{} + } + } else if active && previous == index { + return gfx.EventResult{} + } + state.Hover(index) + if notify != nil { + notify(index, index >= 0) + } + return gfx.EventResult{Repaint: true} +} + +// clear removes the hover. When pointerOnly is set it does nothing to a hover +// the keyboard set. +func (h *hoverState) clear(state *components.ChartState, notify func(int, bool), pointerOnly bool) gfx.EventResult { + if pointerOnly && !h.pointer { + return gfx.EventResult{} + } + h.pointer = false + if _, active := state.Index(); !active { + return gfx.EventResult{} + } + state.Clear() + if notify != nil { + notify(-1, false) + } + return gfx.EventResult{Repaint: true} +} + +// key steps the hovered point with the chart components' own key mapping. +func (h *hoverState) key(state *components.ChartState, notify func(int, bool), event gfx.KeyEvent) gfx.EventResult { + if event.Release { + return gfx.EventResult{} + } + index, active := state.Index() + if !active { + index = -1 + } + next, handled := components.ChartStepForKey(event.Key, index, h.plot.Count()) + if !handled { + return gfx.EventResult{} + } + h.pointer = false + if active && next == index { + return gfx.EventResult{Handled: true} + } + state.Hover(next) + if notify != nil { + notify(next, true) + } + return gfx.EventResult{Handled: true, Repaint: true} +} + +// combine folds a callback's result into the view's own. Repaint and Handled +// from either side are kept, and the first side with a focus, blur, activation +// or clipboard request wins. +func combine(result, extra gfx.EventResult) gfx.EventResult { + result.Handled = result.Handled || extra.Handled + result.Repaint = result.Repaint || extra.Repaint + result.Blur = result.Blur || extra.Blur + result.FocusVisible = result.FocusVisible || extra.FocusVisible + result.ContinueTraversal = result.ContinueTraversal || extra.ContinueTraversal + if result.Focus.IsZero() { + result.Focus = extra.Focus + } + if result.Activate.IsZero() { + result.Activate = extra.Activate + } + if result.ClipboardText == "" { + result.ClipboardText = extra.ClipboardText + } + return result +} diff --git a/ui/chartview/chartview_test.go b/ui/chartview/chartview_test.go new file mode 100644 index 00000000..6b14236e --- /dev/null +++ b/ui/chartview/chartview_test.go @@ -0,0 +1,354 @@ +package chartview_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/chartview" +) + +// The month data of the components' own area chart examples. +var ( + desktop = []float32{186, 305, 237, 73, 209, 214} + mobile = []float32{80, 200, 120, 190, 130, 140} +) + +func areaChart() components.AreaChart { + return components.AreaChart{ + Series: []components.ChartSeries{ + {Key: "desktop", Label: "Desktop", Color: gfx.Color{Red: .2, Green: .4, Blue: .8, Alpha: 1}}, + {Key: "mobile", Label: "Mobile", Color: gfx.Color{Red: .8, Green: .4, Blue: .2, Alpha: 1}}, + }, + Values: [][]float32{desktop, mobile}, + Curve: components.ChartCurveMonotone, + Grid: components.ChartGridHorizontal, + Label: "Monthly visitors", + Version: 1, + } +} + +func barChart() components.BarChart { + return components.BarChart{ + Series: []components.ChartSeries{ + {Key: "desktop", Label: "Desktop", Color: gfx.Color{Red: .2, Green: .4, Blue: .8, Alpha: 1}}, + {Key: "mobile", Label: "Mobile", Color: gfx.Color{Red: .8, Green: .4, Blue: .2, Alpha: 1}}, + }, + Values: [][]float32{desktop, mobile}, + Grid: components.ChartGridHorizontal, + Label: "Monthly visitors", + Version: 1, + } +} + +type harness struct { + t *testing.T + area *chartview.AreaChartView + bar *chartview.BarChartView + box ui.Box + page *ui.Page + drv *app.Driver + inv *app.Invalidator + hover int + active bool + hovers int + moves int + wheels int +} + +func openArea(t *testing.T) *harness { + t.Helper() + h := &harness{t: t, area: &chartview.AreaChartView{Chart: areaChart()}, hover: -1} + h.area.OnHover = func(index int, active bool) { h.hover, h.active, h.hovers = index, active, h.hovers+1 } + h.area.OnPointer = func(gfx.PointerEvent) gfx.EventResult { h.moves++; return gfx.EventResult{} } + h.area.OnScroll = func(gfx.ScrollEvent) gfx.EventResult { h.wheels++; return gfx.EventResult{} } + h.open(func(c ui.C) { h.box = chartview.View(c, "Visitors", h.area).Size(400, 240) }) + return h +} + +func openBar(t *testing.T) *harness { + t.Helper() + h := &harness{t: t, bar: &chartview.BarChartView{Chart: barChart()}, hover: -1} + h.bar.OnHover = func(index int, active bool) { h.hover, h.active, h.hovers = index, active, h.hovers+1 } + h.open(func(c ui.C) { h.box = chartview.Bar(c, "Visitors", h.bar).Size(400, 240) }) + return h +} + +func (h *harness) open(view func(ui.C)) { + h.t.Helper() + var tree gfx.Tree + h.page = ui.NewPage(ui.PageConfig{Tree: &tree, View: view}) + h.inv = new(app.Invalidator) + var err error + h.drv, err = app.NewDriver(ui.Configure(h.page, app.Config{Width: 480, Height: 320, Invalidator: h.inv}), nil) + if err != nil { + h.t.Fatal(err) + } + h.t.Cleanup(h.drv.Close) + h.repaint() +} + +func (h *harness) repaint() { + h.t.Helper() + h.inv.Invalidate() + if err := h.drv.Pump(); err != nil { + h.t.Fatal(err) + } +} + +func (h *harness) index() (int, bool) { + if h.area != nil { + return h.area.State.Index() + } + return h.bar.State.Index() +} + +func (h *harness) move(x, y float32) { + h.t.Helper() + if err := h.drv.Move(x, y); err != nil { + h.t.Fatal(err) + } + h.repaint() +} + +func (h *harness) click(x, y float32) { + h.t.Helper() + if err := h.drv.Click(x, y); err != nil { + h.t.Fatal(err) + } + h.repaint() +} + +func (h *harness) key(key gfx.Key) { + h.t.Helper() + if err := h.drv.Key(key, 0); err != nil { + h.t.Fatal(err) + } + h.repaint() +} + +// The page declares the view, paints it, and the pointer moves the hovered +// point and reports it through the callback; leaving clears it again. +func TestAreaViewPointerHover(t *testing.T) { + h := openArea(t) + r := h.box.Rect() + if r.Width != 400 || r.Height != 240 { + t.Fatalf("chart box = %v, want 400x240", r) + } + centerX, centerY := r.X+r.Width/2, r.Y+r.Height/2 + h.move(centerX, centerY) + index, active := h.index() + if !active || index < 0 { + t.Fatalf("hover after a pointer move = (%d, %v), want an active point", index, active) + } + if h.hover != index || !h.active { + t.Fatalf("OnHover = (%d, %v), want (%d, true)", h.hover, h.active, index) + } + if h.moves == 0 { + t.Fatal("OnPointer did not see the pointer") + } + + // The left edge is an earlier point than the center. + h.move(r.X+8, centerY) + left, active := h.index() + if !active || left >= index { + t.Fatalf("hover at the left edge = (%d, %v), want a point before %d", left, active, index) + } + if h.hover != left { + t.Fatalf("OnHover = %d after the second move, want %d", h.hover, left) + } + + // Leaving the window clears the hover through the repaint. + if err := h.drv.Leave(); err != nil { + t.Fatal(err) + } + h.repaint() + if index, active := h.index(); active || index != -1 { + t.Fatalf("hover after leaving = (%d, %v), want (-1, false)", index, active) + } + if h.hover != -1 || h.active { + t.Fatalf("OnHover = (%d, %v) after leaving, want (-1, false)", h.hover, h.active) + } +} + +// Arrow, Home and End move the hovered point through the components' own key +// mapping, and the chart reports each move. +func TestAreaViewKeyboard(t *testing.T) { + h := openArea(t) + r := h.box.Rect() + h.click(r.X+r.Width/2, r.Y+r.Height/2) + before, active := h.index() + if !active { + t.Fatal("the click did not hover a point") + } + h.key(gfx.KeyRight) + next, active := h.index() + if !active || next != min(before+1, 5) { + t.Fatalf("Right hovered %d, want %d", next, min(before+1, 5)) + } + if h.hover != next || !h.active { + t.Fatalf("OnHover = (%d, %v), want (%d, true)", h.hover, h.active, next) + } + h.key(gfx.KeyHome) + if index, _ := h.index(); index != 0 { + t.Fatalf("Home hovered %d, want 0", index) + } + h.key(gfx.KeyEnd) + if index, _ := h.index(); index != 5 { + t.Fatalf("End hovered %d, want 5", index) + } +} + +// The wheel has no chart behavior of its own: the callback sees it. +func TestAreaViewScrollCallback(t *testing.T) { + h := openArea(t) + r := h.box.Rect() + h.move(r.X+r.Width/2, r.Y+r.Height/2) + if err := h.drv.Scroll(gfx.ScrollEvent{X: r.X + r.Width/2, Y: r.Y + r.Height/2, DeltaY: 1}); err != nil { + t.Fatal(err) + } + if h.wheels != 1 { + t.Fatalf("OnScroll called %d times, want 1", h.wheels) + } +} + +// The bar view declares, paints and hovers with the same model. +func TestBarViewPointerHover(t *testing.T) { + h := openBar(t) + r := h.box.Rect() + h.move(r.X+r.Width/2, r.Y+r.Height/2) + index, active := h.index() + if !active || index < 0 { + t.Fatalf("bar hover = (%d, %v), want an active category", index, active) + } + if h.hover != index || !h.active { + t.Fatalf("OnHover = (%d, %v), want (%d, true)", h.hover, h.active, index) + } + if err := h.drv.Leave(); err != nil { + t.Fatal(err) + } + h.repaint() + if index, active := h.index(); active || index != -1 { + t.Fatalf("bar hover after leaving = (%d, %v), want (-1, false)", index, active) + } +} + +func paintPage(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 320}, view) + canvas.EndFrame() +} + +// A warm chart paint adds no allocation of its own: the view's handlers and +// draw function are made once, and the components painter reuses ChartState. +func BenchmarkAreaViewPaint(b *testing.B) { + view := &chartview.AreaChartView{Chart: areaChart()} + viewFn := func(c ui.C) { + chartview.View(c, "Visitors", view).Size(400, 240) + } + var tree gfx.Tree + page := ui.NewPage(ui.PageConfig{Tree: &tree, View: viewFn}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(func(Value string, Size, Weight float32) float32 { return float32(len(Value)) * Size / 2 }) + paintPage(page, canvas, viewFn) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + paintPage(page, canvas, viewFn) + } +} + +var containerHeights = [...]float32{0.42, 0.28, 0.60, 0.36, 0.72, 0.48, 0.88, 0.62} + +func newContainer() *chartview.Container { + return &chartview.Container{ + Series: []chartview.Series{ + {Key: "native", Label: "Native", Color: gfx.Color{Red: .2, Green: .52, Blue: .96, Alpha: 1}}, + {Key: "web", Label: "Web", Color: gfx.Color{Red: .53, Green: .36, Blue: .92, Alpha: 1}}, + }, + Options: chartview.ContainerOptions{Legend: chartview.LegendBottom}, + Tooltip: &chartview.Tooltip{ + Rows: []chartview.TooltipRow{{Series: 0, Value: "42"}, {Series: 1, Value: "28"}}, + Options: chartview.TooltipOptions{ + Label: "Week 4", Indicator: chartview.TooltipDot, + }, + }, + Draw: func(d *ui.DrawContext, layout chartview.Layout) { + plot := layout.PlotBounds + baseline := plot.Y + plot.Height - 14 + barWidth := min(float32(30), (plot.Width-40)/8) + gap := (plot.Width - barWidth*8) / 9 + for index, scale := range containerHeights { + x := plot.X + gap + float32(index)*(barWidth+gap) + height := (plot.Height - 34) * scale + d.Canvas.Rounded(gfx.Rect{X: x, Y: baseline - height, Width: barWidth, Height: height}, 3, gfx.Color{Red: .2, Green: .4, Blue: .8, Alpha: 1}) + } + }, + } +} + +// ContainerView paints the container, hands Draw the resolved plot, and paints +// the tooltip over it. +func TestContainerViewPaint(t *testing.T) { + container := newContainer() + drawn, bounds := 0, gfx.Rect{} + container.Draw = func(d *ui.DrawContext, layout chartview.Layout) { + drawn++ + bounds = layout.Bounds + d.Canvas.Fill(layout.PlotBounds, gfx.Color{Alpha: .1}) + } + viewFn := func(c ui.C) { + chartview.ContainerView(c, "Commits", container).Size(400, 240) + } + var tree gfx.Tree + page := ui.NewPage(ui.PageConfig{Tree: &tree, View: viewFn}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(func(Value string, Size, Weight float32) float32 { return float32(len(Value)) * Size / 2 }) + paintPage(page, canvas, viewFn) + + if drawn != 1 { + t.Fatalf("Draw called %d times during one paint, want 1", drawn) + } + if bounds.Width != 400 || bounds.Height != 240 { + t.Fatalf("container bounds = %v, want 400x240", bounds) + } + var legend, label, value bool + for _, text := range canvas.Texts() { + switch text.Value { + case "Native": + legend = true + case "Week 4": + label = true + case "42": + value = true + } + } + if !legend { + t.Fatal("the container did not paint its legend") + } + if !label || !value { + t.Fatalf("the tooltip did not paint its label and row: label=%v value=%v", label, value) + } +} + +// A warm container paint adds no allocation: the draw function and handlers are +// made once with the container. +func BenchmarkContainerViewPaint(b *testing.B) { + container := newContainer() + viewFn := func(c ui.C) { + chartview.ContainerView(c, "Commits", container).Size(400, 240) + } + var tree gfx.Tree + page := ui.NewPage(ui.PageConfig{Tree: &tree, View: viewFn}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(func(Value string, Size, Weight float32) float32 { return float32(len(Value)) * Size / 2 }) + paintPage(page, canvas, viewFn) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + paintPage(page, canvas, viewFn) + } +} diff --git a/ui/chartview/container.go b/ui/chartview/container.go new file mode 100644 index 00000000..c1519067 --- /dev/null +++ b/ui/chartview/container.go @@ -0,0 +1,112 @@ +package chartview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// containerDefaultHeight is the height a container takes when the caller gives +// none. It leaves room for the legend and a readable plot. +const containerDefaultHeight float32 = 200 + +// containerTooltipInset is the gap between the tooltip and the plot edge. +const containerTooltipInset float32 = 8 + +// containerTooltipLayer is the layer a tooltip with no explicit Layer uses. +const containerTooltipLayer uint16 = 4 + +// Container is a caller-owned chart container and the geometry drawn inside it. +// PaintChartContainer resolves the legend and the plot rectangle; Draw receives +// that layout so the caller paints its own bars, lines or annotations in it. A +// Tooltip snapshot, when set, is painted over the plot after Draw. +// +// Declare the container with the model and fill Series, Tooltip and any changed +// Options each paint. Draw is set once, when the model is created: ContainerView +// keeps it and the handlers, so a warm paint allocates nothing. Do not copy a +// container after it has been declared. +type Container struct { + // Series is the metadata the legend and the tooltip read. + Series []components.ChartSeries + // Options configures the container chrome, currently its legend. + Options components.ChartContainerOptions + // Tooltip is the caller-owned payload painted over the plot. Nil paints no + // tooltip. + Tooltip *Tooltip + // Draw paints the caller's data geometry inside layout.PlotBounds. It runs + // after the container chrome and before the tooltip; nil draws nothing. + Draw func(*ui.DrawContext, Layout) + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool +} + +// Tooltip is the typed snapshot a Container paints: the rows to show and the +// options that frame them. The container measures it and places it at the +// plot's top-right corner, moving it inside the plot when that would overflow. +type Tooltip struct { + Rows []components.ChartTooltipRow + Options components.ChartTooltipOptions +} + +// ContainerView declares c's chart container. It paints the container chrome, +// calls Container.Draw with the resolved layout, and paints Container.Tooltip +// when one is set. The returned box is full width and 200 high unless a Width +// or Height follows it. label names the control for assistive technology. +// +// Declare the container with the model, not inside a Memo. +func ContainerView(c ui.C, label string, container *Container) ui.Box { + if container == nil { + panic("chartview: ContainerView needs its Container") + } + container.prepare() + return ui.Control(c, label, &container.handlers). + FillWidth().Height(containerDefaultHeight). + Draw(container.drawFn) +} + +func (c *Container) prepare() { + if c.prepared { + return + } + c.prepared = true + c.drawFn = c.draw +} + +func (c *Container) draw(d *ui.DrawContext) { + layout := components.PaintChartContainer(d.Canvas, *d.Theme, d.Rect, c.Series, c.Options) + if c.Draw != nil { + c.Draw(d, layout) + } + if c.Tooltip != nil { + c.paintTooltip(d, layout) + } +} + +// paintTooltip places the tooltip at the plot's top-right corner and keeps it +// inside the plot when it is wider or taller than the space to the edge. +func (c *Container) paintTooltip(d *ui.DrawContext, layout Layout) { + tooltip := c.Tooltip + plot := layout.PlotBounds + options := tooltip.Options + if options.Layer == 0 { + options.Layer = containerTooltipLayer + } + size := components.ChartTooltipSize(d.Canvas, *d.Theme, c.Series, tooltip.Rows, options) + if size.Width <= 0 || size.Height <= 0 { + return + } + x := plot.X + plot.Width - size.Width - containerTooltipInset + if x < plot.X { + x = plot.X + } + y := plot.Y + containerTooltipInset + if y+size.Height > plot.Y+plot.Height { + y = plot.Y + plot.Height - size.Height + } + if y < plot.Y { + y = plot.Y + } + components.PaintChartTooltip(d.Canvas, *d.Theme, gfx.Rect{X: x, Y: y}, c.Series, tooltip.Rows, options) +} diff --git a/ui/chartview/page.go b/ui/chartview/page.go new file mode 100644 index 00000000..b8d07713 --- /dev/null +++ b/ui/chartview/page.go @@ -0,0 +1,90 @@ +package chartview + +import "github.com/vivaui/viva/components" + +// The chart vocabulary a page names without importing package components. The +// types and constants are aliases of the components package's: a chartview data +// set is the same value the painters read, so passing it on costs nothing. + +// Series is one series' metadata: the legend and tooltip label and its color. +type Series = components.ChartSeries + +// AreaChart is the data and presentation of an area or line chart. +type AreaChart = components.AreaChart + +// BarChart is the data and presentation of a bar chart. +type BarChart = components.BarChart + +// Axis configures a chart's X or Y axis. +type Axis = components.ChartAxis + +// AreaStyle overrides one series' area fill. +type AreaStyle = components.ChartAreaStyle + +// AreaGradient is a vertical fill gradient between two colors. +type AreaGradient = components.ChartAreaGradient + +// Layout is the container's resolved bounds: the plot the caller draws its own +// geometry into and the legend chrome around it. +type Layout = components.ChartLayout + +// ContainerOptions configures the chart container's legend. +type ContainerOptions = components.ChartContainerOptions + +// TooltipRow is one row of a tooltip's caller-owned payload. +type TooltipRow = components.ChartTooltipRow + +// TooltipOptions configures the tooltip's label, indicator and layer. +type TooltipOptions = components.ChartTooltipOptions + +// Chart legends. +const ( + LegendNone = components.ChartLegendNone + LegendTop = components.ChartLegendTop + LegendBottom = components.ChartLegendBottom +) + +// Area and bar chart curves. +const ( + CurveLinear = components.ChartCurveLinear + CurveNatural = components.ChartCurveNatural + CurveMonotone = components.ChartCurveMonotone + CurveStep = components.ChartCurveStep +) + +// Area chart fills. +const ( + FillGradient = components.ChartFillGradient + FillSolid = components.ChartFillSolid + FillNone = components.ChartFillNone +) + +// Chart grids. +const ( + GridNone = components.ChartGridNone + GridHorizontal = components.ChartGridHorizontal + GridVertical = components.ChartGridVertical + GridBoth = components.ChartGridBoth +) + +// How series combine at one X. +const ( + StackNone = components.ChartStackNone + StackStacked = components.ChartStackStacked + StackExpand = components.ChartStackExpand +) + +// Tooltip payload indicators. +const ( + TooltipDot = components.ChartTooltipDot + TooltipLine = components.ChartTooltipLine + TooltipDashed = components.ChartTooltipDashed +) + +// Downsample is the page control's name for components.ChartDownsample: it +// returns the ascending indices of the points worth keeping for the bucket +// budget. Reduce once when the data changes and draw the reduced series on +// every paint. +func Downsample(dst []int, x, y []float32, buckets int) []int { + return components.ChartDownsample(dst, x, y, buckets) +} diff --git a/ui/codeeditor/canvas.go b/ui/codeeditor/canvas.go new file mode 100644 index 00000000..c897911d --- /dev/null +++ b/ui/codeeditor/canvas.go @@ -0,0 +1,98 @@ +package codeeditor + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// Canvas is a page canvas of the application's own when no typed wrapper fits: +// the caller paints it and takes its input through callbacks, while the wrapper +// owns the control's stable handlers and identity. The zero value is ready; one +// Canvas serves one place on a page. +// +// Draw runs with the control's ui.DrawContext, whose Node.ID is the control's +// hit, so a canvas that declares hits of its own can name them in Parts. Keep +// Draw a function made once (a method value stored on the model), not a closure +// made in the page function, or a warm paint allocates. +type Canvas struct { + // Role is what assistive technology takes the control for. Zero is a group; + // RoleTextField or RoleTerminal give typed text to Text. + Role gfx.Role + // Draw paints the canvas. Nil paints nothing. + Draw func(*ui.DrawContext) + // Key receives the keys pressed while the canvas has focus. + Key func(gfx.KeyEvent) gfx.EventResult + // Pointer receives the pointer events addressed to the canvas. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Scroll receives the wheel over the canvas. + Scroll func(gfx.ScrollEvent) gfx.EventResult + // Text gives the platform's text service the canvas's editor while it has the + // focus, for a RoleTextField or RoleTerminal canvas. + Text func(window.TextInputContext) *window.TextInput + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + wired bool +} + +// CanvasView declares the canvas at c. Give it a size; it is a ui.Control whose +// Draw is the caller's, with the caller's callbacks routing its input. +func CanvasView(c ui.C, label string, canvas *Canvas) ui.Box { + if canvas == nil { + panic("codeeditor: CanvasView needs its Canvas") + } + canvas.prepare() + return ui.Control(c, label, &canvas.handlers).Draw(canvas.drawFn) +} + +// Parts is the scope of this control's own hit regions. A hit the caller's Draw +// declares may name itself in it so the canvas receives its pointer events. It +// is empty until CanvasView has declared the control at least once. +func (c *Canvas) Parts() gfx.Scope { return c.handlers.Parts() } + +func (c *Canvas) prepare() { + if !c.wired { + c.wired = true + c.handlers.Key = c.key + c.handlers.Pointer = c.pointer + c.handlers.Scroll = c.scroll + c.handlers.Text = c.text + c.drawFn = c.draw + } + c.handlers.Role = c.Role +} + +func (c *Canvas) key(event gfx.KeyEvent) gfx.EventResult { + if c.Key == nil { + return gfx.EventResult{} + } + return c.Key(event) +} + +func (c *Canvas) pointer(event gfx.PointerEvent) gfx.EventResult { + if c.Pointer == nil { + return gfx.EventResult{} + } + return c.Pointer(event) +} + +func (c *Canvas) scroll(event gfx.ScrollEvent) gfx.EventResult { + if c.Scroll == nil { + return gfx.EventResult{} + } + return c.Scroll(event) +} + +func (c *Canvas) text(context window.TextInputContext) *window.TextInput { + if c.Text == nil { + return nil + } + return c.Text(context) +} + +func (c *Canvas) draw(d *ui.DrawContext) { + if c.Draw != nil { + c.Draw(d) + } +} diff --git a/ui/codeeditor/codeeditor.go b/ui/codeeditor/codeeditor.go new file mode 100644 index 00000000..4bab1f62 --- /dev/null +++ b/ui/codeeditor/codeeditor.go @@ -0,0 +1,172 @@ +// Package codeeditor is the opt-in page control for the source-code canvases +// of package components: a code editor, a line-aligned diff, a three-way merge +// and a find and replace bar. Each type keeps the caller-owned component, the +// snapshot painted at every paint and the callbacks that take its input. View +// declares the control; the wrapper owns the control's identity and input +// routing, so a call site never makes a components.Begin* control itself. +// +// editor := &codeeditor.Editor{} +// editor.Snapshot.Value = source +// ... +// codeeditor.View(c, "Source", editor).Fill() +// +// The text, undo history and selection stay in the application's text.Editor; +// Snapshot is the presentation of them. Update Snapshot outside the paint. The +// wrapper copies it at paint time and sets ID and Label to the control's own, +// so a caller does not assign them. +// +// The input callbacks are the application's: Key handles editing commands and +// movements, Pointer handles what the component's scrollbars did not take, and +// Text supplies the platform's text service with the application's editor. +// Each may be nil. Declare a View on its own, not inside a ui.Memo. +package codeeditor + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// New is an Editor that paints document: its value, caret, selection and +// composition are copied from the text model at every paint, so the page does +// not assign them itself. Line numbers, the current-line tint and bracket +// matching are on; turn them off in Snapshot, or set Language and Highlight +// there. +func New(document *text.Editor) *Editor { + return &Editor{ + Document: document, + Snapshot: components.CodeEditorSnapshot{ + LineNumbers: true, CurrentLine: true, MatchBrackets: true, + }, + } +} + +// Editor is one code editor's page control. Keep it in the model beside the +// application's text.Editor. The zero value is ready; one Editor serves one +// place on a page and one text.Editor. Keep it where View finds it: its stable +// handlers and draw function point at this value, so do not copy an Editor +// after it has been declared. +// +// Code keeps the component's layout, scroll and caret caches across paints. +// Snapshot is the presentation painted next; the wrapper sets its ID and Label. +type Editor struct { + // Document, when set, is the application's text model. The wrapper copies + // its value, caret, selection and composition into Snapshot at every paint; + // the application still owns the text, undo and editing commands. + Document *text.Editor + // Code is the caller-owned code editor view. + Code components.CodeEditor + // Snapshot is painted at every paint. Update it when the text, selection or + // other presentation state changes. + Snapshot components.CodeEditorSnapshot + // Key receives the keys pressed while the editor has focus. See + // components.CodeEditorCommandForKey and components.CodeEditor.Move. + Key func(gfx.KeyEvent) gfx.EventResult + // Pointer receives the pointer events the editor's scrollbars did not handle. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Scroll receives the wheel the editor did not scroll. A nil callback leaves + // what the editor cannot scroll to the page. + Scroll func(gfx.ScrollEvent) gfx.EventResult + // Text gives the platform's text service the application's editor for the + // focused control. Nil disables native editing and input methods. + Text func(window.TextInputContext) *window.TextInput + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + wired bool +} + +// View declares the editor at c. Give it a size; it is a ui.Control with a +// text-field role, painted through the component. The component paints in a box +// at least 64 pixels tall, so give it a height a code editor can use. The +// control's identity and labels are the wrapper's, so the snapshot's ID and +// Label are ignored. +func View(c ui.C, label string, editor *Editor) ui.Box { + if editor == nil { + panic("codeeditor: View needs its Editor") + } + editor.prepare() + return ui.Control(c, label, &editor.handlers).Draw(editor.drawFn) +} + +// Parts is the scope of this control's own hit regions. Caller-owned hits +// painted by a snapshot (gutter markers and fold markers) may name themselves +// in it so this control receives their pointer events; the scrollbars use At(0) +// and At(1) when the snapshot enables them. It is empty until View has declared +// the control at least once. +func (e *Editor) Parts() gfx.Scope { return e.handlers.Parts() } + +func (e *Editor) prepare() { + if e.wired { + return + } + e.wired = true + e.handlers.Role = gfx.RoleTextField + e.handlers.Key = e.key + e.handlers.Pointer = e.pointer + e.handlers.Scroll = e.scroll + e.handlers.Text = e.text + e.drawFn = e.draw +} + +func (e *Editor) key(event gfx.KeyEvent) gfx.EventResult { + if e.Key == nil { + return gfx.EventResult{} + } + return e.Key(event) +} + +func (e *Editor) pointer(event gfx.PointerEvent) gfx.EventResult { + if result := e.Code.Pointer(event); result.Handled { + return result + } + if e.Pointer == nil { + return gfx.EventResult{} + } + return e.Pointer(event) +} + +func (e *Editor) scroll(event gfx.ScrollEvent) gfx.EventResult { + if result := e.Code.Scroll(event); result.Handled { + return result + } + if e.Scroll == nil { + return gfx.EventResult{} + } + return e.Scroll(event) +} + +func (e *Editor) text(context window.TextInputContext) *window.TextInput { + if e.Text == nil { + return nil + } + return e.Text(context) +} + +func (e *Editor) draw(d *ui.DrawContext) { + snapshot := e.Snapshot + if e.Document != nil { + snapshot.Value = e.Document.String() + snapshot.Caret = e.Document.ByteOffset(e.Document.Caret()) + selection := e.Document.Selection() + snapshot.SelectionStart = e.Document.ByteOffset(selection.Start) + snapshot.SelectionEnd = e.Document.ByteOffset(selection.End) + snapshot.CompositionStart, snapshot.CompositionEnd = 0, 0 + if composition, ok := e.Document.Composition(); ok { + snapshot.CompositionStart = e.Document.ByteOffset(composition.Start) + snapshot.CompositionEnd = e.Document.ByteOffset(composition.End) + } + } + snapshot.ID = d.Node.ID + snapshot.Label = d.Label + parts := e.handlers.Parts() + if !snapshot.ScrollbarID.IsZero() { + snapshot.ScrollbarID = parts.At(0) + } + if !snapshot.HorizontalScrollbarID.IsZero() { + snapshot.HorizontalScrollbarID = parts.At(1) + } + e.Code.Paint(d.Canvas, *d.Theme, d.Rect, snapshot) +} diff --git a/ui/codeeditor/codeeditor_test.go b/ui/codeeditor/codeeditor_test.go new file mode 100644 index 00000000..d9b403b6 --- /dev/null +++ b/ui/codeeditor/codeeditor_test.go @@ -0,0 +1,404 @@ +package codeeditor_test + +import ( + "testing" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/codeeditor" + "github.com/vivaui/viva/window" +) + +const source = `package main + +func main() { + println("hello") +} +` + +type model struct { + editor codeeditor.Editor + diff codeeditor.Diff + merge codeeditor.Merge + find codeeditor.FindBar + canvas codeeditor.Canvas + input window.TextInput + + keys, pointers, scrolls, texts, paints int +} + +func (m *model) wire() { + m.editor.Key = m.key + m.editor.Pointer = m.pointer + m.editor.Scroll = m.scroll + m.editor.Text = m.text + + m.diff.Key = m.key + m.diff.Pointer = m.pointer + m.diff.Scroll = m.scroll + m.diff.Text = m.text + + m.merge.Key = m.key + m.merge.Pointer = m.pointer + m.merge.Scroll = m.scroll + m.merge.Text = m.text + + m.find.Key = m.key + m.find.Pointer = m.pointer + m.find.Scroll = m.scroll + m.find.Text = m.text + + m.canvas.Key = m.key + m.canvas.Pointer = m.pointer + m.canvas.Scroll = m.scroll + m.canvas.Text = m.text + m.canvas.Draw = m.paint +} + +func (m *model) key(gfx.KeyEvent) gfx.EventResult { + m.keys++ + return gfx.EventResult{Handled: true} +} + +func (m *model) pointer(gfx.PointerEvent) gfx.EventResult { + m.pointers++ + return gfx.EventResult{Handled: true} +} + +func (m *model) scroll(gfx.ScrollEvent) gfx.EventResult { + m.scrolls++ + return gfx.EventResult{Handled: true} +} + +func (m *model) text(window.TextInputContext) *window.TextInput { + m.texts++ + return &m.input +} + +func (m *model) paint(d *ui.DrawContext) { + m.paints++ + d.Canvas.Fill(d.Rect, d.Theme.Card) +} + +func (m *model) editorPage(c ui.C) { codeeditor.View(c, "Source", &m.editor).Fill() } + +func (m *model) diffPage(c ui.C) { codeeditor.DiffView(c, "Changes", &m.diff).Fill() } + +func (m *model) mergePage(c ui.C) { codeeditor.MergeView(c, "Merge", &m.merge).Fill() } + +func (m *model) findPage(c ui.C) { codeeditor.FindBarView(c, "Find", &m.find).FillWidth() } + +func (m *model) canvasPage(c ui.C) { codeeditor.CanvasView(c, "Canvas", &m.canvas).Fill() } + +func testTheme() *gfx.Theme { + theme := gfx.LightTheme() + return &theme +} + +func drawPage(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 420}, view) + canvas.EndFrame() +} + +// hitLabelled returns the front-most hit with the label: the control's own hit +// or, later in the hit order, the text region the component declared over it. +func hitLabelled(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + if hits[i].Label == label && !hits[i].ID.IsZero() { + return hits[i], true + } + } + return gfx.Hit{}, false +} + +// A page declares the editor View, the editor paints, and a pointer, key and +// text call reach the callbacks the model stored. +func TestEditorViewPaintsAndRoutesInput(t *testing.T) { + m := new(model) + m.wire() + m.editor.Snapshot = components.CodeEditorSnapshot{ + Value: source, LineNumbers: true, CurrentLine: true, MatchBrackets: true, + } + page := ui.NewPage(ui.PageConfig{View: m.editorPage, Theme: testTheme()}) + canvas := new(gfx.Canvas) + drawPage(page, canvas, m.editorPage) + + hit, ok := hitLabelled(canvas, "Source") + if !ok { + t.Fatal("the editor view painted no control named Source") + } + if hit.Role != gfx.RoleTextField || !hit.Multiline { + t.Fatalf("editor hit = role %v multiline %v, want a multiline text field", hit.Role, hit.Multiline) + } + + if result := page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: hit.ID, + X: hit.Bounds.X + 4, Y: hit.Bounds.Y + 4, + }); !result.Handled || m.pointers != 1 { + t.Fatalf("pointer result = %+v after %d callbacks", result, m.pointers) + } + if result := page.Key(gfx.KeyEvent{Key: gfx.KeyUp, Target: hit.ID}); !result.Handled || m.keys != 1 { + t.Fatalf("key result = %+v after %d callbacks", result, m.keys) + } + if page.TextInput(window.TextInputContext{ID: hit.ID}) == nil || m.texts != 1 { + t.Fatalf("text service got no editor; callbacks = %d", m.texts) + } +} + +func TestDiffViewPaintsAndRoutesInput(t *testing.T) { + m := new(model) + m.wire() + left, right := "one\ntwo\nthree\n", "one\nTWO\nthree\n" + m.diff.Snapshot = components.CodeDiffSnapshot{ + Result: components.DiffCodeLines(left, right), + Value: right, + } + page := ui.NewPage(ui.PageConfig{View: m.diffPage, Theme: testTheme()}) + canvas := new(gfx.Canvas) + drawPage(page, canvas, m.diffPage) + + hit, ok := hitLabelled(canvas, "Changes") + if !ok { + t.Fatal("the diff view painted no control named Changes") + } + if hit.Role != gfx.RoleTextField || !hit.Multiline { + t.Fatalf("diff hit = role %v multiline %v, want a multiline text field", hit.Role, hit.Multiline) + } + if result := page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: hit.ID, + X: hit.Bounds.X + 4, Y: hit.Bounds.Y + 4, + }); !result.Handled || m.pointers != 1 { + t.Fatalf("pointer result = %+v after %d callbacks", result, m.pointers) + } + if result := page.Key(gfx.KeyEvent{Key: gfx.KeyDown, Target: hit.ID}); !result.Handled || m.keys != 1 { + t.Fatalf("key result = %+v after %d callbacks", result, m.keys) + } + if page.TextInput(window.TextInputContext{ID: hit.ID}) == nil || m.texts != 1 { + t.Fatalf("text service got no editor; callbacks = %d", m.texts) + } +} + +func TestMergeViewPaintsAndRoutesInput(t *testing.T) { + m := new(model) + m.wire() + result := "one\ntwo\nthree" + m.merge.Snapshot = components.CodeMergeSnapshot{ + Current: []string{"one", "two", "three"}, + Incoming: []string{"one", "TWO", "three"}, + Rows: []components.CodeMergeRow{ + {CurrentLine: 0, ResultLine: 0, IncomingLine: 0}, + {CurrentLine: 1, ResultLine: 1, IncomingLine: 1, CurrentChanged: true, IncomingChanged: true}, + {CurrentLine: 2, ResultLine: 2, IncomingLine: 2}, + }, + Editor: components.CodeDiffSnapshot{Value: result}, + } + page := ui.NewPage(ui.PageConfig{View: m.mergePage, Theme: testTheme()}) + canvas := new(gfx.Canvas) + drawPage(page, canvas, m.mergePage) + + hit, ok := hitLabelled(canvas, "Merge") + if !ok { + t.Fatal("the merge view painted no control named Merge") + } + if hit.Role != gfx.RoleTextField || !hit.Multiline { + t.Fatalf("merge hit = role %v multiline %v, want a multiline text field", hit.Role, hit.Multiline) + } + if result := page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: hit.ID, + X: hit.Bounds.X + 4, Y: hit.Bounds.Y + 4, + }); !result.Handled || m.pointers != 1 { + t.Fatalf("pointer result = %+v after %d callbacks", result, m.pointers) + } + if result := page.Key(gfx.KeyEvent{Key: gfx.KeyDown, Target: hit.ID}); !result.Handled || m.keys != 1 { + t.Fatalf("key result = %+v after %d callbacks", result, m.keys) + } + if page.TextInput(window.TextInputContext{ID: hit.ID}) == nil || m.texts != 1 { + t.Fatalf("text service got no editor; callbacks = %d", m.texts) + } +} + +func testFindBarSnapshot() components.FindBarSnapshot { + return components.FindBarSnapshot{ + Find: components.InputSnapshot{ID: codeeditor.Shown, Label: "Query", Value: "name", Placeholder: "Find"}, + Replacement: components.InputSnapshot{ID: codeeditor.Shown, Label: "Replace with", Value: "title", Placeholder: "Replace"}, + Replacing: true, + PreviousID: codeeditor.Shown, NextID: codeeditor.Shown, CloseID: codeeditor.Shown, + MatchCaseID: codeeditor.Shown, WholeWordID: codeeditor.Shown, RegexpID: codeeditor.Shown, + ToggleReplaceID: codeeditor.Shown, ReplaceOneID: codeeditor.Shown, ReplaceAllID: codeeditor.Shown, + MatchCase: true, Status: "2 of 4", + Labels: components.FindBarLabels{ + Previous: "Previous match", Next: "Next match", Close: "Close", + MatchCase: "Match case", WholeWord: "Whole word", Regexp: "Regular expression", + ToggleReplace: "Toggle replace", ReplaceOne: "Replace", ReplaceAll: "Replace all", + }, + } +} + +func TestFindBarViewPaintsAndRoutesInput(t *testing.T) { + m := new(model) + m.wire() + m.find.Snapshot = testFindBarSnapshot() + page := ui.NewPage(ui.PageConfig{View: m.findPage, Theme: testTheme()}) + canvas := new(gfx.Canvas) + drawPage(page, canvas, m.findPage) + + hit, ok := hitLabelled(canvas, "Find") + if !ok { + t.Fatal("the find bar view painted no control named Find") + } + if want := components.FindBarHeight(*testTheme(), true); hit.Bounds.Height != want { + t.Fatalf("find bar height = %g, want %g", hit.Bounds.Height, want) + } + if field, ok := hitLabelled(canvas, "Query"); !ok || field.Role != gfx.RoleTextField { + t.Fatalf("the find input painted no text field: hit %v, found %v", field, ok) + } + if _, ok := hitLabelled(canvas, "Next match"); !ok { + t.Fatal("the find bar painted no next-match button") + } + parts := m.find.Parts() + if parts.IsZero() || parts.At(codeeditor.PartReplaceAll).IsZero() { + t.Fatal("the find bar declared no parts") + } + labels := [...]string{ + "Query", "Replace with", "Previous match", "Next match", "Close", + "Match case", "Whole word", "Regular expression", + "Toggle replace", "Replace", "Replace all", + } + for index, label := range labels { + control, ok := hitLabelled(canvas, label) + if !ok { + t.Fatalf("%q painted no hit", label) + } + if want := parts.At(index); control.ID != want { + t.Fatalf("%q hit = %v, want part %v", label, control.ID, want) + } + } + + if result := page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: parts.At(codeeditor.PartNext), + X: hit.Bounds.X + 4, Y: hit.Bounds.Y + 4, + }); !result.Handled || m.pointers != 1 { + t.Fatalf("pointer result = %+v after %d callbacks", result, m.pointers) + } + if result := page.Key(gfx.KeyEvent{Key: gfx.KeyEnter, Target: parts.At(codeeditor.PartFind)}); !result.Handled || m.keys != 1 { + t.Fatalf("key result = %+v after %d callbacks", result, m.keys) + } + if result := page.Wheel(gfx.ScrollEvent{Target: parts.At(codeeditor.PartFind)}); !result.Handled || m.scrolls != 1 { + t.Fatalf("scroll result = %+v after %d callbacks", result, m.scrolls) + } + if page.TextInput(window.TextInputContext{ID: hit.ID}) == nil || m.texts != 1 { + t.Fatalf("text service got no editor for the control; callbacks = %d", m.texts) + } + if page.TextInput(window.TextInputContext{ID: parts.At(codeeditor.PartFind)}) == nil || m.texts != 2 { + t.Fatalf("text service got no editor for the query field; callbacks = %d", m.texts) + } +} + +func TestCanvasViewPaintsAndRoutesInput(t *testing.T) { + m := new(model) + m.wire() + m.canvas.Role = gfx.RoleTerminal + page := ui.NewPage(ui.PageConfig{View: m.canvasPage, Theme: testTheme()}) + canvas := new(gfx.Canvas) + drawPage(page, canvas, m.canvasPage) + + hit, ok := hitLabelled(canvas, "Canvas") + if !ok || m.paints == 0 { + t.Fatalf("the canvas view painted no control: hit %v, draw calls %d", ok, m.paints) + } + if hit.Role != gfx.RoleTerminal { + t.Fatalf("canvas hit role = %v, want terminal", hit.Role) + } + if result := page.Pointer(gfx.PointerEvent{Kind: gfx.PointerDown, Target: hit.ID}); !result.Handled || m.pointers != 1 { + t.Fatalf("pointer result = %+v after %d callbacks", result, m.pointers) + } + if result := page.Key(gfx.KeyEvent{Key: gfx.KeyEnter, Target: hit.ID}); !result.Handled || m.keys != 1 { + t.Fatalf("key result = %+v after %d callbacks", result, m.keys) + } + if page.TextInput(window.TextInputContext{ID: hit.ID}) == nil || m.texts != 1 { + t.Fatalf("text service got no editor; callbacks = %d", m.texts) + } +} + +func TestNewBindsTheTextDocument(t *testing.T) { + document := text.NewEditor(source) + document.SetSelection(text.Range{Start: 2, End: 5}) + editor := codeeditor.New(document) + if editor.Document != document { + t.Fatal("New did not keep the document") + } + if !editor.Snapshot.LineNumbers || !editor.Snapshot.CurrentLine || !editor.Snapshot.MatchBrackets { + t.Fatalf("New defaults = %+v, want line numbers, current line and brackets", editor.Snapshot) + } +} + +// A warm editor paint, including the page's declaration and the component's +// layout caches, allocates nothing. +func TestEditorViewWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.wire() + m.editor.Snapshot = components.CodeEditorSnapshot{ + Value: source, LineNumbers: true, CurrentLine: true, MatchBrackets: true, + } + page := ui.NewPage(ui.PageConfig{View: m.editorPage, Theme: testTheme()}) + canvas := new(gfx.Canvas) + for range 4 { + drawPage(page, canvas, m.editorPage) + } + if allocs := testing.AllocsPerRun(50, func() { drawPage(page, canvas, m.editorPage) }); allocs != 0 { + t.Fatalf("a warm editor paint allocated %g times", allocs) + } +} + +func BenchmarkEditorViewWarmPaint(b *testing.B) { + m := new(model) + m.wire() + m.editor.Snapshot = components.CodeEditorSnapshot{ + Value: source, LineNumbers: true, CurrentLine: true, MatchBrackets: true, + } + page := ui.NewPage(ui.PageConfig{View: m.editorPage, Theme: testTheme()}) + canvas := new(gfx.Canvas) + for range 4 { + drawPage(page, canvas, m.editorPage) + } + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, m.editorPage) + } +} + +// A warm find bar paint, including the page's declaration and the component's +// text caches, allocates nothing. +func TestFindBarViewWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.wire() + m.find.Snapshot = testFindBarSnapshot() + page := ui.NewPage(ui.PageConfig{View: m.findPage, Theme: testTheme()}) + canvas := new(gfx.Canvas) + for range 4 { + drawPage(page, canvas, m.findPage) + } + if allocs := testing.AllocsPerRun(50, func() { drawPage(page, canvas, m.findPage) }); allocs != 0 { + t.Fatalf("a warm find bar paint allocated %g times", allocs) + } +} + +func BenchmarkFindBarViewWarmPaint(b *testing.B) { + m := new(model) + m.wire() + m.find.Snapshot = testFindBarSnapshot() + page := ui.NewPage(ui.PageConfig{View: m.findPage, Theme: testTheme()}) + canvas := new(gfx.Canvas) + for range 4 { + drawPage(page, canvas, m.findPage) + } + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, m.findPage) + } +} diff --git a/ui/codeeditor/diff.go b/ui/codeeditor/diff.go new file mode 100644 index 00000000..0ae0b0fa --- /dev/null +++ b/ui/codeeditor/diff.go @@ -0,0 +1,115 @@ +package codeeditor + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// Diff is one code diff's page control. Its right pane is the editable source, +// so keep it beside the application's text.Editor and point Text at it. The +// zero value is ready; one Diff serves one place on a page. Keep it where +// DiffView finds it: its stable handlers and draw function point at this value, +// so do not copy a Diff after it has been declared. +// +// Code keeps the component's layout and scroll caches across paints. Snapshot +// is the presentation painted next; the wrapper sets its ID and Label. +type Diff struct { + // Code is the caller-owned diff view. + Code components.CodeDiff + // Snapshot is painted at every paint. + Snapshot components.CodeDiffSnapshot + // Key receives the keys pressed while the diff has focus. + Key func(gfx.KeyEvent) gfx.EventResult + // Pointer receives the pointer events the diff's scrollbars did not handle, + // including presses on gutter regions. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Scroll receives the wheel the diff did not scroll. + Scroll func(gfx.ScrollEvent) gfx.EventResult + // Text gives the platform's text service the application's editor for the + // focused control. Nil disables native editing and input methods. + Text func(window.TextInputContext) *window.TextInput + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + wired bool +} + +// DiffView declares the diff at c. Give it a size; it is a ui.Control with a +// text-field role, painted through the component. The wrapper sets the +// snapshot's ID and Label, and the scrollbar IDs of a snapshot that enables +// them. +func DiffView(c ui.C, label string, diff *Diff) ui.Box { + if diff == nil { + panic("codeeditor: DiffView needs its Diff") + } + diff.prepare() + return ui.Control(c, label, &diff.handlers).Draw(diff.drawFn) +} + +// Parts is the scope of this control's own hit regions, for caller-owned gutter +// actions. The scrollbars use At(0) and At(1) when the snapshot enables them. +// It is empty until DiffView has declared the control at least once. +func (d *Diff) Parts() gfx.Scope { return d.handlers.Parts() } + +func (d *Diff) prepare() { + if d.wired { + return + } + d.wired = true + d.handlers.Role = gfx.RoleTextField + d.handlers.Key = d.key + d.handlers.Pointer = d.pointer + d.handlers.Scroll = d.scroll + d.handlers.Text = d.text + d.drawFn = d.draw +} + +func (d *Diff) key(event gfx.KeyEvent) gfx.EventResult { + if d.Key == nil { + return gfx.EventResult{} + } + return d.Key(event) +} + +func (d *Diff) pointer(event gfx.PointerEvent) gfx.EventResult { + if result := d.Code.Pointer(event); result.Handled { + return result + } + if d.Pointer == nil { + return gfx.EventResult{} + } + return d.Pointer(event) +} + +func (d *Diff) scroll(event gfx.ScrollEvent) gfx.EventResult { + if result := d.Code.Scroll(event); result.Handled { + return result + } + if d.Scroll == nil { + return gfx.EventResult{} + } + return d.Scroll(event) +} + +func (d *Diff) text(context window.TextInputContext) *window.TextInput { + if d.Text == nil { + return nil + } + return d.Text(context) +} + +func (d *Diff) draw(context *ui.DrawContext) { + snapshot := d.Snapshot + snapshot.ID = context.Node.ID + snapshot.Label = context.Label + parts := d.handlers.Parts() + if !snapshot.VerticalScrollbarID.IsZero() { + snapshot.VerticalScrollbarID = parts.At(0) + } + if !snapshot.HorizontalScrollbarID.IsZero() { + snapshot.HorizontalScrollbarID = parts.At(1) + } + d.Code.Paint(context.Canvas, *context.Theme, context.Rect, snapshot) +} diff --git a/ui/codeeditor/findbar.go b/ui/codeeditor/findbar.go new file mode 100644 index 00000000..903de904 --- /dev/null +++ b/ui/codeeditor/findbar.go @@ -0,0 +1,146 @@ +package codeeditor + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// Shown is a nonzero identity for a FindBar snapshot field whose only meaning is +// that the bar shows its control. FindBarView maps every nonzero snapshot ID to +// one of its own parts, so the value itself is not kept; use this where the +// caller has no identity of its own to name the control with. +var Shown = gfx.Item(1) + +// The part of each FindBar control, in the order FindBarView maps a snapshot's +// IDs to Parts().At(i). A pointer event aimed at one carries that identity as +// its Target, and the numbers stay the same when another control is left out. +const ( + PartFind = iota + PartReplacement + PartPrevious + PartNext + PartClose + PartMatchCase + PartWholeWord + PartRegexp + PartToggleReplace + PartReplaceOne + PartReplaceAll +) + +// FindBar is one find and replace bar's page control. The zero value is ready; +// one FindBar serves one place on a page. Keep it where FindBarView finds it: its +// stable handlers and draw function point at this value, so do not copy a +// FindBar after it has been declared. +// +// Snapshot is the presentation painted next. A nonzero ID in it shows its +// control; FindBarView replaces each with its own part, so an application reads +// a click from Parts().At(PartNext), Parts().At(PartClose) and so on rather than +// from the ID it assigned. +type FindBar struct { + // Snapshot is painted at every paint. Update it when the query, options, + // status or available controls change. + Snapshot components.FindBarSnapshot + // Key receives the keys pressed while the bar or one of its parts has focus. + // See components.FindBarCommandForKey for the bar's own commands. + Key func(gfx.KeyEvent) gfx.EventResult + // Pointer receives the pointer events aimed at the bar or one of its parts. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Scroll receives the wheel over the bar. + Scroll func(gfx.ScrollEvent) gfx.EventResult + // Text gives the platform's text service the application's editor for the + // focused query or replacement field. Nil disables native editing. + Text func(window.TextInputContext) *window.TextInput + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + wired bool +} + +// FindBarView declares the bar at c, sized to components.FindBarHeight. Give it +// a width. The bar paints itself as a floating surface and declares the hits of +// its inputs and buttons; the wrapper owns the control's identity and input +// routing, so a call site never makes a components control itself. +func FindBarView(c ui.C, label string, bar *FindBar) ui.Box { + if bar == nil { + panic("codeeditor: FindBarView needs its FindBar") + } + bar.prepare() + return ui.Control(c, label, &bar.handlers). + Height(components.FindBarHeight(*c.Theme(), bar.Snapshot.Replacing)). + Draw(bar.drawFn) +} + +// Parts is the scope of the bar's own hit regions: its inputs and its buttons, +// named by the Part constants. It is empty until FindBarView has declared the +// control at least once. +func (b *FindBar) Parts() gfx.Scope { return b.handlers.Parts() } + +func (b *FindBar) prepare() { + if b.wired { + return + } + b.wired = true + b.handlers.Role = gfx.RoleGroup + b.handlers.Key = b.key + b.handlers.Pointer = b.pointer + b.handlers.Scroll = b.scroll + b.handlers.Text = b.text + b.drawFn = b.draw +} + +func (b *FindBar) key(event gfx.KeyEvent) gfx.EventResult { + if b.Key == nil { + return gfx.EventResult{} + } + return b.Key(event) +} + +func (b *FindBar) pointer(event gfx.PointerEvent) gfx.EventResult { + if b.Pointer == nil { + return gfx.EventResult{} + } + return b.Pointer(event) +} + +func (b *FindBar) scroll(event gfx.ScrollEvent) gfx.EventResult { + if b.Scroll == nil { + return gfx.EventResult{} + } + return b.Scroll(event) +} + +func (b *FindBar) text(context window.TextInputContext) *window.TextInput { + if b.Text == nil { + return nil + } + return b.Text(context) +} + +func (b *FindBar) draw(context *ui.DrawContext) { + snapshot := b.Snapshot + parts := b.handlers.Parts() + snapshot.Find.ID = part(snapshot.Find.ID, parts.At(PartFind)) + snapshot.Replacement.ID = part(snapshot.Replacement.ID, parts.At(PartReplacement)) + snapshot.PreviousID = part(snapshot.PreviousID, parts.At(PartPrevious)) + snapshot.NextID = part(snapshot.NextID, parts.At(PartNext)) + snapshot.CloseID = part(snapshot.CloseID, parts.At(PartClose)) + snapshot.MatchCaseID = part(snapshot.MatchCaseID, parts.At(PartMatchCase)) + snapshot.WholeWordID = part(snapshot.WholeWordID, parts.At(PartWholeWord)) + snapshot.RegexpID = part(snapshot.RegexpID, parts.At(PartRegexp)) + snapshot.ToggleReplaceID = part(snapshot.ToggleReplaceID, parts.At(PartToggleReplace)) + snapshot.ReplaceOneID = part(snapshot.ReplaceOneID, parts.At(PartReplaceOne)) + snapshot.ReplaceAllID = part(snapshot.ReplaceAllID, parts.At(PartReplaceAll)) + components.PaintFindBar(context.Canvas, *context.Theme, context.Rect, snapshot) +} + +// part maps a caller's nonzero identity, which only marks the control as shown, +// to the part this control declares for it. A zero identity leaves it out. +func part(id, mapped gfx.ID) gfx.ID { + if id.IsZero() { + return gfx.ID{} + } + return mapped +} diff --git a/ui/codeeditor/merge.go b/ui/codeeditor/merge.go new file mode 100644 index 00000000..e5b7554e --- /dev/null +++ b/ui/codeeditor/merge.go @@ -0,0 +1,113 @@ +package codeeditor + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// Merge is one three-way merge's page control. Its center pane is the editable +// result, so keep it beside the application's text.Editor and point Text at it. +// The zero value is ready; one Merge serves one place on a page. +// +// Code keeps the component's layout and scroll caches across paints. Snapshot +// is the presentation painted next; the wrapper sets the editor snapshot's ID +// and Label, which the component uses for the editable result pane. +type Merge struct { + // Code is the caller-owned merge view. + Code components.CodeMerge + // Snapshot is painted at every paint. + Snapshot components.CodeMergeSnapshot + // Key receives the keys pressed while the merge has focus. + Key func(gfx.KeyEvent) gfx.EventResult + // Pointer receives the pointer events the merge's scrollbars did not handle, + // including presses on the current and incoming action regions. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Scroll receives the wheel the merge did not scroll. + Scroll func(gfx.ScrollEvent) gfx.EventResult + // Text gives the platform's text service the application's editor for the + // focused control. Nil disables native editing and input methods. + Text func(window.TextInputContext) *window.TextInput + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + wired bool +} + +// MergeView declares the merge at c. Give it a size; it is a ui.Control with a +// text-field role, painted through the component. The wrapper sets the editor +// snapshot's ID and Label, and its scrollbar IDs when the snapshot enables them. +func MergeView(c ui.C, label string, merge *Merge) ui.Box { + if merge == nil { + panic("codeeditor: MergeView needs its Merge") + } + merge.prepare() + return ui.Control(c, label, &merge.handlers).Draw(merge.drawFn) +} + +// Parts is the scope of this control's own hit regions, for caller-owned actions. +// The scrollbars use At(0) and At(1) when the snapshot enables them. It is empty +// until MergeView has declared the control at least once. +func (m *Merge) Parts() gfx.Scope { return m.handlers.Parts() } + +func (m *Merge) prepare() { + if m.wired { + return + } + m.wired = true + m.handlers.Role = gfx.RoleTextField + m.handlers.Key = m.key + m.handlers.Pointer = m.pointer + m.handlers.Scroll = m.scroll + m.handlers.Text = m.text + m.drawFn = m.draw +} + +func (m *Merge) key(event gfx.KeyEvent) gfx.EventResult { + if m.Key == nil { + return gfx.EventResult{} + } + return m.Key(event) +} + +func (m *Merge) pointer(event gfx.PointerEvent) gfx.EventResult { + if result := m.Code.Pointer(event); result.Handled { + return result + } + if m.Pointer == nil { + return gfx.EventResult{} + } + return m.Pointer(event) +} + +func (m *Merge) scroll(event gfx.ScrollEvent) gfx.EventResult { + if result := m.Code.Scroll(event); result.Handled { + return result + } + if m.Scroll == nil { + return gfx.EventResult{} + } + return m.Scroll(event) +} + +func (m *Merge) text(context window.TextInputContext) *window.TextInput { + if m.Text == nil { + return nil + } + return m.Text(context) +} + +func (m *Merge) draw(context *ui.DrawContext) { + snapshot := m.Snapshot + snapshot.Editor.ID = context.Node.ID + snapshot.Editor.Label = context.Label + parts := m.handlers.Parts() + if !snapshot.Editor.VerticalScrollbarID.IsZero() { + snapshot.Editor.VerticalScrollbarID = parts.At(0) + } + if !snapshot.Editor.HorizontalScrollbarID.IsZero() { + snapshot.Editor.HorizontalScrollbarID = parts.At(1) + } + m.Code.Paint(context.Canvas, *context.Theme, context.Rect, snapshot) +} diff --git a/ui/columnresizeview/columnresizeview.go b/ui/columnresizeview/columnresizeview.go new file mode 100644 index 00000000..63fec5f4 --- /dev/null +++ b/ui/columnresizeview/columnresizeview.go @@ -0,0 +1,131 @@ +// Package columnresizeview is the opt-in page control for a row of columns +// whose dividers the user drags. It wraps components.BeginColumnResize in a +// ui.Control: the caller keeps the widths and paints each cell, the wrapper +// paints the dividers, declares their hit regions and maps pointer coordinates +// to the clamped width edit. +// +// cols := &columnresizeview.Columns{ +// Widths: []float32{260, 90, 140}, Minimums: []float32{120, 54, 76}, +// Fits: []float32{180, 64, 100}, Gap: 8, +// DividerIDs: []gfx.ID{first, second}, +// Cell: func(d *ui.DrawContext, index int, bounds gfx.Rect) { ... }, +// } +// columnresizeview.View(c, "Files", cols).FillWidth().Height(220) +package columnresizeview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Columns is one column row's caller-owned widths, geometry and page control. +// Fill Widths and Fits from the model every paint; keep Widths at one entry per +// column. +type Columns struct { + // Widths are the current column widths. The wrapper does not write them; + // Edit reports the pair to write. + Widths []float32 + // Minimums and Fits are the least width and content width of each column. + Minimums, Fits []float32 + // Gap is the room between two columns; dividers sit in its middle. + Gap float32 + // DividerIDs name the dividers for input; zero IDs paint no divider hits. + DividerIDs []gfx.ID + // DividerLabels name the dividers for assistive technology. + DividerLabels []string + // Cell paints column index into bounds. The wrapper paints all cells after + // the dividers, so a cell may cover its own column. + Cell func(*ui.DrawContext, int, gfx.Rect) + // Pointer receives the pointer events aimed at the control, with the + // caller's divider IDs as Target. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Key receives keys while the control has focus. + Key func(gfx.KeyEvent) gfx.EventResult + // Scroll receives the wheel over the control. + Scroll func(gfx.ScrollEvent) gfx.EventResult + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + bounds gfx.Rect + columns []gfx.Rect + dividers []gfx.Rect + hits []gfx.Rect +} + +// View declares the column row at c. Give it a size. +func View(c ui.C, label string, columns *Columns) ui.Box { + if columns == nil { + panic("columnresizeview: View needs its Columns") + } + columns.prepare() + return ui.Control(c, label, &columns.handlers).Draw(columns.drawFn) +} + +func (c *Columns) prepare() { + if c.prepared { + return + } + c.prepared = true + c.handlers.Pointer = c.pointer + c.handlers.Key = c.key + c.handlers.Scroll = c.scroll + c.drawFn = c.draw +} + +// Edit maps pointer x to the new widths of the columns either side of divider. +// Write the pair back to Widths and repaint. The first return is the left +// width, the second the right. +func (c *Columns) Edit(divider int, x float32) (left, right float32, ok bool) { + edit, ok := c.component(nil).Edit(divider, x) + return edit.Left, edit.Right, ok +} + +// Fit is Edit's double-click behavior: the left column takes its content width. +func (c *Columns) Fit(divider int) (left, right float32, ok bool) { + edit, ok := c.component(nil).Fit(divider) + return edit.Left, edit.Right, ok +} + +// Columns returns the rectangles of the last paint, for a caller that needs +// the cell geometry outside Cell. +func (c *Columns) Columns() []gfx.Rect { return c.columns } + +func (c *Columns) component(canvas *gfx.Canvas) components.ColumnResize { + return components.BeginColumnResize(canvas, gfx.Theme{}, c.bounds, c.Widths). + Dividers(c.DividerIDs).Minimums(c.Minimums).Fits(c.Fits).Gap(c.Gap) +} + +func (c *Columns) draw(d *ui.DrawContext) { + c.bounds = d.Rect + layout := c.component(d.Canvas).Paint(c.columns, c.dividers, c.hits, c.DividerLabels) + c.columns, c.dividers, c.hits = layout.Columns, layout.Dividers, layout.Hits + if c.Cell == nil { + return + } + for index, bounds := range c.columns { + c.Cell(d, index, bounds) + } +} + +func (c *Columns) pointer(event gfx.PointerEvent) gfx.EventResult { + if c.Pointer == nil { + return gfx.EventResult{} + } + return c.Pointer(event) +} + +func (c *Columns) key(event gfx.KeyEvent) gfx.EventResult { + if c.Key == nil { + return gfx.EventResult{} + } + return c.Key(event) +} + +func (c *Columns) scroll(event gfx.ScrollEvent) gfx.EventResult { + if c.Scroll == nil { + return gfx.EventResult{} + } + return c.Scroll(event) +} diff --git a/ui/columnresizeview/columnresizeview_test.go b/ui/columnresizeview/columnresizeview_test.go new file mode 100644 index 00000000..117e781d --- /dev/null +++ b/ui/columnresizeview/columnresizeview_test.go @@ -0,0 +1,82 @@ +package columnresizeview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/columnresizeview" +) + +func testTheme() *gfx.Theme { + theme := gfx.LightTheme() + return &theme +} + +func drawPage(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 240}, view) + canvas.EndFrame() +} + +func TestViewPaintsCellsAndDividers(t *testing.T) { + first, second := gfx.ID{}, gfx.ID{} + var columns columnresizeview.Columns + var painted int + view := func(c ui.C) { + first, second = ui.ID(c), ui.ID(c) + columns = columnresizeview.Columns{ + Widths: []float32{260, 90, 140}, Minimums: []float32{120, 54, 76}, + Fits: []float32{180, 64, 100}, Gap: 8, + DividerIDs: []gfx.ID{first, second}, DividerLabels: []string{"Resize name", "Resize size"}, + Cell: func(d *ui.DrawContext, index int, bounds gfx.Rect) { + painted++ + d.Canvas.Fill(bounds, d.Theme.Muted) + }, + } + columnresizeview.View(c, "Files", &columns).FillWidth().Height(180) + } + page := ui.NewPage(ui.PageConfig{View: view, Theme: testTheme()}) + canvas := new(gfx.Canvas) + drawPage(page, canvas, view) + if painted != 3 { + t.Fatalf("painted %d cells, want 3", painted) + } + if len(columns.Columns()) != 3 { + t.Fatalf("columns = %d, want 3", len(columns.Columns())) + } + var found bool + for _, hit := range canvas.Hits() { + if hit.ID == first && hit.Label == "Resize name" { + found = true + } + } + if !found { + t.Fatal("the first divider declared no hit") + } + left, right, ok := columns.Edit(0, columns.Columns()[0].X+220) + if !ok || left+right != 350 || left < 120 || right < 54 { + t.Fatalf("edit = %g/%g ok=%v, want a clamped pair summing to 350", left, right, ok) + } + if l, r, ok := columns.Fit(1); !ok || l+r != 230 { + t.Fatalf("fit = %g/%g ok=%v, want a pair summing to 230", l, r, ok) + } +} + +func BenchmarkViewWarmPaint(b *testing.B) { + widths := []float32{260, 90, 140} + minimums := []float32{120, 54, 76} + cell := func(*ui.DrawContext, int, gfx.Rect) {} + var columns columnresizeview.Columns + view := func(c ui.C) { + columns.Widths, columns.Minimums, columns.Gap, columns.Cell = widths, minimums, 8, cell + columnresizeview.View(c, "Files", &columns).FillWidth().Height(180) + } + page := ui.NewPage(ui.PageConfig{View: view, Theme: testTheme()}) + canvas := new(gfx.Canvas) + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, view) + } +} diff --git a/ui/commandview/commandview.go b/ui/commandview/commandview.go new file mode 100644 index 00000000..110879b5 --- /dev/null +++ b/ui/commandview/commandview.go @@ -0,0 +1,502 @@ +// Package commandview is the opt-in page control for the command palette of +// package components. It wraps components.BeginCommand in a ui.Control: the +// caller owns the query, the filtered results, the selection and the scroll +// position, and the wrapper paints the surface and routes its input. +// +// command := &commandview.Command{ +// Query: query, Selected: selected, +// Filter: func(query string) { /* rebuild m.results */ }, +// Choose: func(index int) { /* run m.results[index] */ }, +// } +// command.Clear() +// command.Group("Suggestions") +// command.Item("Open workspace", "⌘O") +// command.Item("Create window", "⌘N") +// commandview.View(c, "Command", command).FillWidth().Height(180) +// +// The query is edited through the platform's text service: the paint that +// follows a native edit reads it, writes Command.Query and calls Filter, so the +// caller filters in one place. Selected is the ordinal of an item row, not of +// Results: group headings, separators and the empty state take no selection. +// The wrapper moves it from the pointer and the Up and Down keys, and Enter +// calls Choose. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Command in the model beside the data it presents: its +// handlers and draw function are made once, so a warm paint allocates nothing. +// Do not copy a Command after it has been declared. +package commandview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// ResultKind selects what one row of Results paints. +type ResultKind uint8 + +const ( + // ResultItem is a command result. It is the zero kind, so a Result with only + // Label and Shortcut set is an item. + ResultItem ResultKind = iota + // ResultGroup is a compact heading over the items that follow it. + ResultGroup + // ResultSeparator is the one-pixel divider between groups. + ResultSeparator + // ResultEmpty is the centered empty-result state. + ResultEmpty +) + +// Result is one caller-owned row of the result list. Filters, labels and +// shortcuts stay the application's; the wrapper only paints and hit-tests +// them. +type Result struct { + Kind ResultKind + // ID names the item's hit. A zero ID is named by the control's own part + // scope, so a plain list needs no identities of its own. A non-zero ID is + // the caller's, as for any canvas component. + ID gfx.ID + Label string + Value string + Hint string + Shortcut string + Icon gfx.Icon + // Checked paints the persistent check of a chosen command. Selected is the + // transient row the pointer and keys move, and is Command.Selected. + Checked bool + Disabled bool +} + +// Options is the visual and accessibility shape of a command surface. Its +// zero value is the compact embedded geometry. +type Options struct { + Placeholder string + Hint string + Disabled bool + Invalid bool + // Layer is the compositing layer of the popup surface. + Layer uint16 + // Scope, when set, is the focus scope of the palette; DismissID, when set, + // is the Escape target. + Scope gfx.ID + DismissID gfx.ID + + variant components.CommandVariant +} + +// Dialog returns o painting the roomier command-palette geometry used inside a +// dialog. It is the only visual variant; chain it rather than reaching for a +// second constructor: +// +// command.Options = command.Options.Dialog() +func (o Options) Dialog() Options { + o.variant = components.CommandDialog + return o +} + +// Command is one command palette's caller-owned query, results, selection and +// scroll position, with the handlers that route its input. Keep it in the +// model beside the data it presents; its handlers and draw function point at +// this value, so do not copy a Command after it has been declared. +type Command struct { + // Query is the text in the input. The wrapper reads every native edit at the + // next paint, writes it here and calls Filter. Assigning it between paints + // replaces the query without calling Filter; the wrapper then recreates the + // text editor and resets ScrollState.Offset. + Query string + // Results are the rows painted under the input, in order: items, group + // headings, separators and the empty state. Rebuild it when the query + // changes or from Filter. + Results []Result + // Selected is the ordinal of the selected item row: items only, not group + // headings or separators. Out of range selects no row. The wrapper moves it + // from the pointer and the Up and Down keys and reports the new ordinal to + // Select. + Selected int + // ScrollState is the result list's offset and scrollbar state. The wrapper + // paints and scrolls it; the caller may set Offset and read the measured + // geometry after a paint. + ScrollState components.MenuScroll + // Options are the surface's words, state and geometry. + Options Options + + // Filter is called at the start of the paint that first sees a native edit + // change Query, before Results are painted. Rebuild Results there. It is not + // called for an assignment to Query. + Filter func(query string) + // Select is called after Selected changes from a key press, a pointer + // hover or a click. + Select func(index int) + // Choose is called when Enter activates the selected item. A nil Choose + // leaves Enter to the page. + Choose func(index int) + + // Key receives the keys the wrapper leaves unhandled, after Up, Down and + // Enter. + Key func(gfx.KeyEvent) gfx.EventResult + // Pointer receives the pointer events aimed at the control or one of its + // rows. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Scroll receives the wheel the result list did not scroll. + Scroll func(gfx.ScrollEvent) gfx.EventResult + // Text, when set, replaces the wrapper's native query editor. Nil gives the + // platform the wrapper's text.Editor through the control's role. + Text func(window.TextInputContext) *window.TextInput + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + editor *text.Editor + published string + input window.TextInput + controlID gfx.ID + bounds gfx.Rect + inputBound gfx.Rect + itemBounds []gfx.Rect +} + +// View declares the command palette at c. label names the control for +// assistive technology. Give it a height; it is a ui.Control painted through +// the component. Declare it on its own, not inside a Memo. +func View(c ui.C, label string, command *Command) ui.Box { + if command == nil { + panic("commandview: View needs its Command") + } + command.prepare() + box := ui.Control(c, label, &command.handlers) + command.controlID = box.N().ID + return box.Draw(command.drawFn) +} + +// View is View for a command the model keeps, so a page reads +// m.command.View(c, "Command"). +func (command *Command) View(c ui.C, label string) ui.Box { + return View(c, label, command) +} + +// Clear removes every result, keeping the slice for the next declaration. It +// is how a caller rebuilds Results after Filter. +func (command *Command) Clear() { command.Results = command.Results[:0] } + +// Group appends a compact group heading. +func (command *Command) Group(label string) { + command.Results = append(command.Results, Result{Kind: ResultGroup, Label: label}) +} + +// Item appends one plain result. Append a Result to Results for a value, hint, +// icon, check or disabled state. +func (command *Command) Item(label, shortcut string) { + command.Results = append(command.Results, Result{Label: label, Shortcut: shortcut}) +} + +// Separator appends the divider between two groups. +func (command *Command) Separator() { + command.Results = append(command.Results, Result{Kind: ResultSeparator}) +} + +// Empty appends the centered empty-result state. +func (command *Command) Empty(label string) { + command.Results = append(command.Results, Result{Kind: ResultEmpty, Label: label}) +} + +// InputID is the identity of the query row, a part of the control. It is the +// hit the platform text service edits and the gallery resolves an editor for. +func (command *Command) InputID() gfx.ID { return command.handlers.Parts().At(0) } + +// Bounds returns the command surface geometry of the last paint. +func (command *Command) Bounds() gfx.Rect { return command.bounds } + +// InputBounds returns the input row's text geometry of the last paint. +func (command *Command) InputBounds() gfx.Rect { return command.inputBound } + +// ItemBounds returns the rectangle of item row index in the last paint, or the +// empty rectangle when the row was scrolled out or index is not an item. +// Selected is likewise an item ordinal. +func (command *Command) ItemBounds(index int) gfx.Rect { + if index < 0 || index >= len(command.itemBounds) { + return gfx.Rect{} + } + return command.itemBounds[index] +} + +func (command *Command) prepare() { + if command.prepared { + return + } + command.prepared = true + command.handlers.Key = command.key + command.handlers.Pointer = command.pointer + command.handlers.Scroll = command.scroll + command.handlers.Text = command.text + command.drawFn = command.draw + command.editor = text.NewEditor(command.Query) + command.published = command.Query + command.input.Editor = command.editor + command.input.NavigationKeys = true +} + +// Editor returns the text.Editor the platform edits for Query. A host that +// resolves text input by identity, without calling Page.TextInput, gives this +// editor to its provider. It is nil before the first View. +func (command *Command) Editor() *text.Editor { return command.editor } + +// sync reads the query the platform edited since the last paint, or applies a +// Query the caller assigned between paints. +func (command *Command) sync() { + if command.Query != command.published { + command.editor = text.NewEditor(command.Query) + command.published = command.Query + command.input.Editor = command.editor + command.ScrollState.Offset = 0 + return + } + value := command.editor.String() + if value == command.published { + return + } + command.Query = value + command.published = value + command.ScrollState.Offset = 0 + if command.Filter != nil { + command.Filter(value) + } +} + +func (command *Command) text(context window.TextInputContext) *window.TextInput { + if command.Text != nil { + return command.Text(context) + } + command.input.Bounds = command.inputBound + return &command.input +} + +func (command *Command) draw(d *ui.DrawContext) { + command.sync() + command.bounds = d.Rect + command.itemBounds = command.itemBounds[:0] + options := components.CommandOptions{ + InputID: command.handlers.Parts().At(0), + Label: d.Label, Query: command.Query, Placeholder: command.Options.Placeholder, + Hint: command.Options.Hint, Disabled: command.Options.Disabled, Invalid: command.Options.Invalid, + Variant: command.Options.variant, Layer: command.Options.Layer, + Scope: command.Options.Scope, DismissID: command.Options.DismissID, + Scroll: &command.ScrollState, + } + surface := components.BeginCommand(d.Canvas, *d.Theme, d.Rect, options) + // The component lays the list under an input row of 36 pixels (48 for the + // dialog geometry), and its label starts 36 pixels in, 50 short of the row. + inputHeight := float32(36) + if command.Options.variant == components.CommandDialog { + inputHeight = 48 + } + command.inputBound = gfx.Rect{ + X: d.Rect.X + 36, Y: d.Rect.Y, + Width: max(0, d.Rect.Width-50), Height: inputHeight, + } + item := 0 + for index := range command.Results { + result := &command.Results[index] + switch result.Kind { + case ResultGroup: + surface.AddGroup(result.Label) + case ResultSeparator: + surface.AddSeparator() + case ResultEmpty: + surface.AddEmpty(result.Label) + case ResultItem: + id := result.ID + if id.IsZero() { + id = command.handlers.Parts().At(item) + } + row := surface.AddItem(components.CommandItem{ + ID: id, Label: result.Label, Value: result.Value, Hint: result.Hint, + Shortcut: result.Shortcut, Selected: item == command.Selected, + Checked: result.Checked, Disabled: result.Disabled, Icon: result.Icon, + }) + if item < len(command.itemBounds) { + command.itemBounds[item] = row + } else { + command.itemBounds = append(command.itemBounds, row) + } + item++ + } + } + surface.End() + command.pick(d) +} + +// pick moves the selection onto the row the pointer entered or clicked, as the +// component's pointer rows do, and keeps the keyboard and the text service on +// the control when a click lands on a result. +func (command *Command) pick(d *ui.DrawContext) { + if command.itemCount() == 0 { + return + } + if id := d.Canvas.Hovered(); !id.IsZero() { + if item, ok := command.ordinalOf(id); ok { + command.selectItem(item) + } + } + if id, ok := d.Canvas.ClickTarget(); ok { + if item, ok := command.ordinalOf(id); ok { + command.selectItem(item) + d.Canvas.RequestFocus(d.Node.ID) + } + } +} + +func (command *Command) key(event gfx.KeyEvent) gfx.EventResult { + switch event.Key { + case gfx.KeyDown, gfx.KeyUp: + if command.itemCount() == 0 { + break + } + delta := 1 + if event.Key == gfx.KeyUp { + delta = -1 + } + moved, scrolled := command.move(delta) + return gfx.EventResult{Handled: true, Repaint: moved || scrolled} + case gfx.KeyEnter: + if item, ok := command.itemAt(command.Selected); ok && !item.Disabled && command.Choose != nil { + command.Choose(command.Selected) + return gfx.EventResult{Handled: true, Repaint: true} + } + } + if command.Key == nil { + return gfx.EventResult{} + } + return command.Key(event) +} + +func (command *Command) pointer(event gfx.PointerEvent) gfx.EventResult { + if command.Pointer == nil { + return gfx.EventResult{} + } + return command.Pointer(event) +} + +func (command *Command) scroll(event gfx.ScrollEvent) gfx.EventResult { + if command.ScrollState.Wheel(event) { + return gfx.EventResult{Handled: true, Repaint: true} + } + if command.Scroll == nil { + return gfx.EventResult{} + } + return command.Scroll(event) +} + +// move steps to the next enabled item, wrapping at the ends, and reports +// whether the selection changed and whether the list had to scroll. +func (command *Command) move(delta int) (moved, scrolled bool) { + count := command.itemCount() + if count == 0 { + return false, false + } + next := command.Selected + if next < 0 || next >= count { + if delta < 0 { + next = count + } else { + next = -1 + } + } + for range count { + next = (next + delta) % count + if next < 0 { + next += count + } + item, _ := command.itemAt(next) + if item.Disabled { + continue + } + if next != command.Selected { + command.Selected = next + moved = true + if command.Select != nil { + command.Select(next) + } + } + scrolled = command.ScrollState.Reveal(command.itemID(next)) + return moved, scrolled + } + return false, false +} + +func (command *Command) selectItem(item int) { + if item < 0 || item >= command.itemCount() || item == command.Selected { + return + } + result, ok := command.itemAt(item) + if !ok || result.Disabled { + return + } + command.Selected = item + if command.Select != nil { + command.Select(item) + } +} + +func (command *Command) itemCount() int { + count := 0 + for index := range command.Results { + if command.Results[index].Kind == ResultItem { + count++ + } + } + return count +} + +// itemAt returns item row ordinal, skipping headings, separators and the empty +// state. +func (command *Command) itemAt(ordinal int) (Result, bool) { + if ordinal < 0 { + return Result{}, false + } + item := 0 + for index := range command.Results { + if command.Results[index].Kind != ResultItem { + continue + } + if item == ordinal { + return command.Results[index], true + } + item++ + } + return Result{}, false +} + +func (command *Command) itemID(ordinal int) gfx.ID { + item, ok := command.itemAt(ordinal) + if !ok { + return gfx.ID{} + } + if !item.ID.IsZero() { + return item.ID + } + return command.handlers.Parts().At(ordinal) +} + +func (command *Command) ordinalOf(id gfx.ID) (int, bool) { + if id.IsZero() { + return 0, false + } + item := 0 + for index := range command.Results { + if command.Results[index].Kind != ResultItem { + continue + } + named := command.Results[index].ID + if named.IsZero() { + named = command.handlers.Parts().At(item) + } + if named == id { + return item, true + } + item++ + } + return 0, false +} diff --git a/ui/commandview/commandview_test.go b/ui/commandview/commandview_test.go new file mode 100644 index 00000000..f2fcb62d --- /dev/null +++ b/ui/commandview/commandview_test.go @@ -0,0 +1,251 @@ +package commandview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/commandview" + "github.com/vivaui/viva/window" +) + +func testTheme() *gfx.Theme { + theme := gfx.LightTheme() + return &theme +} + +func drawPage(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 240}, view) + canvas.EndFrame() +} + +func hitLabelled(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + if hits[i].Label == label && !hits[i].ID.IsZero() { + return hits[i], true + } + } + return gfx.Hit{}, false +} + +type model struct { + command commandview.Command + page *ui.Page + canvas *gfx.Canvas + selected int + selectedSet bool + chosen int + chosenSet bool + filter []string +} + +func (m *model) wire() { + m.command.Query = "open" + m.command.Results = []commandview.Result{ + {Kind: commandview.ResultGroup, Label: "Suggestions"}, + {ID: gfx.Item(11), Label: "Open workspace", Shortcut: "⌘O"}, + {ID: gfx.Item(12), Label: "Create window", Shortcut: "⌘N"}, + {Kind: commandview.ResultSeparator}, + {ID: gfx.Item(13), Label: "Pin current view", Disabled: true}, + } + m.command.Filter = func(query string) { m.filter = append(m.filter, query) } + m.command.Select = func(index int) { + m.selected, m.selectedSet = index, true + } + m.command.Choose = func(index int) { + m.chosen, m.chosenSet = index, true + } +} + +func (m *model) viewPage(c ui.C) { + commandview.View(c, "Command", &m.command).Size(480, 210) +} + +func (m *model) open(t testing.TB) { + t.Helper() + theme := testTheme() + m.page = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: theme}) + m.canvas = new(gfx.Canvas) + drawPage(m.page, m.canvas, m.viewPage) +} + +func control(t *testing.T, canvas *gfx.Canvas) gfx.Hit { + t.Helper() + hit, ok := hitLabelled(canvas, "Command") + if !ok { + t.Fatal("the control painted no hit") + } + return hit +} + +func TestViewPaintsResultsAndGeometry(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + + ctrl := control(t, m.canvas) + if ctrl.Role != gfx.RoleCombobox || !ctrl.Focusable || ctrl.Value != "open" { + t.Fatalf("control hit = %+v, want the focusable query row of the palette", ctrl) + } + item := func(label string) gfx.Hit { + t.Helper() + hit, ok := hitLabelled(m.canvas, label) + if !ok { + t.Fatalf("no hit labelled %q", label) + } + return hit + } + first := item("Open workspace") + if first.ID != gfx.Item(11) || !first.Selected || first.Role != gfx.RoleOption { + t.Fatalf("first item hit = %+v, want the caller's selected option", first) + } + if second := item("Create window"); second.ID != gfx.Item(12) || second.Selected { + t.Fatalf("second item hit = %+v, want the caller's unselected option", second) + } + pinned := item("Pin current view") + if !pinned.Disabled || pinned.Focusable { + t.Fatalf("disabled item hit = %+v, want inert", pinned) + } + + if bounds := m.command.Bounds(); bounds.Width <= 0 || bounds.Height <= 0 { + t.Fatalf("bounds = %v, want the painted surface", bounds) + } + input := m.command.InputBounds() + if input.Height != 36 || input.Width <= 0 { + t.Fatalf("input bounds = %v, want the compact 36-pixel row", input) + } + if row := m.command.ItemBounds(0); row.Height != 32 || row.Y <= input.Y+input.Height-32 { + t.Fatalf("item bounds = %v, want a 32-pixel row under the input", row) + } + if m.command.ItemBounds(3) != (gfx.Rect{}) || m.command.ItemBounds(-1) != (gfx.Rect{}) { + t.Fatal("ItemBounds reported a row that is not an item") + } +} + +// Dialog is a chained option, not a second constructor, and changes the row +// geometry the component paints. +func TestDialogOptionChangesGeometry(t *testing.T) { + m := new(model) + m.wire() + m.command.Options = m.command.Options.Dialog() + m.open(t) + + if input := m.command.InputBounds(); input.Height != 48 { + t.Fatalf("dialog input bounds = %v, want a 48-pixel row", input) + } + if row := m.command.ItemBounds(0); row.Height != 44 { + t.Fatalf("dialog item bounds = %v, want a 44-pixel row", row) + } +} + +func TestNativeEditingUpdatesQueryAndFilters(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + + input := m.page.TextInput(window.TextInputContext{ID: control(t, m.canvas).ID}) + if input == nil || input.Editor == nil || !input.NavigationKeys { + t.Fatalf("text input = %+v, want the wrapper's editor with navigation keys", input) + } + input.Editor.Insert("x") + drawPage(m.page, m.canvas, m.viewPage) + + if m.command.Query != "openx" { + t.Fatalf("query = %q, want the typed value", m.command.Query) + } + if len(m.filter) != 1 || m.filter[0] != "openx" { + t.Fatalf("filter calls = %v, want the typed value once", m.filter) + } + + // An assignment between paints replaces the query without filtering: the + // caller already owns the results it is about to paint. + m.command.Query = "create" + drawPage(m.page, m.canvas, m.viewPage) + if input := m.page.TextInput(window.TextInputContext{ID: control(t, m.canvas).ID}); input.Editor.String() != "create" { + t.Fatalf("editor = %q, want the assigned query", input.Editor.String()) + } + if len(m.filter) != 1 { + t.Fatalf("filter calls = %v, want no call for an assignment", m.filter) + } +} + +func TestKeysMoveSelectionAndChoose(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + id := control(t, m.canvas).ID + + down := func() gfx.EventResult { + return m.page.Key(gfx.KeyEvent{Key: gfx.KeyDown, Target: id}) + } + if result := down(); !result.Handled || !result.Repaint || m.command.Selected != 1 || !m.selectedSet || m.selected != 1 { + t.Fatalf("first down: selected=%d callback=%d/%t result=%+v", m.command.Selected, m.selected, m.selectedSet, result) + } + // Item 2 is disabled, so the next step wraps to the first item. + if result := down(); !result.Handled || m.command.Selected != 0 || m.selected != 0 { + t.Fatalf("wrapping down: selected=%d callback=%d result=%+v", m.command.Selected, m.selected, result) + } + if result := m.page.Key(gfx.KeyEvent{Key: gfx.KeyUp, Target: id}); !result.Handled || m.command.Selected != 1 { + t.Fatalf("up: selected=%d result=%+v", m.command.Selected, result) + } + if result := m.page.Key(gfx.KeyEvent{Key: gfx.KeyEnter, Target: id}); !result.Handled || !m.chosenSet || m.chosen != 1 { + t.Fatalf("enter: chosen=%d/%t result=%+v", m.chosen, m.chosenSet, result) + } + + // Enter on a disabled row does nothing and stays with the page. + m.command.Selected = 2 + if result := m.page.Key(gfx.KeyEvent{Key: gfx.KeyEnter, Target: id}); result.Handled { + t.Fatalf("enter on a disabled item was handled: %+v", result) + } +} + +func TestPointerMovesAndClicksSelectEnabledItems(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + + m.canvas.SetInteraction(gfx.Item(12), gfx.ID{}, gfx.ID{}, false) + drawPage(m.page, m.canvas, m.viewPage) + if m.command.Selected != 1 || m.selected != 1 { + t.Fatalf("hover selected %d (callback %d), want item 1", m.command.Selected, m.selected) + } + + // A hover over a disabled row leaves the selection alone. + m.canvas.SetInteraction(gfx.Item(13), gfx.ID{}, gfx.ID{}, false) + drawPage(m.page, m.canvas, m.viewPage) + if m.command.Selected != 1 { + t.Fatalf("hover on a disabled row selected %d, want item 1", m.command.Selected) + } + + m.canvas.BeginEventPass(gfx.Item(11), gfx.ClickInfo{}) + drawPage(m.page, m.canvas, m.viewPage) + m.canvas.EndEventPass() + if m.command.Selected != 0 { + t.Fatalf("click selected %d, want item 0", m.command.Selected) + } +} + +// A warm repaint allocates nothing: the wrapper keeps its handlers, draw +// function and row geometry, and the component keeps its own caches. +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + if allocations := testing.AllocsPerRun(100, func() { drawPage(m.page, m.canvas, m.viewPage) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewWarmPaint(b *testing.B) { + m := new(model) + m.wire() + m.open(b) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + drawPage(m.page, m.canvas, m.viewPage) + } +} diff --git a/ui/disclosure.go b/ui/disclosure.go new file mode 100644 index 00000000..20511ff4 --- /dev/null +++ b/ui/disclosure.go @@ -0,0 +1,166 @@ +package ui + +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +// AccordionItem is one disclosure row of an Accordion. Content is declared only +// while the row is open. +type AccordionItem struct { + Title string + Content func() +} + +// AccordionState is the caller-owned expansion of an Accordion. Open has one +// entry per item and keeps its length for as long as the state is used; indexing +// it by item is what keeps each header's identity stable between paints. +// +// Multiple allows more than one row open at once. By default opening a row closes +// the others. Disabled makes every header inert. +type AccordionState struct { + Open []bool + Multiple bool + Disabled bool +} + +// NewAccordionState makes state for n items, all closed. +func NewAccordionState(n int) *AccordionState { + if n < 0 { + n = 0 + } + return &AccordionState{Open: make([]bool, n)} +} + +// IsOpen reports whether item i is expanded. An index outside Open is closed. +func (s *AccordionState) IsOpen(i int) bool { + return s != nil && i >= 0 && i < len(s.Open) && s.Open[i] +} + +// Accordion declares a vertical set of disclosure rows with the theme's look. +// The caller owns which rows are open; a click on a header flips its entry. +// +// ui.Accordion(c, m.help, []ui.AccordionItem{{Title: "Shipping", Content: body}}) +func Accordion(c C, state *AccordionState, items []AccordionItem) Box { + if state == nil { + panic("ui: Accordion needs a state") + } + if len(state.Open) != len(items) { + panic("ui: AccordionState.Open needs one entry per item and must keep its length") + } + root := base.Column(c).FillWidth() + root.Children(func() { + for i := range items { + if i > 0 { + base.Divider(c) + } + index := i + base.Column(c).FillWidth().Children(func() { + header := disclosureHeader(c, &state.Open[index], items[index].Title, state.Disabled) + if header.Clicked() && !state.Multiple { + for j := range state.Open { + if j != index { + state.Open[j] = false + } + } + } + content := base.Column(c) + if state.Open[index] && items[index].Content != nil { + content.PadBottom(16).Children(items[index].Content) + } + }) + } + }) + return root +} + +// CollapsibleState is the caller-owned state of one Collapsible. Disabled keeps +// the trigger painted and inert. +type CollapsibleState struct { + Open bool + Disabled bool +} + +// Collapsible declares one disclosure row with the theme's look: a click on the +// header flips state.Open, and content is declared only while state.Open is true. +func Collapsible(c C, state *CollapsibleState, title string, content func()) Box { + if state == nil { + panic("ui: Collapsible needs a state") + } + root := base.Column(c).FillWidth() + root.Children(func() { + disclosureHeader(c, &state.Open, title, state.Disabled) + body := base.Column(c) + if state.Open && content != nil { + body.PadBottom(16).Children(content) + } + }) + return root +} + +// disclosureHeader is the styled trigger shared by Accordion and Collapsible. +func disclosureHeader(c C, open *bool, title string, disabled bool) Box { + theme := *c.Theme() + foreground := theme.Foreground + if disabled { + foreground.Alpha *= 0.50 + } + header := base.DisclosureBase(c, open, title). + FillWidth(). + Height(components.AccordionHeaderExtent(theme)). + PadX(8). + Radius(theme.Metrics.RadiusControl). + Disabled(disabled) + if !disabled { + header = header. + Hover(Look{}.Background(theme.Hover)). + Focus(Look{}.Ring(3, fadedRing(theme))) + } + header.Children(func() { + base.Text(c, title). + FontSize(theme.Metrics.FontSizeM). + Weight(gfx.WeightMedium). + Color(foreground) + base.Spacer(c) + base.Slot(c).Size(16, 16) + }) + header.Draw(paintDisclosureChevron) + return header +} + +func fadedRing(theme base.Theme) gfx.Color { + ring := theme.Ring + ring.Alpha *= 0.50 + return ring +} + +func paintDisclosureChevron(d *DrawContext) { + icon := disclosureChevronDown + if d.State.Open { + icon = disclosureChevronUp + } + color := d.Theme.MutedForeground + if d.State.Disabled { + color.Alpha *= 0.50 + } + const size = 16 + bounds := gfx.Rect{ + X: d.Rect.X + d.Rect.Width - size - 8, + Y: d.Rect.Y + (d.Rect.Height-size)/2, + Width: size, + Height: size, + } + d.Canvas.DrawIcon(icon, bounds, d.Fade(color)) +} + +var ( + disclosureChevronDown = gfx.Icon{ + ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, + Commands: []gfx.PathCommand{gfx.MoveTo(6, 9), gfx.LineTo(12, 15), gfx.LineTo(18, 9)}, + } + disclosureChevronUp = gfx.Icon{ + ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, + Commands: []gfx.PathCommand{gfx.MoveTo(6, 15), gfx.LineTo(12, 9), gfx.LineTo(18, 15)}, + } +) diff --git a/ui/disclosure_test.go b/ui/disclosure_test.go new file mode 100644 index 00000000..f80a845f --- /dev/null +++ b/ui/disclosure_test.go @@ -0,0 +1,113 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +func TestPageAccordionOpensOneRowAtATime(t *testing.T) { + state := ui.NewAccordionState(2) + d := openPage(t, func(c ui.C) { + ui.Accordion(c, state, []ui.AccordionItem{ + {Title: "Shipping", Content: func() { ui.Button(c, "Shipping details") }}, + {Title: "Returns", Content: func() { ui.Button(c, "Return details") }}, + }) + }) + if hit := d.hit("Shipping"); hit.Expanded || !hit.Expandable { + t.Fatalf("closed header expanded=%v expandable=%v", hit.Expanded, hit.Expandable) + } + d.click("Shipping") + if !state.Open[0] { + t.Fatal("clicking Shipping did not open it") + } + if hit := d.hit("Shipping"); !hit.Expanded { + t.Fatal("the open header does not report itself expanded") + } + if !d.has("Shipping details") { + t.Fatal("open content was not declared") + } + d.click("Returns") + if state.Open[0] || !state.Open[1] { + t.Fatalf("open = %v, want only Returns", state.Open) + } + if d.has("Shipping details") || !d.has("Return details") { + t.Fatal("switching rows did not switch the content") + } +} + +func TestPageAccordionMultipleKeepsBothOpen(t *testing.T) { + state := ui.NewAccordionState(2) + state.Multiple = true + d := openPage(t, func(c ui.C) { + ui.Accordion(c, state, []ui.AccordionItem{ + {Title: "Shipping", Content: func() { ui.Button(c, "Shipping details") }}, + {Title: "Returns", Content: func() { ui.Button(c, "Return details") }}, + }) + }) + d.click("Shipping") + d.click("Returns") + if !state.Open[0] || !state.Open[1] { + t.Fatalf("open = %v, want both rows", state.Open) + } + d.click("Shipping") + if state.Open[0] || !state.Open[1] { + t.Fatalf("open = %v, want only Returns after closing Shipping", state.Open) + } +} + +func TestPageCollapsibleFlipsItsValue(t *testing.T) { + state := ui.CollapsibleState{} + d := openPage(t, func(c ui.C) { + ui.Collapsible(c, &state, "Advanced", func() { + ui.Button(c, "Advanced settings") + }) + }) + hit := d.hit("Advanced") + if hit.Role != gfx.RoleButton || hit.Expanded || !hit.Expandable { + t.Fatalf("header = %+v, want a collapsed disclosure button", hit) + } + d.click("Advanced") + if !state.Open || !d.has("Advanced settings") { + t.Fatal("clicking the header did not open the content") + } + d.click("Advanced") + if state.Open || d.has("Advanced settings") { + t.Fatal("the second click did not close the content") + } +} + +func TestPageAccordionDisabledStaysInert(t *testing.T) { + state := ui.NewAccordionState(1) + state.Disabled = true + d := openPage(t, func(c ui.C) { + ui.Accordion(c, state, []ui.AccordionItem{ + {Title: "Shipping", Content: func() { ui.Button(c, "Shipping details") }}, + }) + }) + if hit := d.hit("Shipping"); !hit.Disabled { + t.Fatal("the disabled accordion header is not disabled") + } + d.click("Shipping") + if state.Open[0] || d.has("Shipping details") { + t.Fatal("a disabled accordion opened") + } +} + +func BenchmarkPageAccordion(b *testing.B) { + state := ui.NewAccordionState(3) + state.Open[0] = true + items := []ui.AccordionItem{ + {Title: "Shipping", Content: func() {}}, + {Title: "Returns", Content: func() {}}, + {Title: "Warranty", Content: func() {}}, + } + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, func(c ui.C) { + ui.Accordion(c, state, items) + }) + } +} diff --git a/ui/engine.go b/ui/engine.go index b9569f9e..b4775bfc 100644 --- a/ui/engine.go +++ b/ui/engine.go @@ -1,9 +1,22 @@ package ui -import "github.com/vivaui/viva/base" +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/style" +) // The engine is base's; ui keeps it under the names applications use. +// PopoverSide is the edge of an anchor a popover opens on. +type PopoverSide = style.PopoverSide + +const ( + PopoverBottom = style.PopoverBottom + PopoverTop = style.PopoverTop + PopoverRight = style.PopoverRight + PopoverLeft = style.PopoverLeft +) + type AlertDialogDecl = base.AlertDialogDecl type AlertDialogSpec = base.AlertDialogSpec type Align = base.Align diff --git a/ui/facade.go b/ui/facade.go index 4b23bf48..c8ce72a9 100644 --- a/ui/facade.go +++ b/ui/facade.go @@ -167,6 +167,10 @@ func ToggleBase(c C, Value *bool, Label string) Box { func Toggle(c C, Value *bool, Label string) Box { return base.Toggle(c, Value, Label) } +func DisclosureBase(c C, Value *bool, Label string) Box { + return base.DisclosureBase(c, Value, Label) +} + func Control(c C, Label string, h *Handlers) Box { useControls(); return base.Control(c, Label, h) } func FormField(c C, state *FormFieldState, Label string) Box { @@ -215,11 +219,6 @@ func SelectID[T comparable](c C, ID gfx.ID, Value *T, choices []T, Label func(T) return base.SelectID(c, ID, Value, choices, Label) } -func SelectIcon[T comparable](c C, Value *T, choices []T, Label func(T) string, icon func(T) gfx.Icon) Box { - useSelect() - return base.SelectIcon(c, Value, choices, Label, icon) -} - func SelectBase[T comparable](c C, Value *T, choices []T, Label func(T) string) Box { useSelect() return base.SelectBase(c, Value, choices, Label) diff --git a/hierarchypicker/hierarchypicker.go b/ui/hierarchypicker/hierarchypicker.go similarity index 100% rename from hierarchypicker/hierarchypicker.go rename to ui/hierarchypicker/hierarchypicker.go diff --git a/hierarchypicker/hierarchypicker_test.go b/ui/hierarchypicker/hierarchypicker_test.go similarity index 98% rename from hierarchypicker/hierarchypicker_test.go rename to ui/hierarchypicker/hierarchypicker_test.go index 086a3bbb..4d63be0e 100644 --- a/hierarchypicker/hierarchypicker_test.go +++ b/ui/hierarchypicker/hierarchypicker_test.go @@ -5,8 +5,8 @@ import ( "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/hierarchypicker" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/hierarchypicker" ) type harness struct { diff --git a/ui/hovercardview/hovercardview.go b/ui/hovercardview/hovercardview.go new file mode 100644 index 00000000..92d9c298 --- /dev/null +++ b/ui/hovercardview/hovercardview.go @@ -0,0 +1,357 @@ +// Package hovercardview is the opt-in page hover card: a non-modal preview +// that appears beside the anchor the pointer rests on, stays open while the +// pointer moves into it, and closes after the pointer leaves. +// +// It is a page control, not a canvas recipe. The anchor is an element the +// caller already declared, the title, description and body are page children, +// and the surface is painted by components.BeginHoverCard. The view keeps its +// hover timing in page-owned state, so the declaration can be a fresh value on +// every paint: +// +// anchor := ui.Button(c, "@viva-framework").Outline().Width(180) +// hovercardview.View(c, "@viva-framework", &hovercardview.HoverCard{ +// Anchor: anchor, +// Title: "Viva Framework", +// Description: "Go-first, GPU-native desktop UI.", +// Body: func() { +// ui.Text(c, "Native, retained and allocation-aware").Muted() +// }, +// }) +// +// The zero value opens after DefaultOpenDelay and closes after +// DefaultCloseDelay; Delays selects another timing, including zero. The view +// asks the canvas for a frame only while a delay is running, so an open idle +// card schedules no work. +// +// It is a separate package so an application that does not import it pays +// nothing for it. +package hovercardview + +import ( + "time" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Side is the edge of the anchor the card opens on. It aliases the component's +// vocabulary so a page that declares a card reads through this package alone. +type Side = components.HoverCardSide + +// The anchor edges a card opens on. +const ( + Bottom = components.HoverCardBottom + Top = components.HoverCardTop + Right = components.HoverCardRight + Left = components.HoverCardLeft +) + +// Align positions the card along the anchor's cross axis. +type Align = components.HoverCardAlign + +// The alignments along the anchor's cross axis. +const ( + Center = components.HoverCardAlignCenter + Start = components.HoverCardAlignStart + End = components.HoverCardAlignEnd +) + +// The default timing and size of a card. +const ( + // DefaultOpenDelay is how long the pointer rests on the anchor before the + // card opens. + DefaultOpenDelay = 700 * time.Millisecond + // DefaultCloseDelay is how long the card waits after the pointer leaves the + // anchor and the card before it closes, so moving from one to the other + // keeps it open. + DefaultCloseDelay = 300 * time.Millisecond + // DefaultWidth is the card's width when Width is not set. + DefaultWidth = float32(256) + // DefaultSideOffset is the gap between the anchor and the card. + DefaultSideOffset = float32(4) + // surfaceMargin is the space the card keeps from the viewport's edges. + surfaceMargin = float32(8) +) + +// HoverCard is one page hover card. Declare it where the anchor is declared; +// the view keeps the hover state in the page, so a fresh value each paint is +// the normal call site. Keep Open in the application's model when the +// application needs to read or set the open state itself. +type HoverCard struct { + // Anchor is the element the card describes, declared before View in the + // same paint. The card uses that element's laid-out geometry. + Anchor ui.Box + // Title and Description are the card's heading text. They are page children + // and stay visible in the declaration. + Title, Description string + // Body declares the card's content, as any container's children. It is nil + // for a card with only a heading. + Body func() + // Open, when non-nil, is the caller's copy of the card's open state. View + // writes it when hover opens and closes the card, so an application that + // wants to read the state holds only this value. The hover timing stays in + // the view; the value is not a second source of truth. + Open *bool + // OnOpenChange is called when the view opens or closes the card because of + // the pointer. It is not called for a caller's own write to Open. It runs + // during the paint, so it must not declare elements. + OnOpenChange func(open bool) + + side Side + align Align + width float32 + openDelay time.Duration + closeWait time.Duration + delays bool + disabled bool +} + +// Side selects the anchor edge the card opens on. +func (card *HoverCard) Side(side Side) *HoverCard { card.side = side; return card } + +// Align lines the card up with the anchor along its cross axis. +func (card *HoverCard) Align(align Align) *HoverCard { card.align = align; return card } + +// Width fixes the card's width; zero keeps DefaultWidth. +func (card *HoverCard) Width(width float32) *HoverCard { card.width = width; return card } + +// Delays selects how long the pointer rests before the card opens, and how long +// it waits after leaving before the card closes. Either may be zero. +func (card *HoverCard) Delays(open, close time.Duration) *HoverCard { + card.openDelay, card.closeWait, card.delays = open, close, true + return card +} + +// Disabled suppresses the card for a disabled anchor. Disabled() is Disabled(true). +func (card *HoverCard) Disabled(disabled ...bool) *HoverCard { + card.disabled = len(disabled) == 0 || disabled[0] + return card +} + +// hoverState is the page-owned state of one declaration. It holds the timing, +// the last card rectangle and the stable declaimers, so a warm paint allocates +// nothing for the package. +type hoverState struct { + open bool + pendingOpen bool + pendingClose bool + since time.Duration + contentRect gfx.Rect + + c ui.C + title string + description string + body func() + children func() + paintCard func(*ui.DrawContext) +} + +// View declares the hover card at c and returns the anchor element. label names +// the anchor for assistive technology; the card announces Title when it has +// one. The anchor must be declared in the same paint and is left as declared +// unless it has no identity, in which case View gives it one for hover +// detection. +func View(c ui.C, label string, card *HoverCard) ui.Box { + if card == nil { + panic("hovercardview: View needs a HoverCard") + } + anchor := card.Anchor + if !anchor.Valid() { + panic("hovercardview: HoverCard.Anchor must be declared before View") + } + canvas := c.Canvas() + state := ui.State[hoverState](c, "hovercard") + if state.children == nil { + // One declaimer for the life of this declaration: a warm paint reuses + // the same functions, as the other page views do. + state.children = func() { state.declareChildren() } + state.paintCard = func(d *ui.DrawContext) { state.paintSurface(d) } + } + + anchorID := anchor.N().ID + contentID := ui.ID(c) + if anchorID.IsZero() { + anchorID = ui.ID(c) + anchor = anchor.Hit(anchorID, label) + } + + if card.disabled { + state.pendingOpen, state.pendingClose = false, false + return anchor + } + + page := c.GetPage() + pointerIn, pointer := page.GetPointerIn(), page.GetPointer() + onAnchor := canvas.Hovered() == anchorID || pointerIn && hoveredWithin(canvas, anchorID, pointer) + open := state.isOpen(card) + onContent := open && (canvas.Hovered() == contentID || pointerIn && contains(state.contentRect, pointer)) + state.settle(canvas, card, canvas.Now(), onAnchor, onContent) + + if !state.isOpen(card) { + return anchor + } + state.declare(c, card, label, contentID, anchor) + return anchor +} + +// isOpen is the card's open state: the caller's when it owns one, else the +// view's own. +func (state *hoverState) isOpen(card *HoverCard) bool { + if card.Open != nil { + return *card.Open + } + return state.open +} + +// setOpen changes the open state and reports it to the caller. +func (state *hoverState) setOpen(card *HoverCard, open bool) { + if state.isOpen(card) == open { + return + } + state.open = open + if card.Open != nil { + *card.Open = open + } + if card.OnOpenChange != nil { + card.OnOpenChange(open) + } +} + +// settle advances the hover timing. A remaining wait asks the canvas for one +// frame at the deadline and for nothing while idle. +func (state *hoverState) settle(canvas *gfx.Canvas, card *HoverCard, now time.Duration, onAnchor, onContent bool) { + open := state.isOpen(card) + if onAnchor || open && onContent { + state.pendingClose = false + if open { + state.pendingOpen = false + return + } + if !state.pendingOpen { + state.pendingOpen, state.since = true, now + } + if wait := card.openWait() - (now - state.since); wait > 0 { + canvas.RequestFrameIn(wait) + return + } + state.pendingOpen = false + state.setOpen(card, true) + return + } + state.pendingOpen = false + if !open { + state.pendingClose = false + return + } + if !state.pendingClose { + state.pendingClose, state.since = true, now + } + if wait := card.closeDelay() - (now - state.since); wait > 0 { + canvas.RequestFrameIn(wait) + return + } + state.pendingClose = false + state.setOpen(card, false) + state.contentRect = gfx.Rect{} +} + +func (card *HoverCard) openWait() time.Duration { + if !card.delays { + return DefaultOpenDelay + } + return max(card.openDelay, 0) +} + +func (card *HoverCard) closeDelay() time.Duration { + if !card.delays { + return DefaultCloseDelay + } + return max(card.closeWait, 0) +} + +// declare opens the page popup the card lives in. The popup places its children +// from the caller's anchor; the card's surface is painted in the popup's place +// by the component. +func (state *hoverState) declare(c ui.C, card *HoverCard, label string, contentID gfx.ID, anchor ui.Box) { + frame := c.GetF() + metrics := c.Theme().Metrics + popup := frame.Popup() + align := ui.Center + switch card.align { + case Start: + align = ui.Start + case End: + align = ui.End + } + switch card.side { + case Top: + popup.AboveBox(anchor, DefaultSideOffset, align) + case Right: + popup.BesideBox(anchor, DefaultSideOffset, align) + case Left: + popup.BesideLeftBox(anchor, DefaultSideOffset, align) + default: + popup.BelowBox(anchor, DefaultSideOffset, align) + } + width := card.width + if width <= 0 { + width = DefaultWidth + } + popup.Width(width).Pad(metrics.PadSurface).Gap(metrics.GapItem) + popup.Within(c.Bounds().Inset(gfx.All(surfaceMargin))) + name := label + if card.Title != "" { + name = card.Title + } + popup.HitWith(contentID, name, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + state.c, state.title, state.description, state.body = c, card.Title, card.Description, card.Body + popup.Draw(state.paintCard) + popup.Children(state.children) +} + +// paintSurface paints the card surface through components.BeginHoverCard at the +// popup's settled rectangle. A local viewport makes the component's placement +// resolve to exactly that rectangle; the caller's anchor already placed the +// popup, so only the component's surface paint is used here. +func (state *hoverState) paintSurface(d *ui.DrawContext) { + state.contentRect = d.Rect + if d.Rect.Width <= 0 || d.Rect.Height <= 0 { + return + } + pad := float32(8) + viewport := gfx.Rect{ + X: d.Rect.X - pad, Y: d.Rect.Y - pad, + Width: d.Rect.Width + 2*pad, Height: d.Rect.Height + 2*pad, + } + components.BeginHoverCard(d.Canvas, *d.Theme, viewport, gfx.Rect{X: viewport.X, Y: viewport.Y}, components.HoverCardOptions{ + ContentSize: gfx.Size{Width: d.Rect.Width, Height: d.Rect.Height}, + }).Paint("", "") +} + +// declareChildren declares the card's content as page children, in the popup +// the view opened. +func (state *hoverState) declareChildren() { + c := state.c + if state.title != "" { + ui.Text(c, state.title).Weight(gfx.WeightMedium).Color(c.Theme().PopoverForeground) + } + if state.description != "" { + ui.Wrap(c, state.description).Muted() + } + if state.body != nil { + state.body() + } +} + +func contains(r gfx.Rect, p gfx.Point) bool { + return r.Width > 0 && r.Height > 0 && p.X >= r.X && p.Y >= r.Y && p.X < r.X+r.Width && p.Y < r.Y+r.Height +} + +// hoveredWithin reports whether point is inside the region the current paint +// declared for id. It covers an anchor whose own hits were split among its +// children, where Canvas.Hovered names a child rather than the anchor. +func hoveredWithin(canvas *gfx.Canvas, id gfx.ID, point gfx.Point) bool { + bounds, ok := canvas.HitBounds(id) + return ok && contains(bounds, point) +} diff --git a/ui/hovercardview/hovercardview_test.go b/ui/hovercardview/hovercardview_test.go new file mode 100644 index 00000000..55377c94 --- /dev/null +++ b/ui/hovercardview/hovercardview_test.go @@ -0,0 +1,281 @@ +package hovercardview_test + +import ( + "testing" + "time" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/hovercardview" +) + +const ( + testOpenDelay = 120 * time.Millisecond + testCloseDelay = 80 * time.Millisecond +) + +// pageDriver is a headless window that paints a page. +type pageDriver struct { + t *testing.T + driver *app.Driver +} + +func openPage(t *testing.T, view func(ui.C)) *pageDriver { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: view}) + driver, err := app.NewDriver(ui.Configure(page, app.Config{Width: 480, Height: 480}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + return &pageDriver{t: t, driver: driver} +} + +func (d *pageDriver) hit(label string) gfx.Hit { + d.t.Helper() + hits := d.driver.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if hit := hits[i]; hit.Label == label && !hit.IsLabel && !hit.Backdrop && !hit.ID.IsZero() { + return hit + } + } + d.t.Fatalf("no hit labeled %q", label) + return gfx.Hit{} +} + +func (d *pageDriver) hasText(value string) bool { + for _, text := range d.driver.Snapshot().Texts { + if text.Value == value { + return true + } + } + return false +} + +func (d *pageDriver) move(x, y float32) { + d.t.Helper() + if err := d.driver.Move(x, y); err != nil { + d.t.Fatal(err) + } +} + +func (d *pageDriver) advance(duration time.Duration) { + d.t.Helper() + if err := d.driver.Advance(duration); err != nil { + d.t.Fatal(err) + } +} + +func center(r gfx.Rect) (float32, float32) { return r.X + r.Width/2, r.Y + r.Height/2 } + +// viewWithCard declares one anchored card and returns its hit's label. +func viewWithCard(delays bool, extra func(*hovercardview.HoverCard)) (func(ui.C), string) { + const bodyLabel = "Engine" + view := func(c ui.C) { + ui.Column(c).Fill().Center().Children(func() { + anchor := ui.Button(c, "Profile").Outline().Width(160) + card := &hovercardview.HoverCard{ + Anchor: anchor, + Title: "Ada Lovelace", + Description: "First programmer.", + Body: func() { + ui.Button(c, bodyLabel) + }, + } + if delays { + card.Delays(testOpenDelay, testCloseDelay) + } + if extra != nil { + extra(card) + } + hovercardview.View(c, "Profile", card) + }) + } + return view, bodyLabel +} + +func TestCardOpensAfterTheOpenDelayAndClosesAfterLeaving(t *testing.T) { + view, bodyLabel := viewWithCard(true, nil) + d := openPage(t, view) + anchor := d.hit("Profile") + x, y := center(anchor.Bounds) + + if d.hasText("Ada Lovelace") && d.hasText("First programmer.") { + t.Fatal("the card painted before the pointer rested on the anchor") + } + d.move(x, y) + if d.hasText("First programmer.") { + t.Fatal("the card opened on the frame the pointer arrived") + } + d.advance(testOpenDelay - time.Millisecond) + if d.hasText("First programmer.") { + t.Fatal("the card opened before the open delay elapsed") + } + d.advance(time.Millisecond) + if !d.hasText("Ada Lovelace") || !d.hasText("First programmer.") || !d.hasText(bodyLabel) { + t.Fatal("the card did not paint its page children when its delay elapsed") + } + + d.move(470, 470) + if !d.hasText("First programmer.") { + t.Fatal("the card closed before the close delay elapsed") + } + d.advance(testCloseDelay - time.Millisecond) + if !d.hasText("First programmer.") { + t.Fatal("the card closed before the close delay elapsed") + } + d.advance(time.Millisecond) + if d.hasText("First programmer.") { + t.Fatal("the card stayed open after the close delay") + } +} + +func TestCardStaysOpenWhileThePointerIsOnItsContent(t *testing.T) { + view, bodyLabel := viewWithCard(true, nil) + d := openPage(t, view) + x, y := center(d.hit("Profile").Bounds) + d.move(x, y) + d.advance(testOpenDelay) + if !d.hasText("First programmer.") { + t.Fatal("the card did not open") + } + + body := d.hit(bodyLabel) + d.move(center(body.Bounds)) + d.advance(testCloseDelay * 4) + if !d.hasText("First programmer.") { + t.Fatal("the card closed while the pointer was on its content") + } + + d.move(470, 470) + d.advance(testCloseDelay + time.Millisecond) + if d.hasText("First programmer.") { + t.Fatal("the card stayed open after the pointer left both the anchor and the card") + } +} + +func TestCardUsesTheCallersAnchorGeometry(t *testing.T) { + view := func(c ui.C) { + ui.Row(c).Fill().Pad(20).Items(ui.Center).Children(func() { + anchor := ui.Button(c, "Profile").Outline().Width(80) + card := &hovercardview.HoverCard{ + Anchor: anchor, + Title: "Ada Lovelace", + Description: "First programmer.", + } + card.Side(hovercardview.Right).Align(hovercardview.Center).Delays(testOpenDelay, testCloseDelay) + hovercardview.View(c, "Profile", card) + }) + } + d := openPage(t, view) + anchor := d.hit("Profile") + d.move(center(anchor.Bounds)) + d.advance(testOpenDelay) + + var content gfx.Hit + for _, hit := range d.driver.Snapshot().Hits { + if hit.Role == gfx.RoleGroup && hit.Label == "Ada Lovelace" && !hit.ID.IsZero() { + content = hit + } + } + if content.ID.IsZero() { + t.Fatal("the open card declared no content hit") + } + if content.Bounds.X < anchor.Bounds.X+anchor.Bounds.Width { + t.Fatalf("card at %+v is not to the right of the anchor %+v", content.Bounds, anchor.Bounds) + } + if got, want := content.Bounds.Y+content.Bounds.Height/2, anchor.Bounds.Y+anchor.Bounds.Height/2; abs(got-want) > 1 { + t.Fatalf("card center Y = %v, anchor center Y = %v; Align(Center) did not center it", got, want) + } + if !d.hasText("Ada Lovelace") { + t.Fatal("the card did not paint its title") + } +} + +func TestOpenStateIsWrittenToTheCallersValue(t *testing.T) { + open := false + view, _ := viewWithCard(true, func(card *hovercardview.HoverCard) { + card.Open = &open + }) + d := openPage(t, view) + x, y := center(d.hit("Profile").Bounds) + d.move(x, y) + d.advance(testOpenDelay) + if !open { + t.Fatal("the card opened without writing the caller's open state") + } + d.move(470, 470) + d.advance(testCloseDelay + time.Millisecond) + if open { + t.Fatal("the card closed without clearing the caller's open state") + } +} + +func TestOnOpenChangeReportsHoverTransitions(t *testing.T) { + var changes []bool + change := func(open bool) { changes = append(changes, open) } + view, _ := viewWithCard(true, func(card *hovercardview.HoverCard) { + card.OnOpenChange = change + }) + d := openPage(t, view) + x, y := center(d.hit("Profile").Bounds) + d.move(x, y) + d.advance(testOpenDelay) + d.move(470, 470) + d.advance(testCloseDelay + time.Millisecond) + if len(changes) != 2 || !changes[0] || changes[1] { + t.Fatalf("OnOpenChange calls = %v, want [true false]", changes) + } +} + +func TestDisabledCardPaintsNothing(t *testing.T) { + view, _ := viewWithCard(true, func(card *hovercardview.HoverCard) { + card.Disabled() + }) + d := openPage(t, view) + x, y := center(d.hit("Profile").Bounds) + d.move(x, y) + d.advance(testOpenDelay * 4) + if d.hasText("First programmer.") { + t.Fatal("a disabled card painted") + } +} + +func BenchmarkViewWarmPaint(b *testing.B) { + open := true + card := &hovercardview.HoverCard{ + Title: "Ada Lovelace", + Description: "First programmer.", + Open: &open, + Body: func() {}, + } + card.Delays(testOpenDelay, testCloseDelay) + view := func(c ui.C) { + card.Anchor = ui.Button(c, "Ada Lovelace").Outline().Width(160) + hovercardview.View(c, "Ada Lovelace", card) + } + page := ui.NewPage(ui.PageConfig{View: view}) + canvas := new(gfx.Canvas) + canvas.SetMeasurer(func(value string, size, weight float32) float32 { return float32(len(value)) * size / 2 }) + paint(page, canvas, view) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + paint(page, canvas, view) + } +} + +func paint(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 480}, view) + canvas.EndFrame() +} + +func abs(v float32) float32 { + if v < 0 { + return -v + } + return v +} diff --git a/ui/markdownview/markdownview.go b/ui/markdownview/markdownview.go new file mode 100644 index 00000000..6f0ea521 --- /dev/null +++ b/ui/markdownview/markdownview.go @@ -0,0 +1,277 @@ +// Package markdownview is the opt-in page control for the Markdown renderer of +// package components. It owns the parsed document and the MarkdownView's layout +// caches, and paints through components.MarkdownView, so a page declares a +// Markdown document without parsing, laying out or painting it itself: +// +// answer := &markdownview.Markdown{ +// Source: message, +// Style: markdownview.Style{Size: c.Theme().Metrics.FontSizeM, LineHeight: 20}, +// } +// ... +// markdownview.View(c, "Assistant answer", answer).FillWidth().Height(420) +// +// Source is parsed when it changes; the document is laid out to the control's +// width when the source, the style's sizing fields or the width change. A warm +// paint with the same source, style and width therefore allocates nothing: the +// parse and layout caches live in the wrapper beside the caller's model. +// +// The caller owns the selection, the scroll offset and the view. Fill +// Markdown.Selection to highlight text, set Markdown.Offset to scroll, and read +// Markdown.SelectedText, Markdown.OffsetAt and Markdown.CaretAt to build a +// selection gesture. Links are hit regions of the control itself: an event +// whose target is not the control can be turned back into a link number with +// Markdown.LinkIndex, and the destination with Markdown.Link. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public gfx, components, markdown +// and ui packages. Keep a Markdown in the model: its handlers and draw function +// are made once, and do not copy it after View has declared it. +package markdownview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/markdown" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// Style sizes the text of a Markdown document. It is components.MarkdownStyle, +// named here so a page that declares Markdown reads through this package alone. +type Style = components.MarkdownStyle + +// Look colors a Markdown document. It is components.MarkdownLook. +type Look = components.MarkdownLook + +// Selection is a range of the rendered text, in byte offsets. +type Selection = components.MarkdownSelection + +// Code is a laid-out fenced code block. +type Code = components.MarkdownCode + +// CodeRun is a colored stretch of one line of highlighted code. +type CodeRun = components.MarkdownCodeRun + +// CodeClass says what a stretch of code is. +type CodeClass = components.MarkdownCodeClass + +// Code classes, as components.MarkdownCodeClass names them. +const ( + CodeComment = components.CodeComment + CodeString = components.CodeString + CodeNumber = components.CodeNumber + CodeKeyword = components.CodeKeyword + CodeFunction = components.CodeFunction + CodeVariable = components.CodeVariable + CodeFlag = components.CodeFlag + CodeKey = components.CodeKey + CodeAdded = components.CodeAdded + CodeRemoved = components.CodeRemoved + // CodeClasses is the size of Look.Code. + CodeClasses = components.MarkdownCodeClasses +) + +// Markdown is one document's page control: the caller's source and +// presentation, the renderer's parse and layout caches, and the callbacks that +// take its input. +// +// Fill Source and the presentation fields from the model every paint. The +// cached Document and MarkdownView are owned by the wrapper; do not call their +// methods to paint at the call site, and do not copy a Markdown after View has +// declared it. +type Markdown struct { + // Source is the Markdown text painted next. It is parsed when it changes. + Source string + // Style sizes the text. It is applied on the next layout; a change to Size, + // LineHeight, MonoFace or CodeInset re-lays the document out. A change to + // Highlight or Image cannot be observed by comparison, so call Relayout + // after replacing either function when the source and width stay the same. + Style Style + // Look colors the text. The zero value derives the look from the page's + // theme with components.MarkdownLookFor. + Look Look + // View is the renderer's layout and paint cache. The wrapper keeps it + // across paints; treat it as read-only. + View components.MarkdownView + // Selection is highlighted behind its text. It is clamped to the rendered + // text when it is painted. + Selection Selection + // Offset is the caller-owned vertical scroll offset in pixels. The document + // is painted Offset pixels above the control's top and clipped to the + // control. + Offset float32 + + // Pointer receives every pointer event aimed at the control or one of its + // links. Markdown.LinkIndex turns a link target back into a link number. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Key receives the keys pressed while the control has the focus. + Key func(gfx.KeyEvent) gfx.EventResult + // Scroll receives the wheel over the control. A nil callback leaves it to + // the page. + Scroll func(gfx.ScrollEvent) gfx.EventResult + // Text supplies the platform's text service while the control has the focus. + // A document is not editable; it lets an application observe or extend the + // text context. + Text func(window.TextInputContext) *window.TextInput + + doc markdown.Document + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + parsed bool + parsedSource string + layout layoutKey + laidOut bool + dirty bool +} + +// layoutKey is the input that decides the document's layout, apart from the +// parsed source and the two callbacks whose function values cannot be compared. +type layoutKey struct { + width float32 + size, line, inset float32 + face gfx.MonoFace + highlight, imageSet bool +} + +// View declares the Markdown document at c. Give it a height: the control lays +// the document out to the width it is given, clips what does not fit, and leaves +// the height to the caller (Height, Fill or the page's flow). label names the +// control for assistive technology. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, markdown *Markdown) ui.Box { + if markdown == nil { + panic("markdownview: View needs its Markdown") + } + markdown.prepare() + return ui.Control(c, label, &markdown.handlers).Draw(markdown.drawFn) +} + +// Relayout lays the document out again on the next paint even when the source, +// the style's sizing fields and the width are unchanged. Call it after the +// answer of Style.Image changes or after replacing Style.Highlight or +// Style.Image with a different function. +func (m *Markdown) Relayout() { m.dirty = true } + +// Height is the height of the document as last laid out, which may be larger +// than the control; use it to clamp Offset. +func (m *Markdown) Height() float32 { return m.View.Height() } + +// TextLen is the length in bytes of the rendered text that can be selected. +func (m *Markdown) TextLen() int { return m.View.TextLen() } + +// SelectedText is what a copy of Selection puts on the clipboard. +func (m *Markdown) SelectedText() string { return m.View.SelectedText(m.Selection) } + +// OffsetAt maps a window point to the nearest rendered text offset. It uses the +// geometry of the last paint, so it is valid from that paint until the next +// layout or paint. +func (m *Markdown) OffsetAt(point gfx.Point) (int, bool) { return m.View.OffsetAt(point) } + +// CaretAt is the window rectangle of a rendered byte offset after a paint. +func (m *Markdown) CaretAt(offset int) (gfx.Rect, bool) { return m.View.CaretAt(offset) } + +// Codes lists the fenced code blocks of the laid-out document, in reading +// order. Their bounds are relative to the painted document origin, which is the +// control's top-left less Offset. +func (m *Markdown) Codes() []components.MarkdownCode { return m.View.Codes() } + +// LinkCount is how many link fragments the document has. +func (m *Markdown) LinkCount() int { return m.View.LinkCount() } + +// Link is the destination of link fragment i, as LinkIndex numbers it, or "". +func (m *Markdown) Link(i int) string { return m.View.Link(i) } + +// LinkIndex returns the link fragment an event target names, and false for the +// control itself or any other target. The number is the one Link and LinkCount +// use. +func (m *Markdown) LinkIndex(target gfx.ID) (int, bool) { + if i, ok := target.In(m.handlers.Parts()); ok && i < m.View.LinkCount() { + return i, true + } + return 0, false +} + +func (m *Markdown) prepare() { + if m.prepared { + return + } + m.prepared = true + m.handlers.Pointer = m.pointer + m.handlers.Key = m.key + m.handlers.Scroll = m.scroll + m.handlers.Text = m.text + m.drawFn = m.draw +} + +func (m *Markdown) pointer(event gfx.PointerEvent) gfx.EventResult { + if m.Pointer == nil { + return gfx.EventResult{} + } + return m.Pointer(event) +} + +func (m *Markdown) key(event gfx.KeyEvent) gfx.EventResult { + if m.Key == nil { + return gfx.EventResult{} + } + return m.Key(event) +} + +func (m *Markdown) scroll(event gfx.ScrollEvent) gfx.EventResult { + if m.Scroll == nil { + return gfx.EventResult{} + } + return m.Scroll(event) +} + +func (m *Markdown) text(context window.TextInputContext) *window.TextInput { + if m.Text == nil { + return nil + } + return m.Text(context) +} + +func (m *Markdown) draw(d *ui.DrawContext) { + width := d.Rect.Width + if width <= 0 || d.Rect.Height <= 0 { + return + } + m.ensureLayout(d.Canvas, width) + look := m.Look + if look == (components.MarkdownLook{}) { + look = components.MarkdownLookFor(*d.Theme) + } + m.View.Paint(d.Canvas, components.MarkdownPaint{ + Look: look, + X: d.Rect.X, + Y: d.Rect.Y - m.Offset, + Clip: d.Rect, + Links: m.handlers.Parts(), + Selection: m.Selection, + }) +} + +// ensureLayout parses a new source and lays the document out when its source, +// style or width changed. Both caches belong to the wrapper, so a repaint with +// the same input does no parse, no measurement and no allocation. +func (m *Markdown) ensureLayout(canvas *gfx.Canvas, width float32) { + if !m.parsed || m.Source != m.parsedSource { + m.doc.Parse(m.Source) + m.parsedSource = m.Source + m.parsed = true + m.dirty = true + } + key := layoutKey{ + width: width, size: m.Style.Size, line: m.Style.LineHeight, + inset: m.Style.CodeInset, face: m.Style.MonoFace, + highlight: m.Style.Highlight != nil, imageSet: m.Style.Image != nil, + } + if m.dirty || !m.laidOut || key != m.layout { + m.View.Layout(canvas, m.Style, &m.doc, width) + m.layout = key + m.laidOut = true + m.dirty = false + } +} diff --git a/ui/markdownview/markdownview_test.go b/ui/markdownview/markdownview_test.go new file mode 100644 index 00000000..4c96f3b5 --- /dev/null +++ b/ui/markdownview/markdownview_test.go @@ -0,0 +1,186 @@ +package markdownview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/markdownview" + "github.com/vivaui/viva/window" +) + +const source = "## Restarting nginx\n\nCheck the **config** with `nginx -t`, then read the [docs](https://nginx.org/en/docs/).\n\n1. run `systemctl status nginx`\n2. restart it\n" + +type model struct { + view markdownview.Markdown + input window.TextInput + + target gfx.ID + keys, pointers int + scrolls, texts int + link int + linkOK bool + control *ui.Page + canvas *gfx.Canvas +} + +func (m *model) wire() { + m.view.Pointer = func(event gfx.PointerEvent) gfx.EventResult { + m.pointers++ + m.target = event.Target + m.link, m.linkOK = m.view.LinkIndex(event.Target) + return gfx.EventResult{Handled: true} + } + m.view.Key = func(event gfx.KeyEvent) gfx.EventResult { + m.keys++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } + m.view.Scroll = func(event gfx.ScrollEvent) gfx.EventResult { + m.scrolls++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } + m.view.Text = func(window.TextInputContext) *window.TextInput { + m.texts++ + return &m.input + } +} + +func (m *model) viewPage(c ui.C) { + markdownview.View(c, "Answer", &m.view).FillWidth().Height(320) +} + +func drawPage(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 360}, view) + canvas.EndFrame() +} + +func hitLabelled(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + if hits[i].Label == label && !hits[i].ID.IsZero() { + return hits[i], true + } + } + return gfx.Hit{}, false +} + +func open(t *testing.T, m *model) { + t.Helper() + m.wire() + m.view.Source = source + m.view.Style = markdownview.Style{Size: 13, LineHeight: 20} + theme := gfx.LightTheme() + m.control = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: &theme}) + m.canvas = new(gfx.Canvas) + drawPage(m.control, m.canvas, m.viewPage) +} + +// The page declares the view, the wrapper parses and lays the source out, and +// the renderer paints its text and the control's link regions. +func TestMarkdownViewPaintsTextAndControl(t *testing.T) { + m := new(model) + open(t, m) + + hit, ok := hitLabelled(m.canvas, "Answer") + if !ok { + t.Fatal("the markdown view painted no control named Answer") + } + if hit.Role != gfx.RoleGroup { + t.Fatalf("control role = %v, want group", hit.Role) + } + if hit.Bounds.Width != 480 || hit.Bounds.Height != 320 { + t.Fatalf("control bounds = %+v, want a 480x320 box", hit.Bounds) + } + if m.view.TextLen() == 0 || m.view.Height() == 0 { + t.Fatalf("document = %d text bytes, height %g; want a laid-out document", m.view.TextLen(), m.view.Height()) + } + if got := m.view.SelectedText(); got != "" { + t.Fatalf("empty selection copied %q", got) + } + if m.view.LinkCount() != 1 { + t.Fatalf("link count = %d, want 1", m.view.LinkCount()) + } + link, ok := hitLabelled(m.canvas, "docs") + if !ok { + t.Fatal("the renderer painted no hit region labelled docs") + } + if link.Role != gfx.RoleLink { + t.Fatalf("link role = %v, want link", link.Role) + } + if index, ok := m.view.LinkIndex(link.ID); !ok || index != 0 { + t.Fatalf("LinkIndex(%v) = %d, %v; want 0, true", link.ID, index, ok) + } + if got := m.view.Link(0); got != "https://nginx.org/en/docs/" { + t.Fatalf("Link(0) = %q", got) + } + if _, ok := m.view.OffsetAt(gfx.Point{X: hit.Bounds.X + 8, Y: hit.Bounds.Y + 8}); !ok { + t.Fatal("OffsetAt found no text after paint") + } +} + +// Pointer, keys, the wheel and the text service reach the callbacks, and a link +// target is still routed to the control that owns the link. +func TestMarkdownViewRoutesInput(t *testing.T) { + m := new(model) + open(t, m) + + hit, ok := hitLabelled(m.canvas, "Answer") + if !ok { + t.Fatal("the markdown view painted no control named Answer") + } + if result := m.control.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: hit.ID, + X: hit.Bounds.X + 8, Y: hit.Bounds.Y + 8, + }); !result.Handled || m.pointers != 1 || m.target != hit.ID { + t.Fatalf("pointer result = %+v after %d callbacks targeting %v", result, m.pointers, m.target) + } + link, _ := hitLabelled(m.canvas, "docs") + if result := m.control.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: link.ID, + X: link.Bounds.X + 1, Y: link.Bounds.Y + 1, + }); !result.Handled || m.pointers != 2 { + t.Fatalf("link pointer result = %+v after %d callbacks", result, m.pointers) + } + if !m.linkOK || m.link != 0 { + t.Fatalf("link target = %d, %v; want link 0", m.link, m.linkOK) + } + if result := m.control.Key(gfx.KeyEvent{Key: gfx.KeyDown, Target: hit.ID}); !result.Handled || m.keys != 1 { + t.Fatalf("key result = %+v after %d callbacks", result, m.keys) + } + if result := m.control.Wheel(gfx.ScrollEvent{Target: hit.ID, Y: 12}); !result.Handled || m.scrolls != 1 { + t.Fatalf("wheel result = %+v after %d callbacks", result, m.scrolls) + } + if m.control.TextInput(window.TextInputContext{ID: hit.ID}) == nil || m.texts != 1 { + t.Fatalf("text service got no input; callbacks = %d", m.texts) + } +} + +// A warm repaint parses nothing and lays nothing out: the wrapper caches both +// by source, style and width. +func TestMarkdownViewWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + open(t, m) + if allocations := testing.AllocsPerRun(100, func() { drawPage(m.control, m.canvas, m.viewPage) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkMarkdownViewWarmPaint(b *testing.B) { + m := new(model) + m.wire() + m.view.Source = source + m.view.Style = markdownview.Style{Size: 13, LineHeight: 20} + theme := gfx.LightTheme() + m.control = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: &theme}) + m.canvas = new(gfx.Canvas) + drawPage(m.control, m.canvas, m.viewPage) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + drawPage(m.control, m.canvas, m.viewPage) + } +} diff --git a/ui/menubarview/menubarview.go b/ui/menubarview/menubarview.go new file mode 100644 index 00000000..998c40fa --- /dev/null +++ b/ui/menubarview/menubarview.go @@ -0,0 +1,613 @@ +// Package menubarview is the opt-in page control for the persistent menu bar +// of package components. It wraps components.BeginMenubar and +// components.BeginMenubarContent in a ui.Control, so a page declares the bar, +// its triggers and their rows without calling the components themselves: +// +// m.menubar.Reset() +// m.menubar.Trigger(fileID, "File"). +// Item(newID, "New window").Shortcut("⌘N"). +// Item(gridID, "Show grid").Checkbox(m.grid). +// Separator(). +// Item(deleteID, "Delete workspace").Destructive() +// m.menubar.Trigger(viewID, "View").Item(reloadID, "Reload") +// m.menubar.View(c, "Menubar").FillWidth().Height(36) +// // After the paint, Selected names the row chosen last. +// if m.menubar.Selected == gridID { +// m.grid = !m.grid +// m.menubar.Selected = gfx.ID{} +// } +// +// The caller owns the open trigger, the focused trigger or row, the selected +// row and every label, description and identity. The wrapper paints through +// the components with exactly the identities the caller supplied, changes Open +// when a trigger is clicked, and reports the clicked or chosen identity with +// Clicked and Selected. Pointer and key events aimed at the control itself reach +// the optional callbacks; clicks on triggers and rows are read with Clicked +// after the paint, as for the component. +// +// Declarations are rebuilt every paint: call Reset, declare the triggers and +// rows in order, then View. The slices keep their capacity, so a warm paint +// allocates nothing. Keep a Menubar in the model beside its state; its handlers +// and draw function are made once. Do not copy a Menubar after View has painted +// it. +// +// It is a separate package so an application that does not import it pays +// nothing for it. +package menubarview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Direction is components.Direction, named here so a page that declares a bar +// reads through this package alone. +type Direction = components.Direction + +// Menubar is one menubar's caller-owned state, its declarations and its page +// control. Fill Open and the callbacks from the model; declare the triggers and +// rows every paint; then call View. +type Menubar struct { + // Open is the trigger whose menu is open, or zero when the bar is closed. + // A trigger click toggles it. + Open gfx.ID + // Focus is the trigger or row the keyboard acts on. Clicking a trigger or + // a row sets it; the arrow keys move it. + Focus gfx.ID + // Selected is the row chosen last by a click or by Enter, or zero before a + // row is chosen. The wrapper writes it; the caller consumes and clears it. + Selected gfx.ID + // Direction selects the arrow movement. The zero value is left to right. + Direction components.Direction + // Layer is the popup's layer. Zero uses layer 1. + Layer uint16 + // Scope and DismissID are passed to the popup: Scope traps focus and + // DismissID is the identity an Escape or an outside press reports. + Scope, DismissID gfx.ID + // Viewport, with DismissID, makes a press outside the popup report DismissID + // and pass through, as a menubar does. + Viewport gfx.Rect + // Content optionally fixes the popup geometry. Zero Width and Height select + // the size the rows need; zero X and Y place the popup under the open + // trigger. A nonzero width or height is used as given. + Content gfx.Rect + + // Pointer receives every pointer event aimed at the control itself. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Key receives the keys pressed while the control has the focus. The + // wrapper moves Focus and updates Open first; the callback's Handled and + // Repaint are merged. + Key func(gfx.KeyEvent) gfx.EventResult + + triggers []triggerDecl + items []itemDecl + + currentTrigger int + currentItem int + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + + triggerModels []components.MenubarTrigger + triggerBounds []gfx.Rect + + clicked gfx.ID + hadClick bool +} + +type triggerDecl struct { + ID gfx.ID + Label string + Hint string + Disabled bool +} + +type itemDecl struct { + Trigger int + Separator bool + Item components.MenubarItem +} + +const ( + // The popup hangs this far below the bar, as the component's own examples do. + popupOffset = float32(8) + // The menubar's minimum popup width, in the component. + minPopupWidth = float32(144) +) + +// Reset forgets the last paint's declarations. Call it before declaring the +// triggers and rows again; the backing slices stay, so the next paint reuses +// them. +func (m *Menubar) Reset() { + m.triggers = m.triggers[:0] + m.items = m.items[:0] + m.currentTrigger, m.currentItem = -1, -1 +} + +// Trigger declares one top-level trigger. The rows declared after it belong to +// it until the next Trigger. +func (m *Menubar) Trigger(id gfx.ID, label string) *Menubar { + m.triggers = append(m.triggers, triggerDecl{ID: id, Label: label}) + m.currentTrigger, m.currentItem = len(m.triggers)-1, -1 + return m +} + +// Item declares one row of the current trigger. Rows are painted only while +// their trigger's menu is open. +func (m *Menubar) Item(id gfx.ID, label string) *Menubar { + if m.currentTrigger < 0 { + return m + } + m.items = append(m.items, itemDecl{ + Trigger: m.currentTrigger, + Item: components.MenubarItem{ID: id, Label: label}, + }) + m.currentItem = len(m.items) - 1 + return m +} + +// Separator declares a divider between the current trigger's rows. +func (m *Menubar) Separator() *Menubar { + if m.currentTrigger < 0 { + return m + } + m.items = append(m.items, itemDecl{Trigger: m.currentTrigger, Separator: true}) + m.currentItem = -1 + return m +} + +// Hint sets the accessible hint of the current row, or of the current trigger +// when no row has been declared since it. +func (m *Menubar) Hint(hint string) *Menubar { + if m.currentItem >= 0 { + m.items[m.currentItem].Item.Hint = hint + return m + } + if m.currentTrigger >= 0 && m.currentTrigger < len(m.triggers) { + m.triggers[m.currentTrigger].Hint = hint + } + return m +} + +// Disabled disables the current row, or the current trigger when no row has +// been declared since it. +func (m *Menubar) Disabled() *Menubar { + if m.currentItem >= 0 { + m.items[m.currentItem].Item.Disabled = true + return m + } + if m.currentTrigger >= 0 && m.currentTrigger < len(m.triggers) { + m.triggers[m.currentTrigger].Disabled = true + } + return m +} + +// Shortcut sets the current row's trailing shortcut text. +func (m *Menubar) Shortcut(shortcut string) *Menubar { + if m.currentItem >= 0 { + m.items[m.currentItem].Item.Shortcut = shortcut + } + return m +} + +// Keys sets the current row's trailing keycaps, replacing Shortcut. +func (m *Menubar) Keys(keys ...string) *Menubar { + if m.currentItem >= 0 { + m.items[m.currentItem].Item.Keys = keys + } + return m +} + +// Value sets the current row's accessible value. +func (m *Menubar) Value(value string) *Menubar { + if m.currentItem >= 0 { + m.items[m.currentItem].Item.Value = value + } + return m +} + +// Checkbox makes the current row a checkbox with the given checked state. +func (m *Menubar) Checkbox(checked bool) *Menubar { + if m.currentItem >= 0 { + item := &m.items[m.currentItem].Item + item.Kind, item.Checked = components.MenubarCheckbox, checked + } + return m +} + +// Radio makes the current row a radio option with the given selected state. +func (m *Menubar) Radio(selected bool) *Menubar { + if m.currentItem >= 0 { + item := &m.items[m.currentItem].Item + item.Kind, item.Selected = components.MenubarRadio, selected + } + return m +} + +// Submenu makes the current row a submenu trigger with the given expanded +// state. +func (m *Menubar) Submenu(expanded bool) *Menubar { + if m.currentItem >= 0 { + item := &m.items[m.currentItem].Item + item.Kind, item.Expanded = components.MenubarSubmenu, expanded + } + return m +} + +// Destructive paints the current row with the destructive treatment. +func (m *Menubar) Destructive() *Menubar { + if m.currentItem >= 0 { + m.items[m.currentItem].Item.Variant = components.MenubarItemDestructive + } + return m +} + +// Inset indents the current row's label, as a submenu row does. +func (m *Menubar) Inset() *Menubar { + if m.currentItem >= 0 { + m.items[m.currentItem].Item.Inset = true + } + return m +} + +// View declares the menubar at c. label names the control for assistive +// technology. Give it the bar's size; the popup is painted above it. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, bar *Menubar) ui.Box { + if bar == nil { + panic("menubarview: View needs its Menubar") + } + bar.prepare() + return ui.Control(c, label, &bar.handlers).Draw(bar.drawFn) +} + +// View declares the menubar at c, for a page that keeps the Menubar in its +// model. +func (m *Menubar) View(c ui.C, label string) ui.Box { return View(c, label, m) } + +// Clicked reports whether the paint just made was an event pass delivering a +// click on id, a trigger or row identity the caller declared. It is false in +// ordinary paints. Ask it after the paint. +func (m *Menubar) Clicked(id gfx.ID) bool { + return m.hadClick && !id.IsZero() && m.clicked == id +} + +func (m *Menubar) prepare() { + if m.prepared { + return + } + m.prepared = true + m.handlers.Pointer = m.pointer + m.handlers.Key = m.key + m.drawFn = m.draw +} + +func (m *Menubar) direction() components.Direction { + if m.Direction == components.RTL { + return components.RTL + } + return components.LTR +} + +func (m *Menubar) layer() uint16 { + if m.Layer == 0 { + return 1 + } + return m.Layer +} + +func (m *Menubar) draw(d *ui.DrawContext) { + raw, had := d.Canvas.ClickTarget() + theme := *d.Theme + canvas := d.Canvas + + m.triggerModels = m.triggerModels[:0] + for index := range m.triggers { + trigger := &m.triggers[index] + m.triggerModels = append(m.triggerModels, components.MenubarTrigger{ + ID: trigger.ID, + Label: trigger.Label, + Hint: trigger.Hint, + Open: m.Open == trigger.ID, + Disabled: trigger.Disabled, + }) + } + bar := components.BeginMenubar(canvas, theme, d.Rect) + m.triggerBounds = m.triggerBounds[:0] + for index := range m.triggerModels { + m.triggerBounds = append(m.triggerBounds, bar.AddTrigger(m.triggerModels[index])) + } + if open := m.triggerIndex(m.Open); open >= 0 && open < len(m.triggerBounds) { + m.paintContent(d, theme, open) + } + + m.clicked, m.hadClick = raw, had + if had { + m.choose() + } +} + +func (m *Menubar) paintContent(d *ui.DrawContext, theme gfx.Theme, trigger int) { + canvas := d.Canvas + bounds := m.contentBounds(canvas, theme, d.Rect, trigger) + options := components.MenubarOverlayOptions{ + Layer: m.layer(), Scope: m.Scope, DismissID: m.DismissID, Viewport: m.Viewport, + } + content := components.BeginMenubarContent(canvas, theme, bounds, options) + for index := range m.items { + item := &m.items[index] + if item.Trigger != trigger { + continue + } + if item.Separator { + content.AddSeparator() + continue + } + content.AddItem(item.Item) + } + content.End() +} + +func (m *Menubar) contentBounds(canvas *gfx.Canvas, theme gfx.Theme, bar gfx.Rect, trigger int) gfx.Rect { + width, height := m.Content.Width, m.Content.Height + if width <= 0 || height <= 0 { + neededWidth, neededHeight := float32(0), 2*components.DropdownMenuPadding + for index := range m.items { + item := &m.items[index] + if item.Trigger != trigger { + continue + } + if item.Separator { + neededHeight += components.DropdownMenuSeparatorHeight + continue + } + row := dropdownItem(item.Item) + neededWidth = max(neededWidth, components.DropdownMenuItemWidth(canvas, theme, row)) + neededHeight += components.DropdownMenuItemHeight(theme, row) + } + if width <= 0 { + width = max(neededWidth, minPopupWidth) + } + if height <= 0 { + height = max(neededHeight, 2*components.DropdownMenuPadding) + } + } + x, y := m.Content.X, m.Content.Y + if x == 0 && trigger >= 0 && trigger < len(m.triggerBounds) { + x = m.triggerBounds[trigger].X + } + if y == 0 { + y = bar.Y + bar.Height + popupOffset + } + return gfx.Rect{X: x, Y: y, Width: width, Height: height} +} + +func dropdownItem(item components.MenubarItem) components.DropdownMenuItem { + return components.DropdownMenuItem{ + ID: item.ID, Label: item.Label, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, + Value: item.Value, Hint: item.Hint, + Kind: components.DropdownMenuItemKind(item.Kind), + Variant: components.DropdownMenuItemVariant(item.Variant), + Checked: item.Checked, Selected: item.Selected, Disabled: item.Disabled, Inset: item.Inset, + Expanded: item.Expanded, Icon: item.Icon, + } +} + +func (m *Menubar) triggerIndex(id gfx.ID) int { + if id.IsZero() { + return -1 + } + for index := range m.triggers { + if m.triggers[index].ID == id { + return index + } + } + return -1 +} + +func (m *Menubar) itemIndex(id gfx.ID) int { + if id.IsZero() { + return -1 + } + for index := range m.items { + if !m.items[index].Separator && m.items[index].Item.ID == id { + return index + } + } + return -1 +} + +// choose applies the click this paint is delivering. +func (m *Menubar) choose() { + switch index := m.itemIndex(m.clicked); { + case m.clicked == m.DismissID && !m.DismissID.IsZero(): + m.Open = gfx.ID{} + case index >= 0: + m.Focus = m.clicked + m.Selected = m.clicked + if m.items[index].Item.Kind == components.MenubarAction { + m.Open = gfx.ID{} + if trigger := m.items[index].Trigger; trigger >= 0 && trigger < len(m.triggers) { + m.Focus = m.triggers[trigger].ID + } + } + case m.triggerIndex(m.clicked) >= 0: + m.Focus = m.clicked + m.Open = gfx.ID(components.MenubarState(m.Open).Toggle(m.clicked)) + } +} + +func (m *Menubar) pointer(event gfx.PointerEvent) gfx.EventResult { + if m.Pointer != nil { + return m.Pointer(event) + } + return gfx.EventResult{} +} + +func (m *Menubar) key(event gfx.KeyEvent) gfx.EventResult { + var result gfx.EventResult + if !event.Release && event.Text == "" && event.Key != gfx.KeyUnknown && !event.Key.IsModifier() { + focus := event.Target + if m.itemIndex(focus) < 0 && m.triggerIndex(focus) < 0 { + focus = m.Focus + } + if focus.IsZero() { + focus = m.Open + } + if focus.IsZero() && len(m.triggers) > 0 { + focus = m.triggers[0].ID + } + if index := m.itemIndex(focus); index >= 0 { + result = m.itemKey(event, index) + } else if index := m.triggerIndex(focus); index >= 0 { + result = m.triggerKey(event, index) + } + } + if m.Key != nil { + callback := m.Key(event) + result.Handled = result.Handled || callback.Handled + result.Repaint = result.Repaint || callback.Repaint + result.Blur = result.Blur || callback.Blur + result.ContinueTraversal = result.ContinueTraversal || callback.ContinueTraversal + if result.Focus.IsZero() { + result.Focus, result.FocusVisible = callback.Focus, callback.FocusVisible + } + if result.Activate.IsZero() { + result.Activate = callback.Activate + } + } + return result +} + +func (m *Menubar) triggerKey(event gfx.KeyEvent, trigger int) gfx.EventResult { + if trigger < 0 || trigger >= len(m.triggers) { + return gfx.EventResult{} + } + var state components.MenubarState + if open := m.triggerIndex(m.Open); open >= 0 { + state = components.MenubarState(m.triggers[open].ID) + } + next, focus, ok := components.MenubarKeyDown(m.triggers[trigger].ID, m.triggerModels, state, m.direction(), event.Key) + if !ok { + return gfx.EventResult{} + } + m.Open, m.Focus = next.ActiveID(), focus + result := gfx.EventResult{Handled: true, Repaint: true, Focus: focus, FocusVisible: true} + switch event.Key { + case gfx.KeyDown, gfx.KeyEnter, gfx.KeySpace: + if open := m.triggerIndex(m.Open); open >= 0 { + if item, ok := m.firstItem(open); ok { + m.Focus = item + result.Focus = item + } + } + } + return result +} + +func (m *Menubar) itemKey(event gfx.KeyEvent, item int) gfx.EventResult { + if item < 0 || item >= len(m.items) || m.items[item].Separator { + return gfx.EventResult{} + } + row := &m.items[item] + if row.Trigger < 0 || row.Trigger >= len(m.triggers) { + return gfx.EventResult{} + } + if m.Open != m.triggers[row.Trigger].ID { + return m.triggerKey(event, row.Trigger) + } + switch event.Key { + case gfx.KeyUp, gfx.KeyDown, gfx.KeyHome, gfx.KeyEnd: + next, ok := m.moveItem(item, event.Key) + if !ok { + return gfx.EventResult{Handled: true} + } + m.Focus = m.items[next].Item.ID + return gfx.EventResult{Handled: true, Repaint: true, Focus: m.Focus, FocusVisible: true} + case gfx.KeyEnter, gfx.KeySpace: + if row.Item.Disabled || row.Item.ID.IsZero() { + return gfx.EventResult{Handled: true} + } + m.Focus, m.Selected = row.Item.ID, row.Item.ID + return gfx.EventResult{Handled: true, Repaint: true, Activate: row.Item.ID} + case gfx.KeyEscape: + m.Open = gfx.ID{} + trigger := row.Trigger + if trigger < 0 || trigger >= len(m.triggers) { + return gfx.EventResult{Handled: true, Repaint: true} + } + m.Focus = m.triggers[trigger].ID + return gfx.EventResult{Handled: true, Repaint: true, Focus: m.Focus, FocusVisible: true} + case gfx.KeyLeft, gfx.KeyRight: + trigger := row.Trigger + if trigger < 0 || trigger >= len(m.triggers) { + return gfx.EventResult{} + } + state := components.MenubarState(m.triggers[trigger].ID) + next, focus, ok := components.MenubarKeyDown(m.triggers[trigger].ID, m.triggerModels, state, m.direction(), event.Key) + if !ok { + return gfx.EventResult{} + } + m.Open, m.Focus = next.ActiveID(), focus + return gfx.EventResult{Handled: true, Repaint: true, Focus: focus, FocusVisible: true} + case gfx.KeyTab: + m.Open = gfx.ID{} + return gfx.EventResult{Handled: true, Repaint: true, ContinueTraversal: true} + } + return gfx.EventResult{} +} + +// moveItem returns the next enabled row of the same menu, skipping separators +// and disabled rows, with wrapping. +func (m *Menubar) moveItem(from int, key gfx.Key) (int, bool) { + trigger := m.items[from].Trigger + if key == gfx.KeyHome || key == gfx.KeyEnd { + step, index := 1, -1 + if key == gfx.KeyEnd { + step, index = -1, len(m.items) + } + for at := index; at >= 0 && at < len(m.items); at += step { + if at == from { + continue + } + if m.usableItem(at, trigger) { + return at, true + } + } + return 0, false + } + step := 1 + if key == gfx.KeyUp { + step = -1 + } + for offset := 1; offset <= len(m.items); offset++ { + at := from + step*offset + for at < 0 { + at += len(m.items) + } + for at >= len(m.items) { + at -= len(m.items) + } + if m.usableItem(at, trigger) { + return at, true + } + } + return 0, false +} + +func (m *Menubar) usableItem(index, trigger int) bool { + item := &m.items[index] + return item.Trigger == trigger && !item.Separator && !item.Item.Disabled && !item.Item.ID.IsZero() +} + +func (m *Menubar) firstItem(trigger int) (gfx.ID, bool) { + for index := range m.items { + if m.usableItem(index, trigger) { + return m.items[index].Item.ID, true + } + } + return gfx.ID{}, false +} diff --git a/ui/menubarview/menubarview_test.go b/ui/menubarview/menubarview_test.go new file mode 100644 index 00000000..e961775e --- /dev/null +++ b/ui/menubarview/menubarview_test.go @@ -0,0 +1,239 @@ +package menubarview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/menubarview" +) + +var ( + fileID = gfx.Item(1) + viewID = gfx.Item(2) + newID = gfx.Item(3) + gridID = gfx.Item(4) + deleteID = gfx.Item(5) + reloadID = gfx.Item(6) + dismissID = gfx.Item(7) +) + +type model struct { + bar menubarview.Menubar + + grid bool + + pointerTarget gfx.ID + keyTarget gfx.ID + keys int +} + +func (m *model) wire() { + m.bar.Scope = gfx.Item(80) + m.bar.DismissID = dismissID + m.bar.Pointer = func(event gfx.PointerEvent) gfx.EventResult { + m.pointerTarget = event.Target + return gfx.EventResult{Handled: true, Repaint: true} + } + m.bar.Key = func(event gfx.KeyEvent) gfx.EventResult { + m.keys++ + m.keyTarget = event.Target + return gfx.EventResult{Handled: true} + } +} + +func (m *model) view(c ui.C) { + m.bar.Reset() + m.bar.Trigger(fileID, "File"). + Item(newID, "New window").Shortcut("⌘N"). + Item(gridID, "Show grid").Checkbox(m.grid). + Separator(). + Item(deleteID, "Delete workspace").Destructive() + m.bar.Trigger(viewID, "View").Item(reloadID, "Reload") + m.bar.View(c, "Menubar").Width(420).Height(36) + if m.bar.Selected == gridID { + m.grid = !m.grid + m.bar.Selected = gfx.ID{} + } +} + +func openPage(t *testing.T, m *model) (*ui.Page, *gfx.Canvas) { + t.Helper() + m.wire() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.view, Theme: &theme}) + canvas := benchCanvas() + draw(page, canvas, m.view) + return page, canvas +} + +func benchCanvas() *gfx.Canvas { + canvas := &gfx.Canvas{} + canvas.SetMeasurer(func(value string, size, weight float32) float32 { return float32(len(value)) * size / 2 }) + return canvas +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 600, Height: 400}, view) + canvas.EndFrame() +} + +func drawClick(page *ui.Page, canvas *gfx.Canvas, view func(ui.C), id gfx.ID) { + canvas.BeginEventPass(id, gfx.ClickInfo{}) + draw(page, canvas, view) + canvas.EndEventPass() +} + +func hitLabel(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for index := len(hits) - 1; index >= 0; index-- { + hit := hits[index] + if hit.Label == label && !hit.ID.IsZero() && !hit.Backdrop { + return hit, true + } + } + return gfx.Hit{}, false +} + +func mustHit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + hit, ok := hitLabel(canvas, label) + if !ok { + t.Fatalf("no hit labelled %q", label) + } + return hit +} + +func TestMenubarOpensFromATriggerAndChoosesARow(t *testing.T) { + m := &model{} + page, canvas := openPage(t, m) + + drawClick(page, canvas, m.view, fileID) + if m.bar.Open != fileID { + t.Fatalf("open = %v, want File", m.bar.Open) + } + draw(page, canvas, m.view) + for _, label := range []string{"New window", "Show grid", "Delete workspace"} { + mustHit(t, canvas, label) + } + + // A click the runtime delivers on the row's internal identity is translated + // back to the caller's identity. + row := mustHit(t, canvas, "New window") + drawClick(page, canvas, m.view, row.ID) + if m.bar.Selected != newID { + t.Fatalf("selected = %v, want the New window row", m.bar.Selected) + } + if !m.bar.Open.IsZero() { + t.Fatal("choosing an action row left the menu open") + } + + // The caller identity works too, as direct event passes and tests do. + m.bar.Open = fileID + drawClick(page, canvas, m.view, deleteID) + if m.bar.Selected != deleteID { + t.Fatalf("selected = %v, want the Delete workspace row", m.bar.Selected) + } +} + +func TestMenubarTogglesACheckboxRow(t *testing.T) { + m := &model{} + m.bar.Open = fileID + page, canvas := openPage(t, m) + if m.grid { + t.Fatal("grid starts checked") + } + drawClick(page, canvas, m.view, gridID) + if m.bar.Selected != gridID { + t.Fatalf("selected = %v, want the Show grid row", m.bar.Selected) + } + // The caller owns the checked state: apply the reported choice and repaint. + m.grid, m.bar.Selected = true, gfx.ID{} + draw(page, canvas, m.view) + row := mustHit(t, canvas, "Show grid") + if !row.Checked { + t.Fatal("the checked row was not painted checked") + } +} + +func TestMenubarKeysMoveOpenAndChoose(t *testing.T) { + m := &model{} + m.bar.Open = fileID + page, canvas := openPage(t, m) + control := mustHit(t, canvas, "Menubar") + file := mustHit(t, canvas, "File") + newRow := mustHit(t, canvas, "New window") + + result, ok := page.RouteKey(gfx.KeyEvent{Key: gfx.KeyDown, Target: control.ID}) + if !ok || !result.Handled { + t.Fatalf("Down was not handled: %+v, %v", result, ok) + } + if m.bar.Open != fileID || result.Focus != newRow.ID { + t.Fatalf("Down opened %v and focused %v, want File and the first row", m.bar.Open, result.Focus) + } + if m.keyTarget != control.ID { + t.Fatalf("the key callback saw %v, want the control", m.keyTarget) + } + + m.bar.Focus = fileID + result, _ = page.RouteKey(gfx.KeyEvent{Key: gfx.KeyRight, Target: control.ID}) + if m.bar.Open != viewID { + t.Fatalf("Right left %v open, want View", m.bar.Open) + } + view := mustHit(t, canvas, "View") + if result.Focus != view.ID { + t.Fatalf("Right focused %v, want the View trigger", result.Focus) + } + + m.bar.Open = fileID + m.bar.Focus = newID + draw(page, canvas, m.view) + newRow = mustHit(t, canvas, "New window") + result, _ = page.RouteKey(gfx.KeyEvent{Key: gfx.KeyEnter, Target: control.ID}) + if result.Activate != newRow.ID || m.bar.Selected != newID { + t.Fatalf("Enter activated %v and selected %v, want the New window row", result.Activate, m.bar.Selected) + } + + result, _ = page.RouteKey(gfx.KeyEvent{Key: gfx.KeyEscape, Target: control.ID}) + if !m.bar.Open.IsZero() || result.Focus != file.ID { + t.Fatalf("Escape left %v open and focused %v, want File", m.bar.Open, result.Focus) + } +} + +func TestMenubarPointerTranslation(t *testing.T) { + m := &model{} + m.bar.Open = fileID + page, canvas := openPage(t, m) + control := mustHit(t, canvas, "Menubar") + page.Pointer(gfx.PointerEvent{Kind: gfx.PointerDown, Target: control.ID, X: control.Bounds.X + 4, Y: control.Bounds.Y + 4}) + if m.pointerTarget != control.ID { + t.Fatalf("the pointer callback saw %v, want the control", m.pointerTarget) + } +} + +func TestMenubarDirectIdentitiesAreReported(t *testing.T) { + m := &model{} + page, canvas := openPage(t, m) + row := mustHit(t, canvas, "File") + drawClick(page, canvas, m.view, row.ID) + if m.bar.Open != fileID { + t.Fatalf("open = %v after a click on the internal trigger identity", m.bar.Open) + } +} + +func BenchmarkMenubarPaint(b *testing.B) { + m := &model{grid: true} + m.bar.Open = fileID + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.view, Theme: &theme}) + canvas := benchCanvas() + view := m.view + draw(page, canvas, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/messagescrollerview/messagescrollerview.go b/ui/messagescrollerview/messagescrollerview.go new file mode 100644 index 00000000..a9798943 --- /dev/null +++ b/ui/messagescrollerview/messagescrollerview.go @@ -0,0 +1,321 @@ +// Package messagescrollerview is the opt-in page control for a controlled +// scrolling stream of messages. It declares the page's own ScrollAt area, so +// the wheel, the scrollbars, clipping and layout are the engine's, and adds the +// earlier/later jump controls: +// +// stream := &messagescrollerview.Scroller{ +// Offset: m.offset, +// EarlierLabel: "Earlier messages", +// LaterLabel: "Later messages", +// Content: func(c ui.C) { +// for _, message := range m.messages { +// ui.Row(c).Height(62).Children(message) +// } +// }, +// } +// stream.OnScroll = func(offset float32) { m.offset = offset } +// messagescrollerview.View(c, "Conversation", stream).FillWidth().Height(280) +// +// The caller owns the offset and the content; the view owns no timer, follows +// no content by itself and schedules no frame. The scroll area is declared with +// ScrollAt, so the page does not handle its wheel: give Config.OnScroll the +// view's Wheel, and call Key for keyboard scrolling when the stream should take +// focus. OnScroll reports every offset the reader moves to, including a +// scrollbar drag, so the caller can store it; OnJump reports the target of an +// earlier/later button. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Scroller in the model with its callbacks set once; the +// view's handlers are the caller's own, and a warm paint allocates nothing. +package messagescrollerview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Direction names the end a jump control goes to. +type Direction uint8 + +const ( + // Earlier jumps to the start of the content. + Earlier Direction = iota + // Later jumps to the end of the content. + Later +) + +// Geometry is the scroll view's complete layout as of the last paint of View. +// Read it after View, in the same paint, beside the other controls that read +// their result there. +type Geometry struct { + // Bounds is the scroll area's rectangle; the toolbar, when shown, is above it. + Bounds gfx.Rect + // Viewport is the visible part of Bounds, less its padding. + Viewport gfx.Rect + // Content is the caller's content translated by Offset. + Content gfx.Rect + // Offset and MaxOffset are the settled offset and the greatest offset. + Offset, MaxOffset float32 + // ContentExtent and ViewportExtent are the content's and the viewport's + // heights before translation. + ContentExtent, ViewportExtent float32 + // CanEarlier and CanLater report whether the jump control for that end does + // anything at this offset. + CanEarlier, CanLater bool +} + +// Scroller is one message stream's page control. Fill the fields from the +// model every paint; callbacks stay as they are and are read when they are +// needed. +type Scroller struct { + // Offset is the caller-owned vertical offset painted this frame. The page's + // ScrollAt area is declared here, so the caller is the source of truth: + // store the offsets OnScroll and OnJump report and write them back. + Offset float32 + + // EarlierLabel and LaterLabel name the two jump controls; an empty label + // omits that control, and both empty omit the toolbar. + EarlierLabel, LaterLabel string + // EarlierID and LaterID name the jump controls for input. A zero ID keeps + // the page's derived identity. + EarlierID, LaterID gfx.ID + // ScrollbarID names the scrollbar for input; zero keeps the derived name. + ScrollbarID gfx.ID + // ScrollbarLabel and ScrollbarValue name the scrollbar for assistive + // technology and give its value, as the component's thin scrollbar does. + ScrollbarLabel, ScrollbarValue string + + // Content declares the caller-owned rows inside the scroll area. The area + // lays them out as a column. + Content func(ui.C) + + // OnScroll receives the clamped offset after the reader scrolls: a wheel + // given to Wheel, a key given to Key, or a drag of the area's scrollbar. + OnScroll func(offset float32) + // OnJump receives an earlier/later button's target offset. Without it the + // view writes Offset itself. + OnJump func(direction Direction, offset float32) + + area ui.Box + state *ui.ScrollState + stateID gfx.ID + requested float32 + settled bool +} + +// View declares the scrolling message stream at c. label names the control for +// assistive technology. Give it a height: the area takes the room the toolbar +// leaves and clips what does not fit. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, scroller *Scroller) ui.Box { + if scroller == nil { + panic("messagescrollerview: View needs its Scroller") + } + offset := scroller.Offset + if scroller.state != nil && scroller.state.ID == scroller.stateID && + scroller.settled && scroller.state.Offset != scroller.requested { + // The reader moved the area since the last declaration, by dragging its + // scrollbar or by a command that did not go through Wheel. Adopt the + // settled offset so it does not snap back, and report it. + offset = scroller.state.Offset + scroller.reportOffset(offset) + } + + metrics := c.Theme().Metrics + column := ui.Column(c).Gap(metrics.GapItem) + if label != "" { + column = column.HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + } + column.Children(func() { + if scroller.EarlierLabel != "" || scroller.LaterLabel != "" { + scroller.toolbar(c) + } + area := ui.ScrollAt(c, offset).Grow(1) + if scroller.ScrollbarLabel != "" || scroller.ScrollbarValue != "" { + area = area.ScrollbarLabels(scroller.ScrollbarLabel, ""). + ScrollbarValues(scroller.ScrollbarValue, "") + } + if !scroller.ScrollbarID.IsZero() { + area = area.ScrollbarIDs(scroller.ScrollbarID, gfx.ID{}) + } + area = area.AlwaysScrollbars() + area.Children(func() { + if scroller.Content != nil { + scroller.Content(c) + } + }) + scroller.area = area + scroller.state = area.ScrollState() + scroller.stateID = scroller.state.ID + scroller.requested = offset + scroller.settled = true + }) + return column +} + +// Geometry is the layout of the stream painted last. It is valid after View in +// the same paint, beside the other controls that read their result there. +func (s *Scroller) Geometry() Geometry { + state := s.state + if state == nil || state.ID != s.stateID || !s.area.Valid() { + return Geometry{} + } + bounds := s.area.Rect() + return Geometry{ + Bounds: bounds, + Viewport: gfx.Rect{X: bounds.X, Y: bounds.Y, Width: bounds.Width, Height: state.Viewport}, + Content: gfx.Rect{X: bounds.X, Y: bounds.Y - state.Offset, Width: bounds.Width, Height: state.Content}, + Offset: state.Offset, + MaxOffset: state.Max(), + ContentExtent: state.Content, + ViewportExtent: state.Viewport, + CanEarlier: s.canEarlier(), + CanLater: s.canLater(), + } +} + +// SettledOffset is the settled offset of the last paint, after clamping. +func (s *Scroller) SettledOffset() float32 { + if s.state == nil || s.state.ID != s.stateID { + return s.Offset + } + return s.state.Offset +} + +// ContentHeight is the content height the area measured at the last paint. +func (s *Scroller) ContentHeight() float32 { + if s.state == nil || s.state.ID != s.stateID { + return 0 + } + return s.state.Content +} + +// ViewportHeight is the visible height the area measured at the last paint. +func (s *Scroller) ViewportHeight() float32 { + if s.state == nil || s.state.ID != s.stateID { + return 0 + } + return s.state.Viewport +} + +// CanEarlier reports whether the earlier jump control does anything at the +// offset painted last. +func (s *Scroller) CanEarlier() bool { return s.canEarlier() } + +// CanLater reports whether the later jump control does anything at the offset +// painted last. +func (s *Scroller) CanLater() bool { return s.canLater() } + +// Contains reports whether a point is inside the scroll area painted last, for +// a page that gives the wheel to the stream only when it is over it. +func (s *Scroller) Contains(x, y float32) bool { + if !s.area.Valid() { + return false + } + bounds := s.area.Rect() + return x >= bounds.X && x < bounds.X+bounds.Width && + y >= bounds.Y && y < bounds.Y+bounds.Height +} + +// Wheel applies a wheel event to the stream: positive reveals content below, +// a mouse notch moves at least a line and a trackpad exactly what it reports. +// Give it to the page's Config.OnScroll; the area is declared with ScrollAt, so +// the page itself leaves the wheel to the application. The settled offset is +// reported to OnScroll, or written to Offset when OnScroll is nil. +func (s *Scroller) Wheel(event gfx.ScrollEvent) gfx.EventResult { + return s.apply(s.state, func(state *ui.ScrollState) gfx.EventResult { + return state.Wheel(event) + }) +} + +// Key applies the keyboard's scrolling to the stream, given to a page that +// gives the stream the focus. A step of zero or less is one line, 32 pixels; +// PageUp and PageDown move by a viewport, Home and End to the ends. +func (s *Scroller) Key(event gfx.KeyEvent, step float32) gfx.EventResult { + return s.apply(s.state, func(state *ui.ScrollState) gfx.EventResult { + return state.Key(event, step) + }) +} + +// apply runs one ScrollState input call and reports the offset it settled on. +func (s *Scroller) apply(state *ui.ScrollState, input func(*ui.ScrollState) gfx.EventResult) gfx.EventResult { + if state == nil || state.ID != s.stateID { + return gfx.EventResult{} + } + result := input(state) + if result.Handled { + s.requested = state.Offset + s.reportOffset(state.Offset) + } + return result +} + +// toolbar declares the two jump controls. They are present but inert at the +// ends they cannot leave, so the stream does not change height as it scrolls. +func (s *Scroller) toolbar(c ui.C) { + row := ui.Row(c).Gap(c.Theme().Metrics.GapItem) + row.Children(func() { + if s.EarlierLabel != "" { + button := ui.Button(c, s.EarlierLabel).Small() + if !s.EarlierID.IsZero() { + button = button.Hit(s.EarlierID, s.EarlierLabel) + } + if !s.canEarlier() { + button = button.Disabled(true) + } + if button.Clicked() { + s.jump(Earlier) + } + } + if s.LaterLabel != "" { + button := ui.Button(c, s.LaterLabel).Small() + if !s.LaterID.IsZero() { + button = button.Hit(s.LaterID, s.LaterLabel) + } + if !s.canLater() { + button = button.Disabled(true) + } + if button.Clicked() { + s.jump(Later) + } + } + }) +} + +// jump reports the offset a jump control goes to: the start or the end of the +// content as of the last paint. +func (s *Scroller) jump(direction Direction) { + target := float32(0) + if direction == Later && s.state != nil && s.state.ID == s.stateID { + target = s.state.Max() + } + if s.OnJump != nil { + s.OnJump(direction, target) + return + } + s.Offset = target +} + +// reportOffset hands the reader's offset to the model, or keeps it in Offset +// when the caller did not ask to observe it. +func (s *Scroller) reportOffset(offset float32) { + if s.OnScroll != nil { + s.OnScroll(offset) + return + } + s.Offset = offset +} + +func (s *Scroller) canEarlier() bool { + state := s.state + return state != nil && state.ID == s.stateID && + state.Offset > components.MessageScrollerEdgeThreshold +} + +func (s *Scroller) canLater() bool { + state := s.state + return state != nil && state.ID == s.stateID && + state.Offset < state.Max()-components.MessageScrollerEdgeThreshold +} diff --git a/ui/messagescrollerview/messagescrollerview_test.go b/ui/messagescrollerview/messagescrollerview_test.go new file mode 100644 index 00000000..7e396a04 --- /dev/null +++ b/ui/messagescrollerview/messagescrollerview_test.go @@ -0,0 +1,217 @@ +package messagescrollerview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/messagescrollerview" +) + +var ( + testEarlier = gfx.Item(71) + testLater = gfx.Item(72) + testScrollbar = gfx.Item(73) + + testLabels = [...]string{ + "Project started", "Build complete", "Review requested", + "Changes approved", "Release ready", + } +) + +type model struct { + view messagescrollerview.Scroller + page *ui.Page + canvas *gfx.Canvas + geom messagescrollerview.Geometry + offsets []float32 + jumps []messagescrollerview.Direction + targets []float32 +} + +func (m *model) content(c ui.C) { + for _, label := range testLabels { + ui.Row(c).Height(62).Children(func() { + ui.Text(c, label) + }) + } +} + +func (m *model) wire() { + m.view = messagescrollerview.Scroller{ + EarlierLabel: "Earlier messages", + LaterLabel: "Later messages", + EarlierID: testEarlier, + LaterID: testLater, + ScrollbarID: testScrollbar, + ScrollbarLabel: "Message position", + ScrollbarValue: "Conversation", + Content: m.content, + } + m.view.OnScroll = func(offset float32) { + m.offsets = append(m.offsets, offset) + m.view.Offset = offset + } + m.view.OnJump = func(direction messagescrollerview.Direction, offset float32) { + m.jumps = append(m.jumps, direction) + m.targets = append(m.targets, offset) + m.view.Offset = offset + } +} + +func (m *model) viewPage(c ui.C) { + messagescrollerview.View(c, "Message stream", &m.view).FillWidth().Height(200) +} + +func (m *model) draw() { + m.canvas.Reset() + m.canvas.BeginFrame() + m.page.Draw(m.canvas, gfx.Rect{Width: 400, Height: 300}, m.viewPage) + m.canvas.EndFrame() + m.geom = m.view.Geometry() +} + +func (m *model) fresh(t testing.TB) *model { + t.Helper() + m.wire() + theme := gfx.LightTheme() + m.page = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: &theme}) + m.canvas = new(gfx.Canvas) + m.draw() + m.draw() // the first paint measures the content and enables the controls + return m +} + +func hitLabelled(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + if hits[i].Label == label && !hits[i].ID.IsZero() { + return hits[i], true + } + } + return gfx.Hit{}, false +} + +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + got, ok := hitLabelled(canvas, label) + if !ok { + t.Fatalf("no hit labelled %q was painted", label) + } + return got +} + +// The view declares the page's own scroll area and the caller's identities: +// the stream region, both jump controls and the named scrollbar. The content +// extent and viewport come from the page's layout. +func TestViewDeclaresControlledStream(t *testing.T) { + m := new(model).fresh(t) + + stream := hit(t, m.canvas, "Message stream") + if stream.Role != gfx.RoleGroup { + t.Fatalf("stream role = %v, want group", stream.Role) + } + earlier := hit(t, m.canvas, "Earlier messages") + later := hit(t, m.canvas, "Later messages") + if earlier.ID != testEarlier || later.ID != testLater { + t.Fatalf("jump hits = %v %v, want %v %v", earlier.ID, later.ID, testEarlier, testLater) + } + if !earlier.Disabled || later.Disabled { + t.Fatalf("jump hits = %+v %+v, want earlier disabled and later enabled", earlier, later) + } + bar := hit(t, m.canvas, "Message position") + if bar.ID != testScrollbar || bar.Role != gfx.RoleSeparator || bar.Value != "Conversation" { + t.Fatalf("scrollbar = %+v, want the caller's named bar with its value", bar) + } + + if m.geom.ContentExtent != 310 || m.geom.ViewportExtent <= 0 { + t.Fatalf("geometry = %+v, want 310 content in a bounded viewport", m.geom) + } + if m.geom.Offset != 0 || m.geom.MaxOffset != 310-m.geom.ViewportExtent { + t.Fatalf("geometry offset = %g/%g, want 0 of %g", m.geom.Offset, m.geom.MaxOffset, 310-m.geom.ViewportExtent) + } + if m.geom.CanEarlier || !m.geom.CanLater { + t.Fatalf("geometry directions = %v/%v, want only later", m.geom.CanEarlier, m.geom.CanLater) + } + center := gfx.Point{X: m.geom.Viewport.X + m.geom.Viewport.Width/2, Y: m.geom.Viewport.Y + m.geom.Viewport.Height/2} + if !m.view.Contains(center.X, center.Y) || m.view.Contains(-1, -1) { + t.Fatalf("Contains = %v/%v, want the viewport but not the page corner", + m.view.Contains(center.X, center.Y), m.view.Contains(-1, -1)) + } + if m.view.SettledOffset() != 0 || m.view.ContentHeight() != 310 || m.view.ViewportHeight() != m.geom.ViewportExtent { + t.Fatalf("settled = %g content %g viewport %g, want 0/310/%g", + m.view.SettledOffset(), m.view.ContentHeight(), m.view.ViewportHeight(), m.geom.ViewportExtent) + } + for _, label := range testLabels { + if _, ok := m.viewText(label); !ok { + t.Fatalf("the content row %q was not painted", label) + } + } +} + +func (m *model) viewText(value string) (gfx.Text, bool) { + for _, text := range m.canvas.Texts() { + if text.Value == value { + return text, true + } + } + return gfx.Text{}, false +} + +// The wheel reports the clamped offset the caller stores; the next paint shows +// it and the earlier control becomes available. +func TestWheelReportsOffset(t *testing.T) { + m := new(model).fresh(t) + + result := m.view.Wheel(gfx.ScrollEvent{DeltaY: 40, Precise: true}) + if !result.Handled || len(m.offsets) != 1 || m.offsets[0] != 40 { + t.Fatalf("wheel = %+v, offsets %v; want a handled 40", result, m.offsets) + } + m.draw() + if m.geom.Offset != 40 || !m.geom.CanEarlier || !m.geom.CanLater { + t.Fatalf("geometry after wheel = %+v, want offset 40 between the ends", m.geom) + } +} + +// A click on a jump control reports the target offset and direction, and an +// ordinary paint reports nothing. +func TestJumpReportsTarget(t *testing.T) { + m := new(model).fresh(t) + target := m.geom.MaxOffset + + m.canvas.BeginEventPass(testLater, gfx.ClickInfo{}) + m.canvas.Reset() + m.canvas.BeginFrame() + m.page.Draw(m.canvas, gfx.Rect{Width: 400, Height: 300}, m.viewPage) + m.canvas.EndFrame() + m.canvas.EndEventPass() + if len(m.jumps) != 1 || m.jumps[0] != messagescrollerview.Later || + len(m.targets) != 1 || m.targets[0] != target { + t.Fatalf("jump = %v targets %v, want one later target %g", m.jumps, m.targets, target) + } + + m.draw() + if len(m.jumps) != 1 { + t.Fatalf("an ordinary paint reported another jump: %v", m.jumps) + } + if m.geom.Offset != target || !m.geom.CanEarlier || m.geom.CanLater { + t.Fatalf("geometry after jump = %+v, want the end", m.geom) + } +} + +// A warm repaint declares the same stream and allocates nothing. +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model).fresh(t) + if allocations := testing.AllocsPerRun(100, m.draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := new(model).fresh(b) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + m.draw() + } +} diff --git a/ui/messageview/messageview.go b/ui/messageview/messageview.go new file mode 100644 index 00000000..3db84493 --- /dev/null +++ b/ui/messageview/messageview.go @@ -0,0 +1,255 @@ +// Package messageview is the opt-in page control for a conversation message +// row or a group of consecutive rows. It composes the page's own primitives, +// including ui.Bubble for the body, so a page declares a message without +// rebuilding its avatar, metadata and alignment: +// +// messageview.View(c, "Ari", messageview.New(). +// Name("Ari · Design").Time("09:42").Avatar("AR"). +// Body("Native preview ready.")) +// +// The caller supplies the visible data and, through Content, any body richer +// than one bubble; the page layer owns the conversation order. End mirrors the +// row: the avatar moves to the end and the bubble, metadata and actions align +// with it. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public components, gfx and ui +// packages. A Message is a value built with chained options; keep no state in +// it, build it from the model in each paint, and View allocates nothing on a +// warm paint. +package messageview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Message is one row's presentation. Its zero value is a start-aligned message +// with no avatar, metadata or body; New is its readable starting point. Every +// option returns the value, so a call site chains only what it shows: +// +// messageview.New().End().Name("You").Time("Delivered").Avatar("YO"). +// Surface(ui.BubblePrimary).Body("Ship the compact variant.") +type Message struct { + name string + time string + initials string + body string + image gfx.Bitmap + surface ui.BubbleVariant + + end bool + avatar bool + reserve bool + content func(ui.C) + actions func(ui.C) +} + +// New returns an empty start-aligned message whose body is a secondary bubble. +func New() Message { + return Message{surface: ui.BubbleSecondary} +} + +// Start aligns the row to the start of the conversation. It is the zero value's +// alignment and undoes End. +func (m Message) Start() Message { + m.end = false + return m +} + +// End aligns the row to the end: the avatar is on the end side and the bubble, +// metadata and actions hug that edge. +func (m Message) End() Message { + m.end = true + return m +} + +// Name is the sender name in the metadata row above the body. +func (m Message) Name(name string) Message { + m.name = name + return m +} + +// Time is the timestamp in the metadata row above the body. +func (m Message) Time(value string) Message { + m.time = value + return m +} + +// Avatar shows a round avatar with the initials, or a muted fallback circle +// when the initials are empty, at the start or end of the row. +func (m Message) Avatar(initials string) Message { + m.initials = initials + m.avatar = true + return m +} + +// AvatarImage shows the bitmap as the avatar instead of initials. The caller +// owns the image and keeps it in its model. +func (m Message) AvatarImage(bitmap gfx.Bitmap) Message { + m.image = bitmap + m.avatar = true + return m +} + +// ReserveAvatar keeps the avatar column without painting an avatar, as an empty +// avatar does: consecutive rows of one sender line up with the row that shows +// it. Avatar takes precedence. +func (m Message) ReserveAvatar() Message { + m.reserve = true + return m +} + +// Body is the text of the bubble. +func (m Message) Body(text string) Message { + m.body = text + return m +} + +// Surface selects the bubble's variant. New starts with BubbleSecondary; +// BubbleGhost draws no surface and no inset. +func (m Message) Surface(variant ui.BubbleVariant) Message { + m.surface = variant + return m +} + +// Content paints the body instead of Body's bubble, for a row whose body is not +// one text: an image, a stack of attachment cards or a rich preview. The +// callback is declared in the content column, so its own alignment is the +// caller's. Body is ignored when Content is set. +func (m Message) Content(content func(ui.C)) Message { + m.content = content + return m +} + +// Actions paints the row's actions below the body, aligned with the message. +// The callback declares the controls, so their identities and handlers are the +// caller's own. +func (m Message) Actions(actions func(ui.C)) Message { + m.actions = actions + return m +} + +// View declares the message row at c. label names the row for assistive +// technology. Give it a width; the row is as tall as its avatar, metadata, body +// and actions. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, message Message) ui.Box { + metrics := c.Theme().Metrics + hasAvatar := message.avatar || message.reserve + row := ui.Row(c).Gap(metrics.GapItem).Items(ui.Start) + if label != "" { + row = row.HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + } + row.Children(func() { + if hasAvatar && !message.end { + avatar(c, message, metrics.ControlHeight) + } + ui.Column(c).Gap(components.MessageSlotGap(metrics)).Grow(1).Children(func() { + if message.name != "" || message.time != "" { + metadata(c, message) + } + body(c, message) + if message.actions != nil { + actions(c, message) + } + }) + if hasAvatar && message.end { + avatar(c, message, metrics.ControlHeight) + } + }) + return row +} + +// Group declares consecutive message rows with the message group gap between +// them, so consecutive rows of one sender read as one turn. label names the +// group for assistive technology; give each Message its own Name, Time and +// avatar or ReserveAvatar. +// +// messageview.Group(c, "Ari", first.ReserveAvatar(), last.Avatar("AR")) +func Group(c ui.C, label string, messages ...Message) ui.Box { + column := ui.Column(c).Gap(components.MessageGroupGap(c.Theme().Metrics)) + if label != "" { + column = column.HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + } + column.Children(func() { + for _, message := range messages { + View(c, "", message) + } + }) + return column +} + +// metadata paints the sender name and timestamp above the body. The name takes +// the free room so the time sits at the far edge, as a chat header does. +func metadata(c ui.C, message Message) { + look := c.Theme() + row := ui.Row(c).Gap(look.Metrics.GapItem).Items(ui.Center) + if message.end { + row = row.Justify(ui.End) + } + row.Children(func() { + if message.name != "" { + name := ui.Text(c, message.name).FontSize(look.Metrics.FontSizeS).Bold() + if message.time != "" { + name.Grow(1) + } + } + if message.time != "" { + ui.Text(c, message.time).FontSize(look.Metrics.FontSizeS).Muted() + } + }) +} + +// body paints the caller's content or one bubble. +func body(c ui.C, message Message) { + if message.content != nil { + message.content(c) + return + } + if message.body == "" { + return + } + bubble := ui.Bubble(c, message.body, message.surface) + if message.end { + bubble.Self(ui.End) + } else { + bubble.Self(ui.Start) + } +} + +// actions paints the caller's action row on the message's side. +func actions(c ui.C, message Message) { + row := ui.Row(c).Gap(c.Theme().Metrics.GapItem).Items(ui.Center) + if message.end { + row = row.Justify(ui.End) + } + row.Children(func() { + message.actions(c) + }) +} + +// avatar paints the initials or image circle, or reserves the column. +func avatar(c ui.C, message Message, side float32) { + if message.reserve && !message.avatar { + ui.Spacer(c).Size(side, side).Shrink(0) + return + } + look := c.Theme() + stack := ui.Stack(c).Size(side, side).Shrink(0) + stack.Children(func() { + if message.image.Width > 0 && message.image.Height > 0 { + ui.Image(c, message.image).Fill().Radius(side / 2) + return + } + face := ui.Column(c).Fill().Radius(side / 2).Background(look.Muted).Center() + face.Children(func() { + if message.initials != "" { + ui.Text(c, message.initials).FontSize(look.Metrics.FontSizeS). + Weight(gfx.WeightSemibold).Muted() + } + }) + }) +} diff --git a/ui/messageview/messageview_test.go b/ui/messageview/messageview_test.go new file mode 100644 index 00000000..f355c197 --- /dev/null +++ b/ui/messageview/messageview_test.go @@ -0,0 +1,194 @@ +package messageview_test + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/messageview" +) + +type model struct { + view messageview.Message + page *ui.Page + canvas *gfx.Canvas + body int + action int +} + +func (m *model) viewPage(c ui.C) { + messageview.View(c, "Incoming message", m.view).FillWidth() +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 400, Height: 300}, view) + canvas.EndFrame() +} + +func open(t testing.TB, m *model) { + t.Helper() + theme := gfx.LightTheme() + m.page = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: &theme}) + m.canvas = new(gfx.Canvas) + draw(m.page, m.canvas, m.viewPage) +} + +func hitLabelled(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + if hits[i].Label == label && !hits[i].ID.IsZero() { + return hits[i], true + } + } + return gfx.Hit{}, false +} + +// textNamed returns the painted text with the value. +func textNamed(canvas *gfx.Canvas, value string) (gfx.Text, bool) { + for _, text := range canvas.Texts() { + if text.Value == value { + return text, true + } + } + return gfx.Text{}, false +} + +func requireText(t *testing.T, canvas *gfx.Canvas, value string) gfx.Text { + t.Helper() + text, ok := textNamed(canvas, value) + if !ok { + var painted []string + for _, text := range canvas.Texts() { + painted = append(painted, text.Value) + } + t.Fatalf("%q was not painted; painted %q", value, strings.Join(painted, " | ")) + } + return text +} + +// The page declares one row; the view paints the avatar, name, time and body and +// names the row for assistive technology. +func TestViewPaintsVisibleData(t *testing.T) { + m := &model{view: messageview.New(). + Name("Ari · Design").Time("09:42").Avatar("AR"). + Body("Native preview ready.")} + open(t, m) + + row, ok := hitLabelled(m.canvas, "Incoming message") + if !ok { + t.Fatal("the message row painted no labelled region") + } + if row.Role != gfx.RoleGroup { + t.Fatalf("row role = %v, want group", row.Role) + } + initials := requireText(t, m.canvas, "AR") + name := requireText(t, m.canvas, "Ari · Design") + time := requireText(t, m.canvas, "09:42") + body := requireText(t, m.canvas, "Native preview ready.") + if initials.Bounds.X >= body.Bounds.X { + t.Fatalf("start avatar x = %g, body x = %g; want the avatar first", initials.Bounds.X, body.Bounds.X) + } + if name.Bounds.Y >= body.Bounds.Y || time.Bounds.Y >= body.Bounds.Y { + t.Fatalf("metadata y = %g/%g, body y = %g; want metadata above", name.Bounds.Y, time.Bounds.Y, body.Bounds.Y) + } + if name.Bounds.X >= time.Bounds.X { + t.Fatalf("name x = %g, time x = %g; want the name first", name.Bounds.X, time.Bounds.X) + } +} + +// End mirrors the row: the avatar moves to the end and the bubble hugs the end +// edge. +func TestEndMirrorsTheRow(t *testing.T) { + start := &model{view: messageview.New().Avatar("AR").Body("Native preview ready.")} + open(t, start) + startInitials := requireText(t, start.canvas, "AR") + startBody := requireText(t, start.canvas, "Native preview ready.") + if startInitials.Bounds.X >= startBody.Bounds.X { + t.Fatalf("start avatar x = %g, body x = %g; want the avatar first", startInitials.Bounds.X, startBody.Bounds.X) + } + + end := &model{view: messageview.New().End().Avatar("YO").Body("Ship the compact variant.")} + open(t, end) + endInitials := requireText(t, end.canvas, "YO") + endBody := requireText(t, end.canvas, "Ship the compact variant.") + if endInitials.Bounds.X <= endBody.Bounds.X { + t.Fatalf("end avatar x = %g, body x = %g; want the avatar last", endInitials.Bounds.X, endBody.Bounds.X) + } + if endBody.Bounds.X <= startBody.Bounds.X { + t.Fatalf("end body x = %g, start body x = %g; want the end body farther along", endBody.Bounds.X, startBody.Bounds.X) + } +} + +// Content replaces the bubble body and Actions add a row below it. +func TestContentAndActions(t *testing.T) { + m := &model{} + m.view = messageview.New().Avatar("AR").Body("this text is replaced"). + Content(func(c ui.C) { + m.body++ + ui.Text(c, "Rich body") + }). + Actions(func(c ui.C) { + m.action++ + ui.Text(c, "Reply") + }) + open(t, m) + + requireText(t, m.canvas, "Rich body") + requireText(t, m.canvas, "Reply") + if _, ok := textNamed(m.canvas, "this text is replaced"); ok { + t.Fatal("Content did not replace Body") + } + if m.body != 1 || m.action != 1 { + t.Fatalf("callbacks ran %d/%d times, want once each", m.body, m.action) + } +} + +// A reserved avatar keeps the column without painting initials, and Group +// paints every row it is given. +func TestReservedAvatarAndGroup(t *testing.T) { + theme := gfx.LightTheme() + var canvas gfx.Canvas + view := func(c ui.C) { + messageview.Group(c, "Ari", + messageview.New().ReserveAvatar().Body("First line."), + messageview.New().Avatar("AR").Body("Second line."), + ).FillWidth() + } + page := ui.NewPage(ui.PageConfig{Theme: &theme, View: view}) + draw(page, &canvas, view) + + requireText(t, &canvas, "First line.") + requireText(t, &canvas, "Second line.") + if _, ok := textNamed(&canvas, "AR"); !ok { + t.Fatal("the grouped row with an avatar did not paint its initials") + } + if _, ok := hitLabelled(&canvas, "Ari"); !ok { + t.Fatal("the group painted no labelled region") + } +} + +// A warm repaint declares the same values and allocates nothing. +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := &model{view: messageview.New(). + Name("Ari · Design").Time("09:42").Avatar("AR"). + Body("Native preview ready.")} + open(t, m) + if allocations := testing.AllocsPerRun(100, func() { draw(m.page, m.canvas, m.viewPage) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := &model{view: messageview.New(). + Name("Ari · Design").Time("09:42").Avatar("AR"). + Body("Native preview ready.")} + open(b, m) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + draw(m.page, m.canvas, m.viewPage) + } +} diff --git a/multiselect/multiselect.go b/ui/multiselect/multiselect.go similarity index 100% rename from multiselect/multiselect.go rename to ui/multiselect/multiselect.go diff --git a/multiselect/multiselect_test.go b/ui/multiselect/multiselect_test.go similarity index 99% rename from multiselect/multiselect_test.go rename to ui/multiselect/multiselect_test.go index a36ebf01..57db2a4c 100644 --- a/multiselect/multiselect_test.go +++ b/ui/multiselect/multiselect_test.go @@ -6,8 +6,8 @@ import ( "github.com/vivaui/viva/app" "github.com/vivaui/viva/base" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/multiselect" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/multiselect" "github.com/vivaui/viva/window" ) diff --git a/ui/navigationmenuview/navigationmenuview.go b/ui/navigationmenuview/navigationmenuview.go new file mode 100644 index 00000000..07b33796 --- /dev/null +++ b/ui/navigationmenuview/navigationmenuview.go @@ -0,0 +1,815 @@ +// Package navigationmenuview is the opt-in page control for the top-level +// navigation menu of package components. It wraps +// components.BeginNavigationMenu in a ui.Control, so a page declares the +// triggers, their direct links and a panel of described destinations without +// calling the component itself: +// +// m.navigation.Reset() +// m.navigation.Trigger(productsID, "Products").Hint("Open product navigation") +// m.navigation.Link(docsID, "Docs").Value("/docs").Active(m.page == "docs") +// m.navigation.ContentLink(guideID, "Getting started"). +// Description("Build a native window and retained scene."). +// Value("/guide").Active(m.page == "guide") +// m.navigation.View(c, "Navigation menu").FillWidth().Height(36) +// // After the paint, Selected names the link chosen last. +// if m.navigation.Selected == docsID { +// m.page = "docs" +// m.navigation.Selected = gfx.ID{} +// } +// +// The caller owns the open trigger, the focused entry or link, the chosen link +// and every label, description and identity. The wrapper paints through the +// component with exactly the identities the caller supplied, changes Open when +// a trigger is clicked, and reports the clicked or chosen identity with Clicked +// and Selected. Pointer and key events aimed at the control itself reach the +// optional callbacks. +// +// DirectContent declares a menu whose panel has no indicator of its own; it is +// an option, not a second constructor. The panel is open whenever Open names a +// trigger. +// +// Declarations are rebuilt every paint: call Reset, declare the entries in +// order, then View. The slices keep their capacity, so a warm paint allocates +// nothing. Keep a NavigationMenu in the model beside its state; its handlers +// and draw function are made once. Do not copy one after View has painted it. +// +// It is a separate package so an application that does not import it pays +// nothing for it. +package navigationmenuview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Direction is components.Direction, named here so a page that declares a +// navigation menu reads through this package alone. +type Direction = components.Direction + +// NavigationMenu is one navigation menu's caller-owned state, its declarations +// and its page control. Fill Open and the callbacks from the model; declare the +// entries every paint; then call View. +type NavigationMenu struct { + // Open is the trigger whose panel is open, or zero when it is closed. A + // trigger click toggles it; choosing a link closes it unless DirectContent + // is set. + Open gfx.ID + // Focus is the trigger, link or panel link the keyboard acts on. Clicking + // an entry or link sets it; the arrow keys move it. + Focus gfx.ID + // Selected is the link chosen last by a click or by Enter, or zero before a + // link is chosen. The wrapper writes it; the caller consumes and clears it. + Selected gfx.ID + // DirectContent paints the open panel without its indicator. + DirectContent bool + // Direction selects the arrow movement. The zero value is left to right. + Direction components.Direction + // Layer is the panel's layer. Zero uses layer 1. + Layer uint16 + // Scope and DismissID are passed to the panel: DismissID is the identity an + // Escape or an outside press reports. + Scope, DismissID gfx.ID + // Viewport, with DismissID, makes a press outside the panel report DismissID + // and pass through, as a non-modal navigation menu does. + Viewport gfx.Rect + // Content optionally fixes the panel geometry. Zero Width and Height select + // the size the links need; zero X and Y place the panel under the open + // trigger. + Content gfx.Rect + + // Pointer receives every pointer event aimed at the control itself. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Key receives keys pressed while the control has the focus. The wrapper + // moves Focus and updates Open first; the callback's Handled and Repaint are + // merged. + Key func(gfx.KeyEvent) gfx.EventResult + + entries []entryDecl + links []linkDecl + + currentEntry int + currentLink int + lastTrigger int + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + + triggerModels []components.NavigationMenuTrigger + entryModel []int + + clicked gfx.ID + hadClick bool +} + +type entryKind uint8 + +const ( + entryTrigger entryKind = iota + entryLink +) + +type entryDecl struct { + Kind entryKind + Trigger components.NavigationMenuTrigger + Link components.NavigationMenuLink +} + +type linkDecl struct { + Entry int + Separator bool + Link components.NavigationMenuLink +} + +const ( + // The panel hangs this far below the bar. + panelOffset = float32(8) + // The width the component uses when the caller names none. + panelWidth = float32(420) + // A content link's row heights, as the component lays them out. + linkHeight = float32(56) + linkHeightShort = float32(36) + linkGap = float32(4) + panelPadding = float32(8) + separatorHeight = float32(9) + triggerLabelInset = float32(48) + linkLabelInset = float32(32) +) + +// Reset forgets the last paint's declarations. Call it before declaring the +// entries again; the backing slices stay, so the next paint reuses them. +func (m *NavigationMenu) Reset() { + m.entries = m.entries[:0] + m.links = m.links[:0] + m.currentEntry, m.currentLink, m.lastTrigger = -1, -1, -1 +} + +// Trigger declares one top-level disclosure. The content links declared after +// it belong to its panel until the next Trigger. +func (m *NavigationMenu) Trigger(id gfx.ID, label string) *NavigationMenu { + m.entries = append(m.entries, entryDecl{Kind: entryTrigger, Trigger: components.NavigationMenuTrigger{ID: id, Label: label}}) + m.currentEntry, m.currentLink = len(m.entries)-1, -1 + m.lastTrigger = m.currentEntry + return m +} + +// Link declares one top-level navigation link. +func (m *NavigationMenu) Link(id gfx.ID, label string) *NavigationMenu { + m.entries = append(m.entries, entryDecl{Kind: entryLink, Link: components.NavigationMenuLink{ID: id, Label: label}}) + m.currentEntry, m.currentLink = len(m.entries)-1, -1 + return m +} + +// ContentLink declares one described destination in the current trigger's +// panel. +func (m *NavigationMenu) ContentLink(id gfx.ID, label string) *NavigationMenu { + if m.lastTrigger < 0 { + return m + } + m.links = append(m.links, linkDecl{ + Entry: m.lastTrigger, + Link: components.NavigationMenuLink{ID: id, Label: label}, + }) + m.currentEntry, m.currentLink = -1, len(m.links)-1 + return m +} + +// Separator declares a divider between the current trigger's content links. +func (m *NavigationMenu) Separator() *NavigationMenu { + if m.lastTrigger < 0 { + return m + } + m.links = append(m.links, linkDecl{Entry: m.lastTrigger, Separator: true}) + m.currentLink = -1 + return m +} + +// Width fixes the current trigger or link width. Zero lets the component +// measure it. +func (m *NavigationMenu) Width(width float32) *NavigationMenu { + if m.currentLink >= 0 && m.currentLink < len(m.links) { + m.links[m.currentLink].Link.Width = width + return m + } + if m.currentEntry < 0 || m.currentEntry >= len(m.entries) { + return m + } + entry := &m.entries[m.currentEntry] + if entry.Kind == entryTrigger { + entry.Trigger.Width = width + } else { + entry.Link.Width = width + } + return m +} + +// Hint sets the current entry's accessible hint. +func (m *NavigationMenu) Hint(hint string) *NavigationMenu { + if m.currentLink >= 0 && m.currentLink < len(m.links) { + m.links[m.currentLink].Link.Hint = hint + return m + } + if m.currentEntry < 0 || m.currentEntry >= len(m.entries) { + return m + } + entry := &m.entries[m.currentEntry] + if entry.Kind == entryTrigger { + entry.Trigger.Hint = hint + } else { + entry.Link.Hint = hint + } + return m +} + +// Disabled disables the current entry or content link. +func (m *NavigationMenu) Disabled() *NavigationMenu { + if m.currentLink >= 0 && m.currentLink < len(m.links) { + m.links[m.currentLink].Link.Disabled = true + return m + } + if m.currentEntry < 0 || m.currentEntry >= len(m.entries) { + return m + } + entry := &m.entries[m.currentEntry] + if entry.Kind == entryTrigger { + entry.Trigger.Disabled = true + } else { + entry.Link.Disabled = true + } + return m +} + +// Value sets the current link's navigation value. +func (m *NavigationMenu) Value(value string) *NavigationMenu { + if m.currentLink >= 0 && m.currentLink < len(m.links) { + m.links[m.currentLink].Link.Value = value + return m + } + if m.currentEntry >= 0 && m.currentEntry < len(m.entries) && m.entries[m.currentEntry].Kind == entryLink { + m.entries[m.currentEntry].Link.Value = value + } + return m +} + +// Description sets the current content link's second line. +func (m *NavigationMenu) Description(description string) *NavigationMenu { + if m.currentLink >= 0 && m.currentLink < len(m.links) { + m.links[m.currentLink].Link.Description = description + } + return m +} + +// Active marks the current trigger or link as the active destination. +func (m *NavigationMenu) Active(active bool) *NavigationMenu { + if m.currentLink >= 0 && m.currentLink < len(m.links) { + m.links[m.currentLink].Link.Active = active + return m + } + if m.currentEntry < 0 || m.currentEntry >= len(m.entries) { + return m + } + entry := &m.entries[m.currentEntry] + if entry.Kind == entryTrigger { + entry.Trigger.Active = active + } else { + entry.Link.Active = active + } + return m +} + +// View declares the navigation menu at c. label names the control for +// assistive technology. Give it the bar's size; the panel is painted above it. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, menu *NavigationMenu) ui.Box { + if menu == nil { + panic("navigationmenuview: View needs its NavigationMenu") + } + menu.prepare() + return ui.Control(c, label, &menu.handlers).Draw(menu.drawFn) +} + +// View declares the navigation menu at c, for a page that keeps the +// NavigationMenu in its model. +func (m *NavigationMenu) View(c ui.C, label string) ui.Box { return View(c, label, m) } + +// Clicked reports whether the paint just made was an event pass delivering a +// click on id, one of the caller's trigger or link identities. It is false in +// ordinary paints. Ask it after the paint. +func (m *NavigationMenu) Clicked(id gfx.ID) bool { + return m.hadClick && !id.IsZero() && m.clicked == id +} + +func (m *NavigationMenu) prepare() { + if m.prepared { + return + } + m.prepared = true + m.handlers.Pointer = m.pointer + m.handlers.Key = m.key + m.drawFn = m.draw +} + +func (m *NavigationMenu) direction() components.Direction { + if m.Direction == components.RTL { + return components.RTL + } + return components.LTR +} + +func (m *NavigationMenu) layer() uint16 { + if m.Layer == 0 { + return 1 + } + return m.Layer +} + +func (m *NavigationMenu) draw(d *ui.DrawContext) { + raw, had := d.Canvas.ClickTarget() + theme := *d.Theme + canvas := d.Canvas + + m.assignTriggerModels() + open := m.triggerEntry(m.Open) + + options := components.NavigationMenuOptions{ + Open: open >= 0, + DirectContent: m.DirectContent, + Content: m.contentBounds(canvas, theme, d.Rect, open), + Layer: m.layer(), + Scope: m.Scope, DismissID: m.DismissID, Viewport: m.Viewport, + } + menu := components.BeginNavigationMenu(canvas, theme, d.Rect, options) + for index := range m.entries { + entry := &m.entries[index] + if entry.Kind == entryTrigger { + trigger := entry.Trigger + trigger.Open = m.Open == trigger.ID + menu.AddTrigger(trigger) + continue + } + menu.AddLink(entry.Link) + } + if open >= 0 { + content := menu.BeginContent() + for index := range m.links { + link := &m.links[index] + if link.Entry != open { + continue + } + if link.Separator { + content.AddSeparator() + continue + } + content.AddLink(link.Link) + } + } + + m.clicked, m.hadClick = raw, had + if had { + m.choose() + } +} + +func (m *NavigationMenu) assignTriggerModels() { + m.triggerModels = m.triggerModels[:0] + if cap(m.entryModel) < len(m.entries) { + m.entryModel = make([]int, len(m.entries)) + } else { + m.entryModel = m.entryModel[:len(m.entries)] + } + for index := range m.entryModel { + m.entryModel[index] = -1 + } + for index := range m.entries { + entry := &m.entries[index] + if entry.Kind != entryTrigger { + continue + } + m.entryModel[index] = len(m.triggerModels) + m.triggerModels = append(m.triggerModels, entry.Trigger) + } +} + +func (m *NavigationMenu) contentBounds(canvas *gfx.Canvas, theme gfx.Theme, bar gfx.Rect, open int) gfx.Rect { + x, y := m.Content.X, m.Content.Y + if x == 0 && open >= 0 { + x = m.anchorX(canvas, theme, bar, open) + } + if x == 0 { + x = bar.X + } + if y == 0 { + y = bar.Y + bar.Height + panelOffset + } + width, height := m.Content.Width, m.Content.Height + if width <= 0 { + width = panelWidth + } + if height <= 0 { + height = 2 * panelPadding + if open >= 0 { + for index := range m.links { + link := &m.links[index] + if link.Entry != open { + continue + } + if link.Separator { + height += separatorHeight + continue + } + if link.Link.Description == "" { + height += linkHeightShort + linkGap + } else { + height += linkHeight + linkGap + } + } + } + } + return gfx.Rect{X: x, Y: y, Width: width, Height: height} +} + +// anchorX simulates the component's horizontal layout up to the open trigger. +// The component has no NextTriggerBounds, so the same label measurement is +// repeated here to place the panel under its trigger. +func (m *NavigationMenu) anchorX(canvas *gfx.Canvas, theme gfx.Theme, bar gfx.Rect, open int) float32 { + x := bar.X + for index := range m.entries { + entry := &m.entries[index] + width := entryWidth(canvas, theme, entry) + if width <= 0 { + continue + } + if index == open { + return x + } + if x+width > bar.X+bar.Width { + break + } + x += width + } + return bar.X +} + +func entryWidth(canvas *gfx.Canvas, theme gfx.Theme, entry *entryDecl) float32 { + if entry.Kind == entryTrigger { + if entry.Trigger.Width > 0 { + return entry.Trigger.Width + } + return canvas.TextWidthWeight(entry.Trigger.Label, theme.Metrics.FontSizeM, gfx.WeightMedium) + triggerLabelInset + } + if entry.Link.Width > 0 { + return entry.Link.Width + } + return canvas.TextWidthWeight(entry.Link.Label, theme.Metrics.FontSizeM, gfx.WeightMedium) + linkLabelInset +} + +func (m *NavigationMenu) triggerEntry(id gfx.ID) int { + if id.IsZero() { + return -1 + } + for index := range m.entries { + entry := &m.entries[index] + if entry.Kind == entryTrigger && entry.Trigger.ID == id { + return index + } + } + return -1 +} + +func (m *NavigationMenu) entryIndex(id gfx.ID) int { + if id.IsZero() { + return -1 + } + for index := range m.entries { + entry := &m.entries[index] + if entry.Kind == entryTrigger && entry.Trigger.ID == id { + return index + } + if entry.Kind == entryLink && entry.Link.ID == id { + return index + } + } + return -1 +} + +func (m *NavigationMenu) linkIndex(id gfx.ID) int { + if id.IsZero() { + return -1 + } + for index := range m.links { + if !m.links[index].Separator && m.links[index].Link.ID == id { + return index + } + } + return -1 +} + +// choose applies the click this paint is delivering. +func (m *NavigationMenu) choose() { + switch { + case m.clicked == m.DismissID && !m.DismissID.IsZero(): + m.Open = gfx.ID{} + default: + if index := m.linkIndex(m.clicked); index >= 0 { + m.Focus = m.clicked + m.Selected = m.clicked + if !m.DirectContent { + m.Open = gfx.ID{} + if entry := m.links[index].Entry; entry >= 0 && entry < len(m.entries) { + m.Focus = m.entryID(entry) + } + } + return + } + if index := m.entryIndex(m.clicked); index >= 0 { + m.Focus = m.clicked + if m.entries[index].Kind == entryLink { + m.Selected = m.clicked + if !m.DirectContent { + m.Open = gfx.ID{} + } + } else if m.Open == m.clicked { + m.Open = gfx.ID{} + } else { + m.Open = m.clicked + } + } + } +} + +func (m *NavigationMenu) pointer(event gfx.PointerEvent) gfx.EventResult { + if m.Pointer != nil { + return m.Pointer(event) + } + return gfx.EventResult{} +} + +func (m *NavigationMenu) key(event gfx.KeyEvent) gfx.EventResult { + var result gfx.EventResult + if !event.Release && event.Text == "" && event.Key != gfx.KeyUnknown && !event.Key.IsModifier() { + focus := event.Target + if m.linkIndex(focus) < 0 && m.entryIndex(focus) < 0 { + focus = m.Focus + } + if focus.IsZero() { + focus = m.Open + } + if focus.IsZero() && len(m.entries) > 0 { + focus = m.entryID(0) + } + if index := m.linkIndex(focus); index >= 0 { + entry := m.links[index].Entry + if entry >= 0 && entry < len(m.entries) && m.triggerEntry(m.Open) != entry { + focus = m.entryID(entry) + } + } + if index := m.linkIndex(focus); index >= 0 { + result = m.contentLinkKey(event, index) + } else if index := m.entryIndex(focus); index >= 0 { + if m.entries[index].Kind == entryTrigger { + result = m.triggerKey(event, index) + } else { + result = m.entryLinkKey(event, index) + } + } + } + if m.Key != nil { + callback := m.Key(event) + result.Handled = result.Handled || callback.Handled + result.Repaint = result.Repaint || callback.Repaint + result.Blur = result.Blur || callback.Blur + result.ContinueTraversal = result.ContinueTraversal || callback.ContinueTraversal + if result.Focus.IsZero() { + result.Focus, result.FocusVisible = callback.Focus, callback.FocusVisible + } + if result.Activate.IsZero() { + result.Activate = callback.Activate + } + } + return result +} + +func (m *NavigationMenu) triggerKey(event gfx.KeyEvent, entry int) gfx.EventResult { + if entry < 0 || entry >= len(m.entries) { + return gfx.EventResult{} + } + model := m.entryModel[entry] + if model < 0 || model >= len(m.triggerModels) { + return gfx.EventResult{} + } + var openPart gfx.ID + if open := m.triggerEntry(m.Open); open >= 0 { + openPart = m.entryID(open) + } + focus, nextOpen, ok := components.NavigationMenuKeyDown(m.entryID(entry), m.triggerModels, openPart, m.direction(), event.Key) + if !ok { + return gfx.EventResult{} + } + m.Open, m.Focus = nextOpen, focus + result := gfx.EventResult{Handled: true, Repaint: true, Focus: focus, FocusVisible: true} + switch event.Key { + case gfx.KeyDown, gfx.KeyEnter, gfx.KeySpace: + if opened := m.triggerEntry(m.Open); opened >= 0 { + if link, ok := m.firstContentLink(opened); ok { + m.Focus = link + result.Focus = link + } + } + } + return result +} + +func (m *NavigationMenu) entryLinkKey(event gfx.KeyEvent, entry int) gfx.EventResult { + if entry < 0 || entry >= len(m.entries) { + return gfx.EventResult{} + } + switch event.Key { + case gfx.KeyLeft, gfx.KeyRight, gfx.KeyHome, gfx.KeyEnd: + next, ok := m.moveEntry(entry, event.Key) + if !ok { + return gfx.EventResult{Handled: true} + } + m.Focus = m.entryID(next) + return gfx.EventResult{Handled: true, Repaint: true, Focus: m.Focus, FocusVisible: true} + case gfx.KeyEnter, gfx.KeySpace: + link := &m.entries[entry].Link + if link.Disabled || link.ID.IsZero() { + return gfx.EventResult{Handled: true} + } + m.Focus, m.Selected = link.ID, link.ID + return gfx.EventResult{Handled: true, Repaint: true, Activate: link.ID} + case gfx.KeyDown: + if open := m.triggerEntry(m.Open); open >= 0 { + if link, ok := m.firstContentLink(open); ok { + m.Focus = link + return gfx.EventResult{Handled: true, Repaint: true, Focus: link, FocusVisible: true} + } + } + return gfx.EventResult{} + case gfx.KeyEscape: + if open := m.triggerEntry(m.Open); open >= 0 { + m.Open = gfx.ID{} + m.Focus = m.entryID(open) + return gfx.EventResult{Handled: true, Repaint: true, Focus: m.Focus, FocusVisible: true} + } + return gfx.EventResult{} + case gfx.KeyTab: + if !m.Open.IsZero() { + m.Open = gfx.ID{} + return gfx.EventResult{Handled: true, Repaint: true, ContinueTraversal: true} + } + } + return gfx.EventResult{} +} + +func (m *NavigationMenu) contentLinkKey(event gfx.KeyEvent, link int) gfx.EventResult { + if link < 0 || link >= len(m.links) || m.links[link].Separator { + return gfx.EventResult{} + } + row := &m.links[link] + switch event.Key { + case gfx.KeyUp, gfx.KeyDown, gfx.KeyHome, gfx.KeyEnd: + next, ok := m.moveContentLink(link, event.Key) + if !ok { + return gfx.EventResult{Handled: true} + } + m.Focus = m.links[next].Link.ID + return gfx.EventResult{Handled: true, Repaint: true, Focus: m.Focus, FocusVisible: true} + case gfx.KeyEnter, gfx.KeySpace: + if row.Link.Disabled || row.Link.ID.IsZero() { + return gfx.EventResult{Handled: true} + } + m.Focus, m.Selected = row.Link.ID, row.Link.ID + return gfx.EventResult{Handled: true, Repaint: true, Activate: row.Link.ID} + case gfx.KeyEscape: + entry := row.Entry + m.Open = gfx.ID{} + if entry < 0 || entry >= len(m.entries) { + return gfx.EventResult{Handled: true, Repaint: true} + } + m.Focus = m.entryID(entry) + return gfx.EventResult{Handled: true, Repaint: true, Focus: m.Focus, FocusVisible: true} + case gfx.KeyLeft, gfx.KeyRight: + entry := row.Entry + if entry < 0 || entry >= len(m.entries) { + return gfx.EventResult{} + } + model := m.entryModel[entry] + if model < 0 || model >= len(m.triggerModels) { + return gfx.EventResult{} + } + focus, nextOpen, ok := components.NavigationMenuKeyDown(m.entryID(entry), m.triggerModels, m.entryID(entry), m.direction(), event.Key) + if !ok { + return gfx.EventResult{} + } + m.Open, m.Focus = nextOpen, focus + return gfx.EventResult{Handled: true, Repaint: true, Focus: focus, FocusVisible: true} + case gfx.KeyTab: + m.Open = gfx.ID{} + return gfx.EventResult{Handled: true, Repaint: true, ContinueTraversal: true} + } + return gfx.EventResult{} +} + +func (m *NavigationMenu) entryID(index int) gfx.ID { + if index < 0 || index >= len(m.entries) { + return gfx.ID{} + } + entry := &m.entries[index] + if entry.Kind == entryTrigger { + return entry.Trigger.ID + } + return entry.Link.ID +} + +func (m *NavigationMenu) moveEntry(from int, key gfx.Key) (int, bool) { + if key == gfx.KeyHome || key == gfx.KeyEnd { + step, index := 1, 0 + if key == gfx.KeyEnd { + step, index = -1, len(m.entries)-1 + } + for at := index; at >= 0 && at < len(m.entries); at += step { + if at != from && m.usableEntry(at) { + return at, true + } + } + return 0, false + } + step := 1 + if key == gfx.KeyLeft { + step = -1 + } + for offset := 1; offset <= len(m.entries); offset++ { + at := from + step*offset + for at < 0 { + at += len(m.entries) + } + for at >= len(m.entries) { + at -= len(m.entries) + } + if m.usableEntry(at) { + return at, true + } + } + return 0, false +} + +func (m *NavigationMenu) usableEntry(index int) bool { + if index < 0 || index >= len(m.entries) { + return false + } + entry := &m.entries[index] + if entry.Kind == entryTrigger { + return !entry.Trigger.Disabled && !entry.Trigger.ID.IsZero() + } + return !entry.Link.Disabled && !entry.Link.ID.IsZero() +} + +func (m *NavigationMenu) moveContentLink(from int, key gfx.Key) (int, bool) { + entry := m.links[from].Entry + if key == gfx.KeyHome || key == gfx.KeyEnd { + step, index := 1, 0 + if key == gfx.KeyEnd { + step, index = -1, len(m.links)-1 + } + for at := index; at >= 0 && at < len(m.links); at += step { + if at != from && m.usableContentLink(at, entry) { + return at, true + } + } + return 0, false + } + step := 1 + if key == gfx.KeyUp { + step = -1 + } + for offset := 1; offset <= len(m.links); offset++ { + at := from + step*offset + for at < 0 { + at += len(m.links) + } + for at >= len(m.links) { + at -= len(m.links) + } + if m.usableContentLink(at, entry) { + return at, true + } + } + return 0, false +} + +func (m *NavigationMenu) usableContentLink(index, entry int) bool { + link := &m.links[index] + return link.Entry == entry && !link.Separator && !link.Link.Disabled && !link.Link.ID.IsZero() +} + +func (m *NavigationMenu) firstContentLink(entry int) (gfx.ID, bool) { + for index := range m.links { + if m.usableContentLink(index, entry) { + return m.links[index].Link.ID, true + } + } + return gfx.ID{}, false +} diff --git a/ui/navigationmenuview/navigationmenuview_test.go b/ui/navigationmenuview/navigationmenuview_test.go new file mode 100644 index 00000000..7421d995 --- /dev/null +++ b/ui/navigationmenuview/navigationmenuview_test.go @@ -0,0 +1,229 @@ +package navigationmenuview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/navigationmenuview" +) + +var ( + productsID = gfx.Item(1) + pricingID = gfx.Item(2) + docsID = gfx.Item(3) + guideID = gfx.Item(4) + apiID = gfx.Item(5) + dismissID = gfx.Item(6) +) + +type model struct { + menu navigationmenuview.NavigationMenu + + open gfx.ID + direct bool + page string + selected gfx.ID + + pointerTarget gfx.ID + keyTarget gfx.ID + keys int +} + +func (m *model) wire() { + m.menu.Scope = gfx.Item(80) + m.menu.DismissID = dismissID + m.menu.Pointer = func(event gfx.PointerEvent) gfx.EventResult { + m.pointerTarget = event.Target + return gfx.EventResult{Handled: true, Repaint: true} + } + m.menu.Key = func(event gfx.KeyEvent) gfx.EventResult { + m.keys++ + m.keyTarget = event.Target + return gfx.EventResult{Handled: true} + } +} + +func (m *model) view(c ui.C) { + m.menu.DirectContent = m.direct + if m.menu.Selected == guideID { + m.page = "guide" + } else if m.menu.Selected == apiID { + m.page = "components" + } else if m.menu.Selected == docsID { + m.page = "docs" + } + m.menu.Reset() + m.menu.Trigger(productsID, "Products").Hint("Open product navigation") + m.menu.Link(docsID, "Docs").Value("/docs").Active(m.page == "docs") + m.menu.ContentLink(guideID, "Getting started"). + Description("Build a native window and retained scene."). + Value("/guide").Active(m.page == "guide") + m.menu.ContentLink(apiID, "Component API"). + Description("Read the source-owned recipes."). + Value("/components").Active(m.page == "components") + m.menu.Trigger(pricingID, "Pricing") + m.menu.View(c, "Navigation menu").Width(520).Height(36) +} + +func openPage(t *testing.T, m *model) (*ui.Page, *gfx.Canvas) { + t.Helper() + m.wire() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.view, Theme: &theme}) + canvas := benchCanvas() + draw(page, canvas, m.view) + return page, canvas +} + +func benchCanvas() *gfx.Canvas { + canvas := &gfx.Canvas{} + canvas.SetMeasurer(func(value string, size, weight float32) float32 { return float32(len(value)) * size / 2 }) + return canvas +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 600, Height: 400}, view) + canvas.EndFrame() +} + +func drawClick(page *ui.Page, canvas *gfx.Canvas, view func(ui.C), id gfx.ID) { + canvas.BeginEventPass(id, gfx.ClickInfo{}) + draw(page, canvas, view) + canvas.EndEventPass() +} + +func hitLabel(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for index := len(hits) - 1; index >= 0; index-- { + hit := hits[index] + if hit.Label == label && !hit.ID.IsZero() && !hit.Backdrop { + return hit, true + } + } + return gfx.Hit{}, false +} + +func mustHit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + hit, ok := hitLabel(canvas, label) + if !ok { + t.Fatalf("no hit labelled %q", label) + } + return hit +} + +func TestNavigationMenuOpensAndChoosesALink(t *testing.T) { + m := &model{} + page, canvas := openPage(t, m) + mustHit(t, canvas, "Products") + mustHit(t, canvas, "Docs") + if _, ok := hitLabel(canvas, "Getting started"); ok { + t.Fatal("a closed navigation menu painted its panel links") + } + + drawClick(page, canvas, m.view, productsID) + if m.menu.Open != productsID { + t.Fatalf("open = %v, want Products", m.menu.Open) + } + draw(page, canvas, m.view) + for _, label := range []string{"Getting started", "Component API"} { + mustHit(t, canvas, label) + } + + row := mustHit(t, canvas, "Getting started") + drawClick(page, canvas, m.view, row.ID) + if m.menu.Selected != guideID { + t.Fatalf("selected = %v, want guide", m.menu.Selected) + } +} + +func TestNavigationMenuDirectContent(t *testing.T) { + m := &model{direct: true} + m.menu.Open = productsID + _, canvas := openPage(t, m) + if _, ok := hitLabel(canvas, "Getting started"); !ok { + t.Fatal("direct content did not paint the panel links") + } +} + +func TestNavigationMenuKeysMoveOpenAndChoose(t *testing.T) { + m := &model{} + m.menu.Open = productsID + page, canvas := openPage(t, m) + control := mustHit(t, canvas, "Navigation menu") + products := mustHit(t, canvas, "Products") + guide := mustHit(t, canvas, "Getting started") + + result, ok := page.RouteKey(gfx.KeyEvent{Key: gfx.KeyDown, Target: control.ID}) + if !ok || !result.Handled || m.menu.Open != productsID { + t.Fatalf("Down = %+v, %v; open %v", result, ok, m.menu.Open) + } + if result.Focus != guide.ID { + t.Fatalf("Down focused %v, want the first panel link", result.Focus) + } + if m.keyTarget != control.ID { + t.Fatalf("the key callback saw %v, want the control", m.keyTarget) + } + + pricing := mustHit(t, canvas, "Pricing") + m.menu.Focus = productsID + result, _ = page.RouteKey(gfx.KeyEvent{Key: gfx.KeyRight, Target: control.ID}) + if m.menu.Open != pricingID || result.Focus != pricing.ID { + t.Fatalf("Right opened %v and focused %v, want Pricing", m.menu.Open, result.Focus) + } + + m.menu.Open = productsID + m.menu.Focus = guideID + draw(page, canvas, m.view) + guide = mustHit(t, canvas, "Getting started") + result, _ = page.RouteKey(gfx.KeyEvent{Key: gfx.KeyEnter, Target: control.ID}) + if result.Activate != guide.ID || m.menu.Selected != guideID { + t.Fatalf("Enter activated %v and selected %v, want Getting started", result.Activate, m.menu.Selected) + } + + result, _ = page.RouteKey(gfx.KeyEvent{Key: gfx.KeyEscape, Target: control.ID}) + if !m.menu.Open.IsZero() || result.Focus != products.ID { + t.Fatalf("Escape left %v open and focused %v, want Products", m.menu.Open, result.Focus) + } +} + +func TestNavigationMenuTopLevelLinkActivates(t *testing.T) { + m := &model{} + page, canvas := openPage(t, m) + control := mustHit(t, canvas, "Navigation menu") + docs := mustHit(t, canvas, "Docs") + m.menu.Focus = docsID + result, _ := page.RouteKey(gfx.KeyEvent{Key: gfx.KeyEnter, Target: control.ID}) + if result.Activate != docs.ID || m.menu.Selected != docsID { + t.Fatalf("Enter activated %v and selected %v, want Docs", result.Activate, m.menu.Selected) + } +} + +func TestNavigationMenuPointerTranslation(t *testing.T) { + m := &model{} + m.menu.Open = productsID + page, canvas := openPage(t, m) + control := mustHit(t, canvas, "Navigation menu") + page.Pointer(gfx.PointerEvent{Kind: gfx.PointerDown, Target: control.ID, X: control.Bounds.X + 4, Y: control.Bounds.Y + 4}) + if m.pointerTarget != control.ID { + t.Fatalf("the pointer callback saw %v, want the control", m.pointerTarget) + } +} + +func BenchmarkNavigationMenuPaint(b *testing.B) { + m := &model{page: "guide"} + m.menu.Open = productsID + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.view, Theme: &theme}) + canvas := benchCanvas() + view := m.view + draw(page, canvas, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/page_test.go b/ui/page_test.go index e89616c4..35d91ae4 100644 --- a/ui/page_test.go +++ b/ui/page_test.go @@ -559,9 +559,9 @@ func TestSelectStaysOpenWhenOneAppearsAbove(t *testing.T) { } } -// SelectIcon opens, chooses and writes back through the option type of the -// application's own, label and icon both named by functions of the option. -func TestSelectIconChoosesAnOption(t *testing.T) { +// Select Icons opens, chooses and writes back through the option type of the +// application's own; the icons are indexed like the choices. +func TestSelectIconsChooseAnOption(t *testing.T) { type locale struct { Name string flag int @@ -572,11 +572,14 @@ func TestSelectIconChoosesAnOption(t *testing.T) { } locales := []locale{{"简体中文", 0}, {"English", 1}, {"日本語", 2}} chosen := locales[1] + icons := make([]gfx.Icon, len(locales)) + for i, locale := range locales { + icons[i] = flagOf(locale.flag) + } d := openPage(t, func(c ui.C) { ui.Column(c).Pad(16).Children(func() { - ui.SelectIcon(c, &chosen, locales, - func(l locale) string { return l.Name }, - func(l locale) gfx.Icon { return flagOf(l.flag) }).Placeholder("Language") + ui.Select(c, &chosen, locales, func(l locale) string { return l.Name }). + Icons(icons).Placeholder("Language") }) }) d.click("Language") diff --git a/ui/reordergridview/reordergridview.go b/ui/reordergridview/reordergridview.go new file mode 100644 index 00000000..9727df44 --- /dev/null +++ b/ui/reordergridview/reordergridview.go @@ -0,0 +1,293 @@ +// Package reordergridview is the opt-in page control for the arbitrary two- +// dimensional reorder surface of package components. It wraps +// components.BeginReorderGrid and components.ReorderGridState in a ui.Control: +// +// grid := &reordergridview.Grid{ +// Draw: m.drawHosts, HandleHitSlop: 8, +// Move: m.applyHostMove, +// } +// ... +// reordergridview.View(c, "Host order", grid).FillWidth().Height(220) +// +// The caller owns the items, their logical order and their rectangles, and +// paints each cell inside Draw; the wrapper begins the component, gives every +// declared item an identity inside the control so the page routes its events to +// the wrapper, and translates mouse and keyboard moves back to the caller's +// identities. The caller applies a Move only after a valid drop or key. +// +// Caller layouts map their cells with ItemBounds, or read the viewport handed +// to Draw. Pointer, key and wheel callbacks receive the caller's targets for +// observation; the wrapper has already updated the drag state before they run. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Grid in the model beside its items: its handlers, draw +// function and item identities are made once, so a warm paint allocates nothing. +// Do not copy a Grid after it has been painted. +package reordergridview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Move is one completed move, with the caller's item identities. From and To +// are the caller's stable order values. +type Move = components.ReorderGridMove + +// Layout is one paint's geometry and the way the callback declares its items. +// It is valid only during the Draw callback; keep the Viewport, not the Layout. +type Layout struct { + // Viewport is the control's rectangle in page coordinates. + Viewport gfx.Rect + + owner *Grid + grid *components.ReorderGrid +} + +// Order declares one item in the caller's logical order without painting it. +// Virtualized layouts declare every item here, then call Item for the cells +// currently on screen. +func (l Layout) Order(id gfx.ID, lane, order int, disabled bool) { + if l.grid == nil || l.owner == nil { + return + } + l.grid.Order(l.owner.part(id), lane, order, disabled) +} + +// Item declares one visible draggable item and paints the framework's handle. +// id is the caller's identity; the handle hit is given an identity inside the +// control so events reach the wrapper. +func (l Layout) Item(id gfx.ID, label string, lane, order int, bounds, handle gfx.Rect, disabled bool) { + if l.grid == nil || l.owner == nil { + return + } + l.grid.Item(l.owner.part(id), label, lane, order, bounds, handle, disabled) +} + +// ItemBounds maps a cell of a fixed-column grid to page coordinates. It returns +// an empty rectangle for a non-positive column count, a negative index or a +// viewport too narrow to hold the columns. +func (l Layout) ItemBounds(columns, index int, gap, height float32) gfx.Rect { + if columns <= 0 || index < 0 || height <= 0 || l.Viewport.Width <= 0 { + return gfx.Rect{} + } + width := (l.Viewport.Width - gap*float32(columns-1)) / float32(columns) + if width <= 0 { + return gfx.Rect{} + } + column, row := index%columns, index/columns + return gfx.Rect{ + X: l.Viewport.X + float32(column)*(width+gap), + Y: l.Viewport.Y + float32(row)*(height+gap), + Width: width, Height: height, + } +} + +// Dragging reports whether a handle is being dragged. +func (l Layout) Dragging() bool { + if l.owner == nil { + return false + } + return l.owner.State.Dragging() +} + +// Active is the caller identity of the item held by the pointer, or zero. +func (l Layout) Active() gfx.ID { + if l.owner == nil { + return gfx.ID{} + } + return l.owner.caller(l.owner.State.Active()) +} + +// Target is the caller identity under the pointer during a drag, or zero. +func (l Layout) Target() gfx.ID { + if l.owner == nil { + return gfx.ID{} + } + return l.owner.caller(l.owner.State.Target()) +} + +// Grid is one reorder grid's state and page control. Keep it in the model; the +// caller paints the cells in Draw and applies a Move after a valid drop or key. +type Grid struct { + // State is the caller-owned drag geometry. Use the zero value for a new grid. + State components.ReorderGridState + // HandleHitSlop expands each handle's interactive area without changing the + // caller's layout. The expansion is clamped to the item's bounds. + HandleHitSlop float32 + // Draw paints the caller's cells and declares them through layout. It runs + // inside the control, after the component has cleared its per-paint geometry. + Draw func(*ui.DrawContext, Layout) + // Move receives every completed pointer or keyboard move with the caller's + // identities. Apply it to the caller's order, then let the next paint run. + Move func(Move) + + // Pointer receives every pointer event aimed at the control, with its target + // translated to the caller's identity when it is one of them. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Key receives the keys pressed while an item handle has the focus. + Key func(gfx.KeyEvent) gfx.EventResult + // Scroll receives the wheel over the control. Reordering itself does not + // consume the wheel; a caller-owned scroll area may use it to auto-scroll. + Scroll func(gfx.ScrollEvent) gfx.EventResult + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + painted components.ReorderGrid + layout Layout + viewport gfx.Rect + + itemParts map[gfx.ID]gfx.ID + itemCallers []gfx.ID +} + +// View declares the grid at c. label names the control for assistive +// technology. Give it a size; it is a ui.Control painted through Draw. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, grid *Grid) ui.Box { + if grid == nil { + panic("reordergridview: View needs its Grid") + } + grid.prepare() + return ui.Control(c, label, &grid.handlers).Draw(grid.drawFn) +} + +// View declares the grid at c without naming it separately, for a page that +// keeps the Grid in its model. +func (g *Grid) View(c ui.C, label string) ui.Box { + return View(c, label, g) +} + +// Viewport is the rectangle painted last, zero until View has painted once. +func (g *Grid) Viewport() gfx.Rect { return g.viewport } + +// ItemBounds maps a cell of a fixed-column grid for the viewport painted last. +func (g *Grid) ItemBounds(columns, index int, gap, height float32) gfx.Rect { + return (Layout{Viewport: g.viewport}).ItemBounds(columns, index, gap, height) +} + +// Active is the caller identity of the item held by the pointer, or zero. +func (g *Grid) Active() gfx.ID { return g.caller(g.State.Active()) } + +// Target is the caller identity under the pointer during a drag, or zero. +func (g *Grid) Target() gfx.ID { return g.caller(g.State.Target()) } + +// Dragging reports whether a handle is being dragged. +func (g *Grid) Dragging() bool { return g.State.Dragging() } + +// PointerPosition is the last captured pointer position while a handle is held, +// for a caller-owned scroll area that auto-scrolls between pointer events. +func (g *Grid) PointerPosition() (gfx.Point, bool) { return g.State.PointerPosition() } + +// Cancel abandons the current drag without a move. +func (g *Grid) Cancel() { g.State.Cancel() } + +func (g *Grid) prepare() { + if g.prepared { + return + } + g.prepared = true + g.handlers.Pointer = g.pointer + g.handlers.Key = g.key + g.handlers.Scroll = g.scroll + g.drawFn = g.draw +} + +func (g *Grid) draw(d *ui.DrawContext) { + g.viewport = d.Rect + g.painted = components.BeginReorderGrid(d.Canvas, *d.Theme, d.Rect, &g.State) + if g.HandleHitSlop > 0 { + g.painted = g.painted.HandleHitSlop(g.HandleHitSlop) + } + g.layout = Layout{Viewport: d.Rect, owner: g, grid: &g.painted} + if g.Draw != nil { + g.Draw(d, g.layout) + } + g.painted.End() +} + +// part gives the caller's item identity a stable identity inside the control, +// so the page routes the handle's events to this control's handlers. Identities +// are assigned once per item and kept across reorder and virtualized paints. +func (g *Grid) part(id gfx.ID) gfx.ID { + if id.IsZero() { + return gfx.ID{} + } + if part, ok := g.itemParts[id]; ok { + return part + } + parts := g.handlers.Parts() + if parts.IsZero() { + // Painted outside a declared Control: keep the caller's identity so the + // component still paints, though no event can be routed here. + return id + } + if g.itemParts == nil { + g.itemParts = make(map[gfx.ID]gfx.ID) + } + part := parts.At(len(g.itemCallers)) + g.itemParts[id] = part + g.itemCallers = append(g.itemCallers, id) + return part +} + +// caller translates an identity inside the control back to the caller's. +func (g *Grid) caller(part gfx.ID) gfx.ID { + if part.IsZero() { + return part + } + if index, ok := part.In(g.handlers.Parts()); ok && index >= 0 && index < len(g.itemCallers) { + return g.itemCallers[index] + } + return part +} + +func (g *Grid) pointer(event gfx.PointerEvent) gfx.EventResult { + move, result := g.State.Pointer(event) + if move.Valid() { + move.ID, move.Target = g.caller(move.ID), g.caller(move.Target) + if g.Move != nil { + g.Move(move) + } + } + if g.Pointer != nil { + event.Target = g.caller(event.Target) + result = mergeResult(result, g.Pointer(event)) + } + return result +} + +func (g *Grid) key(event gfx.KeyEvent) gfx.EventResult { + move, result := g.State.Key(event) + if move.Valid() { + move.ID, move.Target = g.caller(move.ID), g.caller(move.Target) + if g.Move != nil { + g.Move(move) + } + } + if g.Key != nil { + event.Target = g.caller(event.Target) + result = mergeResult(result, g.Key(event)) + } + return result +} + +func (g *Grid) scroll(event gfx.ScrollEvent) gfx.EventResult { + if g.Scroll == nil { + return gfx.EventResult{} + } + event.Target = g.caller(event.Target) + return g.Scroll(event) +} + +// mergeResult keeps the wrapper's handling and focus and adds the caller +// callback's handled and repaint requests. The result's focus stays on the +// identity inside the control so later keys reach the wrapper. +func mergeResult(wrapper, callback gfx.EventResult) gfx.EventResult { + wrapper.Handled = wrapper.Handled || callback.Handled + wrapper.Repaint = wrapper.Repaint || callback.Repaint + return wrapper +} diff --git a/ui/reordergridview/reordergridview_test.go b/ui/reordergridview/reordergridview_test.go new file mode 100644 index 00000000..84fffa19 --- /dev/null +++ b/ui/reordergridview/reordergridview_test.go @@ -0,0 +1,207 @@ +package reordergridview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/reordergridview" +) + +const ( + testColumns = 3 + testGap = float32(10) + testHeight = float32(60) +) + +var testIDs = [6]gfx.ID{ + gfx.Item(1), gfx.Item(2), gfx.Item(3), gfx.Item(4), gfx.Item(5), gfx.Item(6), +} + +type model struct { + view reordergridview.Grid + page *ui.Page + canvas *gfx.Canvas + moves []reordergridview.Move + target gfx.ID + keys int + scrolls int +} + +func (m *model) wire() { + m.view.HandleHitSlop = 8 + m.view.Draw = func(d *ui.DrawContext, layout reordergridview.Layout) { + for order, id := range testIDs { + layout.Order(id, 0, order, false) + } + for order, id := range testIDs { + card := layout.ItemBounds(testColumns, order, testGap, testHeight) + handle := gfx.Rect{X: card.X + 8, Y: card.Y + 12, Width: 28, Height: card.Height - 24} + layout.Item(id, "Host", 0, order, card, handle, false) + } + } + m.view.Move = func(move reordergridview.Move) { m.moves = append(m.moves, move) } + m.view.Pointer = func(event gfx.PointerEvent) gfx.EventResult { + m.target = event.Target + return gfx.EventResult{Handled: true, Repaint: true} + } + m.view.Key = func(event gfx.KeyEvent) gfx.EventResult { + m.keys++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } + m.view.Scroll = func(event gfx.ScrollEvent) gfx.EventResult { + m.scrolls++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } +} + +func (m *model) viewPage(c ui.C) { + reordergridview.View(c, "Hosts", &m.view).Size(600, 220) +} + +func (m *model) open(t testing.TB) { + t.Helper() + theme := gfx.LightTheme() + m.page = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: &theme}) + m.canvas = new(gfx.Canvas) + draw(m.page, m.canvas, m.viewPage) +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 260}, view) + canvas.EndFrame() +} + +func hitLabelled(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + if hits[i].Label == label && !hits[i].ID.IsZero() { + return hits[i], true + } + } + return gfx.Hit{}, false +} + +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + got, ok := hitLabelled(canvas, label) + if !ok { + t.Fatalf("no hit labelled %q was painted", label) + } + return got +} + +// The page declares the view, the caller paints the cells in Draw, and the +// wrapper gives every handle an identity inside the control so pointer and key +// events reach it. Completed moves keep the caller's identities. +func TestViewPaintsAndRoutesReorder(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + + if viewport := m.view.Viewport(); viewport.Width != 600 || viewport.Height != 220 { + t.Fatalf("viewport = %+v, want 600x220", viewport) + } + first := m.view.ItemBounds(testColumns, 0, testGap, testHeight) + last := m.view.ItemBounds(testColumns, 4, testGap, testHeight) + if first.Width <= 0 || last.Y <= first.Y { + t.Fatalf("bounds = %+v %+v, want a laid-out grid", first, last) + } + + hits := m.canvas.Hits() + var handles []gfx.Hit + for _, h := range hits { + if h.Label == "Host" && !h.ID.IsZero() { + handles = append(handles, h) + } + } + if len(handles) != len(testIDs) { + t.Fatalf("painted %d handles, want %d", len(handles), len(testIDs)) + } + for _, h := range handles { + if h.ID == testIDs[0] || h.ID == testIDs[3] { + t.Fatal("a handle was painted with the caller's identity instead of the control's") + } + } + + from := gfx.Point{X: handles[0].Bounds.X + handles[0].Bounds.Width/2, Y: handles[0].Bounds.Y + handles[0].Bounds.Height/2} + to := gfx.Point{X: last.X + last.Width/2, Y: last.Y + last.Height/2} + if result := m.page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: handles[0].ID, X: from.X, Y: from.Y, + }); !result.Handled || m.target != testIDs[0] { + t.Fatalf("pointer down Target = %v (result %+v), want the caller's %v", m.target, result, testIDs[0]) + } + if result := m.page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerMove, Captured: true, Target: handles[0].ID, X: to.X, Y: to.Y, + }); !result.Handled || m.target != testIDs[0] { + t.Fatalf("pointer move Target = %v (result %+v)", m.target, result) + } + if !m.view.Dragging() || m.view.Target() != testIDs[4] { + t.Fatalf("dragging = %v target = %v, want %v", m.view.Dragging(), m.view.Target(), testIDs[4]) + } + if result := m.page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerUp, Captured: true, Target: handles[0].ID, X: to.X, Y: to.Y, + }); !result.Handled { + t.Fatalf("pointer up result = %+v", result) + } + if len(m.moves) != 1 || m.moves[0].ID != testIDs[0] || m.moves[0].Target != testIDs[4] || + m.moves[0].From != 0 || m.moves[0].To != 4 || !m.moves[0].Valid() { + t.Fatalf("moves = %+v, want a caller-identity move from 0 to 4", m.moves) + } + + if result := m.page.Key(gfx.KeyEvent{Key: gfx.KeyEnd, Target: handles[0].ID}); !result.Handled || m.keys != 1 { + t.Fatalf("key result = %+v after %d calls", result, m.keys) + } + if len(m.moves) != 2 || m.moves[1].ID != testIDs[0] || m.moves[1].To != 5 { + t.Fatalf("moves = %+v, want a keyboard move to the last slot", m.moves) + } + + if result := m.page.Wheel(gfx.ScrollEvent{Target: handles[0].ID, DeltaY: 1}); !result.Handled || m.scrolls != 1 { + t.Fatalf("wheel result = %+v after %d calls", result, m.scrolls) + } +} + +// A warm repaint allocates nothing: the wrapper keeps its handlers, draw +// function and item identities, and the component keeps its own geometry. +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.wire() + m.open(t) + if allocations := testing.AllocsPerRun(100, func() { draw(m.page, m.canvas, m.viewPage) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +// An item with the zero identity is neither painted nor draggable. +func TestZeroItemIdentityIsOmitted(t *testing.T) { + var view reordergridview.Grid + view.Draw = func(d *ui.DrawContext, layout reordergridview.Layout) { + card := layout.ItemBounds(1, 0, 0, 40) + layout.Item(gfx.ID{}, "Missing", 0, 0, card, card, false) + layout.Item(gfx.Item(9), "Present", 0, 1, layout.ItemBounds(1, 1, 0, 40), card, false) + } + viewPage := func(c ui.C) { reordergridview.View(c, "Hosts", &view).Size(300, 120) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: viewPage, Theme: &theme}) + canvas := new(gfx.Canvas) + draw(page, canvas, viewPage) + if _, ok := hitLabelled(canvas, "Missing"); ok { + t.Fatal("an item with the zero identity was painted") + } + hit(t, canvas, "Present") +} + +func BenchmarkViewPaint(b *testing.B) { + m := new(model) + m.wire() + m.open(b) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + draw(m.page, m.canvas, m.viewPage) + } +} diff --git a/ui/tabs_icon_test.go b/ui/tabs_icon_test.go new file mode 100644 index 00000000..c0e80427 --- /dev/null +++ b/ui/tabs_icon_test.go @@ -0,0 +1,26 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// A page Tabs with TabIcons is the same tab strip with an icon before each label: a click +// still writes the chosen tab, and both tabs are named for assistive technology. +func TestPageTabsTabIconsSelectsAndNamesTabs(t *testing.T) { + tabs := []string{"Overview", "Activity"} + choice := tabs[0] + icon := gfx.Icon{ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{gfx.MoveTo(4, 4), gfx.LineTo(20, 20)}} + d := openPage(t, func(c ui.C) { + ui.Tabs(c, &choice, tabs, nil).TabIcons(func(int) gfx.Icon { return icon }) + }) + if d.hit("Overview").Role != gfx.RoleTab || d.hit("Activity").Role != gfx.RoleTab { + t.Fatal("the tabs are not declared as tabs") + } + d.click("Activity") + if choice != "Activity" { + t.Fatalf("choice = %q, want Activity", choice) + } +} diff --git a/ui/tabs_paint.go b/ui/tabs_paint.go index 846a2115..d5e37082 100644 --- a/ui/tabs_paint.go +++ b/ui/tabs_paint.go @@ -3,6 +3,7 @@ package ui import ( "github.com/vivaui/viva/base" "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" ) func paintTabs(f *Frame, n *Node) { @@ -20,7 +21,24 @@ func paintTabs(f *Frame, n *Node) { bounds.Width = max(bounds.Width-TabIndicator-1, 0) } } - tabs := components.BeginTabList(f.Surface, f.Palette, bounds, t.GetScope(), t.GetLabels(), t.GetSelected()) + var tabs components.Tabs + if icon := t.GetIcon(); icon != nil { + widgets := base.WidgetsOf(f) + labels := t.GetLabels() + widgets.TabOptions = widgets.TabOptions[:0] + for index, label := range labels { + widgets.TabOptions = append(widgets.TabOptions, base.TabOption{ + ID: t.GetScope().At(index), Label: label, Icon: icon(index), + }) + } + selected := gfx.ID{} + if s := t.GetSelected(); s >= 0 && s < len(widgets.TabOptions) { + selected = widgets.TabOptions[s].ID + } + tabs = components.BeginTabs(f.Surface, f.Palette, bounds, widgets.TabOptions, selected) + } else { + tabs = components.BeginTabList(f.Surface, f.Palette, bounds, t.GetScope(), t.GetLabels(), t.GetSelected()) + } if t.GetLine() { tabs = tabs.Line() } diff --git a/website/content/guides/en/components.md b/website/content/guides/en/components.md index b1d6a944..e491ba72 100644 --- a/website/content/guides/en/components.md +++ b/website/content/guides/en/components.md @@ -19,7 +19,7 @@ components.BeginButton(canvas, theme, hitSave, bounds).Outline("Save") A theme is a value, `gfx.LightTheme()` or `gfx.DarkTheme()`. Switching appearance means painting with the other one. -`Begin*` is the style layer's constructor, not a second page API. Declare page controls with `ui.*`, `ui.*Base` and `ui.Control`; use `components.Begin*` inside a `Draw`, for pure measurement, or in source copied by `viva add`. “Zero Begin” is not a goal: the boundary is that page behaviour is not hand-built, not that the painter constructor disappears. Reusable heavy composites such as `multiselect` and `hierarchypicker` are opt-in packages. +`Begin*` is the style layer's constructor, not a second page API. Declare page controls with `ui.*`, `ui.*Base` and `ui.Control`; use `components.Begin*` inside a `Draw`, for pure measurement, or in source copied by `viva add`. “Zero Begin” is not a goal: the boundary is that page behaviour is not hand-built, not that the painter constructor disappears. Reusable heavy composites such as `ui/multiselect` and `ui/hierarchypicker` are opt-in packages. ## Tree navigation diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md index b8d731e2..bb55a900 100644 --- a/website/content/guides/en/declarative-layout.md +++ b/website/content/guides/en/declarative-layout.md @@ -83,7 +83,7 @@ An element is named by where it is: its kind and its number among the elements o ### Menus, search fields and context menus -`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` is shadcn's dropdown menu of actions: `menu.Item("Rename").Clicked()` reads one as a button is read, the arrows move between items, typing a letter goes to the item it begins, and choosing one closes the menu. `menu.Sub("Move to", func(to *ui.MenuItems) { ... })` is an item with a submenu beside it, which opens as the pointer rests on the item, on a click, or on Right, Enter or Space with its first item focused; Left goes back, Escape closes every menu, and choosing in it closes them all. `menu.Item("Model").Description("What answers")` adds a second line under an item, `menu.Item("Rename").ID()` is the row's identity for anchoring a part or context menu, `menu.WidthRange(140, 320)` bounds the menu's width, `menu.Above()` opens it over the anchor, for a trigger along the bottom of a panel, and `menu.Beside()` to its right, for a row of a list or popup whose menu should leave the rows under it in sight. `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` takes Select's arguments and a label, and filters the choices as the user types into it, with the platform's input methods. `.Clearable()` gives it a button that clears the choice, `.Empty("No zone matches")` is what its list says when nothing matches, and `.Creatable("")` offers what was typed as a new choice ("Create dev"), which `.Created()` reports for the application to add. A multi-select with removable chips is the opt-in `multiselect` package: `picker := multiselect.New(&m.tags)`, then `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`; importing it is what links it, so applications that do not use it pay nothing. Hierarchical paths use the opt-in `hierarchypicker` package the same way: `state := hierarchypicker.NewState(paths)`, `picker := hierarchypicker.New(state)`, then `picker.View(c, hierarchypicker.Spec{Label: "Group", OptionIDs: groupOptions}).FillWidth()`; `state.Value` is the full chosen path. A Button takes an icon before its label with `.Icon(plus)`, or alone with `.IconOnly()`. `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` opens the same items at the pointer on a secondary press of `row`, or under it on Shift+F10; items take an `.Icon`, the keycaps of a shortcut with `.Keys(ui.Primary, "c")` (shown only: the shortcut is a `Shortcut` where its action is), and `.Checked` or `.Chosen` to be a checkbox or a radio item. A search field is a TextField with `.Icon(search)` before its text and `.Action(cross, "Clear")`, a small button at its end that `.ActionClicked()` reads. +`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` is shadcn's dropdown menu of actions: `menu.Item("Rename").Clicked()` reads one as a button is read, the arrows move between items, typing a letter goes to the item it begins, and choosing one closes the menu. `menu.Sub("Move to", func(to *ui.MenuItems) { ... })` is an item with a submenu beside it, which opens as the pointer rests on the item, on a click, or on Right, Enter or Space with its first item focused; Left goes back, Escape closes every menu, and choosing in it closes them all. `menu.Item("Model").Description("What answers")` adds a second line under an item, `menu.Item("Rename").ID()` is the row's identity for anchoring a part or context menu, `menu.WidthRange(140, 320)` bounds the menu's width, `menu.Above()` opens it over the anchor, for a trigger along the bottom of a panel, and `menu.Beside()` to its right, for a row of a list or popup whose menu should leave the rows under it in sight. `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` takes Select's arguments and a label, and filters the choices as the user types into it, with the platform's input methods. `.Clearable()` gives it a button that clears the choice, `.Empty("No zone matches")` is what its list says when nothing matches, and `.Creatable("")` offers what was typed as a new choice ("Create dev"), which `.Created()` reports for the application to add. A multi-select with removable chips is the opt-in `ui/multiselect` package: `picker := multiselect.New(&m.tags)`, then `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`; importing it is what links it, so applications that do not use it pay nothing. Hierarchical paths use the opt-in `ui/hierarchypicker` package the same way: `state := hierarchypicker.NewState(paths)`, `picker := hierarchypicker.New(state)`, then `picker.View(c, hierarchypicker.Spec{Label: "Group", OptionIDs: groupOptions}).FillWidth()`; `state.Value` is the full chosen path. A Button takes an icon before its label with `.Icon(plus)`, or alone with `.IconOnly()`. `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` opens the same items at the pointer on a secondary press of `row`, or under it on Shift+F10; items take an `.Icon`, the keycaps of a shortcut with `.Keys(ui.Primary, "c")` (shown only: the shortcut is a `Shortcut` where its action is), and `.Checked` or `.Chosen` to be a checkbox or a radio item. A search field is a TextField with `.Icon(search)` before its text and `.Action(cross, "Clear")`, a small button at its end that `.ActionClicked()` reads. ### Drawers diff --git a/website/content/guides/zh/components.md b/website/content/guides/zh/components.md index 82a805de..5091fea3 100644 --- a/website/content/guides/zh/components.md +++ b/website/content/guides/zh/components.md @@ -19,7 +19,7 @@ components.BeginButton(canvas, theme, hitSave, bounds).Outline("Save") 主题是一个值,`gfx.LightTheme()` 或 `gfx.DarkTheme()`。切换外观就是改用另一个主题绘制。 -`Begin*` 是样式层的构造器,不是第二套页面 API。页面控件用 `ui.*`、`ui.*Base` 和 `ui.Control` 声明;`components.Begin*` 用于 `Draw` 内部、纯测量或 `viva add` 复制出的源码。“零 Begin”不是目标:边界是页面行为不再手拼,而不是绘制构造器消失。`multiselect`、`hierarchypicker` 这类可复用的重型复合控件走 opt-in 包。 +`Begin*` 是样式层的构造器,不是第二套页面 API。页面控件用 `ui.*`、`ui.*Base` 和 `ui.Control` 声明;`components.Begin*` 用于 `Draw` 内部、纯测量或 `viva add` 复制出的源码。“零 Begin”不是目标:边界是页面行为不再手拼,而不是绘制构造器消失。`ui/multiselect`、`ui/hierarchypicker` 这类可复用的重型复合控件走 opt-in 包。 ## 树形导航 diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md index 16cc3c8a..1d874a65 100644 --- a/website/content/guides/zh/declarative-layout.md +++ b/website/content/guides/zh/declarative-layout.md @@ -84,7 +84,7 @@ ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, m.page) ### 菜单、搜索框与右键菜单 -`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` 是 shadcn 的下拉菜单:像读按钮一样用 `menu.Item("Rename").Clicked()` 读取一项,方向键在各项之间移动,输入字母会跳到以它开头的项,选中一项后菜单关闭。`menu.Sub("Move to", func(to *ui.MenuItems) { ... })` 是一个旁边带子菜单的项:指针在它上面停留、点击它,或按 Right、Enter、Space 时打开(键盘打开时焦点落在子菜单第一项);Left 返回,Escape 关闭所有菜单,在子菜单里选中一项也会全部关闭。 `menu.Item("Model").Description("What answers")` 给项加一行说明;`menu.Item("Rename").ID()` 是该项的标识,可用来锚定部件或右键菜单;`menu.WidthRange(140, 320)` 限制菜单宽度,`menu.Above()` 让菜单在锚点上方展开(锚点在面板底部时),`menu.Beside()` 让菜单在锚点右侧展开(列表或弹出层里的行,菜单不遮住下面的行)。`ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` 接受 Select 的参数再加一个标签,用户输入时(支持平台输入法)筛选选项。`.Clearable()` 加一个清除选择的按钮,`.Empty("No zone matches")` 是没有匹配项时列表显示的文字,`.Creatable("")` 把输入的内容作为新选项提供("Create dev"),由 `.Created()` 报告,应用自己把它加进选项。带可移除 chip 的多选用可选的 `multiselect` 包:`picker := multiselect.New(&m.tags)`,然后 `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`;只有 import 它的应用才会链接它,不用的应用零成本。层级路径用可选的 `hierarchypicker` 包:`state := hierarchypicker.NewState(paths)`,`picker := hierarchypicker.New(state)`,然后 `picker.View(c, hierarchypicker.Spec{Label: "Group", OptionIDs: groupOptions}).FillWidth()`;`state.Value` 是选中的完整路径。Button 用 `.Icon(plus)` 在标签前加图标,加 `.IconOnly()` 则只显示图标。`ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` 在 `row` 上按下副键时于指针处打开同样的菜单项,按 Shift+F10 时在它下方打开;菜单项可以加 `.Icon`、用 `.Keys(ui.Primary, "c")` 显示快捷键键帽(只显示,快捷键本身是动作所在处的一个 `Shortcut`),用 `.Checked` 或 `.Chosen` 成为复选或单选项。搜索框是带 `.Icon(search)`(文字前的图标)和 `.Action(cross, "Clear")`(末尾的小按钮,用 `.ActionClicked()` 读取)的 TextField。 +`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` 是 shadcn 的下拉菜单:像读按钮一样用 `menu.Item("Rename").Clicked()` 读取一项,方向键在各项之间移动,输入字母会跳到以它开头的项,选中一项后菜单关闭。`menu.Sub("Move to", func(to *ui.MenuItems) { ... })` 是一个旁边带子菜单的项:指针在它上面停留、点击它,或按 Right、Enter、Space 时打开(键盘打开时焦点落在子菜单第一项);Left 返回,Escape 关闭所有菜单,在子菜单里选中一项也会全部关闭。 `menu.Item("Model").Description("What answers")` 给项加一行说明;`menu.Item("Rename").ID()` 是该项的标识,可用来锚定部件或右键菜单;`menu.WidthRange(140, 320)` 限制菜单宽度,`menu.Above()` 让菜单在锚点上方展开(锚点在面板底部时),`menu.Beside()` 让菜单在锚点右侧展开(列表或弹出层里的行,菜单不遮住下面的行)。`ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` 接受 Select 的参数再加一个标签,用户输入时(支持平台输入法)筛选选项。`.Clearable()` 加一个清除选择的按钮,`.Empty("No zone matches")` 是没有匹配项时列表显示的文字,`.Creatable("")` 把输入的内容作为新选项提供("Create dev"),由 `.Created()` 报告,应用自己把它加进选项。带可移除 chip 的多选用可选的 `ui/multiselect` 包:`picker := multiselect.New(&m.tags)`,然后 `picker.View(c, multiselect.Spec{Label: "Tags", Options: tagOptions, Removes: tagRemoves}).FillWidth()`;只有 import 它的应用才会链接它,不用的应用零成本。层级路径用可选的 `ui/hierarchypicker` 包:`state := hierarchypicker.NewState(paths)`,`picker := hierarchypicker.New(state)`,然后 `picker.View(c, hierarchypicker.Spec{Label: "Group", OptionIDs: groupOptions}).FillWidth()`;`state.Value` 是选中的完整路径。Button 用 `.Icon(plus)` 在标签前加图标,加 `.IconOnly()` 则只显示图标。`ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` 在 `row` 上按下副键时于指针处打开同样的菜单项,按 Shift+F10 时在它下方打开;菜单项可以加 `.Icon`、用 `.Keys(ui.Primary, "c")` 显示快捷键键帽(只显示,快捷键本身是动作所在处的一个 `Shortcut`),用 `.Checked` 或 `.Chosen` 成为复选或单选项。搜索框是带 `.Icon(search)`(文字前的图标)和 `.Action(cross, "Clear")`(末尾的小按钮,用 `.ActionClicked()` 读取)的 TextField。 ### 抽屉 diff --git a/website/src/lib/i18n.test.ts b/website/src/lib/i18n.test.ts index e4a822a1..3a1ff48c 100644 --- a/website/src/lib/i18n.test.ts +++ b/website/src/lib/i18n.test.ts @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import test from 'node:test'; -import { categoryLabel, componentPath, componentsPath, defaultLocale, isLocale, languagePath, locales, localizePage, messages } from './i18n.ts'; +import { categoryLabel, componentName, componentPath, componentsPath, defaultLocale, isLocale, languagePath, locales, localizePage, messages } from './i18n.ts'; import type { Catalog } from './types.ts'; const catalog: Catalog = JSON.parse(readFileSync(new URL('../../../build/docs-data/catalog.json', import.meta.url), 'utf8')); @@ -29,6 +29,12 @@ test('both message dictionaries have exactly the same nonempty keys', () => { } }); +test('every component has a Chinese name in the sidebar', () => { + for (const page of catalog.pages) { + assert.notEqual(componentName('zh', page.ID, '__missing__'), '__missing__', page.ID); + } +}); + test('every generated component, example, section and platform has both translations', () => { // Coverage lists the components package's source files; a page-layer control // (ui.List) has a page of its own without one. diff --git a/website/src/lib/i18n.ts b/website/src/lib/i18n.ts index 6af1fa62..ea3dd55c 100644 --- a/website/src/lib/i18n.ts +++ b/website/src/lib/i18n.ts @@ -150,7 +150,21 @@ const chineseComponentNames: Record = { 'dropdown-menu': '下拉菜单', 'hover-card': '悬停卡片', 'code-diff': '代码差异', + 'code-editor': '代码编辑器', 'code-merge': '三方合并', + 'color-picker': '颜色选择器', + 'color-swatch': '颜色色块', + 'multi-select': '多选', + 'single-select': '单选', + 'avatar-editor': '头像编辑器', + 'image-view': '图片视图', + 'column-resize': '列宽调整', + 'reorder-grid': '排序网格', + 'reorder-list': '排序列表', + 'icon-hover': '图标悬停', + 'chart-area': '面积图', + 'chart-bar': '柱状图', + 'chart-downsample': '图表降采样', 'split-button': '分离按钮', list: '列表', }; @@ -271,11 +285,6 @@ const genericChineseSections: Record> = { Text: '此预览直接调用生产 Go 组件。稳定 ID、值与打开状态仍由应用持有;组件只负责绘制并声明交互语义。', Items: ['标题旁的源码链接列出了全部选项与视觉决策。', '请使用原生命令验证系统文本、焦点、无障碍与平台集成。', '浏览器预览验证共享布局和场景行为,不代表原生性能。'], }, - verification: { - Title: '验证边界', - Text: '示例覆盖当前 API 的代表性状态,但不表示每个桌面后端都已完成真机验证。', - Items: [], - }, }; function englishLabel(value: string): string { diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index 004c1a57..4107b04c 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -20,6 +20,30 @@ const themes = { light: 'github-light', dark: 'github-dark' } as const; const sourceFile = `${page.ID.replaceAll('-', '_')}.go`; const sourcePath = page.PageUsage && page.PageSource ? page.PageSource : (page.Source || `components/${sourceFile}`); const sections = page.Sections.filter(section => section.ID !== 'source-ownership'); +const optionalImports = { + text: 'github.com/vivaui/viva/text', + gfx: 'github.com/vivaui/viva/gfx', + style: 'github.com/vivaui/viva/style', + base: 'github.com/vivaui/viva/base', + codeeditor: 'github.com/vivaui/viva/ui/codeeditor', + chartview: 'github.com/vivaui/viva/ui/chartview', + calendarview: 'github.com/vivaui/viva/ui/calendarview', + carouselview: 'github.com/vivaui/viva/ui/carouselview', + markdownview: 'github.com/vivaui/viva/ui/markdownview', + hovercardview: 'github.com/vivaui/viva/ui/hovercardview', + navigationmenuview: 'github.com/vivaui/viva/ui/navigationmenuview', + menubarview: 'github.com/vivaui/viva/ui/menubarview', + commandview: 'github.com/vivaui/viva/ui/commandview', + messagescrollerview: 'github.com/vivaui/viva/ui/messagescrollerview', + messageview: 'github.com/vivaui/viva/ui/messageview', + attachmentview: 'github.com/vivaui/viva/ui/attachmentview', + avatarview: 'github.com/vivaui/viva/ui/avatarview', + columnresizeview: 'github.com/vivaui/viva/ui/columnresizeview', + avatareditorview: 'github.com/vivaui/viva/ui/avatareditorview', + reordergridview: 'github.com/vivaui/viva/ui/reordergridview', + multiselect: 'github.com/vivaui/viva/ui/multiselect', + hierarchypicker: 'github.com/vivaui/viva/ui/hierarchypicker', +}; --- @@ -40,10 +64,15 @@ const sections = page.Sections.filter(section => section.ID !== 'source-ownershi {(() => { const own = example.Snippet && !/components\.|Begin/.test(example.Snippet); const localized = locale === 'zh' ? example.PageSnippetZh : example.PageSnippet; - const usage = localized || example.PageSnippet || (own ? example.Snippet : '') || `ui.Control(c, "${example.Title.replaceAll('"', '')}", &m.handlers).Draw(paint)`; + const usage = localized || example.PageSnippet || (own ? example.Snippet : ''); + if (!usage.trim()) throw new Error(`No page usage for ${page.ID}/${example.ID} (${locale})`); + const imports = Object.entries(optionalImports) + .filter(([name]) => new RegExp(`\\b${name}\\.`).test(usage)) + .map(([, path]) => `import "${path}"`); + const shown = imports.length > 0 ? `${imports.join('\n')}\n\n${usage}` : usage; return
-
{text.exampleUsage}
-
+
{text.exampleUsage}
+
; })()}
)} From 9a0dfc3ac82bac4dfdcba168569d46e9a0ea79b1 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 17:38:02 +0800 Subject: [PATCH 38/66] feat(ui): add page views for form and layout components --- docs/maintaining-controls.md | 4 +- internal/componentdemo/aspect_ratio.go | 99 ++-- internal/componentdemo/badge.go | 35 +- internal/componentdemo/image_view.go | 143 +++++- internal/componentdemo/input_group.go | 271 +++++++---- internal/componentdemo/input_otp.go | 180 +++---- internal/componentdemo/marker.go | 109 ++--- internal/componentdemo/metric_card.go | 127 ++--- internal/componentdemo/page_source.go | 18 +- internal/componentdemo/page_usage.go | 18 +- internal/componentdemo/questionnaire.go | 220 +++++---- internal/componentdemo/sidebar.go | 328 ++++--------- internal/componentdemo/skeleton.go | 204 ++++---- tools/docs/catalog_test.go | 9 + ui/aspectratioview/aspectratioview.go | 142 ++++++ ui/aspectratioview/aspectratioview_test.go | 160 +++++++ ui/codeeditor/parity_test.go | 58 +++ ui/imageview/imageview.go | 174 +++++++ ui/imageview/imageview_test.go | 207 +++++++++ ui/inputgroupview/inputgroupview.go | 301 ++++++++++++ ui/inputgroupview/inputgroupview_test.go | 181 ++++++++ ui/inputotpview/inputotpview.go | 391 ++++++++++++++++ ui/inputotpview/inputotpview_test.go | 200 ++++++++ ui/markerview/markerview.go | 140 ++++++ ui/markerview/markerview_test.go | 178 +++++++ ui/metriccardview/metriccardview.go | 140 ++++++ ui/metriccardview/metriccardview_test.go | 135 ++++++ ui/questionnaireview/questionnaireview.go | 241 ++++++++++ .../questionnaireview_test.go | 178 +++++++ ui/sidebarview/sidebarview.go | 438 ++++++++++++++++++ ui/sidebarview/sidebarview_test.go | 195 ++++++++ ui/skeletonview/skeletonview.go | 158 +++++++ ui/skeletonview/skeletonview_test.go | 149 ++++++ website/src/pages/[lang]/ui/[component].astro | 9 + 34 files changed, 4690 insertions(+), 850 deletions(-) create mode 100644 ui/aspectratioview/aspectratioview.go create mode 100644 ui/aspectratioview/aspectratioview_test.go create mode 100644 ui/codeeditor/parity_test.go create mode 100644 ui/imageview/imageview.go create mode 100644 ui/imageview/imageview_test.go create mode 100644 ui/inputgroupview/inputgroupview.go create mode 100644 ui/inputgroupview/inputgroupview_test.go create mode 100644 ui/inputotpview/inputotpview.go create mode 100644 ui/inputotpview/inputotpview_test.go create mode 100644 ui/markerview/markerview.go create mode 100644 ui/markerview/markerview_test.go create mode 100644 ui/metriccardview/metriccardview.go create mode 100644 ui/metriccardview/metriccardview_test.go create mode 100644 ui/questionnaireview/questionnaireview.go create mode 100644 ui/questionnaireview/questionnaireview_test.go create mode 100644 ui/sidebarview/sidebarview.go create mode 100644 ui/sidebarview/sidebarview_test.go create mode 100644 ui/skeletonview/skeletonview.go create mode 100644 ui/skeletonview/skeletonview_test.go diff --git a/docs/maintaining-controls.md b/docs/maintaining-controls.md index 4853d8a9..46e79a3f 100644 --- a/docs/maintaining-controls.md +++ b/docs/maintaining-controls.md @@ -47,7 +47,9 @@ Opt-in page packages live under `ui/` (`ui/codeeditor`, `ui/chartview`, `ui/calendarview`, `ui/carouselview`, `ui/markdownview`, `ui/columnresizeview`, `ui/avatareditorview`, `ui/reordergridview`, `ui/avatarview`, `ui/attachmentview`, `ui/messageview`, `ui/messagescrollerview`, `ui/commandview`, `ui/menubarview`, -`ui/navigationmenuview`, `ui/hovercardview`, `ui/multiselect`, +`ui/navigationmenuview`, `ui/hovercardview`, `ui/imageview`, `ui/aspectratioview`, +`ui/skeletonview`, `ui/inputgroupview`, `ui/inputotpview`, `ui/questionnaireview`, +`ui/metriccardview`, `ui/markerview`, `ui/sidebarview`, `ui/multiselect`, `ui/hierarchypicker`). They import only `base`, `components`, `gfx`, `ui` and `window`, own stable handlers, and are never imported by package `ui`; importing one is the explicit diff --git a/internal/componentdemo/aspect_ratio.go b/internal/componentdemo/aspect_ratio.go index 9aff1cac..61b2062b 100644 --- a/internal/componentdemo/aspect_ratio.go +++ b/internal/componentdemo/aspect_ratio.go @@ -1,59 +1,90 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/aspectratioview" ) var aspectRatioComponent = Component{ ID: "aspect-ratio", Title: "Aspect Ratio", Category: "Layout", Summary: "在不同容器宽度下保持稳定内容比例。", paint: (*State).paintAspectRatio, Examples: []Example{ - {ID: "default", Title: "16:9 预览", Description: "通过生产布局函数计算媒体区域高度。", Snippet: `ratio := float32(16.0 / 9.0) -width := min(size.Width-48, float32(520)) + {ID: "default", Title: "16:9 预览", Description: "页面盒子按调用方给出的宽度推导高度,内容仍是应用的页面子节点。", Snippet: `ratio := float32(16.0 / 9.0) +width := min(size.Width-48, float32(480)) height := components.AspectRatio(gfx.Rect{Width: width}, ratio).Height media := ui.Slot(c).Size(width, height) bounds := components.AspectRatio(media.Rect(), ratio) -canvas.Rounded(bounds, theme.Metrics.RadiusSurface, theme.Muted)`, PageSnippet: `ui.Column(c).FillWidth().MaxWidth(520).Height(293).Center(). - Radius(c.Theme().Metrics.RadiusSurface).Background(c.Theme().Muted).Children(func() { - ui.Text(c, "16:9 release preview").Muted() -})`, PageSnippetZh: `ui.Column(c).FillWidth().MaxWidth(520).Height(293).Center(). - Radius(c.Theme().Metrics.RadiusSurface).Background(c.Theme().Muted).Children(func() { - ui.Text(c, "16:9 发布预览").Muted() -})`}, - {ID: "square", Title: "方形封面", Description: "同一 API 使用 1:1 比例。", Snippet: `width := min(size.Width-48, float32(250)) +canvas.Rounded(bounds, theme.Metrics.RadiusSurface, theme.Muted)`, PageSnippet: `m.media.Ratio(16, 9) +aspectratioview.View(c, "16:9 release preview", m.media, func() { + ui.Column(c).Center().Radius(c.Theme().Metrics.RadiusSurface). + Background(c.Theme().Muted).Children(func() { + ui.Text(c, "16:9 release preview").Muted() + }) +}).FillWidth().MaxWidth(480)`, PageSnippetZh: `m.media.Ratio(16, 9) +aspectratioview.View(c, "16:9 发布预览", m.media, func() { + ui.Column(c).Center().Radius(c.Theme().Metrics.RadiusSurface). + Background(c.Theme().Muted).Children(func() { + ui.Text(c, "16:9 发布预览").Muted() + }) +}).FillWidth().MaxWidth(480)`}, + {ID: "square", Title: "方形封面", Description: "同一 API 改用 1:1 比例;没有为某种比例单独设构造函数。", Snippet: `width := min(size.Width-48, float32(240)) height := components.AspectRatio(gfx.Rect{Width: width}, 1).Height media := ui.Slot(c).Size(width, height) bounds := components.AspectRatio(media.Rect(), 1) -canvas.Rounded(bounds, theme.Metrics.RadiusSurface, theme.Muted)`, PageSnippet: `ui.Column(c).Size(250, 250).Center(). - Radius(c.Theme().Metrics.RadiusSurface).Background(c.Theme().Muted).Children(func() { - ui.Text(c, "1:1 cover").Muted() -})`, PageSnippetZh: `ui.Column(c).Size(250, 250).Center(). - Radius(c.Theme().Metrics.RadiusSurface).Background(c.Theme().Muted).Children(func() { - ui.Text(c, "1:1 封面").Muted() -})`}, +canvas.Rounded(bounds, theme.Metrics.RadiusSurface, theme.Muted)`, PageSnippet: `m.media.Ratio(1, 1) +aspectratioview.View(c, "1:1 cover", m.media, func() { + ui.Column(c).Center().Radius(c.Theme().Metrics.RadiusSurface). + Background(c.Theme().Muted).Children(func() { + ui.Text(c, "1:1 cover").Muted() + }) +}).FillWidth().MaxWidth(240)`, PageSnippetZh: `m.media.Ratio(1, 1) +aspectratioview.View(c, "1:1 封面", m.media, func() { + ui.Column(c).Center().Radius(c.Theme().Metrics.RadiusSurface). + Background(c.Theme().Muted).Children(func() { + ui.Text(c, "1:1 封面").Muted() + }) +}).FillWidth().MaxWidth(240)`}, }, } +// aspectRatioDemo is one example's ratio box. It is kept beside the State +// rather than rebuilt in each paint, so the layout is reused and a warm paint +// allocates nothing. +type aspectRatioDemo struct { + box aspectratioview.Box +} + +// aspectRatioDemos is keyed by State because the constrained demo model has no +// field for this example; a State is painted on one thread at a time. +var aspectRatioDemos = map[*State]*aspectRatioDemo{} + +func aspectRatioDemoFor(state *State) *aspectRatioDemo { + if demo := aspectRatioDemos[state]; demo != nil { + return demo + } + demo := &aspectRatioDemo{box: *aspectratioview.New()} + aspectRatioDemos[state] = demo + return demo +} + func (state *State) paintAspectRatio(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - maxWidth := float32(520) - ratio := float32(16.0 / 9.0) - title, heading := state.Text("16:9 发布预览", "16:9 release preview"), state.Text("Aspect Ratio · 16:9 发布预览", "Aspect Ratio · 16:9 release preview") + demo := aspectRatioDemoFor(state) + ratioWidth, ratioHeight, maxWidth := float32(16), float32(9), float32(480) + title := state.Text("16:9 发布预览", "16:9 release preview") if state.exampleID == "square" { - maxWidth, ratio = 250, 1 - title, heading = state.Text("1:1 封面", "1:1 cover"), state.Text("Aspect Ratio · 1:1 封面", "Aspect Ratio · 1:1 cover") + ratioWidth, ratioHeight, maxWidth = 1, 1, 240 + title = state.Text("1:1 封面", "1:1 cover") } - // The height follows from the width the page gives the slot: the width is - // the page's (the viewport less its padding, up to maxWidth) and - // components.AspectRatio turns it into the media rectangle. - width := min(size.Width-48, maxWidth) - height := min(components.AspectRatio(gfx.Rect{Width: width}, ratio).Height, size.Height-92) - var media ui.Box - state.drawPage(canvas, theme, size, maxWidth, heading, func(c ui.C) { - media = ui.Slot(c).Size(width, height) + demo.box.Ratio(ratioWidth, ratioHeight) + state.drawPage(canvas, theme, size, 520, title, func(c ui.C) { + aspectratioview.View(c, title, &demo.box, func() { + ui.Column(c).Center(). + Radius(theme.Metrics.RadiusSurface). + Background(theme.Muted). + Children(func() { + ui.Text(c, title).Muted() + }) + }).FillWidth().MaxWidth(maxWidth) }) - bounds := components.AspectRatio(media.Rect(), ratio) - canvas.Rounded(bounds, theme.Metrics.RadiusSurface, theme.Muted) - canvas.LabelCenter(title, bounds, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.MutedForeground}) } diff --git a/internal/componentdemo/badge.go b/internal/componentdemo/badge.go index bf215392..6163e82a 100644 --- a/internal/componentdemo/badge.go +++ b/internal/componentdemo/badge.go @@ -124,26 +124,27 @@ func (state *State) paintBadge(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Siz } variants = []components.BadgeVariant{components.BadgeSecondary, components.BadgeOutline, components.BadgeDefault} } - // A badge is as wide as its label. The grid's cell is as wide as the widest - // one, so the badges wrap onto new rows when the stage is too narrow for them - // side by side; each is a Slot of its natural size that the component paints. - cell := float32(0) - for _, label := range labels { - width, _ := components.BadgeExtent(canvas, theme, label) - cell = max(cell, width) - } - var slots [6]ui.Box state.drawPage(canvas, theme, size, 560, state.Text("Badge · 内容决定宽度", "Badge · Width follows content"), func(c ui.C) { - ui.Grid(c, cell).Gap(12).Children(func() { + ui.Flow(c).Gap(12).Children(func() { for index, label := range labels { - width, height := components.BadgeExtent(canvas, theme, label) - slots[index] = ui.Slot(c).Size(width, height).Self(ui.Start) + badge := ui.Badge(c, label) + switch variants[index] { + case components.BadgeSecondary: + badge.Secondary() + case components.BadgeDestructive: + badge.Destructive() + case components.BadgeOutline: + badge.Outline() + case components.BadgeGhost: + badge.Ghost() + case components.BadgeLink: + badge.Link() + } } }) - ui.Text(c, state.Text("仅展示状态,不声明点击区域。", "Display only; no click target is declared.")).FontSize(theme.Metrics.FontSizeS).Muted() + if state.exampleID == "default" { + ui.Text(c, state.Text("仅展示状态,不声明点击区域。", "Display only; no click target is declared.")). + FontSize(theme.Metrics.FontSizeS).Muted() + } }) - for index, label := range labels { - bounds := slots[index].Rect() - components.PaintBadge(canvas, theme, gfx.Rect{X: bounds.X, Y: bounds.Y}, label, variants[index]) - } } diff --git a/internal/componentdemo/image_view.go b/internal/componentdemo/image_view.go index 58ab959a..5d276b0c 100644 --- a/internal/componentdemo/image_view.go +++ b/internal/componentdemo/image_view.go @@ -1,35 +1,130 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/imageview" ) var imageViewComponent = Component{ ID: "image-view", Title: "Image View", Category: "Media", Summary: "按视口适配或按实际像素显示位图,与显示缩放无关。", - initialize: func(state *State) { - const w, h = 160, 100 - pix := make([]byte, w*h*4) - for y := range h { - for x := range w { - i := (y*w + x) * 4 - pix[i] = byte(x * 255 / w) - pix[i+1] = byte(y * 255 / h) - pix[i+2] = 100 - pix[i+3] = 255 - } - } - state.imageBitmap = &gfx.Bitmap{Pix: pix, Width: w, Height: h, Stride: w * 4, ID: 1, Version: 1} - }, - paint: func(state *State, canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var zoom float32 - if state.exampleID == "actual" { - zoom = 1 - } - components.PaintImageView(canvas, theme, gfx.Rect{X: 24, Y: 24, Width: max(0, size.Width-48), Height: max(0, size.Height-48)}, components.ImageViewOptions{Bitmap: *state.imageBitmap, Zoom: zoom}) - }, + initialize: (*State).initializeImageView, + paint: (*State).paintImageView, Examples: []Example{ - {ID: "fit", Title: "适配视口", Description: "应用提供已解码且有界的像素,组件只负责绘制。", Height: 260, Snippet: `components.PaintImageView(canvas, theme, bounds, components.ImageViewOptions{Bitmap: bitmap})`, PageSnippet: `ui.Image(c, m.bitmap).Fill()`, PageSnippetZh: `ui.Image(c, m.bitmap).Fill()`}, - {ID: "actual", Title: "一个图像像素对应一个设备像素", Description: "Zoom 1 在分数 DPI 缩放下保持实际像素尺寸。", Height: 260, Snippet: `components.PaintImageView(canvas, theme, bounds, components.ImageViewOptions{Bitmap: bitmap, Zoom: 1})`, PageSnippet: `ui.Image(c, m.bitmap).Size(float32(m.bitmap.Width), float32(m.bitmap.Height))`, PageSnippetZh: `ui.Image(c, m.bitmap).Size(float32(m.bitmap.Width), float32(m.bitmap.Height))`}, + {ID: "fit", Title: "适配视口", Description: "应用提供已解码且有界的像素;页面控件把整张图居中放进调用方给出的视口。", Height: 300, Snippet: `components.PaintImageView(canvas, theme, bounds, components.ImageViewOptions{Bitmap: bitmap})`, PageSnippet: `// m.bitmap is the caller-decoded 160 × 100 image. +m.picture.Reset().Bitmap(m.bitmap).Fit() +imageview.View(c, "Fit preview", m.picture).FillWidth().Height(240)`, PageSnippetZh: `// m.bitmap 是调用方已解码的 160 × 100 图像。 +m.picture.Reset().Bitmap(m.bitmap).Fit() +imageview.View(c, "适配预览", m.picture).FillWidth().Height(240)`}, + {ID: "actual", Title: "一个图像像素对应一个设备像素", Description: "Actual 在分数 DPI 缩放下保持实际像素尺寸;视口由页面用 Size 给出。", Height: 300, Snippet: `components.PaintImageView(canvas, theme, bounds, components.ImageViewOptions{Bitmap: bitmap, Zoom: 1})`, PageSnippet: `// m.bitmap is 160 × 100 bitmap pixels; Actual is one per device pixel. +m.picture.Reset().Bitmap(m.bitmap).Actual() +imageview.View(c, "Actual pixels", m.picture).Size(160, 100)`, PageSnippetZh: `// m.bitmap 是 160 × 100 位图像素;Actual 让一个位图像素对应一个设备像素。 +m.picture.Reset().Bitmap(m.bitmap).Actual() +imageview.View(c, "实际像素", m.picture).Size(160, 100)`}, + {ID: "zoom-pan", Title: "缩放与平移", Description: "显式 Zoom 与 Pan 让大图超出视口并由组件裁剪;Pointer 与 Scroll 交给应用处理拖动和滚轮缩放。", Height: 300, Snippet: `components.PaintImageView(canvas, theme, bounds, components.ImageViewOptions{ + Bitmap: bitmap, Zoom: 2, Pan: gfx.Point{X: 18, Y: -12}, +})`, PageSnippet: `// m.zoom and m.pan are the application's zoom and pan state. +m.picture.Reset().Bitmap(m.bitmap).Zoom(m.zoom).Pan(m.pan) +m.picture.Pointer = m.dragImage +m.picture.Scroll = m.zoomImage +imageview.View(c, "Zoom and pan", m.picture).FillWidth().Height(240)`, PageSnippetZh: `// m.zoom 和 m.pan 是应用的缩放与平移状态。 +m.picture.Reset().Bitmap(m.bitmap).Zoom(m.zoom).Pan(m.pan) +m.picture.Pointer = m.dragImage +m.picture.Scroll = m.zoomImage +imageview.View(c, "缩放与平移", m.picture).FillWidth().Height(240)`}, }, } + +func (state *State) initializeImageView() { + const w, h = 160, 100 + pix := make([]byte, w*h*4) + for y := range h { + for x := range w { + i := (y*w + x) * 4 + pix[i] = byte(x * 255 / w) + pix[i+1] = byte(y * 255 / h) + pix[i+2] = 100 + pix[i+3] = 255 + } + } + state.imageBitmap = &gfx.Bitmap{Pix: pix, Width: w, Height: h, Stride: w * 4, ID: 1, Version: 1} +} + +// imageViewDemo is one image example's page control and its drag/zoom state. It +// is kept beside the State rather than rebuilt in each paint, so the control's +// handlers and draw function are stable and a warm paint allocates nothing. +type imageViewDemo struct { + state *State + view imageview.Image + zoom float32 + pan gfx.Point + last gfx.Point + dragging bool +} + +// imageViewDemos is keyed by State because the constrained demo model has no +// field for this example; a State is painted on one thread at a time. +var imageViewDemos = map[*State]*imageViewDemo{} + +func imageViewDemoFor(state *State) *imageViewDemo { + if demo := imageViewDemos[state]; demo != nil { + return demo + } + demo := &imageViewDemo{state: state, zoom: 2, pan: gfx.Point{X: 18, Y: -12}} + demo.view.Pointer = demo.pointer + demo.view.Scroll = demo.scroll + imageViewDemos[state] = demo + return demo +} + +func (state *State) paintImageView(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := imageViewDemoFor(state) + state.drawPage(canvas, theme, size, 520, state.Text("图像视图", "Image View"), func(c ui.C) { + switch state.exampleID { + case "actual": + demo.view.Reset().Bitmap(*state.imageBitmap).Actual() + imageview.View(c, state.Text("实际像素", "Actual pixels"), &demo.view).Size(160, 100) + case "zoom-pan": + demo.view.Reset().Bitmap(*state.imageBitmap).Zoom(demo.zoom).Pan(demo.pan) + imageview.View(c, state.Text("缩放与平移", "Zoom and pan"), &demo.view).FillWidth().Height(240) + default: + demo.view.Reset().Bitmap(*state.imageBitmap).Fit() + imageview.View(c, state.Text("适配预览", "Fit preview"), &demo.view).FillWidth().Height(240) + } + }) +} + +// pointer drags the zoomed image. Only the zoom example shows it; the fitted +// and actual views leave pointer input to the page. +func (demo *imageViewDemo) pointer(event gfx.PointerEvent) gfx.EventResult { + if demo.state.exampleID != "zoom-pan" { + return gfx.EventResult{} + } + switch event.Kind { + case gfx.PointerDown: + demo.dragging = true + demo.last = gfx.Point{X: event.X, Y: event.Y} + return gfx.EventResult{Handled: true} + case gfx.PointerMove: + if !demo.dragging && !event.Captured { + return gfx.EventResult{} + } + demo.pan.X += event.X - demo.last.X + demo.pan.Y += event.Y - demo.last.Y + demo.last = gfx.Point{X: event.X, Y: event.Y} + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.PointerUp: + demo.dragging = false + return gfx.EventResult{Handled: true} + } + return gfx.EventResult{} +} + +// scroll zooms the zoom example between 50% and 400%. +func (demo *imageViewDemo) scroll(event gfx.ScrollEvent) gfx.EventResult { + if demo.state.exampleID != "zoom-pan" { + return gfx.EventResult{} + } + demo.zoom = min(max(demo.zoom-event.DeltaY*0.01, 0.5), 4) + return gfx.EventResult{Handled: true, Repaint: true} +} diff --git a/internal/componentdemo/input_group.go b/internal/componentdemo/input_group.go index 71c532c2..9b3fe72c 100644 --- a/internal/componentdemo/input_group.go +++ b/internal/componentdemo/input_group.go @@ -5,6 +5,7 @@ import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/text" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/inputgroupview" ) var inputGroupComponent = Component{ @@ -25,11 +26,17 @@ var inputGroupComponent = Component{ Icon: clearIcon, ButtonSize: components.InputGroupButtonIconXS, Label: "Clear domain", }, -})`, PageSnippet: `domain := "viva.dev" -ui.TextField(c, &domain, "Project domain", "project-name"). - Action(m.clearIcon, "Clear domain")`, PageSnippetZh: `domain := "viva.dev" -ui.TextField(c, &domain, "Project domain", "project-name"). - Action(m.clearIcon, "Clear domain")`}, +})`, PageSnippet: `// m.domain starts as "viva.dev". +group := inputgroupview.New(&m.domain). + Placeholder("project-name"). + Prefix("https://"). + Action(m.clearID, m.crossIcon, "Clear domain", m.clearDomain) +group.View(c, "Project domain").FillWidth()`, PageSnippetZh: `// m.domain 初始为 "viva.dev"。 +group := inputgroupview.New(&m.domain). + Placeholder("project-name"). + Prefix("https://"). + Action(m.clearID, m.crossIcon, "清除域名", m.clearDomain) +group.View(c, "Project domain").FillWidth()`}, {ID: "addons", Title: "块级附加项", Description: "块级说明、键帽和多行控制槽。", Snippet: `components.PaintInputGroup(canvas, theme, bounds, components.InputGroupSnapshot{ ID: tree.ID(page, "description"), Label: "Release description", Value: value, Multiline: true, @@ -40,9 +47,17 @@ ui.TextField(c, &domain, "Project domain", "project-name"). BlockEnd: components.InputGroupSlot{ Kind: components.InputGroupSlotKbd, Text: "⌘↵", }, -})`, PageSnippet: `description := "Ship the component gallery.\nAdd the keyboard shortcuts." -ui.TextArea(c, &description, "Release description", "").Height(128)`, PageSnippetZh: `description := "Ship the component gallery.\nAdd the keyboard shortcuts." -ui.TextArea(c, &description, "Release description", "").Height(128)`}, +})`, PageSnippet: `// m.description starts as "Ship the component gallery.\nAdd the keyboard shortcuts." +group := inputgroupview.New(&m.description). + Multiline(). + BlockStart("Release description"). + BlockKbd("⌘↵") +group.View(c, "Release description").FillWidth()`, PageSnippetZh: `// m.description 初始为 "发布组件画廊。\n补充键盘快捷键。"。 +group := inputgroupview.New(&m.description). + Multiline(). + BlockStart("发布说明"). + BlockKbd("⌘↵") +group.View(c, "Release description").FillWidth()`}, {ID: "buttons", Title: "图标按钮与加载", Description: "icon-xs / icon-sm 按钮切换密码可见,以及 Spinner 附加槽。", Snippet: `reveal := tree.ID(page, "reveal") components.PaintInputGroup(canvas, theme, bounds, components.InputGroupSnapshot{ ID: tree.ID(page, "password"), Label: "Password", Value: value, @@ -54,21 +69,27 @@ components.PaintInputGroup(canvas, theme, bounds, components.InputGroupSnapshot{ }) if canvas.Clicked(reveal) { revealed = !revealed -}`, PageSnippet: `password := "viva.dev" -ui.TextField(c, &password, "Password", ""). - Secure().Action(m.eyeIcon, "Show password") -search := "viva" -ui.Row(c).Gap(8).Children(func() { - ui.TextField(c, &search, "Search", "").Grow(1) - ui.Spinner(c) -})`, PageSnippetZh: `password := "viva.dev" -ui.TextField(c, &password, "Password", ""). - Secure().Action(m.eyeIcon, "Show password") -search := "viva" -ui.Row(c).Gap(8).Children(func() { - ui.TextField(c, &search, "Search", "").Grow(1) - ui.Spinner(c) -})`}, +}`, PageSnippet: `// m.password starts as "viva.dev"; it is secure until m.reveal runs. +m.password.Secure = m.passwordHidden +password := inputgroupview.New(&m.password). + Action(m.revealID, m.eyeIcon, "Show password", m.reveal). + Small() +password.View(c, "Password").FillWidth() +// m.search starts as "viva". +search := inputgroupview.New(&m.search). + Prefix("Search"). + Spinner(m.spinnerPhase) +search.View(c, "Search").FillWidth()`, PageSnippetZh: `// m.password 初始为 "viva.dev";m.reveal 运行前保持密文。 +m.password.Secure = m.passwordHidden +password := inputgroupview.New(&m.password). + Action(m.revealID, m.eyeIcon, "显示密码", m.reveal). + Small() +password.View(c, "Password").FillWidth() +// m.search 初始为 "viva"。 +search := inputgroupview.New(&m.search). + Prefix("搜索"). + Spinner(m.spinnerPhase) +search.View(c, "Search").FillWidth()`}, {ID: "states", Title: "输入状态", Description: "无效与禁用快照保留完整语义。", Snippet: `invalid := components.InputGroupSnapshot{ ID: tree.ID(page, "email"), Label: "Project domain", Value: value, Invalid: true, @@ -85,17 +106,25 @@ locked := components.InputGroupSnapshot{ ID: tree.ID(page, "locked"), Label: "Project domain", Value: "locked", Disabled: true, } -components.PaintInputGroup(canvas, theme, lockedBounds, locked)`, PageSnippet: `// m.email starts as "viva.dev". +components.PaintInputGroup(canvas, theme, lockedBounds, locked)`, PageSnippet: `// m.email starts as "viva.dev"; m.locked starts as "locked". m.email.Invalid = true -ui.TextFieldID(c, ui.ID(c), &m.email, "Project domain", "") -// m.locked starts as "locked". +email := inputgroupview.New(&m.email). + Prefix("@"). + Button(m.inviteID, "Invite", m.invite). + DisableAction() +email.View(c, "Project domain").FillWidth() m.locked.Disabled = true -ui.TextFieldID(c, ui.ID(c), &m.locked, "Project domain", "")`, PageSnippetZh: `// m.email starts as "viva.dev". +locked := inputgroupview.New(&m.locked) +locked.View(c, "Project domain").FillWidth()`, PageSnippetZh: `// m.email 初始为 "viva.dev";m.locked 初始为 "locked"。 m.email.Invalid = true -ui.TextFieldID(c, ui.ID(c), &m.email, "Project domain", "") -// m.locked starts as "locked". +email := inputgroupview.New(&m.email). + Prefix("@"). + Button(m.inviteID, "Invite", m.invite). + DisableAction() +email.View(c, "Project domain").FillWidth() m.locked.Disabled = true -ui.TextFieldID(c, ui.ID(c), &m.locked, "Project domain", "")`}, +locked := inputgroupview.New(&m.locked) +locked.View(c, "Project domain").FillWidth()`}, }, } @@ -128,14 +157,94 @@ func inputGroupInitial(exampleID string) string { return "viva.dev" } -func (state *State) initializeInputGroup() { state.flags |= 1 } +// inputGroupDemo is one example's page controls, fields and stable callbacks. +// They are kept beside the State rather than rebuilt in each paint, so the +// handlers and draw functions are stable and a warm paint allocates nothing. +type inputGroupDemo struct { + group *inputgroupview.Group + search *inputgroupview.Group + locked *inputgroupview.Group -// clearInputGroup is the clear button's action. Without editing it only toggles -// the snapshot's text; with it, it empties the editor and fills it back in when -// it is already empty. + field ui.Field + searchField ui.Field + lockedField ui.Field + + clear func() + reveal func() + bound bool +} + +// inputGroupDemos is keyed by State because the constrained demo model has no +// field for these controls; a State is painted on one thread at a time. +var inputGroupDemos = map[*State]*inputGroupDemo{} + +func (state *State) initializeInputGroup() { + state.flags |= 1 + demo := &inputGroupDemo{} + demo.clear = func() { state.clearInputGroup() } + demo.reveal = func() { state.flags ^= 2 } + demo.field.SetText(inputGroupInitial(state.exampleID)) + switch state.exampleID { + case "addons": + demo.group = inputgroupview.New(&demo.field). + FieldID(inputGroupField). + Multiline(). + BlockStart("Release description"). + BlockKbd("⌘↵") + case "buttons": + demo.group = inputgroupview.New(&demo.field). + FieldID(inputGroupField). + Action(inputGroupReveal, inputGroupEyeIcon, "Show password", demo.reveal). + Small() + demo.searchField.SetText("viva") + demo.search = inputgroupview.New(&demo.searchField). + FieldID(inputGroupSearchID). + Prefix("Search"). + Spinner(0) + case "states": + demo.group = inputgroupview.New(&demo.field). + FieldID(inputGroupField). + Prefix("@"). + Button(inputGroupInvite, "Invite", nil). + DisableAction() + demo.lockedField.SetText("locked") + demo.lockedField.Disabled = true + demo.locked = inputgroupview.New(&demo.lockedField). + FieldID(inputGroupLocked) + default: + demo.group = inputgroupview.New(&demo.field). + FieldID(inputGroupField). + Placeholder("project-name"). + Prefix("https://"). + Action(inputGroupClear, inputGroupCrossIcon, "Clear domain", demo.clear) + } + inputGroupDemos[state] = demo +} + +func inputGroupDemoFor(state *State) *inputGroupDemo { + if demo := inputGroupDemos[state]; demo != nil { + return demo + } + demo := &inputGroupDemo{} + demo.clear = func() { state.clearInputGroup() } + demo.reveal = func() { state.flags ^= 2 } + demo.field.SetText(inputGroupInitial(state.exampleID)) + inputGroupDemos[state] = demo + return demo +} + +// clearInputGroup is the clear button's action. Without editing it toggles the +// field's text; with editing it empties the editor and fills it back in when it +// is already empty. func (state *State) clearInputGroup() { if !state.editing { state.flags ^= 1 + demo := inputGroupDemoFor(state) + if state.flags&1 != 0 { + demo.field.SetText(inputGroupInitial(state.exampleID)) + } else { + demo.field.SetText("") + } return } value := "" @@ -147,76 +256,38 @@ func (state *State) clearInputGroup() { } func (state *State) paintInputGroup(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - height := theme.Metrics.ControlHeight - if state.exampleID == "addons" { - // A 32px block add-on above and below, and a 64px multiline control. - height = theme.Metrics.ControlHeight * 4 - } - var group, locked, searching ui.Box - state.drawPage(canvas, theme, size, 560, state.Text("Input Group · 附加槽", "Input Group · Add-on slots"), func(c ui.C) { - group = ui.Slot(c).FillWidth().Height(height) - if state.exampleID == "states" { - locked = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) - } - if state.exampleID == "buttons" { - searching = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) - } - }) - value := state.fieldValue("") - if !state.editing && state.flags&1 != 0 { - value = inputGroupInitial(state.exampleID) - } - snapshot := components.InputGroupSnapshot{ID: inputGroupField, Label: "Project domain", Value: value, Placeholder: "project-name", - ReadOnly: !state.editing, HideEditorText: true, InlineStart: components.InputGroupSlot{Kind: components.InputGroupSlotText, Text: "https://", Separated: true}, InlineEnd: components.InputGroupSlot{Kind: components.InputGroupSlotButton, ID: inputGroupClear, Icon: inputGroupCrossIcon, ButtonSize: components.InputGroupButtonIconXS, Label: "Clear domain"}} - if state.editing && state.editor != nil && canvas.Focused() == inputGroupField { - selection := state.editor.Selection() - snapshot.SelectionStart, snapshot.SelectionEnd = byteOffsetOfRune(value, selection.Start), byteOffsetOfRune(value, selection.End) - snapshot.Caret = byteOffsetOfRune(value, state.editor.Caret()) - snapshot.ShowCaret = selection.Start == selection.End - snapshot.Blink = &state.blink - if marked, composing := state.editor.Composition(); composing { - snapshot.CompositionStart, snapshot.CompositionEnd = byteOffsetOfRune(value, marked.Start), byteOffsetOfRune(value, marked.End) - } - } - if state.exampleID == "addons" { - snapshot.Multiline = true - // The description is not a domain: no "https://" in front of it. - snapshot.InlineStart = components.InputGroupSlot{} - snapshot.BlockStart = components.InputGroupSlot{Kind: components.InputGroupSlotText, Text: "Release description", Separated: true} - snapshot.BlockEnd = components.InputGroupSlot{Kind: components.InputGroupSlotKbd, Text: "⌘↵"} - } - if state.exampleID == "buttons" { - // A secret with a reveal button, and a field that is searching. - snapshot.Secure = state.flags&2 == 0 - snapshot.InlineStart = components.InputGroupSlot{} - snapshot.InlineEnd = components.InputGroupSlot{Kind: components.InputGroupSlotButton, ID: inputGroupReveal, Icon: inputGroupEyeIcon, ButtonSize: components.InputGroupButtonIconSM, Label: "Show password"} - } - if state.exampleID == "states" { - snapshot.Invalid = true - snapshot.InlineStart = components.InputGroupSlot{Kind: components.InputGroupSlotText, Text: "@", Separated: true} - snapshot.InlineEnd = components.InputGroupSlot{Kind: components.InputGroupSlotButton, ID: inputGroupInvite, Text: "Invite", Disabled: true} - } - components.PaintInputGroup(canvas, theme, group.Rect(), snapshot) - if canvas.Clicked(inputGroupClear) { - state.clearInputGroup() + demo := inputGroupDemoFor(state) + if state.editing && state.editor != nil && !demo.bound { + demo.field.Bind(state.editor) + demo.bound = true } - if canvas.Clicked(inputGroupReveal) { - state.flags ^= 2 + if state.editing { + demo.group.Editable() + } else { + demo.group.ReadOnly() } if state.exampleID == "buttons" { - components.PaintInputGroup(canvas, theme, searching.Rect(), components.InputGroupSnapshot{ - ID: inputGroupSearchID, Label: "Search", Value: "viva", ReadOnly: true, - InlineStart: components.InputGroupSlot{Kind: components.InputGroupSlotText, Text: "Search"}, - InlineEnd: components.InputGroupSlot{Kind: components.InputGroupSlotSpinner, Phase: components.SpinnerPhase(state.values[1] & 7)}, - }) + demo.field.Secure = state.flags&2 == 0 + demo.search.ReadOnly() + demo.search.Spinner(components.SpinnerPhase(state.values[1] & 7)) } if state.exampleID == "states" { - disabled := snapshot - disabled.ID = inputGroupLocked - disabled.Invalid = false - disabled.Disabled = true - disabled.Value = "locked" - disabled.InlineEnd.ID = gfx.ID{} - components.PaintInputGroup(canvas, theme, locked.Rect(), disabled) + demo.field.Invalid = true } + state.drawPage(canvas, theme, size, 560, state.Text("Input Group · 附加槽", "Input Group · Add-on slots"), func(c ui.C) { + switch state.exampleID { + case "addons": + demo.group.View(c, "Release description").FillWidth() + case "buttons": + demo.group.View(c, "Password").FillWidth() + demo.search.View(c, "Search").FillWidth() + case "states": + ui.Column(c).Gap(theme.Metrics.GapItem).Children(func() { + demo.group.View(c, "Project domain").FillWidth() + demo.locked.View(c, "Project domain").FillWidth() + }) + default: + demo.group.View(c, "Project domain").FillWidth() + } + }) } diff --git a/internal/componentdemo/input_otp.go b/internal/componentdemo/input_otp.go index ab911b8c..f6a0a2e3 100644 --- a/internal/componentdemo/input_otp.go +++ b/internal/componentdemo/input_otp.go @@ -1,9 +1,9 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/inputotpview" ) var inputOTPComponent = Component{ @@ -20,20 +20,40 @@ var inputOTPComponent = Component{ ID: tree.ID(page, "code"), Label: "Verification code", Value: code, Slots: 6, GroupSize: 3, HasActiveSlot: true, ActiveSlot: min(len(code), 5), ShowCaret: true, -})`, PageSnippet: `code := "482" -ui.TextField(c, &code, "Verification code", "000000")`, PageSnippetZh: `code := "482" -ui.TextField(c, &code, "Verification code", "000000")`}, +})`, PageSnippet: `// m.codeEditor starts as "482"; m.codeField is bound to it. +code := inputotpview.New(). + Bind(&m.codeField, m.codeEditor). + Slots(6). + GroupSize(3). + Filter(inputotpview.Digits) +code.View(c, "Verification code")`, PageSnippetZh: `// m.codeEditor 初始为 "482";m.codeField 已绑定到它。 +code := inputotpview.New(). + Bind(&m.codeField, m.codeEditor). + Slots(6). + GroupSize(3). + Filter(inputotpview.Digits) +code.View(c, "Verification code")`}, {ID: "states", Title: "验证码状态", Description: "选择、输入法组合与错误状态。", Snippet: `components.PaintInputOTP(canvas, theme, bounds, components.InputOTPSnapshot{ ID: tree.ID(page, "code"), Label: "Verification code", Value: "482901", Slots: 6, GroupSize: 3, Invalid: true, Focused: true, ShowCaret: true, HasSelection: true, SelectionStart: 1, SelectionEnd: 3, HasComposition: true, CompositionStart: 3, CompositionEnd: 5, ActiveSlot: 0, -})`, PageSnippet: `// m.code starts as "482901". -m.code.Invalid = true -ui.TextFieldID(c, ui.ID(c), &m.code, "Verification code", "000000")`, PageSnippetZh: `// m.code 初始为 "482901"。 -m.code.Invalid = true -ui.TextFieldID(c, ui.ID(c), &m.code, "Verification code", "000000")`}, +})`, PageSnippet: `// m.codeEditor starts as "482901" with slots 1–3 selected. +m.codeEditor.SetSelection(text.Range{Start: 1, End: 3}) +code := inputotpview.New(). + Bind(&m.codeField, m.codeEditor). + Slots(6). + GroupSize(3). + Invalid() +code.View(c, "Verification code")`, PageSnippetZh: `// m.codeEditor 初始为 "482901",槽位 1–3 选中。 +m.codeEditor.SetSelection(text.Range{Start: 1, End: 3}) +code := inputotpview.New(). + Bind(&m.codeField, m.codeEditor). + Slots(6). + GroupSize(3). + Invalid() +code.View(c, "Verification code")`}, }, } @@ -56,100 +76,98 @@ func inputOTPInitial(exampleID string) string { return "482901" } -// initializeInputOTP places the static (not editable) default example's active -// slot at the first empty one. +// inputOTPDemo is one example's page control, field and stable state. It is +// kept beside the State rather than rebuilt in each paint, so the handlers and +// draw function are stable and a warm paint allocates nothing. +type inputOTPDemo struct { + view *inputotpview.OTP + field ui.Field + bound bool +} + +// inputOTPDemos is keyed by State because the constrained demo model has no +// field for this control; a State is painted on one thread at a time. +var inputOTPDemos = map[*State]*inputOTPDemo{} + func (state *State) initializeInputOTP() { if state.exampleID == "default" { state.values[0] = int32(len(inputOTPInitial("default"))) } + demo := &inputOTPDemo{ + view: inputotpview.New(). + FieldID(inputOTPField). + Slots(inputOTPSlots). + GroupSize(3), + } + if state.exampleID == "states" { + demo.view.Value("482901").Invalid().Focused().ActiveSlot(0). + Select(1, 3).Composition(3, 5) + } + inputOTPDemos[state] = demo +} + +func inputOTPDemoFor(state *State) *inputOTPDemo { + if demo := inputOTPDemos[state]; demo != nil { + return demo + } + demo := &inputOTPDemo{ + view: inputotpview.New(). + FieldID(inputOTPField). + Slots(inputOTPSlots). + GroupSize(3), + } + inputOTPDemos[state] = demo + return demo } // pointerInputOTP puts the caret on the slot that was clicked, or after the last // digit when the click is past the end of the code: the next digit typed fills -// that slot. +// that slot. The hit is the example's identity, so the page control is not the +// pointer's target; the view's SelectAt applies the slot geometry it painted. func (state *State) pointerInputOTP(event gfx.PointerEvent) gfx.EventResult { if !state.editing || event.Kind != gfx.PointerDown || event.Target != inputOTPField { return gfx.EventResult{} } - layout := state.inputOTPLayout(inputOTPLeft(pointerViewport(event).Width)) - slot := inputOTPSlots - 1 - for index := 0; index < inputOTPSlots; index++ { - bounds := layout.SlotBounds(index) - if event.X < bounds.X+bounds.Width { - slot = index - break - } + if inputOTPDemoFor(state).view.SelectAt(event.X) { + return gfx.EventResult{Repaint: true} } - caret := min(slot, state.editor.RuneCount()) - state.editor.SetSelection(textRange(caret, caret)) - return gfx.EventResult{Repaint: true} -} - -// inputOTPWidth is the widest the demo page gets; inputOTPLeft is where its -// content starts in a viewport of the given width (the page pads 24 and centers -// the column). The pointer callback needs the slot geometry without having -// painted, so it derives it the way the page lays it out. -const inputOTPWidth = 600 - -func inputOTPLeft(viewport float32) float32 { - return (viewport - min(viewport-48, inputOTPWidth)) / 2 -} - -// inputOTPLayout is the slot geometry for a code whose left edge is at x, shared -// by painting and by hit-testing a click to a slot. -func (state *State) inputOTPLayout(x float32) components.InputOTPLayout { - return components.PaintInputOTP(nil, state.themeFor(), gfx.Rect{X: x}, components.InputOTPSnapshot{Slots: inputOTPSlots, GroupSize: 3}) + return gfx.EventResult{} } func (state *State) paintInputOTP(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - measure := state.inputOTPLayout(0).Bounds - var code ui.Box - state.drawPage(canvas, theme, size, inputOTPWidth, state.Text("Input OTP · 验证码", "Input OTP · Verification code"), func(c ui.C) { - code = ui.Slot(c).Size(measure.Width, measure.Height).Self(ui.Start) + demo := inputOTPDemoFor(state) + if state.editing && state.editor != nil && !demo.bound { + demo.field.Bind(state.editor) + demo.view.Bind(&demo.field, state.editor) + demo.bound = true + } + if state.editing { + demo.view.Editable() + } else { + demo.view.ReadOnly() + } + if !state.editing { + switch state.exampleID { + case "default": + demo.view.Value(inputOTPInitial("default")).Focused().ShowCaret(). + ActiveSlot(int(state.values[0])) + case "states": + demo.view.Value(inputOTPInitial("states")).Invalid().Focused(). + ActiveSlot(0).Select(1, 3).Composition(3, 5) + } + } + state.drawPage(canvas, theme, size, 600, state.Text("Input OTP · 验证码", "Input OTP · Verification code"), func(c ui.C) { + demo.view.View(c, "Verification code") caption := "Slots: 6 · Groups: 3 + 3" if state.editing { caption = state.Text("只接受数字,最多 6 位 · 输入后自动前进 · 退格删除 · ← → 移动", "Digits only, up to 6 · advance as you type · backspace deletes · ← → moves") } ui.Paragraph(c, caption, 3).FontSize(theme.Metrics.FontSizeS).Muted() }) - bounds := code.Rect() - value := state.fieldValue(inputOTPInitial(state.exampleID)) - snapshot := components.InputOTPSnapshot{ - ID: inputOTPField, Label: "Verification code", Value: value, Slots: inputOTPSlots, GroupSize: 3, - ReadOnly: !state.editing, PlatformInput: state.editing, HasActiveSlot: true, ShowCaret: true, - } - if state.editing { - // The editor is the source of truth: the active slot is where the caret - // is, clamped to the last slot once the code is complete, and the - // selection and any composition come straight from it. - selection := state.editor.Selection() - snapshot.ActiveSlot = min(selection.Start, inputOTPSlots-1) - if selection.Start != selection.End { - snapshot.HasSelection, snapshot.SelectionStart, snapshot.SelectionEnd = true, selection.Start, selection.End - } - if composition, composing := state.editor.Composition(); composing { - snapshot.HasComposition, snapshot.CompositionStart, snapshot.CompositionEnd = true, composition.Start, composition.End - } - } else { - // A snapshot is shown focused so its ring and caret are visible. - snapshot.Focused = true - snapshot.ActiveSlot = int(state.values[0]) - } - if state.exampleID == "states" { - snapshot.Invalid = true - snapshot.HasSelection = true - snapshot.SelectionStart = 1 - snapshot.SelectionEnd = 3 - snapshot.HasComposition = true - snapshot.CompositionStart = 3 - snapshot.CompositionEnd = 5 - snapshot.ActiveSlot = 0 - } - components.PaintInputOTP(canvas, theme, gfx.Rect{X: bounds.X, Y: bounds.Y}, snapshot) - // Without editing the code is a static snapshot: a click moves its active slot - // along. With editing the editor owns the position (typing, arrows, a click on - // a slot: see pointerInputOTP). - if canvas.Clicked(inputOTPField) && !state.editing { + // Without editing the code is a static snapshot: a click moves its active + // slot along. With editing the editor owns the position (typing, arrows, a + // click on a slot: see pointerInputOTP). + if !state.editing && canvas.Clicked(inputOTPField) { state.values[0] = (state.values[0] + 1) % inputOTPSlots } } diff --git a/internal/componentdemo/marker.go b/internal/componentdemo/marker.go index 2654595b..cf5b78f0 100644 --- a/internal/componentdemo/marker.go +++ b/internal/componentdemo/marker.go @@ -1,9 +1,9 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/markerview" ) var markerComponent = Component{ @@ -12,59 +12,31 @@ var markerComponent = Component{ Examples: []Example{ {ID: "default", Title: "元数据", Description: "图标与文本组成的标准标记。", Snippet: `// m.clockIcon is a caller-owned gfx.Icon; a nil icon paints none. components.Marker(canvas, theme, bounds, components.MarkerDefault, - &m.clockIcon, "Updated 2 minutes ago")`, PageSnippet: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Icon(c, m.clockIcon).Size(16, 16).Muted() - ui.Text(c, "Updated 2 minutes ago").Muted() -})`, PageSnippetZh: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Icon(c, m.clockIcon).Size(16, 16).Muted() - ui.Text(c, "Updated 2 minutes ago").Muted() -})`}, + &m.clockIcon, "Updated 2 minutes ago")`, PageSnippet: `m.marker.Reset().Icon(m.clockIcon).Label("Updated 2 minutes ago") +m.marker.View(c, "Updated 2 minutes ago")`, PageSnippetZh: `m.marker.Reset().Icon(m.clockIcon).Label("Updated 2 minutes ago") +m.marker.View(c, "Updated 2 minutes ago")`}, {ID: "variants", Title: "三种形式", Description: "普通、居中分隔和底部边框形式。", Snippet: `// The separator centers its content between rules; the border draws one below. components.Marker(canvas, theme, bounds[0], components.MarkerDefault, &m.checkIcon, "Default") components.Marker(canvas, theme, bounds[1], components.MarkerSeparator, nil, "October 2026") components.Marker(canvas, theme, bounds[2], components.MarkerBorder, - &m.clockIcon, "Release channel")`, PageSnippet: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Icon(c, m.checkIcon).Size(16, 16).Muted() - ui.Text(c, "Default").Muted() -}) -ui.Row(c).Gap(10).Items(ui.Center).Children(func() { - ui.Column(c).Grow(1).Height(1).Background(c.Theme().Border) - ui.Text(c, "October 2026").Muted() - ui.Column(c).Grow(1).Height(1).Background(c.Theme().Border) -}) -ui.Column(c).Gap(6).Children(func() { - ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Icon(c, m.clockIcon).Size(16, 16).Muted() - ui.Text(c, "Release channel").Muted() - }) - ui.Divider(c) -})`, PageSnippetZh: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Icon(c, m.checkIcon).Size(16, 16).Muted() - ui.Text(c, "Default").Muted() -}) -ui.Row(c).Gap(10).Items(ui.Center).Children(func() { - ui.Column(c).Grow(1).Height(1).Background(c.Theme().Border) - ui.Text(c, "October 2026").Muted() - ui.Column(c).Grow(1).Height(1).Background(c.Theme().Border) -}) -ui.Column(c).Gap(6).Children(func() { - ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Icon(c, m.clockIcon).Size(16, 16).Muted() - ui.Text(c, "Release channel").Muted() - }) - ui.Divider(c) -})`}, - {ID: "progress", Title: "进行中", Description: "用 Spinner 代替图标表示正在进行的工作。", Snippet: `// Advance the phase from an animation frame and request the next paint. + &m.clockIcon, "Release channel")`, PageSnippet: `m.markers[0].Reset().Icon(m.checkIcon).Label("Default") +m.markers[0].View(c, "Default") +m.markers[1].Reset().Separator().Label("October 2026") +m.markers[1].View(c, "October 2026") +m.markers[2].Reset().Border().Icon(m.clockIcon).Label("Release channel") +m.markers[2].View(c, "Release channel")`, PageSnippetZh: `m.markers[0].Reset().Icon(m.checkIcon).Label("Default") +m.markers[0].View(c, "Default") +m.markers[1].Reset().Separator().Label("October 2026") +m.markers[1].View(c, "October 2026") +m.markers[2].Reset().Border().Icon(m.clockIcon).Label("Release channel") +m.markers[2].View(c, "Release channel")`}, + {ID: "progress", Title: "进行中", Description: "Spinner 取代图标表示正在进行的工作;调用方拥有相位和帧。", Snippet: `// Advance the phase from an animation frame and request the next paint. phase = (phase + 1) % 8 -components.MarkerProgress(canvas, theme, bounds, components.MarkerDefault, phase, "Thinking")`, PageSnippet: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Spinner(c) - ui.Text(c, "Thinking").Muted() -})`, PageSnippetZh: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Spinner(c) - ui.Text(c, "Thinking").Muted() -})`}, +components.MarkerProgress(canvas, theme, bounds, components.MarkerDefault, phase, "Thinking")`, PageSnippet: `m.marker.Reset().Progress(m.phase).Label("Thinking") +m.marker.View(c, "Thinking")`, PageSnippetZh: `m.marker.Reset().Progress(m.phase).Label("Thinking") +m.marker.View(c, "Thinking")`}, }, } @@ -90,31 +62,28 @@ func demoCircle(cx, cy, r float32) []gfx.PathCommand { } } +// markerDemo is the demo's reusable marker declaration. State cannot hold it +// without widening the preview model, so the demo keeps configured views and +// resets them in every paint; their handlers are made once. A view belongs to +// one place, so the variants example keeps one per row. The progress example +// shows a fixed frame: the demo schedules no frames, an application advances +// the phase. +var ( + markerDemo = markerview.New() + markerVariants [3]markerview.Marker +) + func (state *State) paintMarker(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var rows [3]ui.Box state.drawPage(canvas, theme, size, 560, state.Text("Marker · 内容分组", "Marker · Content grouping"), func(c ui.C) { - count := 3 - if state.exampleID != "variants" { - count = 1 - } - rowHeight := theme.Metrics.FontSizeM + 7 - for index := range count { - height := rowHeight - if state.exampleID == "variants" && index == 2 { - height += 8*(theme.Metrics.ControlHeight/32) + 1 // MarkerBorder's rule - } - rows[index] = ui.Slot(c).FillWidth().Height(height) + switch state.exampleID { + case "default": + markerDemo.Reset().Icon(markerClockIcon).Label("Updated 2 minutes ago").View(c, "Updated 2 minutes ago") + case "progress": + markerDemo.Reset().Progress(2).Label("Thinking").View(c, "Thinking") + default: + markerVariants[0].Reset().Icon(markerCheckIcon).Label("Default").View(c, "Default") + markerVariants[1].Reset().Separator().Label("October 2026").View(c, "October 2026") + markerVariants[2].Reset().Border().Icon(markerClockIcon).Label("Release channel").View(c, "Release channel") } }) - switch state.exampleID { - case "default": - components.Marker(canvas, theme, rows[0].Rect(), components.MarkerDefault, &markerClockIcon, "Updated 2 minutes ago") - case "progress": - // A fixed frame: the demo does not schedule frames, an application turns the phase. - components.MarkerProgress(canvas, theme, rows[0].Rect(), components.MarkerDefault, 2, "Thinking") - default: - components.Marker(canvas, theme, rows[0].Rect(), components.MarkerDefault, &markerCheckIcon, "Default") - components.Marker(canvas, theme, rows[1].Rect(), components.MarkerSeparator, nil, "October 2026") - components.Marker(canvas, theme, rows[2].Rect(), components.MarkerBorder, &markerClockIcon, "Release channel") - } } diff --git a/internal/componentdemo/metric_card.go b/internal/componentdemo/metric_card.go index d7624b0f..cdf02a24 100644 --- a/internal/componentdemo/metric_card.go +++ b/internal/componentdemo/metric_card.go @@ -1,87 +1,56 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/metriccardview" ) var metricCardComponent = Component{ ID: "metric-card", Title: "Metric Card", Category: "Data Display", Summary: "标题、数值和趋势组成的仪表盘指标卡。", paint: (*State).paintMetricCard, Examples: []Example{ - {ID: "default", Title: "单项指标", Description: "生产 MetricCard 展示当前值与正向趋势。", Snippet: `// bounds is the dashboard slot reserved for the card. + {ID: "default", Title: "单项指标", Description: "生产 MetricCard 展示当前值、正向趋势、周期说明和图标。", Snippet: `// bounds is the dashboard slot reserved for the card. components.MetricCard(canvas, theme, bounds, "Active sessions", - "12,840", "+18.2% from last week", true)`, PageSnippet: `ui.Column(c).FillWidth().Pad(c.Theme().Metrics.PadSurface).Gap(6). - Background(c.Theme().Card).Border(1, c.Theme().Border). - Radius(c.Theme().Metrics.RadiusSurface).Children(func() { - ui.Text(c, "Active sessions"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() - ui.Text(c, "12,840"). - FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) - ui.Text(c, "+18.2% from last week"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Success) -})`, PageSnippetZh: `ui.Column(c).FillWidth().Pad(c.Theme().Metrics.PadSurface).Gap(6). - Background(c.Theme().Card).Border(1, c.Theme().Border). - Radius(c.Theme().Metrics.RadiusSurface).Children(func() { - ui.Text(c, "Active sessions"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() - ui.Text(c, "12,840"). - FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) - ui.Text(c, "+18.2% from last week"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Success) -})`}, + "12,840", "+18.2% from last week", true)`, PageSnippet: `metriccardview.View(c, "Active sessions", metriccardview.New(). + Title("Active sessions").Value("12,840"). + Trend("+18.2% from last week").Up(). + Description("Compared with the previous 7 days"). + Icon(m.metricIcon)). + FillWidth().Height(150)`, PageSnippetZh: `metriccardview.View(c, "Active sessions", metriccardview.New(). + Title("Active sessions").Value("12,840"). + Trend("+18.2% from last week").Up(). + Description("Compared with the previous 7 days"). + Icon(m.metricIcon)). + FillWidth().Height(150)`}, {ID: "trends", Title: "趋势对比", Description: "正向和负向趋势并列展示。", Snippet: `// left and right are equal-width slots in the page's row. // true paints the trend in Success; false paints it in Danger. components.MetricCard(canvas, theme, left, "Revenue", "$48.2K", "+12.4%", true) components.MetricCard(canvas, theme, right, "Refunds", "$1.3K", "+4.1%", false)`, PageSnippet: `ui.Row(c).FillWidth().Gap(16).Children(func() { - ui.Column(c).Grow(1).Pad(c.Theme().Metrics.PadSurface).Gap(6). - Background(c.Theme().Card).Border(1, c.Theme().Border). - Radius(c.Theme().Metrics.RadiusSurface).Children(func() { - ui.Text(c, "Revenue"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() - ui.Text(c, "$48.2K"). - FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) - ui.Text(c, "+12.4%"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Success) - }) - ui.Column(c).Grow(1).Pad(c.Theme().Metrics.PadSurface).Gap(6). - Background(c.Theme().Card).Border(1, c.Theme().Border). - Radius(c.Theme().Metrics.RadiusSurface).Children(func() { - ui.Text(c, "Refunds"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() - ui.Text(c, "$1.3K"). - FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) - ui.Text(c, "+4.1%"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Danger) - }) + metriccardview.View(c, "Revenue", metriccardview.New(). + Title("Revenue").Value("$48.2K").Trend("+12.4%").Up()). + Grow(1).Height(120) + metriccardview.View(c, "Refunds", metriccardview.New(). + Title("Refunds").Value("$1.3K").Trend("+4.1%").Down()). + Grow(1).Height(120) })`, PageSnippetZh: `ui.Row(c).FillWidth().Gap(16).Children(func() { - ui.Column(c).Grow(1).Pad(c.Theme().Metrics.PadSurface).Gap(6). - Background(c.Theme().Card).Border(1, c.Theme().Border). - Radius(c.Theme().Metrics.RadiusSurface).Children(func() { - ui.Text(c, "Revenue"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() - ui.Text(c, "$48.2K"). - FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) - ui.Text(c, "+12.4%"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Success) - }) - ui.Column(c).Grow(1).Pad(c.Theme().Metrics.PadSurface).Gap(6). - Background(c.Theme().Card).Border(1, c.Theme().Border). - Radius(c.Theme().Metrics.RadiusSurface).Children(func() { - ui.Text(c, "Refunds"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Muted() - ui.Text(c, "$1.3K"). - FontSize(c.Theme().Metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) - ui.Text(c, "+4.1%"). - FontSize(c.Theme().Metrics.FontSizeS).Weight(gfx.WeightMedium).Color(c.Theme().Danger) - }) + metriccardview.View(c, "Revenue", metriccardview.New(). + Title("Revenue").Value("$48.2K").Trend("+12.4%").Up()). + Grow(1).Height(120) + metriccardview.View(c, "Refunds", metriccardview.New(). + Title("Refunds").Value("$1.3K").Trend("+4.1%").Down()). + Grow(1).Height(120) })`}, }, } +// metricTrendIcon is Lucide's trending-up arrow, compiled to the gfx.Icon form. +var metricTrendIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(3, 17), gfx.LineTo(9, 11), gfx.LineTo(13, 15), gfx.LineTo(21, 7), + gfx.MoveTo(15, 7), gfx.LineTo(21, 7), gfx.LineTo(21, 13), +}} + func (state *State) paintMetricCard(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var cards [2]ui.Box // Two cards share a row when the page is wide enough for both; otherwise // the second example stacks them. wide := state.exampleID == "trends" && min(size.Width-48, float32(600)) >= 480 @@ -89,24 +58,28 @@ func (state *State) paintMetricCard(canvas *gfx.Canvas, theme gfx.Theme, size gf switch { case wide: ui.Row(c).FillWidth().Gap(16).Children(func() { - cards[0] = ui.Slot(c).Grow(1).Height(120) - cards[1] = ui.Slot(c).Grow(1).Height(120) + metriccardview.View(c, "Revenue", metriccardview.New(). + Title("Revenue").Value("$48.2K").Trend("+12.4%").Up()). + Grow(1).Height(120) + metriccardview.View(c, "Refunds", metriccardview.New(). + Title("Refunds").Value("$1.3K").Trend("+4.1%").Down()). + Grow(1).Height(120) }) case state.exampleID == "trends": - cards[0] = ui.Slot(c).FillWidth().Height(120) - cards[1] = ui.Slot(c).FillWidth().Height(120) + metriccardview.View(c, "Active sessions", metriccardview.New(). + Title("Active sessions").Value("12,840"). + Trend("+18.2% from last week").Up()). + FillWidth().Height(120) + metriccardview.View(c, "Error rate", metriccardview.New(). + Title("Error rate").Value("0.42%").Trend("-0.08% improvement").Up()). + FillWidth().Height(120) default: - cards[0] = ui.Slot(c).FillWidth().Height(120) + metriccardview.View(c, "Active sessions", metriccardview.New(). + Title("Active sessions").Value("12,840"). + Trend("+18.2% from last week").Up(). + Description("Compared with the previous 7 days"). + Icon(metricTrendIcon)). + FillWidth().Height(150) } }) - switch { - case wide: - components.MetricCard(canvas, theme, cards[0].Rect(), "Revenue", "$48.2K", "+12.4%", true) - components.MetricCard(canvas, theme, cards[1].Rect(), "Refunds", "$1.3K", "+4.1%", false) - case state.exampleID == "trends": - components.MetricCard(canvas, theme, cards[0].Rect(), "Active sessions", "12,840", "+18.2% from last week", true) - components.MetricCard(canvas, theme, cards[1].Rect(), "Error rate", "0.42%", "-0.08% improvement", true) - default: - components.MetricCard(canvas, theme, cards[0].Rect(), "Active sessions", "12,840", "+18.2% from last week", true) - } } diff --git a/internal/componentdemo/page_source.go b/internal/componentdemo/page_source.go index 0509075d..7923d39d 100644 --- a/internal/componentdemo/page_source.go +++ b/internal/componentdemo/page_source.go @@ -70,25 +70,25 @@ var pageSource = map[string]string{ "avatar-editor": "ui/avatareditorview/avatareditorview.go", "reorder-grid": "ui/reordergridview/reordergridview.go", "alert": "base/box.go", - "aspect-ratio": "base/box.go", + "aspect-ratio": "ui/aspectratioview/aspectratioview.go", "attachment": "ui/attachmentview/attachmentview.go", "avatar": "ui/avatarview/avatarview.go", "breadcrumb": "base/elements.go", "button-group": "base/controls.go", "command": "ui/commandview/commandview.go", "icon-hover": "base/icon_motion.go", - "image-view": "base/elements.go", - "input-group": "base/field.go", - "input-otp": "base/field.go", - "marker": "base/elements.go", + "image-view": "ui/imageview/imageview.go", + "input-group": "ui/inputgroupview/inputgroupview.go", + "input-otp": "ui/inputotpview/inputotpview.go", + "marker": "ui/markerview/markerview.go", "menubar": "ui/menubarview/menubarview.go", "message": "ui/messageview/messageview.go", "message-scroller": "ui/messagescrollerview/messagescrollerview.go", - "metric-card": "base/box.go", + "metric-card": "ui/metriccardview/metriccardview.go", "navigation-menu": "ui/navigationmenuview/navigationmenuview.go", - "questionnaire": "base/radio.go", + "questionnaire": "ui/questionnaireview/questionnaireview.go", "reorder-list": "base/list_reorder.go", "segmented-control": "base/elements.go", - "sidebar": "base/list.go", - "skeleton": "base/box.go", + "sidebar": "ui/sidebarview/sidebarview.go", + "skeleton": "ui/skeletonview/skeletonview.go", } diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index d5dd2f93..676bf6d2 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -80,24 +80,24 @@ ui.Table(c, &m.table, ui.TableSpec{ "avatar-editor": `m.avatarEditor.View(c, "Image crop").FillWidth().MaxWidth(440)`, "reorder-grid": `m.reorderGrid.View(c, "Host order").FillWidth().Height(220)`, "alert": `ui.Row(c).FillWidth().Pad(14).Gap(10).Background(c.Theme().Card).Border(1, c.Theme().Border).Children(func() { ui.Text(c, "Sync complete").Bold() })`, - "aspect-ratio": `ui.Column(c).FillWidth().MaxWidth(520).Height(293).Center().Radius(c.Theme().Metrics.RadiusSurface).Background(c.Theme().Muted)`, + "aspect-ratio": `aspectratioview.View(c, "16:9 release preview", m.media, func() { ui.Text(c, "16:9 release preview").Muted() })`, "attachment": `m.attachment.View(c, "product-demo.mov").FillWidth()`, "avatar": `m.avatar.View(c, "Skyler").Size(64, 64)`, "breadcrumb": `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { ui.Text(c, "Workspace").Muted(); ui.Text(c, "›").Muted(); ui.Text(c, "Preview") })`, "button-group": `ui.Row(c).Children(func() { ui.Button(c, "Left").Outline(); ui.Button(c, "Center").Outline(); ui.Button(c, "Right").Outline() })`, "command": `commandview.View(c, "Command", &m.command).FillWidth().Height(220)`, "icon-hover": `id := ui.ID(c); ui.Icon(c, m.moreIcon).Size(24, 24).Hit(id, "More actions").BindIconHover(ui.BindIconHover(&m.iconHover, id))`, - "image-view": `ui.Image(c, m.bitmap).Fill()`, - "input-group": `ui.TextField(c, &m.domain, "Project domain", "project-name").Action(m.clearIcon, "Clear domain")`, - "input-otp": `ui.TextField(c, &m.code, "Verification code", "000000")`, - "marker": `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { ui.Icon(c, m.clockIcon).Size(16, 16).Muted(); ui.Text(c, "Updated 2 minutes ago").Muted() })`, + "image-view": `imageview.View(c, "Fit preview", &m.picture).FillWidth().Height(240)`, + "input-group": `m.group.View(c, "Project domain")`, + "input-otp": `m.otp.View(c, "Verification code")`, + "marker": `markerview.View(c, "Updated", markerview.New().Label("Updated 2 minutes ago"))`, "menubar": `menubarview.View(c, "File", &m.menubar)`, "message": `messageview.View(c, "Ari", messageview.New().Name("Ari").Body("Native preview ready."))`, - "metric-card": `ui.Column(c).FillWidth().Pad(c.Theme().Metrics.PadSurface).Gap(6).Background(c.Theme().Card).Border(1, c.Theme().Border).Children(func() { ui.Text(c, "Active sessions").Muted(); ui.Text(c, "12,840").Bold() })`, + "metric-card": `metriccardview.View(c, "Active sessions", metriccardview.New().Title("Active sessions").Value("12,840").Trend("+18.2% from last week").Up()).FillWidth().Height(150)`, "navigation-menu": `navigationmenuview.View(c, "Site", &m.menu)`, - "questionnaire": `ui.Column(c).Gap(12).Children(func() { ui.Text(c, "Question 2 of 5").Muted(); ui.RadioGroup(c).Children(func() { ui.Radio(c, &m.answer, "Low memory", "Low memory") }); ui.Button(c, "Continue") })`, + "questionnaire": `m.questions.View(c, "Setup")`, "reorder-list": `items := []string{"Editor", "Terminal", "Explorer"}; m.list.Key = func(i int) int { return i }; ui.List(c, &m.list, len(items), func(row ui.ListRow) { ui.Text(row.C, items[row.Index]).Grow(1) })`, "segmented-control": `ui.Choice(c, &m.view, []string{"List", "Board", "Timeline"}, nil)`, - "sidebar": `items := []string{"Overview", "Components", "Benchmarks"}; ui.Column(c).Width(240).FillHeight().Gap(8).Children(func() { ui.Text(c, "Viva Studio").Bold(); ui.List(c, &m.nav, len(items), func(row ui.ListRow) { ui.Text(row.C, items[row.Index]) }) })`, - "skeleton": `ui.Column(c).FillWidth().Height(14).Radius(4).Background(c.Theme().Muted)`, + "sidebar": `sidebarview.View(c, "Workspace", &m.sidebar)`, + "skeleton": `skeletonview.View(c, "Loading", &m.skeleton).FillWidth()`, } diff --git a/internal/componentdemo/questionnaire.go b/internal/componentdemo/questionnaire.go index 3f731c6b..7c3420eb 100644 --- a/internal/componentdemo/questionnaire.go +++ b/internal/componentdemo/questionnaire.go @@ -1,9 +1,9 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/questionnaireview" ) var questionnaireComponent = Component{ @@ -27,31 +27,29 @@ q.PaintActions(components.QuestionnaireActions{ }) if index, ok := canvas.ClickedIn(choice); ok { selected = index -}`, PageSnippet: `ui.Text(c, "Question 2 of 5").Muted() -ui.Text(c, "What should Viva optimize first?") -ui.Text(c, "Answers stay in application state.").Muted() -ui.RadioGroup(c).Children(func() { - ui.Radio(c, &m.answer, "Low memory", "Low memory") - ui.Radio(c, &m.answer, "Fast startup", "Fast startup") - ui.Radio(c, &m.answer, "Small binaries", "Small binaries") -}) -ui.Row(c).Gap(8).Children(func() { - ui.Button(c, "Back").Outline() - ui.Button(c, "Skip").Outline() - ui.Button(c, "Continue") -})`, PageSnippetZh: `ui.Text(c, "Question 2 of 5").Muted() -ui.Text(c, "What should Viva optimize first?") -ui.Text(c, "Answers stay in application state.").Muted() -ui.RadioGroup(c).Children(func() { - ui.Radio(c, &m.answer, "Low memory", "Low memory") - ui.Radio(c, &m.answer, "Fast startup", "Fast startup") - ui.Radio(c, &m.answer, "Small binaries", "Small binaries") -}) -ui.Row(c).Gap(8).Children(func() { - ui.Button(c, "Back").Outline() - ui.Button(c, "Skip").Outline() - ui.Button(c, "Continue") -})`}, +}`, PageSnippet: `question := questionnaireview.New(). + Progress("Question 2 of 5"). + Title("What should Viva optimize first?"). + Description("Answers stay in application state."). + Single(). + Choice(m.choiceIDs[0], "Low memory", m.answer == 0, m.choose[0]). + Choice(m.choiceIDs[1], "Fast startup", m.answer == 1, m.choose[1]). + Choice(m.choiceIDs[2], "Small binaries", m.answer == 2, m.choose[2]). + Back(m.previousID, "Back", m.back). + Skip(m.skipID, "Skip", m.skip). + Continue(m.nextID, "Continue", m.next) +question.View(c, "Questionnaire").FillWidth()`, PageSnippetZh: `question := questionnaireview.New(). + Progress("第 2 题,共 5 题"). + Title("Viva 应优先优化什么?"). + Description("答案保留在应用状态中。"). + Single(). + Choice(m.choiceIDs[0], "低内存", m.answer == 0, m.choose[0]). + Choice(m.choiceIDs[1], "快速启动", m.answer == 1, m.choose[1]). + Choice(m.choiceIDs[2], "小体积", m.answer == 2, m.choose[2]). + Back(m.previousID, "返回", m.back). + Skip(m.skipID, "跳过", m.skip). + Continue(m.nextID, "继续", m.next) +question.View(c, "问卷").FillWidth()`}, {ID: "multiple-choice", Title: "多选题", Description: "切换多个性能目标,组件不隐藏答案状态。", Snippet: `choice := tree.Sub(page, tree.Name("choice")) q := components.BeginQuestionnaire(canvas, theme, bounds, components.QuestionnaireData{ Progress: "Question 2 of 5", Title: "Which performance goals matter?", @@ -65,29 +63,29 @@ for index, label := range []string{"Low memory", "Fast startup", "Small binaries } if index, ok := canvas.ClickedIn(choice); ok { checked[index] = !checked[index] -}`, PageSnippet: `ui.Text(c, "Question 2 of 5").Muted() -ui.Text(c, "Which performance goals matter?") -ui.Text(c, "Answers stay in application state.").Muted() -memory, startup, binaries := false, false, false -ui.Checkbox(c, &memory, "Low memory") -ui.Checkbox(c, &startup, "Fast startup") -ui.Checkbox(c, &binaries, "Small binaries") -ui.Row(c).Gap(8).Children(func() { - ui.Button(c, "Back").Outline() - ui.Button(c, "Skip").Outline() - ui.Button(c, "Continue") -})`, PageSnippetZh: `ui.Text(c, "Question 2 of 5").Muted() -ui.Text(c, "Which performance goals matter?") -ui.Text(c, "Answers stay in application state.").Muted() -memory, startup, binaries := false, false, false -ui.Checkbox(c, &memory, "Low memory") -ui.Checkbox(c, &startup, "Fast startup") -ui.Checkbox(c, &binaries, "Small binaries") -ui.Row(c).Gap(8).Children(func() { - ui.Button(c, "Back").Outline() - ui.Button(c, "Skip").Outline() - ui.Button(c, "Continue") -})`}, +}`, PageSnippet: `question := questionnaireview.New(). + Progress("Question 2 of 5"). + Title("Which performance goals matter?"). + Description("Answers stay in application state."). + Multiple(). + Choice(m.choiceIDs[0], "Low memory", m.memory, m.toggle[0]). + Choice(m.choiceIDs[1], "Fast startup", m.startup, m.toggle[1]). + Choice(m.choiceIDs[2], "Small binaries", m.binaries, m.toggle[2]). + Back(m.previousID, "Back", m.back). + Skip(m.skipID, "Skip", m.skip). + Continue(m.nextID, "Continue", m.next) +question.View(c, "Questionnaire").FillWidth()`, PageSnippetZh: `question := questionnaireview.New(). + Progress("第 2 题,共 5 题"). + Title("哪些性能目标重要?"). + Description("答案保留在应用状态中。"). + Multiple(). + Choice(m.choiceIDs[0], "低内存", m.memory, m.toggle[0]). + Choice(m.choiceIDs[1], "快速启动", m.startup, m.toggle[1]). + Choice(m.choiceIDs[2], "小体积", m.binaries, m.toggle[2]). + Back(m.previousID, "返回", m.back). + Skip(m.skipID, "跳过", m.skip). + Continue(m.nextID, "继续", m.next) +question.View(c, "问卷").FillWidth()`}, }, } @@ -100,65 +98,103 @@ var ( questionnaireNext = tree.ID(questionnaireUI, "next") ) +// questionnaireDemo is one example's page control and its stable callbacks. It +// is kept beside the State rather than rebuilt in each paint, so the handlers +// are stable and a warm re-declaration allocates nothing. +type questionnaireDemo struct { + view questionnaireview.Questionnaire + choose [3]func() + toggle [3]func() + back func() + skip func() + next func() +} + +// questionnaireDemos is keyed by State because the constrained demo model has +// no field for this control; a State is painted on one thread at a time. +var questionnaireDemos = map[*State]*questionnaireDemo{} + func (state *State) initializeQuestionnaire() { if state.exampleID == "single-choice" { state.values[0] = 0 } + demo := &questionnaireDemo{} + for index := range demo.choose { + value := index + demo.choose[index] = func() { state.values[0] = int32(value) } + demo.toggle[index] = func() { state.flags ^= uint64(1) << value } + } + demo.back = func() { state.values[1]-- } + demo.skip = func() { state.values[1]++ } + demo.next = func() { state.values[1]++ } + questionnaireDemos[state] = demo +} + +func questionnaireDemoFor(state *State) *questionnaireDemo { + if demo := questionnaireDemos[state]; demo != nil { + return demo + } + demo := &questionnaireDemo{} + for index := range demo.choose { + value := index + demo.choose[index] = func() { state.values[0] = int32(value) } + demo.toggle[index] = func() { state.flags ^= uint64(1) << value } + } + demo.back = func() { state.values[1]-- } + demo.skip = func() { state.values[1]++ } + demo.next = func() { state.values[1]++ } + questionnaireDemos[state] = demo + return demo } func (state *State) paintQuestionnaire(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { multiple := state.exampleID == "multiple-choice" - data := components.QuestionnaireData{ - Progress: "Question 2 of 5", Title: "What should Viva optimize first?", - Description: "Answers stay in application state.", ChoiceType: components.QuestionnaireRadio, - } + demo := questionnaireDemoFor(state) + height := max(size.Height-48-36, 0) + title := "What should Viva optimize first?" + description := "Answers stay in application state." if multiple { - data.Title = "Which performance goals matter?" - data.ChoiceType = components.QuestionnaireCheckbox + title = "Which performance goals matter?" } - var card ui.Box - state.drawPage(canvas, theme, size, 560, "Questionnaire", func(c ui.C) { - // The question fills what the page leaves: its own choices and actions - // decide what fits (a narrow card drops its last choice). - card = ui.Slot(c).Height(max(size.Height-48-36, 0)) - }) - bounds := card.Rect() - if bounds.Height < 280 { - data.Description = "" // a short card drops its description to keep the actions + if height < 280 { + description = "" // a short card drops its description to keep the actions } - questionnaire := components.BeginQuestionnaire(canvas, theme, bounds, data) labels := [...]string{"Low memory", "Fast startup", "Small binaries"} - for index, label := range labels { - checked := state.values[0] == int32(index) - if multiple { - checked = state.flags&(uint64(1)< 0) || !(b.height > 0) { + return 0 + } + ratio := b.width / b.height + if math.IsInf(float64(ratio), 0) { + return 0 + } + return ratio +} + +// ratioLayout lays the caller's children in the largest box that keeps the +// ratio inside the container's width. A CustomLayout is kept in the model, so +// it holds only the box it reads. +type ratioLayout struct { + box *Box +} + +func (layout *ratioLayout) MeasureWidth(*ui.LayoutContext) float32 { + // The page owns the width: FillWidth or an explicit Width. The height is + // what this layout derives. + return 0 +} + +func (layout *ratioLayout) PlaceWidth(ctx *ui.LayoutContext, bounds ui.Rect) { + for index := 0; index < ctx.Count(); index++ { + ctx.SetX(index, bounds.X) + ctx.SetWidth(index, bounds.Width) + } +} + +func (layout *ratioLayout) MeasureHeight(ctx *ui.LayoutContext) float32 { + return aspectHeight(ctx.ContentWidth(), layout.ratio()) +} + +func (layout *ratioLayout) PlaceHeight(ctx *ui.LayoutContext, bounds ui.Rect) { + height := aspectHeight(bounds.Width, layout.ratio()) + for index := 0; index < ctx.Count(); index++ { + ctx.SetY(index, bounds.Y) + ctx.SetHeight(index, height) + } +} + +func (layout *ratioLayout) ratio() float32 { + if layout.box == nil { + return 0 + } + return layout.box.ratio() +} + +func aspectHeight(width, ratio float32) float32 { + if !(ratio > 0) || !(width > 0) { + return 0 + } + return width / ratio +} diff --git a/ui/aspectratioview/aspectratioview_test.go b/ui/aspectratioview/aspectratioview_test.go new file mode 100644 index 00000000..a73b7588 --- /dev/null +++ b/ui/aspectratioview/aspectratioview_test.go @@ -0,0 +1,160 @@ +package aspectratioview_test + +import ( + "math" + "testing" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/aspectratioview" +) + +type model struct { + box aspectratioview.Box + page *ui.Page + canvas *gfx.Canvas + maxWidth float32 + title string + draws int +} + +func (m *model) viewPage(c ui.C) { + aspectratioview.View(c, m.title, &m.box, func() { + m.draws++ + ui.Column(c).Center().Children(func() { + ui.Text(c, m.title) + }) + }).FillWidth().MaxWidth(m.maxWidth) +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 400, Height: 300}, view) + canvas.EndFrame() +} + +func open(t testing.TB, m *model) { + t.Helper() + theme := gfx.LightTheme() + m.page = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: &theme}) + m.canvas = new(gfx.Canvas) + draw(m.page, m.canvas, m.viewPage) +} + +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + hits := canvas.Hits() + for index := len(hits) - 1; index >= 0; index-- { + if hits[index].Label == label && !hits[index].ID.IsZero() { + return hits[index] + } + } + t.Fatalf("no hit labelled %q was painted", label) + return gfx.Hit{} +} + +func hasText(canvas *gfx.Canvas, value string) bool { + for _, text := range canvas.Texts() { + if text.Value == value { + return true + } + } + return false +} + +func closeTo(got, want float32) bool { return math.Abs(float64(got-want)) < .001 } + +// The box takes the caller's width and derives its height from the chained +// ratio; the content is the page's own children inside it. +func TestRatioDerivesHeightAndLaysOutContent(t *testing.T) { + for _, test := range []struct { + name string + width float32 + height float32 + ratio float32 + maxWidth float32 + }{ + {name: "16:9", width: 16, height: 9, ratio: 16.0 / 9.0, maxWidth: 240}, + {name: "1:1", width: 1, height: 1, ratio: 1, maxWidth: 240}, + {name: "4:3", width: 4, height: 3, ratio: 4.0 / 3.0, maxWidth: 300}, + } { + t.Run(test.name, func(t *testing.T) { + m := &model{box: *aspectratioview.New(), maxWidth: test.maxWidth, title: test.name + " preview"} + m.box.Ratio(test.width, test.height) + open(t, m) + + control := hit(t, m.canvas, m.title) + if control.Role != gfx.RoleGroup { + t.Fatalf("role = %v, want group", control.Role) + } + bounds := components.AspectRatio(gfx.Rect{Width: test.maxWidth}, test.ratio) + if !closeTo(control.Bounds.Width, bounds.Width) || !closeTo(control.Bounds.Height, bounds.Height) { + t.Fatalf("box = %+v, want %+v", control.Bounds, bounds) + } + if !hasText(m.canvas, m.title) { + t.Fatalf("content %q was not painted inside the box", m.title) + } + if m.draws != 1 { + t.Fatalf("content declared %d times, want 1", m.draws) + } + }) + } +} + +// Square is the same call as Ratio(1, 1); there is no constructor per ratio. +func TestSquare(t *testing.T) { + m := &model{box: *aspectratioview.New(), maxWidth: 240, title: "Square"} + m.box.Square() + open(t, m) + control := hit(t, m.canvas, m.title) + if !closeTo(control.Bounds.Width, 240) || !closeTo(control.Bounds.Height, 240) { + t.Fatalf("square = %+v, want 240x240", control.Bounds) + } +} + +// An invalid ratio gives a zero-height box instead of a non-finite layout. +func TestInvalidRatioIsDeterministic(t *testing.T) { + for _, ratio := range [][2]float32{{0, 9}, {-16, 9}, {16, 0}} { + m := &model{box: *aspectratioview.New(), maxWidth: 240, title: "Invalid"} + m.box.Ratio(ratio[0], ratio[1]) + open(t, m) + control := hit(t, m.canvas, m.title) + if control.Bounds.Height > 0 { + t.Fatalf("ratio %v produced height %g, want 0", ratio, control.Bounds.Height) + } + } +} + +// The content is laid out again on every paint; the box state is the page's. +func TestContentDeclaredOnEveryPaint(t *testing.T) { + m := &model{box: *aspectratioview.New(), maxWidth: 240, title: "Repaint"} + m.box.Ratio(16, 9) + open(t, m) + draw(m.page, m.canvas, m.viewPage) + if m.draws != 2 { + t.Fatalf("content declared %d times over two paints, want 2", m.draws) + } +} + +// A warm repaint allocates nothing: the layout and box are kept in the model. +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := &model{box: *aspectratioview.New(), maxWidth: 240, title: "Warm"} + m.box.Ratio(16, 9) + open(t, m) + if allocations := testing.AllocsPerRun(100, func() { draw(m.page, m.canvas, m.viewPage) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := &model{box: *aspectratioview.New(), maxWidth: 240, title: "Benchmark"} + m.box.Ratio(16, 9) + open(b, m) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + draw(m.page, m.canvas, m.viewPage) + } +} diff --git a/ui/codeeditor/parity_test.go b/ui/codeeditor/parity_test.go new file mode 100644 index 00000000..6fb1ccc1 --- /dev/null +++ b/ui/codeeditor/parity_test.go @@ -0,0 +1,58 @@ +package codeeditor_test + +import ( + "fmt" + "testing" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/codeeditor" +) + +// The page control adds identity and input routing, not pixels: painting the +// same snapshot through the component and through codeeditor.View produces the +// same rectangles and labels. +func TestPageViewPaintsTheSameAsTheComponent(t *testing.T) { + snapshot := components.CodeEditorSnapshot{ + Value: source, LineNumbers: true, CurrentLine: true, MatchBrackets: true, + Language: "go", TabWidth: 4, Focused: true, ShowCaret: false, + SelectionStart: 2, SelectionEnd: 8, Caret: 8, + } + var direct, wrapped *gfx.Canvas + directPage := ui.NewPage(ui.PageConfig{Theme: testTheme(), View: func(c ui.C) { + ui.Slot(c).Fill().Draw(func(d *ui.DrawContext) { + var view components.CodeEditor + view.Paint(d.Canvas, *d.Theme, d.Rect, snapshot) + }) + }}) + var page codeeditor.Editor + page.Snapshot = snapshot + wrappedPage := ui.NewPage(ui.PageConfig{Theme: testTheme(), View: func(c ui.C) { + codeeditor.View(c, "Source", &page).Fill() + }}) + direct, wrapped = new(gfx.Canvas), new(gfx.Canvas) + drawPage(directPage, direct, func(c ui.C) { + ui.Slot(c).Fill().Draw(func(d *ui.DrawContext) { + var view components.CodeEditor + view.Paint(d.Canvas, *d.Theme, d.Rect, snapshot) + }) + }) + drawPage(wrappedPage, wrapped, func(c ui.C) { + codeeditor.View(c, "Source", &page).Fill() + }) + if got, want := describeCanvas(wrapped), describeCanvas(direct); got != want { + t.Fatalf("page view and component paint differently\n%s\nwant\n%s", got, want) + } +} + +func describeCanvas(canvas *gfx.Canvas) string { + var out string + for _, rectangle := range canvas.Rectangles() { + out += fmt.Sprintf("rect %+v %+v %g\n", rectangle.Bounds, rectangle.Color, rectangle.Radius) + } + for _, text := range canvas.Texts() { + out += fmt.Sprintf("text %q %+v %+v\n", text.Value, text.Bounds, text.Style) + } + return out +} diff --git a/ui/imageview/imageview.go b/ui/imageview/imageview.go new file mode 100644 index 00000000..42570e8c --- /dev/null +++ b/ui/imageview/imageview.go @@ -0,0 +1,174 @@ +// Package imageview is the opt-in page control for an image of package +// components. A page declares an image with the caller's decoded bitmap and a +// viewport, then chooses how the image is scaled: +// +// picture := imageview.New() +// ... +// picture.Reset().Bitmap(m.bitmap).Fit() +// imageview.View(c, "Fit preview", picture).FillWidth().Height(220) +// +// picture.Reset().Bitmap(m.bitmap).Actual() +// imageview.View(c, "Actual pixels", picture).Size(160, 100) +// +// picture.Reset().Bitmap(m.bitmap).Zoom(m.zoom).Pan(m.pan) +// imageview.View(c, "Zoom and pan", picture).FillWidth().Height(220) +// +// The caller owns the decoded pixels, their lifetime and the viewport size; the +// wrapper owns the control's handlers and draw function. File decoding, byte +// and pixel limits and document lifetime remain the application's. There is no +// hidden loading or animation: the bitmap is painted where the caller put it. +// +// Fit is the default and shows the whole image inside the viewport. Actual +// shows one bitmap pixel per device pixel, independent of the display scale. +// Zoom sets an explicit scale; Pan moves the scaled image inside the viewport. +// The component clamps Pan so it never exposes empty space. +// +// Pointer, Key and Scroll are the caller's interaction callbacks. The wrapper +// routes the events aimed at the view to them, so a page can drag to pan or +// handle the wheel to zoom without reproducing the control's input plumbing. +// Clicked reports a click after View, like the component views do. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an Image in the model beside its bitmap: its handlers +// and draw function are made once, so a warm paint allocates nothing. Do not +// copy one after it has been painted. +package imageview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Image is one image's caller-owned values and page control. Configure it with +// the chainable methods, then view it. A new Image fits its bitmap; the zero +// value paints nothing. +type Image struct { + bitmap gfx.Bitmap + zoom float32 + pan gfx.Point + + // Pointer receives the presses, moves and releases over the view, such as a + // drag that pans the image. A nil callback leaves them to the page. + Pointer func(gfx.PointerEvent) gfx.EventResult + // Key receives the keys pressed while the view has the focus. + Key func(gfx.KeyEvent) gfx.EventResult + // Scroll receives the wheel over the view, such as a zoom gesture. A nil + // callback leaves the wheel to the page. + Scroll func(gfx.ScrollEvent) gfx.EventResult + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + id gfx.ID + clicked gfx.ID + hadClick bool +} + +// New returns an empty image view that fits its bitmap in the viewport. +func New() *Image { return new(Image) } + +// Reset clears the bitmap, zoom and pan, returning the image to fit. The +// interaction callbacks are kept, so a page that reconfigures the view every +// paint does not lose its input wiring. +func (i *Image) Reset() *Image { + i.bitmap = gfx.Bitmap{} + i.zoom = 0 + i.pan = gfx.Point{} + i.id = gfx.ID{} + i.clicked = gfx.ID{} + i.hadClick = false + return i +} + +// Bitmap is the caller-decoded, immutable picture painted in the viewport. +// The caller owns Pix and must keep it unchanged while a canvas can retain it. +func (i *Image) Bitmap(bitmap gfx.Bitmap) *Image { i.bitmap = bitmap; return i } + +// Fit shows the whole image inside the viewport, centered and with its original +// proportions. It is the default and clears any explicit zoom and pan. +func (i *Image) Fit() *Image { + i.zoom = 0 + i.pan = gfx.Point{} + return i +} + +// Actual shows one bitmap pixel per device pixel, independent of the display +// scale, like the component's Zoom 1. It keeps the current pan. +func (i *Image) Actual() *Image { i.zoom = 1; return i } + +// Zoom sets an explicit scale. A zoom of one is Actual; zero or less fits the +// viewport. It keeps the current pan. +func (i *Image) Zoom(zoom float32) *Image { + if zoom < 0 { + zoom = 0 + } + i.zoom = zoom + return i +} + +// Pan offsets the scaled image inside the viewport. The component clamps it so +// the viewport is never left with empty space beside an oversized image. +func (i *Image) Pan(pan gfx.Point) *Image { i.pan = pan; return i } + +// View declares the image at c. label names it for assistive technology. The +// caller must give the box its viewport dimensions: Size, FillWidth with +// Height, or the layout of the page around it. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, image *Image) ui.Box { + if image == nil { + panic("imageview: View needs its Image") + } + image.prepare() + return ui.Control(c, label, &image.handlers).Draw(image.drawFn) +} + +// Clicked reports whether the paint just made delivered a click on the view. It +// is false in ordinary paints. Ask it after View. +func (i *Image) Clicked() bool { + return i.hadClick && !i.id.IsZero() && i.clicked == i.id +} + +func (i *Image) prepare() { + if i.prepared { + return + } + i.prepared = true + i.handlers.Role = gfx.RoleGroup + i.handlers.Pointer = i.pointer + i.handlers.Key = i.key + i.handlers.Scroll = i.scroll + i.drawFn = i.draw +} + +func (i *Image) pointer(event gfx.PointerEvent) gfx.EventResult { + if i.Pointer == nil { + return gfx.EventResult{} + } + return i.Pointer(event) +} + +func (i *Image) key(event gfx.KeyEvent) gfx.EventResult { + if i.Key == nil { + return gfx.EventResult{} + } + return i.Key(event) +} + +func (i *Image) scroll(event gfx.ScrollEvent) gfx.EventResult { + if i.Scroll == nil { + return gfx.EventResult{} + } + return i.Scroll(event) +} + +func (i *Image) draw(d *ui.DrawContext) { + i.id = d.Node.ID + i.clicked, i.hadClick = d.Canvas.ClickTarget() + components.PaintImageView(d.Canvas, *d.Theme, d.Rect, components.ImageViewOptions{ + Bitmap: i.bitmap, + Zoom: i.zoom, + Pan: i.pan, + }) +} diff --git a/ui/imageview/imageview_test.go b/ui/imageview/imageview_test.go new file mode 100644 index 00000000..38888840 --- /dev/null +++ b/ui/imageview/imageview_test.go @@ -0,0 +1,207 @@ +package imageview_test + +import ( + "math" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/imageview" +) + +var testBitmap = gfx.Bitmap{ + Pix: make([]byte, 40*20*4), Width: 40, Height: 20, Stride: 40 * 4, ID: 7, Version: 1, +} + +type model struct { + view imageview.Image + page *ui.Page + canvas *gfx.Canvas + pointer int + key int + scroll int + target gfx.ID +} + +func (m *model) viewPage(c ui.C) { + imageview.View(c, "Preview", &m.view).Size(200, 120) +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 400, Height: 300}, view) + canvas.EndFrame() +} + +func drawClick(page *ui.Page, canvas *gfx.Canvas, view func(ui.C), id gfx.ID) { + canvas.BeginEventPass(id, gfx.ClickInfo{}) + draw(page, canvas, view) + canvas.EndEventPass() +} + +func open(t testing.TB, m *model) { + t.Helper() + m.view.Reset().Bitmap(testBitmap).Fit() + m.view.Pointer = func(event gfx.PointerEvent) gfx.EventResult { + m.pointer++ + m.target = event.Target + return gfx.EventResult{Handled: true, Repaint: true} + } + m.view.Key = func(event gfx.KeyEvent) gfx.EventResult { + m.key++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } + m.view.Scroll = func(event gfx.ScrollEvent) gfx.EventResult { + m.scroll++ + m.target = event.Target + return gfx.EventResult{Handled: true} + } + theme := gfx.LightTheme() + m.page = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: &theme}) + m.canvas = new(gfx.Canvas) + draw(m.page, m.canvas, m.viewPage) +} + +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + hits := canvas.Hits() + for index := len(hits) - 1; index >= 0; index-- { + if hits[index].Label == label && !hits[index].ID.IsZero() { + return hits[index] + } + } + t.Fatalf("no hit labelled %q was painted", label) + return gfx.Hit{} +} + +func image(t *testing.T, canvas *gfx.Canvas) gfx.Image { + t.Helper() + images := canvas.Images() + if len(images) != 1 { + t.Fatalf("painted %d images, want 1", len(images)) + } + return images[0] +} + +func closeTo(got, want float32) bool { return math.Abs(float64(got-want)) < .001 } + +// Fit centers the whole bitmap in the caller's viewport and keeps its +// proportions; the page names the view for assistive technology. +func TestFitCentersWholeBitmap(t *testing.T) { + m := new(model) + open(t, m) + + control := hit(t, m.canvas, "Preview") + if control.Role != gfx.RoleGroup || !control.Focusable { + t.Fatalf("control = %+v, want a focusable group", control) + } + painted := image(t, m.canvas) + if !closeTo(painted.Bounds.X, 0) || !closeTo(painted.Bounds.Y, 10) || + !closeTo(painted.Bounds.Width, 200) || !closeTo(painted.Bounds.Height, 100) { + t.Fatalf("fit bounds = %+v, want 200x100 centered at y=10", painted.Bounds) + } + if painted.Bitmap.ID != testBitmap.ID { + t.Fatalf("painted bitmap ID = %d, want %d", painted.Bitmap.ID, testBitmap.ID) + } +} + +// Actual maps one bitmap pixel to one device pixel, independent of the display +// scale, and keeps the chained pan while the component clamps it. +func TestActualSizeAndChainedOptions(t *testing.T) { + m := new(model) + open(t, m) + m.canvas.SetPixelScale(2) + m.view.Actual() + draw(m.page, m.canvas, m.viewPage) + + painted := image(t, m.canvas) + if !closeTo(painted.Bounds.Width*2, float32(testBitmap.Width)) || + !closeTo(painted.Bounds.Height*2, float32(testBitmap.Height)) { + t.Fatalf("actual bounds = %+v at 2x, want 40x20 device pixels", painted.Bounds) + } + + m.view.Zoom(16).Pan(gfx.Point{X: 1e6, Y: -1e6}) + draw(m.page, m.canvas, m.viewPage) + painted = image(t, m.canvas) + if !closeTo(painted.Bounds.Width, 320) || !closeTo(painted.Bounds.Height, 160) { + t.Fatalf("zoomed bounds = %+v, want 320x160", painted.Bounds) + } + if !closeTo(painted.Bounds.X, 0) || !closeTo(painted.Bounds.Y, -40) { + t.Fatalf("panned bounds = %+v, want the clamps at x=0 y=-40", painted.Bounds) + } + + m.view.Fit() + draw(m.page, m.canvas, m.viewPage) + if painted = image(t, m.canvas); !closeTo(painted.Bounds.Width, 200) { + t.Fatalf("Fit after Zoom bounds = %+v, want the fitted width", painted.Bounds) + } +} + +// The wrapper routes the control's pointer, key and wheel events to the +// caller's callbacks, which a page uses to drag and zoom. +func TestInteractionCallbacksReceiveEvents(t *testing.T) { + m := new(model) + open(t, m) + control := hit(t, m.canvas, "Preview") + + if result := m.page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: control.ID, + X: control.Bounds.X + 2, Y: control.Bounds.Y + 2, + }); !result.Handled || m.pointer != 1 || m.target != control.ID { + t.Fatalf("pointer = %+v after %d calls, target %v; want %v", result, m.pointer, m.target, control.ID) + } + if result := m.page.Key(gfx.KeyEvent{Key: gfx.KeyLeft, Target: control.ID}); !result.Handled || m.key != 1 || m.target != control.ID { + t.Fatalf("key = %+v after %d calls, target %v; want %v", result, m.key, m.target, control.ID) + } + if result := m.page.Wheel(gfx.ScrollEvent{Target: control.ID, DeltaY: 1}); !result.Handled || m.scroll != 1 || m.target != control.ID { + t.Fatalf("wheel = %+v after %d calls, target %v; want %v", result, m.scroll, m.target, control.ID) + } +} + +// A click on the view is reported after View and not in an ordinary paint. +func TestClickedReportsTheEventPass(t *testing.T) { + m := new(model) + open(t, m) + control := hit(t, m.canvas, "Preview") + drawClick(m.page, m.canvas, m.viewPage, control.ID) + if !m.view.Clicked() { + t.Fatal("Clicked did not report the event pass's click") + } + draw(m.page, m.canvas, m.viewPage) + if m.view.Clicked() { + t.Fatal("Clicked reported a click in an ordinary paint") + } +} + +// An empty bitmap paints the viewport surface but no image command. +func TestEmptyBitmapPaintsNoImage(t *testing.T) { + m := new(model) + open(t, m) + m.view.Reset() + draw(m.page, m.canvas, m.viewPage) + if images := m.canvas.Images(); len(images) != 0 { + t.Fatalf("empty bitmap painted %d images", len(images)) + } +} + +// A warm repaint allocates nothing: the handlers and draw function are made +// once and the component keeps its own layout. +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + open(t, m) + if allocations := testing.AllocsPerRun(100, func() { draw(m.page, m.canvas, m.viewPage) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := new(model) + open(b, m) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + draw(m.page, m.canvas, m.viewPage) + } +} diff --git a/ui/inputgroupview/inputgroupview.go b/ui/inputgroupview/inputgroupview.go new file mode 100644 index 00000000..b663394f --- /dev/null +++ b/ui/inputgroupview/inputgroupview.go @@ -0,0 +1,301 @@ +// Package inputgroupview is the opt-in page control for the bordered input +// groups of package components. A page composes one with a caller-owned +// ui.Field and chained options: +// +// group := inputgroupview.New(&m.domain). +// Placeholder("project-name"). +// Prefix("https://"). +// Action(m.clearID, m.crossIcon, "Clear domain", m.clearDomain) +// group.View(c, "Project domain").FillWidth() +// if group.ActionClicked() { +// // the action ran too, if it had a callback +// } +// +// The field is the page's own ui.Field: its value, focus, caret, selection, +// composition and Secure/Invalid/Disabled state are painted through the +// component, and the platform text service edits the same editor a +// ui.TextField would. Prefix, Suffix, Icon, Action, Button and the block +// addons are chained options; there is no second constructor for a size or a +// visual variant. Small changes the button sizes, Spinner replaces the end +// action with a loading indicator. +// +// View declares a ui.Control around the component's text-field hit. By +// default the field's hit is the control's own identity, so a page configured +// with ui.Configure gives its platform the field's editor. FieldID names the +// hit explicitly for an embedding runner that resolves text by an application +// identity. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Group in the model beside its Field: its handlers, +// text provider and draw function are made once, so a warm paint allocates +// nothing. Do not copy a Group after it has been declared. +package inputgroupview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// Group is one input group's caller-owned field and its page control. +// Configure it with the chainable methods before each View. +type Group struct { + field *ui.Field + placeholder string + fieldID gfx.ID + + inlineStart components.InputGroupSlot + inlineEnd components.InputGroupSlot + blockStart components.InputGroupSlot + blockEnd components.InputGroupSlot + + small bool + multiline bool + readOnly bool + actionID gfx.ID + action func() + + // label is the accessible name of the paint being declared. + label string + + handlers ui.Handlers + textProvider func(window.TextInputContext) *window.TextInput + drawFn func(*ui.DrawContext) + prepared bool + clicked gfx.ID + hadClick bool +} + +// New returns an input group over field, an application-owned ui.Field. The +// field is required; bind it to the editor the page's text service edits, as a +// ui.TextField's field is bound. +func New(field *ui.Field) *Group { + if field == nil { + panic("inputgroupview: New needs its ui.Field") + } + return &Group{field: field} +} + +// Placeholder is the text shown while the field is empty. +func (g *Group) Placeholder(text string) *Group { + g.placeholder = text + return g +} + +// FieldID gives the field's hit an explicit identity instead of the control's +// own. It is for a runner that resolves the platform text service by an +// application identity, such as a component preview. +func (g *Group) FieldID(id gfx.ID) *Group { + g.fieldID = id + return g +} + +// Prefix puts a separated text addon before the field. +func (g *Group) Prefix(text string) *Group { + g.inlineStart = components.InputGroupSlot{ + Kind: components.InputGroupSlotText, Text: text, Separated: true, + } + return g +} + +// Suffix puts a separated text addon after the field. +func (g *Group) Suffix(text string) *Group { + g.inlineEnd = components.InputGroupSlot{ + Kind: components.InputGroupSlotText, Text: text, Separated: true, + } + g.actionID, g.action = gfx.ID{}, nil + return g +} + +// Icon puts a decorative icon before the field. +func (g *Group) Icon(icon gfx.Icon) *Group { + g.inlineStart = components.InputGroupSlot{Kind: components.InputGroupSlotIcon, Icon: icon} + return g +} + +// Action puts an icon button after the field. id is the caller-owned hit +// identity; onClick runs after the click is read, and may be nil. +func (g *Group) Action(id gfx.ID, icon gfx.Icon, label string, onClick func()) *Group { + g.inlineEnd = components.InputGroupSlot{ + Kind: components.InputGroupSlotButton, ID: id, Icon: icon, Label: label, + ButtonSize: g.iconButtonSize(), + } + g.actionID, g.action = id, onClick + return g +} + +// Button puts a text button after the field. id is the caller-owned hit +// identity; onClick runs after the click is read, and may be nil. +func (g *Group) Button(id gfx.ID, label string, onClick func()) *Group { + g.inlineEnd = components.InputGroupSlot{ + Kind: components.InputGroupSlotButton, ID: id, Text: label, + ButtonSize: g.textButtonSize(), + } + g.actionID, g.action = id, onClick + return g +} + +// Small selects the small button sizes for the action and button slots. +func (g *Group) Small() *Group { + g.small = true + if g.inlineEnd.Kind == components.InputGroupSlotButton { + g.inlineEnd.ButtonSize = g.buttonSizeFor(g.inlineEnd) + } + return g +} + +// DisableAction paints the end action or button inert without changing the +// field, as the invalid state of a form does with an invitation button. +func (g *Group) DisableAction() *Group { + g.inlineEnd.Disabled = true + return g +} + +// Spinner replaces the end action with a loading indicator at phase. Advancing +// the phase is the application's job. +func (g *Group) Spinner(phase components.SpinnerPhase) *Group { + g.inlineEnd = components.InputGroupSlot{Kind: components.InputGroupSlotSpinner, Phase: phase} + g.actionID, g.action = gfx.ID{}, nil + return g +} + +// Multiline makes the field several rows tall, as a textarea is. +func (g *Group) Multiline() *Group { + g.multiline = true + return g +} + +// ReadOnly paints the field as not editable without taking it out of the tab +// order or the pointer's reach. +func (g *Group) ReadOnly() *Group { + g.readOnly = true + return g +} + +// Editable clears ReadOnly, for a page that enables editing after the first +// paint. +func (g *Group) Editable() *Group { + g.readOnly = false + return g +} + +// BlockStart puts a full-width text addon above the field. +func (g *Group) BlockStart(text string) *Group { + g.blockStart = components.InputGroupSlot{ + Kind: components.InputGroupSlotText, Text: text, Separated: true, + } + return g +} + +// BlockEnd puts a full-width text addon below the field. +func (g *Group) BlockEnd(text string) *Group { + g.blockEnd = components.InputGroupSlot{Kind: components.InputGroupSlotText, Text: text} + return g +} + +// BlockKbd puts a full-width keyboard badge below the field. +func (g *Group) BlockKbd(text string) *Group { + g.blockEnd = components.InputGroupSlot{Kind: components.InputGroupSlotKbd, Text: text} + return g +} + +// View declares the group at c. label names the field for assistive +// technology. The box is one control row high, plus any block addons; give it a +// width. +// +// Declare the view on its own, not inside a Memo. +func (g *Group) View(c ui.C, label string) ui.Box { + if g == nil { + panic("inputgroupview: View needs its Group") + } + g.prepare() + g.label = label + return ui.Control(c, label, &g.handlers).Height(g.height(*c.Theme())).Draw(g.drawFn) +} + +// ActionClicked reports whether the paint just made delivered a click on the +// group's action. It is false in ordinary paints or when there is no action. +func (g *Group) ActionClicked() bool { + return g.hadClick && !g.actionID.IsZero() && g.clicked == g.actionID +} + +func (g *Group) prepare() { + if g.prepared { + return + } + g.prepared = true + g.handlers.Role = gfx.RoleGroup + g.handlers.Text = g.text + g.textProvider = ui.Fields(g.field) + g.drawFn = g.draw +} + +func (g *Group) text(context window.TextInputContext) *window.TextInput { + if g.textProvider == nil { + return nil + } + return g.textProvider(context) +} + +func (g *Group) iconButtonSize() components.InputGroupButtonSize { + if g.small { + return components.InputGroupButtonIconSM + } + return components.InputGroupButtonIconXS +} + +func (g *Group) textButtonSize() components.InputGroupButtonSize { + if g.small { + return components.InputGroupButtonSM + } + return components.InputGroupButtonXS +} + +func (g *Group) buttonSizeFor(slot components.InputGroupSlot) components.InputGroupButtonSize { + if slot.Text == "" && (len(slot.Icon.Commands) != 0 || len(slot.Icon.Layers) != 0) { + return g.iconButtonSize() + } + return g.textButtonSize() +} + +func (g *Group) height(theme gfx.Theme) float32 { + height := theme.Metrics.ControlHeight + if g.multiline { + height = 64 + } + if g.blockStart.Kind != components.InputGroupSlotNone { + height += 32 + } + if g.blockEnd.Kind != components.InputGroupSlotNone { + height += 32 + } + return height +} + +func (g *Group) draw(d *ui.DrawContext) { + id := g.fieldID + if id.IsZero() { + id = d.Node.ID + } + g.clicked, g.hadClick = d.Canvas.ClickTarget() + input := g.field.Snapshot(d.Frame, id, g.label, g.placeholder) + snapshot := components.InputGroupSnapshot{ + ID: id, Label: g.label, Value: input.Value, Placeholder: g.placeholder, + Disabled: input.Disabled, Invalid: input.Invalid, Secure: input.Secure, + Focused: input.Focused, Multiline: g.multiline, ReadOnly: g.readOnly, + HideEditorText: true, ShowCaret: input.ShowCaret, Caret: input.Caret, + SelectionStart: input.SelectionStart, SelectionEnd: input.SelectionEnd, + CompositionStart: input.CompositionStart, CompositionEnd: input.CompositionEnd, + Blink: input.Blink, + InlineStart: g.inlineStart, InlineEnd: g.inlineEnd, + BlockStart: g.blockStart, BlockEnd: g.blockEnd, + } + components.PaintInputGroup(d.Canvas, *d.Theme, d.Rect, snapshot) + if g.hadClick && !g.actionID.IsZero() && g.clicked == g.actionID { + d.Canvas.RequestFocus(id) + if g.action != nil { + g.action() + } + } +} diff --git a/ui/inputgroupview/inputgroupview_test.go b/ui/inputgroupview/inputgroupview_test.go new file mode 100644 index 00000000..9e744d77 --- /dev/null +++ b/ui/inputgroupview/inputgroupview_test.go @@ -0,0 +1,181 @@ +package inputgroupview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/inputgroupview" + "github.com/vivaui/viva/window" +) + +var ( + clearID = gfx.Item(91) + testIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{ + gfx.MoveTo(6, 6), gfx.LineTo(18, 18), + }} +) + +func testTheme() gfx.Theme { return gfx.LightTheme() } + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 560, Height: 240}, view) + canvas.EndFrame() +} + +func drawClick(page *ui.Page, canvas *gfx.Canvas, view func(ui.C), id gfx.ID) { + canvas.BeginEventPass(id, gfx.ClickInfo{}) + draw(page, canvas, view) + canvas.EndEventPass() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := testTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := new(gfx.Canvas) + draw(page, canvas, view) + return page, canvas +} + +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + hits := canvas.Hits() + for index := len(hits) - 1; index >= 0; index-- { + if hits[index].Label == label { + return hits[index] + } + } + t.Fatalf("no hit labelled %q was painted", label) + return gfx.Hit{} +} + +func hasText(canvas *gfx.Canvas, value string) bool { + for _, label := range canvas.Texts() { + if label.Value == value { + return true + } + } + return false +} + +type model struct { + editor *text.Editor + field ui.Field + group inputgroupview.Group + cleared int +} + +func (m *model) init() { + m.editor = text.NewEditor("viva.dev") + m.field.Bind(m.editor) + m.group = *inputgroupview.New(&m.field). + Placeholder("project-name"). + Prefix("https://"). + Action(clearID, testIcon, "Clear domain", func() { m.cleared++ }) +} + +func (m *model) view(c ui.C) { + m.group.View(c, "Project domain").FillWidth() +} + +// The group paints the caller's field text and addons, and the action's click +// runs the caller's callback and is read after View. +func TestGroupPaintsFieldAndRunsAction(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.view) + + field := hit(t, canvas, "Project domain") + if field.ID.IsZero() || field.Role != gfx.RoleTextField { + t.Fatalf("field hit = %+v, want the control's text field", field) + } + if !hasText(canvas, "viva.dev") || !hasText(canvas, "https://") { + t.Fatal("the field's text or prefix was not painted") + } + action := hit(t, canvas, "Clear domain") + if action.ID != clearID || action.Role != gfx.RoleButton { + t.Fatalf("action hit = %+v, want the caller's button", action) + } + + input := page.TextInput(window.TextInputContext{ID: field.ID}) + if input == nil || input.Editor != m.editor { + t.Fatalf("the platform text service got %+v, want the field's editor", input) + } + + drawClick(page, canvas, m.view, clearID) + if m.cleared != 1 { + t.Fatalf("the action callback ran %d times, want 1", m.cleared) + } + if !m.group.ActionClicked() { + t.Fatal("ActionClicked did not report the action") + } + draw(page, canvas, m.view) + if m.group.ActionClicked() { + t.Fatal("ActionClicked reported a click in an ordinary paint") + } +} + +// The chained options place every addon the component knows: a suffix, a +// button, block addons and a spinner. +func TestGroupAddons(t *testing.T) { + var field ui.Field + field.SetText("viva.dev") + var group inputgroupview.Group + group = *inputgroupview.New(&field).Suffix("@viva.dev") + page, canvas := open(t, func(c ui.C) { + group.View(c, "Project domain").FillWidth() + }) + _ = page + if !hasText(canvas, "@viva.dev") { + t.Fatal("the suffix was not painted") + } + + buttonID := gfx.Item(92) + group = *inputgroupview.New(&field). + BlockStart("Release description"). + BlockKbd("⌘↵"). + Button(buttonID, "Invite", nil). + Small(). + DisableAction() + _, canvas = open(t, func(c ui.C) { + group.View(c, "Release description").FillWidth() + }) + if !hasText(canvas, "Release description") || !hasText(canvas, "⌘↵") { + t.Fatal("the block addons were not painted") + } + if invite := hit(t, canvas, "Invite"); invite.ID != buttonID || invite.Disabled == false { + t.Fatalf("button hit = %+v, want the disabled caller's button", invite) + } + + group = *inputgroupview.New(&field).Prefix("Search").Spinner(2) + _, canvas = open(t, func(c ui.C) { + group.View(c, "Search").FillWidth() + }) + if !hasText(canvas, "Search") || hasText(canvas, "Clear domain") { + t.Fatal("the spinner did not replace the action") + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, m.view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := new(model) + m.init() + page, canvas := open(b, m.view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, m.view) + } +} diff --git a/ui/inputotpview/inputotpview.go b/ui/inputotpview/inputotpview.go new file mode 100644 index 00000000..01d77ad6 --- /dev/null +++ b/ui/inputotpview/inputotpview.go @@ -0,0 +1,391 @@ +// Package inputotpview is the opt-in page control for the grouped one-time-code +// slots of package components. It is a real text field backed by a +// caller-owned text.Editor: +// +// code := inputotpview.New(). +// Bind(&m.codeField, m.codeEditor). +// Slots(6).GroupSize(3).Filter(inputotpview.Digits) +// code.View(c, "Verification code") +// if code.Clicked() { +// // a press on the control, already moved to the slot under the pointer +// } +// +// The application owns the field and its editor; the view paints the editor's +// value, caret, selection and composition into the slots and gives the +// platform text service the same editor. Slots, GroupSize, Filter, Invalid, +// Disabled, ReadOnly and the static snapshot options are chained; there is no +// second constructor. The filter restricts typing and paste to the code's +// characters and overwrite mode fills the slot under the caret, as a fixed-width +// code should. +// +// View declares a ui.Control with a text-field role. By default the field's +// hit is the control's own identity, so a page configured with ui.Configure +// gives its platform the editor through the control's Text handler. FieldID +// names the hit explicitly for an embedding runner that resolves text by an +// application identity; SelectAt lets such a runner route a press to a slot. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an OTP in the model beside its editor: its handlers and +// draw function are made once, so a warm paint allocates nothing. Do not copy +// an OTP after it has been declared. +package inputotpview + +import ( + "unicode/utf8" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// Filter selects which characters the code accepts. It is +// components.InputOTPFilter, named here so a page reads through this package +// alone. +type Filter = components.InputOTPFilter + +const ( + // Any accepts every visible character. + Any Filter = components.InputOTPAny + // Digits accepts the ASCII digits 0-9, the default. + Digits Filter = components.InputOTPDigits + // Alphanumeric accepts the ASCII digits and letters. + Alphanumeric Filter = components.InputOTPAlphanumeric +) + +// OTP is one one-time-code field and its page control. +type OTP struct { + field *ui.Field + editor *text.Editor + fieldID gfx.ID + + value string + slots int + group int + filter Filter + + invalid bool + disabled bool + readOnly bool + + focused bool + showCaret bool + activeSlot int + hasSelection bool + selStart int + selEnd int + hasCompose bool + compStart int + compEnd int + + label string + paintedID gfx.ID + layout components.InputOTPLayout + input window.TextInput + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + clicked gfx.ID + hadClick bool +} + +// New returns an empty six-slot code. Give it a field or a static Value. +func New() *OTP { return &OTP{slots: 6, filter: Digits} } + +// Bind gives the view the caller-owned field and the editor its slots paint and +// the platform text service edits. Either may be nil: an editor alone paints +// the code without a page field, and a field alone paints its text without +// slot editing. Bind applies the filter and overwrite mode to the editor. +func (o *OTP) Bind(field *ui.Field, editor *text.Editor) *OTP { + o.field, o.editor = field, editor + o.restrict() + return o +} + +// Slots sets how many characters the code has. The default is six. +func (o *OTP) Slots(count int) *OTP { + if count <= 0 { + count = 6 + } + o.slots = count + o.restrict() + return o +} + +// GroupSize sets how many slots share one rounded border before a separator. +// Zero or a value not smaller than Slots paints one group. +func (o *OTP) GroupSize(size int) *OTP { + o.group = size + return o +} + +// Filter selects which characters may be typed or pasted. The default is +// Digits. +func (o *OTP) Filter(filter Filter) *OTP { + o.filter = filter + o.restrict() + return o +} + +// Value is the code painted when there is no editor. +func (o *OTP) Value(value string) *OTP { + o.value = value + return o +} + +// Invalid paints the error state. +func (o *OTP) Invalid() *OTP { + o.invalid = true + return o +} + +// Disabled paints the code inert. +func (o *OTP) Disabled() *OTP { + o.disabled = true + return o +} + +// ReadOnly paints the code focused but not editable. +func (o *OTP) ReadOnly() *OTP { + o.readOnly = true + return o +} + +// Editable clears ReadOnly, for a page that enables editing after the first +// paint. +func (o *OTP) Editable() *OTP { + o.readOnly = false + return o +} + +// Focused shows the focus ring and active slot for a static snapshot. +func (o *OTP) Focused() *OTP { + o.focused = true + return o +} + +// ShowCaret shows the caret in the active empty slot of a static snapshot. An +// editor shows it whenever the slot is focused and the selection is collapsed. +func (o *OTP) ShowCaret() *OTP { + o.showCaret = true + return o +} + +// ActiveSlot selects the active slot of a static snapshot. +func (o *OTP) ActiveSlot(index int) *OTP { + o.activeSlot = index + return o +} + +// Select marks the selected slot range of a static snapshot. +func (o *OTP) Select(start, end int) *OTP { + o.hasSelection, o.selStart, o.selEnd = start != end, start, end + return o +} + +// Composition marks the input-method composition range of a static snapshot. +func (o *OTP) Composition(start, end int) *OTP { + o.hasCompose, o.compStart, o.compEnd = start != end, start, end + return o +} + +// FieldID gives the field's hit an explicit identity instead of the control's +// own, for a runner that resolves the platform text service by an application +// identity. +func (o *OTP) FieldID(id gfx.ID) *OTP { + o.fieldID = id + return o +} + +// View declares the code at c. label names the field for assistive technology. +// The box is the slots' intrinsic size; give it a width to place it. +// +// Declare the view on its own, not inside a Memo. +func (o *OTP) View(c ui.C, label string) ui.Box { + if o == nil { + panic("inputotpview: View needs its OTP") + } + o.prepare() + o.label = label + layout := components.PaintInputOTP(nil, *c.Theme(), gfx.Rect{}, components.InputOTPSnapshot{ + Slots: o.slots, GroupSize: o.group, + }) + return ui.Control(c, label, &o.handlers).Size(layout.Bounds.Width, layout.Bounds.Height).Draw(o.drawFn) +} + +// Layout is the slot geometry painted last. It is zero until View has painted. +func (o *OTP) Layout() components.InputOTPLayout { return o.layout } + +// Clicked reports whether the paint just made delivered a press on the code. +// It is false in ordinary paints. +func (o *OTP) Clicked() bool { + return o.hadClick && !o.paintedID.IsZero() && o.clicked == o.paintedID +} + +// SelectAt moves the caret to the slot under x, in window coordinates, or to +// the end when the press is past the last slot. It reports whether it acted. +// It is for a runner that paints the field under an external identity and routes +// the press itself; the control's own pointer handler calls the same method. +func (o *OTP) SelectAt(x float32) bool { + if o.editor == nil || o.disabled || o.readOnly || o.layout.Slots == 0 { + return false + } + slot := o.layout.Slots - 1 + for index := 0; index < o.layout.Slots; index++ { + bounds := o.layout.SlotBounds(index) + if x < bounds.X+bounds.Width { + slot = index + break + } + } + caret := min(slot, o.editor.RuneCount()) + o.editor.SetSelection(text.Range{Start: caret, End: caret}) + return true +} + +func (o *OTP) restrict() { + if o.editor == nil { + return + } + o.editor.Restrict(o.filter.Accepts, o.slotCount()) + o.editor.SetOverwrite(true) +} + +func (o *OTP) slotCount() int { + if o.slots <= 0 { + return 6 + } + return o.slots +} + +func (o *OTP) prepare() { + if o.prepared { + return + } + o.prepared = true + o.handlers.Role = gfx.RoleGroup + o.handlers.Key = o.key + o.handlers.Pointer = o.pointer + o.handlers.Text = o.text + o.drawFn = o.draw +} + +func (o *OTP) text(window.TextInputContext) *window.TextInput { + if o.editor == nil { + return nil + } + o.input = window.TextInput{Editor: o.editor} + return &o.input +} + +func (o *OTP) key(event gfx.KeyEvent) gfx.EventResult { + if o.editor == nil || o.disabled || o.readOnly { + return gfx.EventResult{} + } + if !o.paintedID.IsZero() && event.Target != o.paintedID { + return gfx.EventResult{} + } + command, ok := components.InputOTPCommandForKey(components.InputOTPSnapshot{ + Disabled: o.disabled, ReadOnly: o.readOnly, + }, event.Key) + if !ok { + return gfx.EventResult{} + } + extend := event.Modifiers&gfx.ModifierShift != 0 + switch command { + case components.InputOTPCommandMovePrevious: + o.editor.MoveLeft(extend) + case components.InputOTPCommandMoveNext: + o.editor.MoveRight(extend) + case components.InputOTPCommandMoveFirst: + o.editor.MoveTo(0, extend) + case components.InputOTPCommandMoveLast: + o.editor.MoveTo(o.editor.RuneCount(), extend) + case components.InputOTPCommandDeleteBackward: + o.editor.DeleteBackward() + case components.InputOTPCommandDeleteForward: + o.editor.DeleteForward() + default: + return gfx.EventResult{} + } + return gfx.EventResult{Handled: true, Repaint: true} +} + +func (o *OTP) pointer(event gfx.PointerEvent) gfx.EventResult { + if event.Kind != gfx.PointerDown || event.Button != gfx.PointerButtonPrimary { + return gfx.EventResult{} + } + if !o.paintedID.IsZero() && event.Target != o.paintedID { + return gfx.EventResult{} + } + if !o.SelectAt(event.X) { + return gfx.EventResult{} + } + return gfx.EventResult{Handled: true, Repaint: true} +} + +func (o *OTP) draw(d *ui.DrawContext) { + id := o.fieldID + if id.IsZero() { + id = d.Node.ID + } + o.paintedID = id + o.clicked, o.hadClick = d.Canvas.ClickTarget() + + slots := o.slotCount() + focused := o.focused || (!id.IsZero() && d.Canvas.Focused() == id) + value := o.value + caret := o.activeSlot + selStart, selEnd := o.selStart, o.selEnd + hasSelection := o.hasSelection + compStart, compEnd := o.compStart, o.compEnd + hasCompose := o.hasCompose + showCaret := o.showCaret + if o.editor != nil { + value = o.editor.String() + selection := o.editor.Selection() + caret = o.editor.Caret() + selStart, selEnd = selection.Start, selection.End + hasSelection = selStart != selEnd + hasCompose = false + if composition, composing := o.editor.Composition(); composing { + hasCompose, compStart, compEnd = true, composition.Start, composition.End + } + showCaret = focused && !hasSelection && !o.disabled + } else if o.field != nil { + input := o.field.Snapshot(d.Frame, id, o.label, "") + value = input.Value + caret = utf8.RuneCountInString(input.Value[:clampOffset(input.Value, input.Caret)]) + selStart = utf8.RuneCountInString(input.Value[:clampOffset(input.Value, input.SelectionStart)]) + selEnd = utf8.RuneCountInString(input.Value[:clampOffset(input.Value, input.SelectionEnd)]) + compStart = utf8.RuneCountInString(input.Value[:clampOffset(input.Value, input.CompositionStart)]) + compEnd = utf8.RuneCountInString(input.Value[:clampOffset(input.Value, input.CompositionEnd)]) + hasSelection = selStart != selEnd + hasCompose = compStart != compEnd + focused = focused || input.Focused + showCaret = showCaret || input.ShowCaret + } + active := min(caret, slots-1) + snapshot := components.InputOTPSnapshot{ + ID: id, Label: o.label, Value: value, Slots: slots, GroupSize: o.group, + Disabled: o.disabled, ReadOnly: o.readOnly, Invalid: o.invalid, + Focused: focused, ShowCaret: !o.disabled && showCaret, + PlatformInput: o.editor != nil && !o.disabled && !o.readOnly, + HasActiveSlot: focused && !o.disabled, ActiveSlot: active, + HasSelection: hasSelection, SelectionStart: selStart, SelectionEnd: selEnd, + HasComposition: hasCompose, CompositionStart: compStart, CompositionEnd: compEnd, + } + o.layout = components.PaintInputOTP(d.Canvas, *d.Theme, d.Rect, snapshot) +} + +func clampOffset(value string, offset int) int { + if offset < 0 { + return 0 + } + if offset > len(value) { + return len(value) + } + return offset +} diff --git a/ui/inputotpview/inputotpview_test.go b/ui/inputotpview/inputotpview_test.go new file mode 100644 index 00000000..ac7ccc44 --- /dev/null +++ b/ui/inputotpview/inputotpview_test.go @@ -0,0 +1,200 @@ +package inputotpview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/inputotpview" + "github.com/vivaui/viva/window" +) + +func testTheme() gfx.Theme { return gfx.LightTheme() } + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 560, Height: 240}, view) + canvas.EndFrame() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := testTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := new(gfx.Canvas) + draw(page, canvas, view) + return page, canvas +} + +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + hits := canvas.Hits() + for index := len(hits) - 1; index >= 0; index-- { + if hits[index].Label == label { + return hits[index] + } + } + t.Fatalf("no hit labelled %q was painted", label) + return gfx.Hit{} +} + +func hasText(canvas *gfx.Canvas, value string) bool { + for _, label := range canvas.Texts() { + if label.Value == value { + return true + } + } + return false +} + +func caretCount(canvas *gfx.Canvas) int { + count := 0 + for _, rectangle := range canvas.Rectangles() { + if rectangle.Bounds.Width == 1 && rectangle.Bounds.Height == 16 { + count++ + } + } + return count +} + +type model struct { + editor *text.Editor + field ui.Field + code inputotpview.OTP +} + +func (m *model) init() { + m.editor = text.NewEditor("482901") + m.field.Bind(m.editor) + m.code = *inputotpview.New(). + Bind(&m.field, m.editor). + Slots(6).GroupSize(3).Filter(inputotpview.Digits) +} + +func (m *model) view(c ui.C) { m.code.View(c, "Verification code") } + +// The slots paint the editor's value, and the platform text service gets the +// same editor a ui.TextField would. +func TestViewPaintsEditorAndRoutesText(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.view) + control := hit(t, canvas, "Verification code") + if control.ID.IsZero() || control.Role != gfx.RoleTextField { + t.Fatalf("hit = %+v, want the control's text field", control) + } + for _, digit := range []string{"4", "8", "2", "9", "0", "1"} { + if !hasText(canvas, digit) { + t.Fatalf("digit %q was not painted", digit) + } + } + input := page.TextInput(window.TextInputContext{ID: control.ID}) + if input == nil || input.Editor != m.editor { + t.Fatalf("the platform text service got %+v, want the slot editor", input) + } +} + +// A press moves the editor's caret to the slot under the pointer. +func TestPointerSelectsSlot(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.view) + control := hit(t, canvas, "Verification code") + layout := m.code.Layout() + slot := layout.SlotBounds(1) + result := page.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: control.ID, + X: slot.X + slot.Width/2, Y: slot.Y + slot.Height/2, + }) + if !result.Handled { + t.Fatal("the press was not handled") + } + if m.editor.Caret() != 1 { + t.Fatalf("caret = %d, want slot 1", m.editor.Caret()) + } +} + +// Keys that move between slots are the control's, and go through the same +// editor. +func TestKeysMoveAndDelete(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.view) + control := hit(t, canvas, "Verification code") + if result := page.Key(gfx.KeyEvent{Key: gfx.KeyHome, Target: control.ID}); !result.Handled { + t.Fatal("Home was not handled") + } + if m.editor.Caret() != 0 { + t.Fatalf("caret = %d after Home, want 0", m.editor.Caret()) + } + if result := page.Key(gfx.KeyEvent{Key: gfx.KeyEnd, Target: control.ID}); !result.Handled { + t.Fatal("End was not handled") + } + if m.editor.Caret() != m.editor.RuneCount() { + t.Fatalf("caret = %d after End, want %d", m.editor.Caret(), m.editor.RuneCount()) + } + if result := page.Key(gfx.KeyEvent{Key: gfx.KeyBackspace, Target: control.ID}); !result.Handled { + t.Fatal("Backspace was not handled") + } + if m.editor.RuneCount() != 5 { + t.Fatalf("the code has %d digits after Backspace, want 5", m.editor.RuneCount()) + } +} + +// A static snapshot paints the same slots without an editor, including the +// active slot's caret and the states example's selection and composition. +func TestStaticSnapshot(t *testing.T) { + theme := testTheme() + page := ui.NewPage(ui.PageConfig{Theme: &theme}) + canvas := new(gfx.Canvas) + var code inputotpview.OTP + view := func(c ui.C) { + code = *inputotpview.New(). + Value("482").Slots(6).GroupSize(3). + Focused().ShowCaret().ActiveSlot(3) + code.View(c, "Verification code") + } + draw(page, canvas, view) + if !hasText(canvas, "4") || !hasText(canvas, "8") || !hasText(canvas, "2") { + t.Fatal("the static code was not painted") + } + if hasText(canvas, "9") { + t.Fatal("a digit beyond the code was painted") + } + if caret := caretCount(canvas); caret != 1 { + t.Fatalf("%d carets painted, want one in the active empty slot", caret) + } + + view = func(c ui.C) { + code = *inputotpview.New(). + Value("482901").Slots(6).GroupSize(3). + Invalid().Focused().ActiveSlot(0).Select(1, 3).Composition(3, 5) + code.View(c, "Verification code") + } + draw(page, canvas, view) + if caret := caretCount(canvas); caret != 0 { + t.Fatalf("%d carets painted through a complete code, want 0", caret) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, m.view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := new(model) + m.init() + page, canvas := open(b, m.view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, m.view) + } +} diff --git a/ui/markerview/markerview.go b/ui/markerview/markerview.go new file mode 100644 index 00000000..e663a514 --- /dev/null +++ b/ui/markerview/markerview.go @@ -0,0 +1,140 @@ +// Package markerview is the opt-in page control for a lightweight metadata +// marker: an icon and a label, a centered separator, a bottom-border row, or a +// progress row. It wraps components.Marker and components.MarkerProgress in a +// ui.Control, so a page declares the visible content with chained options: +// +// markerview.View(c, "Updated 2 minutes ago", markerview.New(). +// Icon(m.clockIcon).Label("Updated 2 minutes ago")) +// +// markerview.View(c, "October 2026", markerview.New(). +// Separator().Label("October 2026")) +// +// phase = (phase + 1) % 8 +// markerview.View(c, "Thinking", markerview.New(). +// Progress(phase).Label("Thinking")) +// +// The caller owns the progress phase and the frames that advance it, as for +// components.MarkerProgress: an unchanged marker schedules no work. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public components, gfx and ui +// packages. A Marker belongs to one place on one page: keep one in the model +// per marker, make its handlers and draw function once, and Reset its +// declaration in each paint. Do not copy one after it has been painted. +package markerview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Variant is the component's marker form: plain, centered separator or +// bottom-border. +type Variant = components.MarkerVariant + +// Phase is the spinner frame of a progress marker. +type Phase = components.SpinnerPhase + +// Marker is one marker's configuration and its page control. Configure it with +// the chainable methods after Reset and before View. +type Marker struct { + label string + icon gfx.Icon + variant Variant + progress bool + phase Phase + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool +} + +// New returns an empty plain marker. +func New() *Marker { return new(Marker) } + +// Reset clears the label, icon, variant and progress state. +func (m *Marker) Reset() *Marker { + m.label = "" + m.icon = gfx.Icon{} + m.variant = components.MarkerDefault + m.progress = false + m.phase = 0 + return m +} + +// Label is the marker's muted content. +func (m *Marker) Label(label string) *Marker { m.label = label; return m } + +// Icon paints a 16 pixel leading icon. A zero icon paints none. Progress takes +// its place when both are set. +func (m *Marker) Icon(icon gfx.Icon) *Marker { m.icon = icon; return m } + +// Separator centers the label between two rules, as a date separator does. It +// replaces Border. +func (m *Marker) Separator() *Marker { m.variant = components.MarkerSeparator; return m } + +// Border draws a rule below the row, as a section boundary does. It replaces +// Separator. +func (m *Marker) Border() *Marker { m.variant = components.MarkerBorder; return m } + +// Plain selects the default form with no separator or border. +func (m *Marker) Plain() *Marker { m.variant = components.MarkerDefault; return m } + +// Progress replaces the icon with the spinner frame, as work in progress does. +// Advancing the phase and scheduling the next frame are the caller's, as for +// components.MarkerProgress. +func (m *Marker) Progress(phase Phase) *Marker { + m.progress, m.phase = true, phase + return m +} + +// View declares the marker at c. label names the row for assistive technology. +// The box is full width and as tall as the component's line, plus its rule for +// the border variant; a Width or Height after it overrides that. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, marker *Marker) ui.Box { + if marker == nil { + panic("markerview: View needs its Marker") + } + marker.prepare() + return ui.Control(c, label, &marker.handlers). + FillWidth().Height(marker.height(*c.Theme())). + Draw(marker.drawFn) +} + +// View declares the marker at c, for a page that keeps the Marker in its +// model. +func (m *Marker) View(c ui.C, label string) ui.Box { return View(c, label, m) } + +func (m *Marker) prepare() { + if m.prepared { + return + } + m.prepared = true + m.drawFn = m.draw +} + +func (m *Marker) draw(d *ui.DrawContext) { + if m.progress { + components.MarkerProgress(d.Canvas, *d.Theme, d.Rect, m.variant, m.phase, m.label) + return + } + var icon *gfx.Icon + if m.icon.ViewBox > 0 { + icon = &m.icon + } + components.Marker(d.Canvas, *d.Theme, d.Rect, m.variant, icon, m.label) +} + +// height is the line the component paints, plus MarkerBorder's padding and +// rule. +func (m *Marker) height(theme gfx.Theme) float32 { + metrics := theme.Metrics + line := metrics.FontSizeM + 7 + if m.variant == components.MarkerBorder { + return line + 8*(metrics.ControlHeight/32) + 1 + } + return line +} diff --git a/ui/markerview/markerview_test.go b/ui/markerview/markerview_test.go new file mode 100644 index 00000000..dfc92718 --- /dev/null +++ b/ui/markerview/markerview_test.go @@ -0,0 +1,178 @@ +package markerview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/markerview" +) + +var testIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(4, 12), gfx.LineTo(20, 12), +}} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 360, Height: 240}, view) + canvas.EndFrame() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + canvas := new(gfx.Canvas) + canvas.SetReduceMotion(true) + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + draw(page, canvas, view) + return page, canvas +} + +func hasText(canvas *gfx.Canvas, value string) bool { + for _, text := range canvas.Texts() { + if text.Value == value { + return true + } + } + return false +} + +func textBounds(canvas *gfx.Canvas, value string) (gfx.Rect, bool) { + for _, text := range canvas.Texts() { + if text.Value == value { + return text.Bounds, true + } + } + return gfx.Rect{}, false +} + +// A default marker paints its icon and label in the muted metadata color. +func TestViewPaintsIconAndLabel(t *testing.T) { + theme := gfx.LightTheme() + marker := markerview.New() + view := func(c ui.C) { + marker.Reset().Icon(testIcon).Label("Updated 2 minutes ago") + marker.View(c, "Updated 2 minutes ago") + } + _, canvas := open(t, view) + if !hasText(canvas, "Updated 2 minutes ago") { + t.Fatal("the marker did not paint its label") + } + if len(canvas.Triangles()) == 0 { + t.Fatal("the marker did not paint its icon") + } + for _, text := range canvas.Texts() { + if text.Value == "Updated 2 minutes ago" && text.Style.Color != theme.MutedForeground { + t.Fatalf("marker label color = %+v, want muted foreground", text.Style.Color) + } + } +} + +// The separator variant centers the label between two rules. +func TestSeparatorPaintsRulesOnBothSides(t *testing.T) { + marker := markerview.New() + view := func(c ui.C) { + marker.Reset().Separator().Label("October 2026") + marker.View(c, "October 2026") + } + _, canvas := open(t, view) + bounds, ok := textBounds(canvas, "October 2026") + if !ok { + t.Fatal("the separator did not paint its label") + } + // Label bounds span the rest of the row; the rules sit outside the glyphs. + glyphEnd := bounds.X + canvas.TextWidth("October 2026", gfx.LightTheme().Metrics.FontSizeM) + var left, right int + for _, rectangle := range canvas.Rectangles() { + if rectangle.Bounds.Height > 1 { + continue + } + if rectangle.Bounds.X+rectangle.Bounds.Width <= bounds.X { + left++ + } + if rectangle.Bounds.X >= glyphEnd { + right++ + } + } + if left == 0 || right == 0 { + t.Fatalf("separator rules = %d left, %d right; want one on each side; text=%+v rects=%+v", left, right, bounds, canvas.Rectangles()) + } +} + +// The border variant paints a rule below the row. +func TestBorderPaintsARuleBelowTheLabel(t *testing.T) { + marker := markerview.New() + view := func(c ui.C) { + marker.Reset().Border().Icon(testIcon).Label("Release channel") + marker.View(c, "Release channel") + } + _, canvas := open(t, view) + bounds, ok := textBounds(canvas, "Release channel") + if !ok { + t.Fatal("the border marker did not paint its label") + } + for _, rectangle := range canvas.Rectangles() { + if rectangle.Bounds.Y >= bounds.Y+bounds.Height && rectangle.Bounds.Height <= 1 { + return + } + } + t.Fatalf("no rule was painted below the label at %+v", bounds) +} + +// Progress paints the caller's spinner frame in the icon slot. +func TestProgressPaintsSpinnerAndLabel(t *testing.T) { + marker := markerview.New() + view := func(c ui.C) { + marker.Reset().Progress(2).Label("Thinking") + marker.View(c, "Thinking") + } + _, canvas := open(t, view) + if !hasText(canvas, "Thinking") { + t.Fatal("the progress marker did not paint its label") + } + if len(canvas.Rectangles()) == 0 { + t.Fatal("the progress marker did not paint the spinner") + } + if canvas.Animating() { + t.Fatal("an unchanged progress marker requested another frame") + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + var plain, separator, border, progress markerview.Marker + view := func(c ui.C) { + plain.Reset().Icon(testIcon).Label("Default") + plain.View(c, "Default") + separator.Reset().Separator().Label("October 2026") + separator.View(c, "October 2026") + border.Reset().Border().Icon(testIcon).Label("Release channel") + border.View(c, "Release channel") + progress.Reset().Progress(2).Label("Thinking") + progress.View(c, "Thinking") + } + page, canvas := open(t, view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + var plain, separator, border, progress markerview.Marker + view := func(c ui.C) { + plain.Reset().Icon(testIcon).Label("Default") + plain.View(c, "Default") + separator.Reset().Separator().Label("October 2026") + separator.View(c, "October 2026") + border.Reset().Border().Icon(testIcon).Label("Release channel") + border.View(c, "Release channel") + progress.Reset().Progress(2).Label("Thinking") + progress.View(c, "Thinking") + } + page, canvas := open(b, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/metriccardview/metriccardview.go b/ui/metriccardview/metriccardview.go new file mode 100644 index 00000000..28f4e86d --- /dev/null +++ b/ui/metriccardview/metriccardview.go @@ -0,0 +1,140 @@ +// Package metriccardview is the opt-in page control for a dashboard metric: a +// title, a value and a trend, with an optional description and icon. A page +// declares the visible data with chained options: +// +// metriccardview.View(c, "Active sessions", metriccardview.New(). +// Title("Active sessions").Value("12,840"). +// Trend("+18.2% from last week").Up()). +// FillWidth().Height(150) +// +// It composes the page's own primitives, so the card participates in the page +// layout, theme and density. The caller supplies every string, the trend's +// direction and any icon; Content paints additional page content below the +// card's rows, such as a sparkline or a row of links. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public gfx and ui packages. A +// Metric is a value built with chained options; keep no state in it, build it +// from the model in each paint, and View allocates nothing on a warm paint. +package metriccardview + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// trendKind selects the trend row's color. +type trendKind uint8 + +const ( + trendNeutral trendKind = iota + trendUp + trendDown +) + +// Metric is one card's presentation. Its zero value is an empty card; New is +// its readable starting point. Every option returns the value, so a call site +// chains only what it shows. +type Metric struct { + title string + value string + trend string + description string + icon gfx.Icon + kind trendKind + content func(ui.C) +} + +// New returns an empty card. +func New() Metric { return Metric{} } + +// Title is the muted caption above the value. +func (m Metric) Title(title string) Metric { m.title = title; return m } + +// Value is the card's large numeric reading. +func (m Metric) Value(value string) Metric { m.value = value; return m } + +// Trend is the delta line below the value, such as "+18.2% from last week". +func (m Metric) Trend(trend string) Metric { m.trend = trend; return m } + +// Up paints the trend in the theme's success color: the metric moved the +// favorable way. +func (m Metric) Up() Metric { m.kind = trendUp; return m } + +// Down paints the trend in the theme's danger color: the metric moved the +// unfavorable way. +func (m Metric) Down() Metric { m.kind = trendDown; return m } + +// Neutral paints the trend in the muted foreground color. It is the zero +// value's color, so it is only needed to undo Up or Down. +func (m Metric) Neutral() Metric { m.kind = trendNeutral; return m } + +// Description is an optional muted line below the trend, such as the period the +// value covers. +func (m Metric) Description(description string) Metric { + m.description = description + return m +} + +// Icon paints a 16 pixel icon before the trailing edge of the title row. A zero +// icon paints none. +func (m Metric) Icon(icon gfx.Icon) Metric { m.icon = icon; return m } + +// Content paints caller content below the card's rows, inside its padding. The +// callback declares page elements, so their identities and handlers are the +// caller's own. It is not painted when nil. +func (m Metric) Content(content func(ui.C)) Metric { m.content = content; return m } + +// View declares the card at c. label names the card for assistive technology. +// Give it a size; the card is as tall as its rows and, when the caller gives a +// height, fills it. Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, metric Metric) ui.Box { + if c == nil { + panic("metriccardview: View needs a page") + } + theme := c.Theme() + metrics := theme.Metrics + card := ui.Column(c).Pad(metrics.PadSurface).Gap(metrics.GapItem*0.75). + Background(theme.Card).Border(1, theme.Border).Radius(metrics.RadiusSurface) + if label != "" { + card = card.HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + } + card.Children(func() { + if metric.title != "" || metric.icon.ViewBox > 0 { + ui.Row(c).FillWidth().Items(ui.Center).Gap(metrics.GapItem).Children(func() { + if metric.title != "" { + ui.Text(c, metric.title). + FontSize(metrics.FontSizeS).Weight(gfx.WeightMedium).Muted().Grow(1) + } else { + ui.Spacer(c).Grow(1) + } + if metric.icon.ViewBox > 0 { + ui.Icon(c, metric.icon).Size(16, 16).Muted() + } + }) + } + if metric.value != "" { + ui.Text(c, metric.value). + FontSize(metrics.FontSizeL - 2).Weight(gfx.WeightSemibold) + } + if metric.trend != "" { + trend := ui.Text(c, metric.trend). + FontSize(metrics.FontSizeS).Weight(gfx.WeightMedium) + switch metric.kind { + case trendUp: + trend.Color(theme.Success) + case trendDown: + trend.Color(theme.Danger) + default: + trend.Muted() + } + } + if metric.description != "" { + ui.Text(c, metric.description).FontSize(metrics.FontSizeS).Muted() + } + if metric.content != nil { + metric.content(c) + } + }) + return card +} diff --git a/ui/metriccardview/metriccardview_test.go b/ui/metriccardview/metriccardview_test.go new file mode 100644 index 00000000..c75d4ff6 --- /dev/null +++ b/ui/metriccardview/metriccardview_test.go @@ -0,0 +1,135 @@ +package metriccardview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/metriccardview" +) + +var testIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(4, 20), gfx.LineTo(20, 4), +}} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 360, Height: 240}, view) + canvas.EndFrame() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + canvas := new(gfx.Canvas) + canvas.SetReduceMotion(true) + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + draw(page, canvas, view) + return page, canvas +} + +func hasText(canvas *gfx.Canvas, value string) bool { + for _, text := range canvas.Texts() { + if text.Value == value { + return true + } + } + return false +} + +func textColor(canvas *gfx.Canvas, value string) (gfx.Color, bool) { + for _, text := range canvas.Texts() { + if text.Value == value { + return text.Style.Color, true + } + } + return gfx.Color{}, false +} + +// The view paints every part of the metric with the page's theme, including the +// description, the icon and the caller's content. +func TestViewPaintsTitleValueTrendDescriptionIconAndContent(t *testing.T) { + theme := gfx.LightTheme() + metric := metriccardview.New(). + Title("Active sessions").Value("12,840"). + Trend("+18.2% from last week").Up(). + Description("Compared with the previous 7 days"). + Icon(testIcon). + Content(func(c ui.C) { ui.Text(c, "Extra note") }) + view := func(c ui.C) { + metriccardview.View(c, "Active sessions", metric).FillWidth().Height(150) + } + _, canvas := open(t, view) + + for _, value := range []string{ + "Active sessions", "12,840", "+18.2% from last week", + "Compared with the previous 7 days", "Extra note", + } { + if !hasText(canvas, value) { + t.Fatalf("the card did not paint %q", value) + } + } + if color, ok := textColor(canvas, "+18.2% from last week"); !ok || color != theme.Success { + t.Fatalf("up trend color = %+v, want the theme's success color", color) + } + if len(canvas.Triangles()) == 0 { + t.Fatal("the card did not paint its icon") + } +} + +// Up and Down are the caller's direction choice, and Neutral is the default. +func TestViewPaintsTrendDirection(t *testing.T) { + for _, test := range []struct { + name string + apply func(metriccardview.Metric) metriccardview.Metric + want gfx.Color + }{ + {"up", func(m metriccardview.Metric) metriccardview.Metric { return m.Up() }, gfx.LightTheme().Success}, + {"down", func(m metriccardview.Metric) metriccardview.Metric { return m.Down() }, gfx.LightTheme().Danger}, + {"neutral", func(m metriccardview.Metric) metriccardview.Metric { return m.Neutral() }, gfx.LightTheme().MutedForeground}, + } { + t.Run(test.name, func(t *testing.T) { + metric := test.apply(metriccardview.New().Title("Metric").Value("1").Trend("delta")) + view := func(c ui.C) { + metriccardview.View(c, "Metric", metric).FillWidth().Height(120) + } + _, canvas := open(t, view) + if color, ok := textColor(canvas, "delta"); !ok || color != test.want { + t.Fatalf("trend color = %+v, want %+v", color, test.want) + } + }) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + metric := metriccardview.New(). + Title("Active sessions").Value("12,840"). + Trend("+18.2% from last week").Up(). + Description("Compared with the previous 7 days"). + Icon(testIcon) + view := func(c ui.C) { + metriccardview.View(c, "Active sessions", metric).FillWidth().Height(150) + } + page, canvas := open(t, view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + metric := metriccardview.New(). + Title("Active sessions").Value("12,840"). + Trend("+18.2% from last week").Up(). + Description("Compared with the previous 7 days"). + Icon(testIcon) + view := func(c ui.C) { + metriccardview.View(c, "Active sessions", metric).FillWidth().Height(150) + } + page, canvas := open(b, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/questionnaireview/questionnaireview.go b/ui/questionnaireview/questionnaireview.go new file mode 100644 index 00000000..5c168b14 --- /dev/null +++ b/ui/questionnaireview/questionnaireview.go @@ -0,0 +1,241 @@ +// Package questionnaireview is the opt-in page control for the questionnaire +// item of package components: a progress line, a question title and +// description, single or multiple choice answers, and Back, Skip and Continue +// actions. The application owns the visible labels, the selection and what each +// action does: +// +// question := questionnaireview.New(). +// Progress("Question 2 of 5"). +// Title("What should Viva optimize first?"). +// Description("Answers stay in application state."). +// Choice(m.choiceIDs[0], "Low memory", m.answer == 0, m.chooseLow). +// Choice(m.choiceIDs[1], "Fast startup", m.answer == 1, m.chooseStartup). +// Choice(m.choiceIDs[2], "Small binaries", m.answer == 2, m.chooseBinaries). +// Back(m.previousID, "Back", m.back). +// Skip(m.skipID, "Skip", m.skip). +// Continue(m.nextID, "Continue", m.next) +// question.View(c, "Questionnaire").FillWidth() +// +// Choices and actions are chained; the view paints exactly the Checked values +// the caller supplies and calls the caller's callback after a click, so the +// application is the only owner of the answer state and the navigation. Single +// and Multiple choose the radio or checkbox indicator; there is no second +// constructor. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Questionnaire in the model: Reset keeps the choice +// storage, so re-declaring the same answers every paint allocates nothing. +// Do not copy a Questionnaire after it has been declared. +package questionnaireview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Choice is one answer option: the caller's identity, visible labels and +// selected state, and the callback run after a click. +type Choice struct { + ID gfx.ID + Label string + Description string + Shortcut string + Checked bool + Disabled bool + OnSelect func() +} + +// action is one footer action. +type action struct { + id gfx.ID + label string + onClick func() + disabled bool +} + +// Questionnaire is one questionnaire item and its page control. +type Questionnaire struct { + progress string + title string + description string + multiple bool + invalid bool + choices []Choice + back action + skip action + next action + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool +} + +// New returns an empty single-choice question. +func New() *Questionnaire { return new(Questionnaire) } + +// Reset clears the text, choices and actions, keeping the choice storage so a +// page that rebuilds the same question every paint does not allocate. +func (q *Questionnaire) Reset() *Questionnaire { + q.progress, q.title, q.description = "", "", "" + q.multiple, q.invalid = false, false + q.choices = q.choices[:0] + q.back, q.skip, q.next = action{}, action{}, action{} + return q +} + +// Progress is the caller-formatted line above the question, such as +// "Question 2 of 5". +func (q *Questionnaire) Progress(text string) *Questionnaire { + q.progress = text + return q +} + +// Title is the question. +func (q *Questionnaire) Title(text string) *Questionnaire { + q.title = text + return q +} + +// Description is the muted line under the title. +func (q *Questionnaire) Description(text string) *Questionnaire { + q.description = text + return q +} + +// Single selects the radio indicator, the default. +func (q *Questionnaire) Single() *Questionnaire { + q.multiple = false + return q +} + +// Multiple selects the checkbox indicator. +func (q *Questionnaire) Multiple() *Questionnaire { + q.multiple = true + return q +} + +// Invalid paints the question and its choices as failing validation. +func (q *Questionnaire) Invalid() *Questionnaire { + q.invalid = true + return q +} + +// Choice adds one answer. The view paints Checked as given and runs onSelect, +// which may be nil, after the click is read. +func (q *Questionnaire) Choice(id gfx.ID, label string, checked bool, onSelect func()) *Questionnaire { + if len(q.choices) == cap(q.choices) { + q.choices = append(q.choices, Choice{}) + } else { + q.choices = q.choices[:len(q.choices)+1] + q.choices[len(q.choices)-1] = Choice{} + } + choice := &q.choices[len(q.choices)-1] + choice.ID, choice.Label, choice.Checked, choice.OnSelect = id, label, checked, onSelect + return q +} + +// Detail sets the description and shortcut badge of the choice added last. +func (q *Questionnaire) Detail(description, shortcut string) *Questionnaire { + if len(q.choices) == 0 { + return q + } + choice := &q.choices[len(q.choices)-1] + choice.Description, choice.Shortcut = description, shortcut + return q +} + +// DisableChoice paints the choice added last inert. +func (q *Questionnaire) DisableChoice() *Questionnaire { + if len(q.choices) > 0 { + q.choices[len(q.choices)-1].Disabled = true + } + return q +} + +// Back adds the previous action at the start. An empty label omits it. +func (q *Questionnaire) Back(id gfx.ID, label string, onClick func()) *Questionnaire { + q.back = action{id: id, label: label, onClick: onClick} + return q +} + +// Skip adds the skip action next to Continue. An empty label omits it. +func (q *Questionnaire) Skip(id gfx.ID, label string, onClick func()) *Questionnaire { + q.skip = action{id: id, label: label, onClick: onClick} + return q +} + +// Continue adds the primary action at the end. An empty label omits it. +func (q *Questionnaire) Continue(id gfx.ID, label string, onClick func()) *Questionnaire { + q.next = action{id: id, label: label, onClick: onClick} + return q +} + +// DisableContinue paints the Continue action inert. +func (q *Questionnaire) DisableContinue() *Questionnaire { + q.next.disabled = true + return q +} + +// View declares the question at c. label names the group for assistive +// technology. Give it a width and the height the item may use; choices and +// actions that do not fit are not painted, as in the component. +// +// Declare the view on its own, not inside a Memo. +func (q *Questionnaire) View(c ui.C, label string) ui.Box { + if q == nil { + panic("questionnaireview: View needs its Questionnaire") + } + q.prepare() + return ui.Control(c, label, &q.handlers).Draw(q.drawFn) +} + +func (q *Questionnaire) prepare() { + if q.prepared { + return + } + q.prepared = true + q.handlers.Role = gfx.RoleGroup + q.drawFn = q.draw +} + +func (q *Questionnaire) draw(d *ui.DrawContext) { + choiceType := components.QuestionnaireRadio + if q.multiple { + choiceType = components.QuestionnaireCheckbox + } + item := components.BeginQuestionnaire(d.Canvas, *d.Theme, d.Rect, components.QuestionnaireData{ + Progress: q.progress, Title: q.title, Description: q.description, + ChoiceType: choiceType, Invalid: q.invalid, + }) + for index := range q.choices { + choice := &q.choices[index] + item.AddChoice(components.QuestionnaireChoice{ + ID: choice.ID, Label: choice.Label, Description: choice.Description, + Shortcut: choice.Shortcut, Checked: choice.Checked, Disabled: choice.Disabled, + }) + } + item.PaintActions(components.QuestionnaireActions{ + PreviousID: q.back.id, PreviousLabel: q.back.label, + SkipID: q.skip.id, SkipLabel: q.skip.label, + NextID: q.next.id, NextLabel: q.next.label, NextDisabled: q.next.disabled, + }) + for index := range q.choices { + choice := &q.choices[index] + if !choice.ID.IsZero() && !choice.Disabled && d.Canvas.Clicked(choice.ID) && choice.OnSelect != nil { + choice.OnSelect() + } + } + q.notify(q.back, d) + q.notify(q.skip, d) + q.notify(q.next, d) +} + +func (q *Questionnaire) notify(item action, d *ui.DrawContext) { + if item.label == "" || item.id.IsZero() || item.disabled { + return + } + if d.Canvas.Clicked(item.id) && item.onClick != nil { + item.onClick() + } +} diff --git a/ui/questionnaireview/questionnaireview_test.go b/ui/questionnaireview/questionnaireview_test.go new file mode 100644 index 00000000..ee9676bc --- /dev/null +++ b/ui/questionnaireview/questionnaireview_test.go @@ -0,0 +1,178 @@ +package questionnaireview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/questionnaireview" +) + +var ( + choiceID = gfx.Item(101) + secondID = gfx.Item(102) + thirdID = gfx.Item(103) + previousID = gfx.Item(104) + skipID = gfx.Item(105) + nextID = gfx.Item(106) +) + +func testTheme() gfx.Theme { return gfx.LightTheme() } + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 560, Height: 520}, view) + canvas.EndFrame() +} + +func drawClick(page *ui.Page, canvas *gfx.Canvas, view func(ui.C), id gfx.ID) { + canvas.BeginEventPass(id, gfx.ClickInfo{}) + draw(page, canvas, view) + canvas.EndEventPass() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := testTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := new(gfx.Canvas) + draw(page, canvas, view) + return page, canvas +} + +func hit(t *testing.T, canvas *gfx.Canvas, label string) gfx.Hit { + t.Helper() + hits := canvas.Hits() + for index := len(hits) - 1; index >= 0; index-- { + if hits[index].Label == label { + return hits[index] + } + } + t.Fatalf("no hit labelled %q was painted", label) + return gfx.Hit{} +} + +func hasText(canvas *gfx.Canvas, value string) bool { + for _, label := range canvas.Texts() { + if label.Value == value { + return true + } + } + return false +} + +type model struct { + question questionnaireview.Questionnaire + selected int + backs, skips, nexts int + choose [3]func() + back, skip, continueNext func() +} + +func (m *model) init() { + for index := range m.choose { + value := index + m.choose[index] = func() { m.selected = value } + } + m.back = func() { m.backs++ } + m.skip = func() { m.skips++ } + m.continueNext = func() { m.nexts++ } +} + +func (m *model) rebuild() { + m.question.Reset(). + Progress("Question 2 of 5"). + Title("What should Viva optimize first?"). + Description("Answers stay in application state."). + Single(). + Choice(choiceID, "Low memory", m.selected == 0, m.choose[0]). + Choice(secondID, "Fast startup", m.selected == 1, m.choose[1]). + Choice(thirdID, "Small binaries", m.selected == 2, m.choose[2]). + Back(previousID, "Back", m.back). + Skip(skipID, "Skip", m.skip). + Continue(nextID, "Continue", m.continueNext) +} + +func (m *model) view(c ui.C) { + m.rebuild() + m.question.View(c, "Questionnaire").Height(480) +} + +// The question paints the caller's progress, title, description, labels and +// actions, and a choice's callback runs after its click is read. +func TestQuestionPaintsAndCallsBack(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.view) + for _, value := range []string{ + "Question 2 of 5", "What should Viva optimize first?", + "Answers stay in application state.", "Low memory", "Fast startup", + "Small binaries", "Back", "Skip", "Continue", + } { + if !hasText(canvas, value) { + t.Fatalf("%q was not painted", value) + } + } + choice := hit(t, canvas, "Fast startup") + if choice.ID != secondID || choice.Role != gfx.RoleRadio { + t.Fatalf("choice = %+v, want the caller's radio identity", choice) + } + + drawClick(page, canvas, m.view, secondID) + if m.selected != 1 { + t.Fatalf("selection = %d after the click, want 1", m.selected) + } + drawClick(page, canvas, m.view, nextID) + if m.nexts != 1 { + t.Fatalf("Continue ran %d times, want 1", m.nexts) + } +} + +// Multiple choices paint checkbox indicators, and every action has its own +// callback. +func TestMultipleChoicesAndActions(t *testing.T) { + m := new(model) + m.init() + view := func(c ui.C) { + m.question.Reset(). + Title("Which performance goals matter?"). + Multiple(). + Choice(choiceID, "Low memory", true, nil). + Choice(secondID, "Fast startup", false, nil). + Back(previousID, "Back", func() { m.backs++ }). + Skip(skipID, "Skip", func() { m.skips++ }). + Continue(nextID, "Continue", func() { m.nexts++ }) + m.question.View(c, "Questionnaire").Height(400) + } + page, canvas := open(t, view) + choice := hit(t, canvas, "Low memory") + if choice.Role != gfx.RoleCheckbox || !choice.Checked { + t.Fatalf("choice = %+v, want a checked checkbox", choice) + } + drawClick(page, canvas, view, previousID) + drawClick(page, canvas, view, skipID) + if m.backs != 1 || m.skips != 1 { + t.Fatalf("Back ran %d times and Skip %d, want 1 each", m.backs, m.skips) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, m.view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := new(model) + m.init() + page, canvas := open(b, m.view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, m.view) + } +} diff --git a/ui/sidebarview/sidebarview.go b/ui/sidebarview/sidebarview.go new file mode 100644 index 00000000..5fa94ba7 --- /dev/null +++ b/ui/sidebarview/sidebarview.go @@ -0,0 +1,438 @@ +// Package sidebarview is the opt-in page control for the application sidebar. +// It wraps components.BeginSidebarWithOptions in a ui.Control, so a page +// declares a header, sections of items and a footer without calling the +// component itself: +// +// m.nav.Reset().Title("Viva Studio").Fixed(). +// Group("Workspace"). +// Item(m.overviewID, "Overview").Icon("O").Badge("12"). +// Active(m.section == "overview"). +// Item(m.componentsID, "Components").Icon("C"). +// Active(m.section == "components"). +// Separator(). +// Account(m.accountID, "Skyler").Icon("S") +// sidebarview.View(c, "Application navigation", &m.nav).Width(240).FillHeight() +// +// The caller owns the selection, the collapsed/open state and the callbacks. +// Active marks the current destination, Collapsed asks for the icon-only rail, +// and OnSelect is told the caller's identity when one of the declared items is +// clicked. Selected and Clicked report the last paint's click for a page that +// would rather read it where the sidebar is declared. +// +// Declarations are rebuilt every paint: call Reset, declare the entries in +// order, then View. The slices keep their capacity, so a warm paint allocates +// nothing. Keep a Sidebar in the model beside its state; its handlers and draw +// function are made once. Do not copy one after View has painted it. +// +// It is a separate package so an application that does not import it pays +// nothing for it. It depends only on the public components, gfx and ui +// packages. +package sidebarview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Side is the desktop edge carrying the sidebar's separator. +type Side = components.SidebarSide + +const ( + Left Side = components.SidebarLeft + Right Side = components.SidebarRight +) + +type entryKind uint8 + +const ( + entryGroup entryKind = iota + entryItem + entrySeparator +) + +// sidebarEntry is one declared group, item or separator. The slice is reused +// between paints, so a declaration that resets and rebuilds the same entries +// does not allocate. +type sidebarEntry struct { + kind entryKind + label string + item components.SidebarMenuItem + sub []components.SidebarSubItem + subCount int +} + +// Sidebar is one sidebar's declarations and its page control. Configure it +// with the chainable methods after Reset and before View; the caller's model +// owns the values the methods are given. +type Sidebar struct { + title string + side Side + variant components.SidebarVariant + collapsible components.SidebarCollapsible + collapsed bool + + entries []sidebarEntry + entryCount int + footers []components.SidebarMenuItem + footerCount int + + currentEntry int + currentSub int + currentFooter int + + // OnSelect is told the caller's identity when one of the declared items, + // sub items or footer items is clicked. It runs in the click's event pass, + // where changing the model is allowed. It is optional. + OnSelect func(gfx.ID) + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + + clicked gfx.ID + hadClick bool + selected gfx.ID +} + +// New returns a sidebar with the component's fixed behavior and no +// declarations. The zero value also paints; choose Fixed, IconCollapse or +// Offcanvas before asking it to collapse. +func New() *Sidebar { return &Sidebar{collapsible: components.SidebarFixed} } + +// Reset forgets the declared groups, items, sub items and footers and returns +// the sidebar to the start of a new declaration. The title, surface, collapse +// configuration, callback and storage are kept. +func (s *Sidebar) Reset() *Sidebar { + for index := 0; index < s.entryCount; index++ { + entry := &s.entries[index] + entry.kind = entryGroup + entry.label = "" + entry.item = components.SidebarMenuItem{} + entry.sub = entry.sub[:0] + entry.subCount = 0 + } + for index := 0; index < s.footerCount; index++ { + s.footers[index] = components.SidebarMenuItem{} + } + s.entryCount, s.footerCount = 0, 0 + s.currentEntry, s.currentSub, s.currentFooter = -1, -1, -1 + return s +} + +// Title is the product or workspace header. An empty title paints none. +func (s *Sidebar) Title(title string) *Sidebar { s.title = title; return s } + +// Side selects the desktop edge carrying the separator. +func (s *Sidebar) Side(side Side) *Sidebar { s.side = side; return s } + +// Standard paints the plain surface. It is the zero value's surface. +func (s *Sidebar) Standard() *Sidebar { s.variant = components.SidebarStandard; return s } + +// Floating paints the rounded, ringed card inside a small margin. +func (s *Sidebar) Floating() *Sidebar { s.variant = components.SidebarFloating; return s } + +// Inset paints the plain surface around a page card; paint the page side with +// components.PaintSidebarInset. +func (s *Sidebar) Inset() *Sidebar { s.variant = components.SidebarInset; return s } + +// Fixed keeps the sidebar in place when it collapses. It is the default. +func (s *Sidebar) Fixed() *Sidebar { s.collapsible = components.SidebarFixed; return s } + +// IconCollapse collapses to an icon rail; labels and groups are suppressed. +func (s *Sidebar) IconCollapse() *Sidebar { + s.collapsible = components.SidebarIcon + return s +} + +// Offcanvas collapses to no commands at all. +func (s *Sidebar) Offcanvas() *Sidebar { + s.collapsible = components.SidebarOffcanvas + return s +} + +// Collapsed asks for the collapsed state. Callers own it, so a toggle is the +// caller's own control. It only has an effect with IconCollapse or Offcanvas. +func (s *Sidebar) Collapsed(collapsed bool) *Sidebar { + s.collapsed = collapsed + return s +} + +// Group declares a section caption. Items declared after it belong to it until +// the next Group. +func (s *Sidebar) Group(label string) *Sidebar { + entry := s.appendEntry(entryGroup) + entry.label = label + return s +} + +// Item declares one navigation destination with the caller's identity. A zero +// ID paints an inert item. Configure it with Icon, VectorIcon, Badge, Active, +// Disabled and Outline; declare an open sub menu with Sub. +func (s *Sidebar) Item(id gfx.ID, label string) *Sidebar { + entry := s.appendEntry(entryItem) + entry.item.ID, entry.item.Label = id, label + return s +} + +// Separator declares a divider between content items. +func (s *Sidebar) Separator() *Sidebar { + s.appendEntry(entrySeparator) + return s +} + +// Sub declares one item of the current item's sub menu. Declare sub items only +// while the section is open; that open state is the caller's. +func (s *Sidebar) Sub(id gfx.ID, label string) *Sidebar { + if s.currentEntry < 0 || s.currentEntry >= s.entryCount { + return s + } + entry := &s.entries[s.currentEntry] + if entry.kind != entryItem { + return s + } + if entry.subCount < len(entry.sub) { + entry.sub[entry.subCount] = components.SidebarSubItem{ID: id, Label: label} + } else { + entry.sub = append(entry.sub, components.SidebarSubItem{ID: id, Label: label}) + } + s.currentSub = entry.subCount + entry.subCount++ + return s +} + +// Footer declares a menu item against the bottom edge, above footers declared +// before it. +func (s *Sidebar) Footer(id gfx.ID, label string) *Sidebar { + item := s.appendFooter() + item.ID, item.Label = id, label + return s +} + +// Account declares the signed-in account as a footer item. It is Footer for a +// row whose identity and label are the account's. +func (s *Sidebar) Account(id gfx.ID, label string) *Sidebar { + item := s.appendFooter() + item.ID, item.Label = id, label + return s +} + +// Icon sets the current item's text glyph. +func (s *Sidebar) Icon(icon string) *Sidebar { + if item := s.currentItem(); item != nil { + item.Icon = icon + } + return s +} + +// VectorIcon sets the current item's vector icon, which paints instead of the +// text glyph. +func (s *Sidebar) VectorIcon(icon gfx.Icon) *Sidebar { + if item := s.currentItem(); item != nil { + item.VectorIcon = icon + } + return s +} + +// Badge sets the current item's trailing count or short label. +func (s *Sidebar) Badge(badge string) *Sidebar { + if item := s.currentItem(); item != nil { + item.Trailing = badge + } + return s +} + +// Active marks the current item as the selected destination. The caller owns +// the selection, so this is set from the model on every paint. +func (s *Sidebar) Active(active bool) *Sidebar { + if item := s.currentItem(); item != nil { + item.Active = active + } + return s +} + +// Disabled paints the current item inert. +func (s *Sidebar) Disabled(disabled bool) *Sidebar { + if item := s.currentItem(); item != nil { + item.Disabled = disabled + } + return s +} + +// Outline paints the current item with the outlined menu-button recipe. +func (s *Sidebar) Outline() *Sidebar { + if item := s.currentItem(); item != nil { + item.Variant = components.SidebarMenuOutline + } + return s +} + +// SubActive marks the current sub item as the selected destination. +func (s *Sidebar) SubActive(active bool) *Sidebar { + if sub := s.currentSubItem(); sub != nil { + sub.Active = active + } + return s +} + +// SubDisabled paints the current sub item inert. +func (s *Sidebar) SubDisabled(disabled bool) *Sidebar { + if sub := s.currentSubItem(); sub != nil { + sub.Disabled = disabled + } + return s +} + +// View declares the sidebar at c. label names it for assistive technology. Give +// it a width and height; the component fills the box. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, sidebar *Sidebar) ui.Box { + if sidebar == nil { + panic("sidebarview: View needs its Sidebar") + } + sidebar.prepare() + return ui.Control(c, label, &sidebar.handlers).Draw(sidebar.drawFn) +} + +// View declares the sidebar at c, for a page that keeps the Sidebar in its +// model. +func (s *Sidebar) View(c ui.C, label string) ui.Box { return View(c, label, s) } + +// Selected is the identity clicked in the paint just made, or zero. It is not +// retained across paints: read it after View, where the click is handled. +func (s *Sidebar) Selected() gfx.ID { return s.selected } + +// Clicked reports whether the paint just made delivered a click on id. It is +// false in ordinary paints. Ask it after View. +func (s *Sidebar) Clicked(id gfx.ID) bool { + return s.hadClick && !id.IsZero() && s.clicked == id +} + +func (s *Sidebar) prepare() { + if s.prepared { + return + } + s.prepared = true + s.handlers.Role = gfx.RoleGroup + s.drawFn = s.draw +} + +func (s *Sidebar) draw(d *ui.DrawContext) { + s.clicked, s.hadClick = d.Canvas.ClickTarget() + s.selected = gfx.ID{} + theme := *d.Theme + options := components.SidebarOptions{ + Side: s.side, Variant: s.variant, Collapsible: s.collapsible, Collapsed: s.collapsed, + } + sidebar := components.BeginSidebarWithOptions(d.Canvas, theme, d.Rect, s.title, options) + for index := 0; index < s.footerCount; index++ { + sidebar.AddFooterMenuItem(s.footers[index]) + } + for index := 0; index < s.entryCount; index++ { + entry := &s.entries[index] + switch entry.kind { + case entryGroup: + sidebar.AddGroup(entry.label) + case entrySeparator: + sidebar.AddSeparator() + case entryItem: + sidebar.AddMenuItem(entry.item) + if entry.subCount > 0 { + sidebar.AddSubMenu(entry.sub[:entry.subCount]) + } + } + } + if s.hadClick && s.owns(s.clicked) { + s.selected = s.clicked + if s.OnSelect != nil { + s.OnSelect(s.clicked) + } + } +} + +// appendEntry starts one content declaration, reusing its storage. +func (s *Sidebar) appendEntry(kind entryKind) *sidebarEntry { + if s.entryCount == len(s.entries) { + s.entries = append(s.entries, sidebarEntry{}) + } + entry := &s.entries[s.entryCount] + entry.kind = kind + entry.label = "" + entry.item = components.SidebarMenuItem{} + entry.sub = entry.sub[:0] + entry.subCount = 0 + s.currentEntry = s.entryCount + s.currentSub = -1 + s.currentFooter = -1 + s.entryCount++ + return entry +} + +// appendFooter starts one footer declaration, reusing its storage. +func (s *Sidebar) appendFooter() *components.SidebarMenuItem { + if s.footerCount == len(s.footers) { + s.footers = append(s.footers, components.SidebarMenuItem{}) + } + item := &s.footers[s.footerCount] + *item = components.SidebarMenuItem{} + s.footerCount++ + s.currentEntry = -1 + s.currentSub = -1 + s.currentFooter = s.footerCount - 1 + return item +} + +// currentItem is the item or footer the value methods configure. +func (s *Sidebar) currentItem() *components.SidebarMenuItem { + if s.currentFooter >= 0 && s.currentFooter < s.footerCount { + return &s.footers[s.currentFooter] + } + if s.currentEntry < 0 || s.currentEntry >= s.entryCount { + return nil + } + entry := &s.entries[s.currentEntry] + if entry.kind != entryItem { + return nil + } + return &entry.item +} + +// currentSubItem is the sub item the sub value methods configure. +func (s *Sidebar) currentSubItem() *components.SidebarSubItem { + if s.currentSub < 0 || s.currentEntry < 0 || s.currentEntry >= s.entryCount { + return nil + } + entry := &s.entries[s.currentEntry] + if entry.kind != entryItem || s.currentSub >= entry.subCount { + return nil + } + return &entry.sub[s.currentSub] +} + +// owns reports whether id names one of the declared items. +func (s *Sidebar) owns(id gfx.ID) bool { + if id.IsZero() { + return false + } + for index := 0; index < s.entryCount; index++ { + entry := &s.entries[index] + if entry.kind != entryItem { + continue + } + if entry.item.ID == id { + return true + } + for sub := 0; sub < entry.subCount; sub++ { + if entry.sub[sub].ID == id { + return true + } + } + } + for index := 0; index < s.footerCount; index++ { + if s.footers[index].ID == id { + return true + } + } + return false +} diff --git a/ui/sidebarview/sidebarview_test.go b/ui/sidebarview/sidebarview_test.go new file mode 100644 index 00000000..beedd4b2 --- /dev/null +++ b/ui/sidebarview/sidebarview_test.go @@ -0,0 +1,195 @@ +package sidebarview_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/sidebarview" +) + +var ( + overviewID = gfx.Item(1) + componentsID = gfx.Item(2) + benchmarksID = gfx.Item(3) + buttonsID = gfx.Item(4) + inputsID = gfx.Item(5) + settingsID = gfx.Item(6) + accountID = gfx.Item(7) +) + +type model struct { + sidebar sidebarview.Sidebar + selected gfx.ID + clicks int +} + +func (m *model) init() { + m.sidebar.OnSelect = func(id gfx.ID) { + m.clicks++ + m.selected = id + } +} + +func (m *model) declare(collapsed bool) { + m.sidebar.Reset().Title("Viva Studio").Fixed().Collapsed(collapsed) + if collapsed { + m.sidebar.IconCollapse() + } + m.sidebar.Group("Workspace"). + Item(overviewID, "Overview").Icon("O").Badge("12").Active(true). + Item(componentsID, "Components").Icon("C"). + Sub(buttonsID, "Buttons").SubActive(true). + Sub(inputsID, "Inputs"). + Item(benchmarksID, "Benchmarks").Icon("B"). + Separator(). + Footer(settingsID, "Settings").Icon("S"). + Account(accountID, "Skyler").Icon("S") +} + +func (m *model) view(c ui.C) { + m.declare(false) + sidebarview.View(c, "Application navigation", &m.sidebar).Size(230, 420) +} + +func (m *model) collapsedView(c ui.C) { + m.declare(true) + sidebarview.View(c, "Application navigation", &m.sidebar).Size(56, 420) +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 460}, view) + canvas.EndFrame() +} + +func drawClick(page *ui.Page, canvas *gfx.Canvas, view func(ui.C), id gfx.ID) { + canvas.BeginEventPass(id, gfx.ClickInfo{}) + draw(page, canvas, view) + canvas.EndEventPass() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + canvas := new(gfx.Canvas) + canvas.SetReduceMotion(true) + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + draw(page, canvas, view) + return page, canvas +} + +func hasText(canvas *gfx.Canvas, value string) bool { + for _, text := range canvas.Texts() { + if text.Value == value { + return true + } + } + return false +} + +func findHit(canvas *gfx.Canvas, id gfx.ID) (gfx.Hit, bool) { + for _, hit := range canvas.Hits() { + if hit.ID == id { + return hit, true + } + } + return gfx.Hit{}, false +} + +// The view paints the header, group, items, badge, sub items and footer, and +// the component's menu-button semantics carry the caller's identities. +func TestViewPaintsHeaderItemsBadgeAndFooter(t *testing.T) { + m := new(model) + m.init() + _, canvas := open(t, m.view) + + for _, value := range []string{"Viva Studio", "Workspace", "Overview", "12", "Components", "Buttons", "Benchmarks", "Settings", "Skyler"} { + if !hasText(canvas, value) { + t.Fatalf("the sidebar did not paint %q", value) + } + } + hit, ok := findHit(canvas, overviewID) + if !ok { + t.Fatal("the active item has no hit") + } + if hit.Role != gfx.RoleMenuItem || !hit.Selected { + t.Fatalf("active item semantics = %+v, want a selected menu item", hit) + } + if _, ok := findHit(canvas, settingsID); !ok { + t.Fatal("the footer item has no hit") + } +} + +// A click calls OnSelect with the caller's identity, and Clicked and Selected +// report it for the paint that delivered it. +func TestClickReportsTheCallerIdentity(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.view) + + drawClick(page, canvas, m.view, componentsID) + if m.clicks != 1 || m.selected != componentsID { + t.Fatalf("OnSelect ran %d times with %v, want once with %v", m.clicks, m.selected, componentsID) + } + if !m.sidebar.Clicked(componentsID) || m.sidebar.Selected() != componentsID { + t.Fatal("Clicked or Selected did not report the clicked item") + } + + draw(page, canvas, m.view) + if m.clicks != 1 { + t.Fatalf("an ordinary paint ran OnSelect %d times", m.clicks) + } + if m.sidebar.Clicked(componentsID) || !m.sidebar.Selected().IsZero() { + t.Fatal("an ordinary paint reported a click") + } +} + +// A click on an identity the sidebar did not declare is not reported. +func TestForeignClickIsIgnored(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.view) + drawClick(page, canvas, m.view, gfx.Item(99)) + if m.clicks != 0 || !m.sidebar.Selected().IsZero() { + t.Fatalf("a foreign click was reported: %v / %v", m.clicks, m.sidebar.Selected()) + } +} + +// Collapsed with IconCollapse keeps the icons and hides labels, groups and +// badges; the caller owns the collapsed state. +func TestIconCollapsedSidebarHidesLabelsAndKeepsIcons(t *testing.T) { + m := new(model) + m.init() + _, canvas := open(t, m.collapsedView) + if hasText(canvas, "Viva Studio") || hasText(canvas, "Overview") || hasText(canvas, "Workspace") { + t.Fatal("the icon-collapsed sidebar painted a label or group") + } + if !hasText(canvas, "O") || !hasText(canvas, "C") { + t.Fatal("the icon-collapsed sidebar did not paint its icons") + } + if _, ok := findHit(canvas, overviewID); !ok { + t.Fatal("the icon-collapsed item has no hit") + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + m.init() + page, canvas := open(t, m.view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, m.view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := new(model) + m.init() + page, canvas := open(b, m.view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, m.view) + } +} diff --git a/ui/skeletonview/skeletonview.go b/ui/skeletonview/skeletonview.go new file mode 100644 index 00000000..37844356 --- /dev/null +++ b/ui/skeletonview/skeletonview.go @@ -0,0 +1,158 @@ +// Package skeletonview is the opt-in page control for static loading +// placeholders. A page declares each placeholder with its kind, size, radius and +// opacity, then views it: +// +// line := skeletonview.New() +// ... +// line.Reset().Text().Size(236, 14).Radius(4).Opacity(1) +// skeletonview.View(c, "Body line", line) +// +// avatar := skeletonview.New() +// avatar.Reset().Circle().Size(56, 56).Opacity(0.75) +// skeletonview.View(c, "Avatar placeholder", avatar) +// +// Text is a thin rounded line, Circle is a circle inside the shorter side, and +// Block is the default rounded surface. Size is the placeholder's page box; +// Radius overrides the corner radius; Opacity fades the muted surface without +// changing what it occupies. None of them is a visual constructor: New plus the +// chained options is the only way to declare one. +// +// There is no timer, shimmer worker or implicit animation. The component paints +// one neutral surface, and a page that wants motion schedules it explicitly, as +// it would for any other frame. An idle placeholder does no work. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Skeleton in the model: its draw function is made once, +// so a warm paint allocates nothing. Do not copy one after it has been painted. +package skeletonview + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/ui" +) + +// Kind is the shape of one placeholder. +type Kind uint8 + +const ( + // Block is a rounded surface the size of its box. + Block Kind = iota + // Text is a thin line with the recipe's 4 pixel radius unless Radius says + // otherwise. + Text + // Circle is a circle inside the shorter side of its box. + Circle +) + +// Skeleton is one placeholder's caller-owned values and page control. The zero +// value is a fully opaque Block at no size; set the values through the chained +// methods and give it a size. +type Skeleton struct { + kind Kind + width float32 + height float32 + radius float32 + radiusSet bool + opacity float32 + opacitySet bool + + drawFn func(*ui.DrawContext) + prepared bool +} + +// New returns an empty Block placeholder. +func New() *Skeleton { return new(Skeleton) } + +// Reset returns the placeholder to a fully opaque Block of no size. The draw +// function is kept, so a page that reconfigures the placeholder every paint +// allocates nothing. +func (s *Skeleton) Reset() *Skeleton { + s.kind = Block + s.width, s.height = 0, 0 + s.radius, s.radiusSet = 0, false + s.opacity, s.opacitySet = 0, false + return s +} + +// Block selects the default rounded surface. +func (s *Skeleton) Block() *Skeleton { s.kind = Block; return s } + +// Text selects the thin text-line placeholder. +func (s *Skeleton) Text() *Skeleton { s.kind = Text; return s } + +// Circle selects the circular placeholder. +func (s *Skeleton) Circle() *Skeleton { s.kind = Circle; return s } + +// Size sets the placeholder's page box. The page may still override it on the +// returned ui.Box. +func (s *Skeleton) Size(width, height float32) *Skeleton { + if width < 0 { + width = 0 + } + if height < 0 { + height = 0 + } + s.width, s.height = width, height + return s +} + +// Radius overrides the corner radius, clamped at zero. For Circle it overrides +// the circle radius but keeps the square bounds. +func (s *Skeleton) Radius(pixels float32) *Skeleton { + if pixels < 0 { + pixels = 0 + } + s.radius, s.radiusSet = pixels, true + return s +} + +// Opacity sets the surface's alpha, 0 to 1. It is a static visual value, not an +// animation phase; the placeholder never schedules a repaint for it. +func (s *Skeleton) Opacity(fraction float32) *Skeleton { + if fraction < 0 { + fraction = 0 + } + if fraction > 1 { + fraction = 1 + } + s.opacity, s.opacitySet = fraction, true + return s +} + +// View declares the placeholder at c. label names it for assistive technology. +// The box uses the Skeleton's Size; the page may override its dimensions. +// +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, skeleton *Skeleton) ui.Box { + if skeleton == nil { + panic("skeletonview: View needs its Skeleton") + } + skeleton.prepare() + return ui.Slot(c).Size(skeleton.width, skeleton.height).Label(label).Draw(skeleton.drawFn) +} + +func (s *Skeleton) prepare() { + if s.prepared { + return + } + s.prepared = true + s.drawFn = s.draw +} + +func (s *Skeleton) draw(d *ui.DrawContext) { + theme := *d.Theme + if s.opacitySet { + theme.Muted.Alpha *= s.opacity + } + placeholder := components.BeginSkeleton(d.Canvas, theme, d.Rect) + switch s.kind { + case Circle: + placeholder = placeholder.Circle() + case Text: + placeholder = placeholder.Radius(4) + } + if s.radiusSet { + placeholder = placeholder.Radius(s.radius) + } + placeholder.Paint() +} diff --git a/ui/skeletonview/skeletonview_test.go b/ui/skeletonview/skeletonview_test.go new file mode 100644 index 00000000..2249ddd3 --- /dev/null +++ b/ui/skeletonview/skeletonview_test.go @@ -0,0 +1,149 @@ +package skeletonview_test + +import ( + "math" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/skeletonview" +) + +type model struct { + block, text, circle, faded skeletonview.Skeleton + page *ui.Page + canvas *gfx.Canvas + theme gfx.Theme +} + +func (m *model) viewPage(c ui.C) { + // A page reconfigures the placeholders every paint; the draw functions and + // any storage stay on the values in the model. + m.block.Reset().Block().Size(100, 10).Opacity(1) + m.text.Reset().Text().Size(120, 14).Opacity(1) + m.circle.Reset().Circle().Size(40, 56).Opacity(1) + m.faded.Reset().Block().Size(80, 8).Opacity(0.5) + ui.Column(c).Gap(6).Children(func() { + skeletonview.View(c, "Block placeholder", &m.block) + skeletonview.View(c, "Text placeholder", &m.text) + skeletonview.View(c, "Circle placeholder", &m.circle) + skeletonview.View(c, "Faded placeholder", &m.faded) + }) +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 400, Height: 300}, view) + canvas.EndFrame() +} + +func open(t testing.TB, m *model) { + t.Helper() + m.theme = gfx.LightTheme() + m.page = ui.NewPage(ui.PageConfig{View: m.viewPage, Theme: &m.theme}) + m.canvas = new(gfx.Canvas) + draw(m.page, m.canvas, m.viewPage) +} + +// Block, Text and Circle paint one neutral surface each with the sizes and +// radii the page declared; the colored surface carries the explicit opacity. +func TestPrimitivesPaintDeclaredSizeRadiusAndOpacity(t *testing.T) { + m := new(model) + open(t, m) + + rectangles := m.canvas.Rectangles() + if len(rectangles) != 4 { + t.Fatalf("painted %d rectangles, want 4", len(rectangles)) + } + block, text, circle, faded := rectangles[0], rectangles[1], rectangles[2], rectangles[3] + + if block.Bounds.Width != 100 || block.Bounds.Height != 10 { + t.Fatalf("block bounds = %+v, want 100x10", block.Bounds) + } + if block.Radius != m.theme.Metrics.RadiusControl { + t.Fatalf("block radius = %g, want the control radius", block.Radius) + } + if text.Radius != 4 { + t.Fatalf("text radius = %g, want 4", text.Radius) + } + if text.Bounds.Width != 120 || text.Bounds.Height != 14 { + t.Fatalf("text bounds = %+v, want 120x14", text.Bounds) + } + if circle.Bounds.Width != 40 || circle.Bounds.Height != 40 || circle.Radius != 20 { + t.Fatalf("circle = %+v radius %g, want 40x40 radius 20", circle.Bounds, circle.Radius) + } + if !closeTo(faded.Color.Alpha, m.theme.Muted.Alpha*0.5) { + t.Fatalf("faded alpha = %g, want %g", faded.Color.Alpha, m.theme.Muted.Alpha*0.5) + } + if block.Color.Alpha != m.theme.Muted.Alpha { + t.Fatalf("block alpha = %g, want %g", block.Color.Alpha, m.theme.Muted.Alpha) + } + if hits := m.canvas.Hits(); len(hits) != 0 { + t.Fatalf("skeleton declared %d hits, want none", len(hits)) + } + if m.canvas.Animating() { + t.Fatal("static placeholder requested another frame") + } +} + +// Radius overrides the circle's radius without changing its square bounds. +func TestRadiusOverridesCircle(t *testing.T) { + m := &model{theme: gfx.LightTheme()} + m.circle.Reset().Circle().Size(40, 56).Radius(7) + m.page = ui.NewPage(ui.PageConfig{Theme: &m.theme}) + m.canvas = new(gfx.Canvas) + draw(m.page, m.canvas, func(c ui.C) { + skeletonview.View(c, "Circle", &m.circle) + }) + rectangles := m.canvas.Rectangles() + if len(rectangles) != 1 { + t.Fatalf("painted %d rectangles, want 1", len(rectangles)) + } + if rectangles[0].Bounds.Width != 40 || rectangles[0].Bounds.Height != 40 || rectangles[0].Radius != 7 { + t.Fatalf("circle = %+v radius %g, want 40x40 radius 7", rectangles[0].Bounds, rectangles[0].Radius) + } +} + +// Reset returns a placeholder to an opaque Block so a reconfigured page does +// not keep a stale circle, radius or opacity. +func TestResetClearsVisualOptions(t *testing.T) { + var placeholder skeletonview.Skeleton + placeholder.Circle().Radius(9).Opacity(0.25) + placeholder.Reset().Block().Size(30, 12) + m := &model{theme: gfx.LightTheme()} + m.block = placeholder + m.page = ui.NewPage(ui.PageConfig{Theme: &m.theme}) + m.canvas = new(gfx.Canvas) + draw(m.page, m.canvas, func(c ui.C) { + skeletonview.View(c, "Block", &m.block) + }) + rectangles := m.canvas.Rectangles() + if len(rectangles) != 1 { + t.Fatalf("painted %d rectangles, want 1", len(rectangles)) + } + if rectangles[0].Radius != m.theme.Metrics.RadiusControl || rectangles[0].Color.Alpha != m.theme.Muted.Alpha { + t.Fatalf("reset placeholder = %+v, want the default block", rectangles[0]) + } +} + +// A warm repaint allocates nothing: the placeholders live in the model. +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := new(model) + open(t, m) + if allocations := testing.AllocsPerRun(100, func() { draw(m.page, m.canvas, m.viewPage) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func closeTo(got, want float32) bool { return math.Abs(float64(got-want)) < .001 } + +func BenchmarkViewPaint(b *testing.B) { + m := new(model) + open(b, m) + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + draw(m.page, m.canvas, m.viewPage) + } +} diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index 4107b04c..2a683e7f 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -31,6 +31,15 @@ const optionalImports = { carouselview: 'github.com/vivaui/viva/ui/carouselview', markdownview: 'github.com/vivaui/viva/ui/markdownview', hovercardview: 'github.com/vivaui/viva/ui/hovercardview', + sidebarview: 'github.com/vivaui/viva/ui/sidebarview', + markerview: 'github.com/vivaui/viva/ui/markerview', + metriccardview: 'github.com/vivaui/viva/ui/metriccardview', + questionnaireview: 'github.com/vivaui/viva/ui/questionnaireview', + inputotpview: 'github.com/vivaui/viva/ui/inputotpview', + inputgroupview: 'github.com/vivaui/viva/ui/inputgroupview', + skeletonview: 'github.com/vivaui/viva/ui/skeletonview', + aspectratioview: 'github.com/vivaui/viva/ui/aspectratioview', + imageview: 'github.com/vivaui/viva/ui/imageview', navigationmenuview: 'github.com/vivaui/viva/ui/navigationmenuview', menubarview: 'github.com/vivaui/viva/ui/menubarview', commandview: 'github.com/vivaui/viva/ui/commandview', From da9f1a8c650348081d801b8bb42b261d8b871fea Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 18:23:09 +0800 Subject: [PATCH 39/66] refactor(componentdemo): drive previews through page controls --- internal/componentdemo/accordion.go | 82 ++++--- internal/componentdemo/alert_dialog.go | 71 +++--- internal/componentdemo/breadcrumb.go | 136 ++++++++--- internal/componentdemo/button_group.go | 85 ++++--- internal/componentdemo/card.go | 13 +- internal/componentdemo/catalog_a_test.go | 52 ++-- internal/componentdemo/catalog_b_test.go | 37 ++- internal/componentdemo/checkbox.go | 48 ++-- internal/componentdemo/collapsible.go | 71 +++--- internal/componentdemo/color_picker.go | 60 +++-- internal/componentdemo/color_swatch.go | 3 + internal/componentdemo/combobox.go | 41 +++- internal/componentdemo/context_menu.go | 87 ++----- internal/componentdemo/drawer.go | 125 ++++++---- internal/componentdemo/dropdown_menu.go | 64 ++--- internal/componentdemo/empty.go | 34 ++- internal/componentdemo/field.go | 49 ++-- internal/componentdemo/form.go | 39 ++- internal/componentdemo/group_c_test.go | 62 +++-- internal/componentdemo/input.go | 155 ++++++++---- internal/componentdemo/item.go | 83 ++++--- internal/componentdemo/multi_select.go | 67 ++---- internal/componentdemo/native_select.go | 48 +++- internal/componentdemo/pagination.go | 74 +++--- internal/componentdemo/popover.go | 78 +++--- internal/componentdemo/radio_group.go | 56 ++++- internal/componentdemo/reorder_list.go | 103 +++++--- internal/componentdemo/resizable.go | 139 ++++------- internal/componentdemo/scroll_area.go | 167 ++++--------- internal/componentdemo/segmented_control.go | 41 +++- internal/componentdemo/select.go | 39 ++- internal/componentdemo/sheet.go | 113 +++++---- internal/componentdemo/single_select.go | 76 ++---- internal/componentdemo/slider.go | 66 +++--- internal/componentdemo/sonner.go | 94 ++++++-- internal/componentdemo/split_button.go | 38 ++- internal/componentdemo/state_test.go | 21 +- internal/componentdemo/table.go | 114 +++++++-- internal/componentdemo/textarea.go | 19 ++ internal/componentdemo/toast.go | 157 ++++++++----- internal/componentdemo/toggle.go | 88 ++++--- internal/componentdemo/toggle_group.go | 68 +++--- internal/componentdemo/tooltip.go | 77 ++---- internal/componentdemo/tree.go | 248 ++++++++++++++------ internal/componentdemo/typed_events_test.go | 142 +++++------ internal/componentdemo/typography.go | 32 ++- internal/gallery/gallery.go | 6 +- internal/gallery/gallery_test.go | 4 +- 48 files changed, 2125 insertions(+), 1447 deletions(-) diff --git a/internal/componentdemo/accordion.go b/internal/componentdemo/accordion.go index 0b9e3e74..bafa971f 100644 --- a/internal/componentdemo/accordion.go +++ b/internal/componentdemo/accordion.go @@ -1,7 +1,6 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -21,7 +20,8 @@ for index, title := range titles { if canvas.Clicked(items.At(index)) { open ^= 1 << index } -}`, PageSnippet: `ui.Accordion(c, m.faq, []ui.AccordionItem{ +}`, PageSnippet: `m.faq.Multiple = true +ui.Accordion(c, m.faq, []ui.AccordionItem{ {Title: "Does it repaint constantly?", Content: func() { ui.Text(c, "A new frame is submitted only when content changes.").Muted() }}, @@ -31,7 +31,8 @@ for index, title := range titles { {Title: "Is it keyboard accessible?", Content: func() { ui.Text(c, "Headers declare focusable button semantics.").Muted() }}, -})`, PageSnippetZh: `ui.Accordion(c, m.faq, []ui.AccordionItem{ +})`, PageSnippetZh: `m.faq.Multiple = true +ui.Accordion(c, m.faq, []ui.AccordionItem{ {Title: "是否持续重绘?", Content: func() { ui.Text(c, "仅在内容变化时提交新帧。").Muted() }}, @@ -51,6 +52,7 @@ for index, title := range titles { canvas.Label(answers[index], content, style) } }`, PageSnippet: `m.faq.Disabled = true +m.faq.Multiple = true ui.Accordion(c, m.faq, []ui.AccordionItem{ {Title: "Does it repaint constantly?", Content: func() { ui.Text(c, "A new frame is submitted only when content changes.").Muted() @@ -62,6 +64,7 @@ ui.Accordion(c, m.faq, []ui.AccordionItem{ ui.Text(c, "Headers declare focusable button semantics.").Muted() }}, })`, PageSnippetZh: `m.faq.Disabled = true +m.faq.Multiple = true ui.Accordion(c, m.faq, []ui.AccordionItem{ {Title: "是否持续重绘?", Content: func() { ui.Text(c, "仅在内容变化时提交新帧。").Muted() @@ -76,55 +79,58 @@ ui.Accordion(c, m.faq, []ui.AccordionItem{ }, } -var ( - accordionUI = tree.Feature("accordion") - // accordionItem's item i is the i-th disclosure header. - accordionItem = tree.Sub(accordionUI, tree.Name("item")) -) +func initializeAccordion(state *State) { state.flags = 1 } -const accordionContentHeight = 38 +// accordionDemo is one example's page disclosure state and the fixed items it +// declares. It is kept beside the State rather than rebuilt in each paint, so a +// warm paint allocates nothing and the content closures stay stable. +type accordionDemo struct { + faq ui.AccordionState + items []ui.AccordionItem + c ui.C +} -func initializeAccordion(state *State) { state.flags = 1 } +var accordionDemos = map[*State]*accordionDemo{} -func (state *State) paintAccordion(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - titles := [...]string{ +func accordionDemoFor(state *State) *accordionDemo { + if demo := accordionDemos[state]; demo != nil { + return demo + } + titles := [3]string{ state.Text("是否持续重绘?", "Does it repaint constantly?"), state.Text("状态由谁持有?", "Who owns the state?"), state.Text("是否支持键盘?", "Is it keyboard accessible?"), } - answers := [...]string{ + answers := [3]string{ state.Text("仅在内容变化时提交新帧。", "A new frame is submitted only when content changes."), state.Text("展开位由应用状态明确持有。", "The expanded state is owned explicitly by the application."), state.Text("标题声明为可聚焦按钮语义。", "Headers declare focusable button semantics."), } - // The accordion paints its own rows; the slot reserves the height they take: - // every header, a divider between them and the answer of each open item. - height := components.AccordionHeaderExtent(theme)*float32(len(titles)) + float32(len(titles)-1) - for index := range titles { - if state.flags&(1< 0 { - canvas.Label(answers[index], gfx.Rect{X: content.X, Y: content.Y, Width: content.Width - 20, Height: 24}, gfx.TextStyle{ - Size: theme.Metrics.FontSizeM, Color: theme.MutedForeground, - }) - } - if !disabled && canvas.Clicked(id) { - state.flags ^= 1 << index + var flags uint64 + for index, open := range demo.faq.Open { + if open { + flags |= 1 << index } } + state.flags = flags } diff --git a/internal/componentdemo/alert_dialog.go b/internal/componentdemo/alert_dialog.go index 0d84da1d..ce6a4c16 100644 --- a/internal/componentdemo/alert_dialog.go +++ b/internal/componentdemo/alert_dialog.go @@ -39,7 +39,7 @@ canvas.LabelCenter("SK", layout.Media, gfx.TextStyle{Size: theme.Metrics.FontSiz dialog.End()`, PageSnippet: `ui.Dialog(c, ui.DialogSpec{ Title: "Replace avatar?", Description: "The current avatar is replaced immediately with the new local image.", - Width: 320, Scope: m.scope, DismissID: m.scope, CloseID: m.cancelID, + Width: 320, Scope: m.scope, DismissID: m.scope, NoClose: true, }).Body(func() { ui.Column(c).Size(64, 64).Center().Radius(32).Background(c.Theme().Muted).Children(func() { ui.Text(c, "SK").Weight(gfx.WeightMedium) @@ -54,7 +54,7 @@ dialog.End()`, PageSnippet: `ui.Dialog(c, ui.DialogSpec{ })`, PageSnippetZh: `ui.Dialog(c, ui.DialogSpec{ Title: "替换头像?", Description: "当前头像将立即被新的本地图片替换。", - Width: 320, Scope: m.scope, DismissID: m.scope, CloseID: m.cancelID, + Width: 320, Scope: m.scope, DismissID: m.scope, NoClose: true, }).Body(func() { ui.Column(c).Size(64, 64).Center().Radius(32).Background(c.Theme().Muted).Children(func() { ui.Text(c, "SK").Weight(gfx.WeightMedium) @@ -92,34 +92,41 @@ func (state *State) paintAlertDialog(canvas *gfx.Canvas, theme gfx.Theme, size g }) return } - // The alert dialog covers the whole viewport and lays itself out on it. - viewport := gfx.Rect{Width: size.Width, Height: size.Height} - options := components.AlertDialogOptions{ - Layer: 8, Scope: alertDialogScope, ActionID: alertDialogAction, CancelID: alertDialogCancel, - } - if state.exampleID == "media" { - options.Size = components.AlertDialogSmall - dialog := components.BeginAlertDialog(canvas, theme, viewport, options).WithMedia() - layout := dialog.Begin( - state.Text("替换头像?", "Replace avatar?"), - state.Text("当前头像将立即被新的本地图片替换。", "The current avatar is replaced immediately with the new local image."), - state.Text("替换", "Replace"), - state.Text("取消", "Cancel"), - ) - canvas.Rounded(layout.Media, min(layout.Media.Width, layout.Media.Height)/2, theme.Muted) - canvas.LabelCenter("SK", layout.Media, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightSemibold, Color: theme.MutedForeground}) - dialog.End() - } else { - options.ActionVariant = components.ButtonDestructive - components.BeginAlertDialog(canvas, theme, viewport, options). - Paint( - state.Text("永久删除这个项目?", "Permanently delete this project?"), - state.Text("此操作无法撤销,本地数据将被移除。", "This cannot be undone. Local data will be removed."), - state.Text("删除", "Delete"), - state.Text("取消", "Cancel"), - ) - } - if canvas.Clicked(alertDialogAction) || canvas.Clicked(alertDialogCancel) { - state.flags &^= alertDialogOpenFlag - } + state.drawPage(canvas, theme, size, 320, state.Text("Alert Dialog · 确认", "Alert Dialog · Confirmation"), func(c ui.C) { + if state.exampleID == "media" { + dialog := ui.Dialog(c, ui.DialogSpec{ + Title: state.Text("替换头像?", "Replace avatar?"), + Description: state.Text("当前头像将立即被新的本地图片替换。", "The current avatar is replaced immediately with the new local image."), + Width: 320, Scope: alertDialogScope, DismissID: alertDialogScope, NoClose: true, + }) + dialog.Body(func() { + ui.Column(c).Size(64, 64).Center().Radius(32).Background(c.Theme().Muted).Children(func() { + ui.Text(c, "SK").Weight(gfx.WeightMedium) + }) + }) + dialog.Footer(func() { + cancel, replace := state.Text("取消", "Cancel"), state.Text("替换", "Replace") + if ui.Button(c, cancel).Outline().Hit(alertDialogCancel, cancel).Clicked() { + state.flags &^= alertDialogOpenFlag + } + if ui.Button(c, replace).Hit(alertDialogAction, replace).Clicked() { + state.flags &^= alertDialogOpenFlag + } + }) + if dialog.Dismissed() { + state.flags &^= alertDialogOpenFlag + } + return + } + dialog := ui.AlertDialog(c, ui.AlertDialogSpec{ + Title: state.Text("永久删除这个项目?", "Permanently delete this project?"), + Description: state.Text("此操作无法撤销,本地数据将被移除。", "This cannot be undone. Local data will be removed."), + Scope: alertDialogScope, ActionID: alertDialogAction, CancelID: alertDialogCancel, + ActionLabel: state.Text("删除", "Delete"), CancelLabel: state.Text("取消", "Cancel"), + ActionVariant: components.ButtonDestructive, + }) + if id, ok := dialog.Chosen(); ok && (id == alertDialogAction || id == alertDialogCancel) { + state.flags &^= alertDialogOpenFlag + } + }) } diff --git a/internal/componentdemo/breadcrumb.go b/internal/componentdemo/breadcrumb.go index e910addd..88149a3c 100644 --- a/internal/componentdemo/breadcrumb.go +++ b/internal/componentdemo/breadcrumb.go @@ -1,7 +1,6 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -18,21 +17,47 @@ breadcrumb.AddCurrent("Preview") if index, ok := canvas.ClickedIn(links); ok { selected = int32(index + 1) }`, PageSnippet: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Text(c, "Workspace").Muted() + first := ui.Text(c, "Workspace").Muted().Hit(ui.ID(c), "Workspace") + if first.Clicked() { + m.parent = 0 + } ui.Text(c, "›").Muted() - ui.Text(c, "Viva").Muted() + parent := ui.Text(c, "Viva").Muted().Hit(ui.ID(c), "Viva") + if parent.Clicked() { + m.parent = 1 + } ui.Text(c, "›").Muted() ui.Text(c, "Preview") }) -ui.Text(c, "Choose a parent path to go back."). +caption := "Choose a parent path to go back." +if m.parent == 0 { + caption = "Selected: Workspace" +} +if m.parent == 1 { + caption = "Selected: Parent" +} +ui.Text(c, caption). FontSize(c.Theme().Metrics.FontSizeS).Muted()`, PageSnippetZh: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Text(c, "工作区").Muted() + first := ui.Text(c, "工作区").Muted().Hit(ui.ID(c), "工作区") + if first.Clicked() { + m.parent = 0 + } ui.Text(c, "›").Muted() - ui.Text(c, "Viva").Muted() + parent := ui.Text(c, "Viva").Muted().Hit(ui.ID(c), "Viva") + if parent.Clicked() { + m.parent = 1 + } ui.Text(c, "›").Muted() ui.Text(c, "预览") }) -ui.Text(c, "选择上级路径以返回。"). +caption := "选择上级路径以返回。" +if m.parent == 0 { + caption = "已选择:工作区" +} +if m.parent == 1 { + caption = "已选择:上一级" +} +ui.Text(c, caption). FontSize(c.Theme().Metrics.FontSizeS).Muted()`}, {ID: "overflow", Title: "折叠路径", Description: "长层级使用省略项保持紧凑。", Snippet: `links := tree.Sub(page, tree.Name("link")) breadcrumb := components.BeginBreadcrumb(canvas, theme, trail.Rect()) @@ -40,25 +65,51 @@ breadcrumb.AddLink(links.At(0), "Workspace") breadcrumb.AddEllipsis(tree.ID(page, "more")) breadcrumb.AddLink(links.At(1), "Components") breadcrumb.AddCurrent("Breadcrumb")`, PageSnippet: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Text(c, "Workspace").Muted() + first := ui.Text(c, "Workspace").Muted().Hit(ui.ID(c), "Workspace") + if first.Clicked() { + m.parent = 0 + } ui.Text(c, "›").Muted() ui.Text(c, "…").Muted() ui.Text(c, "›").Muted() - ui.Text(c, "Components").Muted() + parent := ui.Text(c, "Components").Muted().Hit(ui.ID(c), "Components") + if parent.Clicked() { + m.parent = 1 + } ui.Text(c, "›").Muted() ui.Text(c, "Breadcrumb") }) -ui.Text(c, "Choose a parent path to go back."). +caption := "Choose a parent path to go back." +if m.parent == 0 { + caption = "Selected: Workspace" +} +if m.parent == 1 { + caption = "Selected: Parent" +} +ui.Text(c, caption). FontSize(c.Theme().Metrics.FontSizeS).Muted()`, PageSnippetZh: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - ui.Text(c, "工作区").Muted() + first := ui.Text(c, "工作区").Muted().Hit(ui.ID(c), "工作区") + if first.Clicked() { + m.parent = 0 + } ui.Text(c, "›").Muted() ui.Text(c, "…").Muted() ui.Text(c, "›").Muted() - ui.Text(c, "组件").Muted() + parent := ui.Text(c, "组件").Muted().Hit(ui.ID(c), "组件") + if parent.Clicked() { + m.parent = 1 + } ui.Text(c, "›").Muted() ui.Text(c, "Breadcrumb") }) -ui.Text(c, "选择上级路径以返回。"). +caption := "选择上级路径以返回。" +if m.parent == 0 { + caption = "已选择:工作区" +} +if m.parent == 1 { + caption = "已选择:上一级" +} +ui.Text(c, caption). FontSize(c.Theme().Metrics.FontSizeS).Muted()`}, }, } @@ -67,33 +118,46 @@ var ( breadcrumbUI = tree.Feature("breadcrumb") // breadcrumbLink's item i is the i-th link of the path. breadcrumbLink = tree.Sub(breadcrumbUI, tree.Name("link")) - breadcrumbMore = tree.ID(breadcrumbUI, "more") ) func (state *State) paintBreadcrumb(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var trail ui.Box + caption := state.Text("选择上级路径以返回。", "Choose a parent path to go back.") + switch state.values[0] { + case 1: + caption = state.Text("已选择:工作区", "Selected: Workspace") + case 2: + caption = state.Text("已选择:上一级", "Selected: Parent") + } + workspace := state.Text("工作区", "Workspace") + components := state.Text("组件", "Components") + viva := "Viva" + preview := state.Text("预览", "Preview") + overflow := state.exampleID == "overflow" state.drawPage(canvas, theme, size, 620, state.Text("Breadcrumb · 当前上下文", "Breadcrumb · Current context"), func(c ui.C) { - trail = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) - caption := state.Text("选择上级路径以返回。", "Choose a parent path to go back.") - switch state.values[0] { - case 1: - caption = state.Text("已选择:工作区", "Selected: Workspace") - case 2: - caption = state.Text("已选择:上一级", "Selected: Parent") - } + ui.Row(c).Gap(6).Items(ui.Center).Children(func() { + link := ui.Text(c, workspace).Muted().Hit(breadcrumbLink.At(0), workspace) + if link.Clicked() { + state.values[0] = 1 + } + ui.Text(c, "›").Muted() + if overflow { + ui.Text(c, "…").Muted() + ui.Text(c, "›").Muted() + link = ui.Text(c, components).Muted().Hit(breadcrumbLink.At(1), components) + if link.Clicked() { + state.values[0] = 2 + } + ui.Text(c, "›").Muted() + ui.Text(c, "Breadcrumb") + } else { + link = ui.Text(c, viva).Muted().Hit(breadcrumbLink.At(1), viva) + if link.Clicked() { + state.values[0] = 2 + } + ui.Text(c, "›").Muted() + ui.Text(c, preview) + } + }) ui.Text(c, caption).FontSize(theme.Metrics.FontSizeS).Muted() }) - breadcrumb := components.BeginBreadcrumb(canvas, theme, trail.Rect()) - breadcrumb.AddLink(breadcrumbLink.At(0), state.Text("工作区", "Workspace")) - if state.exampleID == "overflow" { - breadcrumb.AddEllipsis(breadcrumbMore) - breadcrumb.AddLink(breadcrumbLink.At(1), state.Text("组件", "Components")) - breadcrumb.AddCurrent("Breadcrumb") - } else { - breadcrumb.AddLink(breadcrumbLink.At(1), "Viva") - breadcrumb.AddCurrent(state.Text("预览", "Preview")) - } - if index, ok := canvas.ClickedIn(breadcrumbLink); ok { - state.values[0] = int32(index + 1) - } } diff --git a/internal/componentdemo/button_group.go b/internal/componentdemo/button_group.go index ae28170c..322a9bc3 100644 --- a/internal/componentdemo/button_group.go +++ b/internal/componentdemo/button_group.go @@ -1,7 +1,6 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -139,45 +138,59 @@ var ( func (state *State) paintButtonGroup(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { vertical := state.exampleID == "vertical" disabled := state.exampleID == "disabled" - var slot ui.Box + variants := state.exampleID == "variants" + labels := [3]string{ + state.Text("左对齐", "Left"), + state.Text("居中", "Center"), + state.Text("右对齐", "Right"), + } + captions := [3]string{ + state.Text("当前:左对齐", "Current: Left"), + state.Text("当前:居中", "Current: Center"), + state.Text("当前:右对齐", "Current: Right"), + } + if variants { + labels = [3]string{state.Text("保存", "Save"), state.Text("删除", "Delete"), state.Text("帮助", "Help")} + captions = [3]string{ + state.Text("当前:保存", "Current: Save"), + state.Text("当前:删除", "Current: Delete"), + state.Text("当前:帮助", "Current: Help"), + } + } + caption := captions[state.values[0]] + if disabled { + caption = state.Text("整个操作组已禁用。", "The whole group is disabled.") + } state.drawPage(canvas, theme, size, 360, state.Text("Button Group · 对齐方式", "Button Group · Alignment"), func(c ui.C) { if vertical { - slot = ui.Slot(c).Size(220, theme.Metrics.ControlHeight*3).Self(ui.Start) + ui.Column(c).Children(func() { + for index := range labels { + button := ui.Button(c, labels[index]).Outline().Hit(buttonGroupItem.At(index), labels[index]) + if button.Clicked() { + state.values[0] = int32(index) + } + } + }) } else { - slot = ui.Slot(c).FillWidth().MaxWidth(360).Height(theme.Metrics.ControlHeight).Self(ui.Start) - } - labels := [...]string{ - state.Text("当前:左对齐", "Current: Left"), - state.Text("当前:居中", "Current: Center"), - state.Text("当前:右对齐", "Current: Right"), - } - caption := labels[state.values[0]] - if disabled { - caption = state.Text("整个操作组已禁用。", "The whole group is disabled.") + ui.Row(c).Children(func() { + for index := range labels { + var button ui.Box + switch { + case disabled: + button = ui.Button(c, labels[index]).Outline().Disabled(true).Hit(buttonGroupItem.At(index), labels[index]) + case variants && index == 1: + button = ui.Button(c, labels[index]).DestructiveOutline().Hit(buttonGroupItem.At(index), labels[index]) + case variants && index == 2: + button = ui.Button(c, labels[index]).Link().Hit(buttonGroupItem.At(index), labels[index]) + default: + button = ui.Button(c, labels[index]).Outline().Hit(buttonGroupItem.At(index), labels[index]) + } + if button.Clicked() { + state.values[0] = int32(index) + } + } + }) } ui.Text(c, caption).FontSize(theme.Metrics.FontSizeS).Muted() }) - var options [3]components.ButtonGroupOption - if state.exampleID == "variants" { - options = [3]components.ButtonGroupOption{ - {ID: buttonGroupItem.At(0), Label: state.Text("保存", "Save"), Variant: components.ButtonOutline}, - {ID: buttonGroupItem.At(1), Label: state.Text("删除", "Delete"), Variant: components.ButtonDestructiveOutline}, - {ID: buttonGroupItem.At(2), Label: state.Text("帮助", "Help"), Variant: components.ButtonLink}, - } - } else { - options = [3]components.ButtonGroupOption{ - {ID: buttonGroupItem.At(0), Label: state.Text("左对齐", "Left"), Variant: components.ButtonOutline}, - {ID: buttonGroupItem.At(1), Label: state.Text("居中", "Center"), Variant: components.ButtonOutline}, - {ID: buttonGroupItem.At(2), Label: state.Text("右对齐", "Right"), Variant: components.ButtonOutline}, - } - } - group := components.BeginButtonGroup(canvas, theme, slot.Rect(), options[:]) - if vertical { - group = group.Vertical() - } else if disabled { - group = group.Disabled() - } - if id, ok := group.Paint().Clicked(); ok { - state.values[0] = int32(listIndex(id, buttonGroupItem)) - } } diff --git a/internal/componentdemo/card.go b/internal/componentdemo/card.go index bbe7e804..d499fc37 100644 --- a/internal/componentdemo/card.go +++ b/internal/componentdemo/card.go @@ -1,7 +1,6 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -92,20 +91,18 @@ ui.Column(c).FillWidth().Pad(16).Gap(8). } func (state *State) paintCard(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - cardSize := components.CardSizeDefault + padding := float32(24) if state.exampleID == "compact" { - cardSize = components.CardSizeSmall + padding = 16 } - // The card is a ui column dressed as components.PaintCard draws a card: the - // same padding, radius and hairline ring. ring := theme.Foreground ring.Alpha *= 0.10 state.drawPage(canvas, theme, size, 520, state.Text("Card · 项目摘要", "Card · Project summary"), func(c ui.C) { - ui.Column(c).FillWidth().Pad(components.CardSpacing(theme, cardSize)).Gap(8). + ui.Column(c).FillWidth().Pad(padding).Gap(8). Background(theme.Card).Border(1, ring).Radius(theme.Metrics.RadiusSurface + 4).Shadow(gfx.ShadowXS).Children(func() { - ui.Text(c, "Native preview").FontSize(theme.Metrics.FontSizeM + 2).Weight(gfx.WeightSemibold).Color(theme.CardForeground) + ui.Text(c, "Native preview").FontSize(theme.Metrics.FontSizeM + 2).Weight(gfx.WeightSemibold) ui.Text(c, state.Text("保留场景节点,只在内容变化时重绘。", "Keeps scene nodes and repaints only when content changes.")).FontSize(theme.Metrics.FontSizeS).Muted() - ui.Text(c, "0").FontSize(28).Bold().Color(theme.Foreground) + ui.Text(c, "0").FontSize(28).Bold() ui.Text(c, "idle GPU submissions").FontSize(theme.Metrics.FontSizeS).Muted() ui.Divider(c) ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() diff --git a/internal/componentdemo/catalog_a_test.go b/internal/componentdemo/catalog_a_test.go index 6a9124e7..950eb61c 100644 --- a/internal/componentdemo/catalog_a_test.go +++ b/internal/componentdemo/catalog_a_test.go @@ -146,33 +146,51 @@ func TestGroupAClicksChangeCallerState(t *testing.T) { cases := []struct { component, example string target gfx.ID + label string changed func(*State) bool }{ - {"accordion", "default", accordionItem.At(1), func(s *State) bool { return s.flags == 3 }}, - {"accordion", "disabled", accordionItem.At(1), func(s *State) bool { return s.flags == 1 }}, - {"alert-dialog", "default", alertDialogAction, func(s *State) bool { return s.flags&alertDialogOpenFlag == 0 }}, - {"alert-dialog", "media", alertDialogCancel, func(s *State) bool { return s.flags&alertDialogOpenFlag == 0 }}, - {"attachment", "default", attachmentItem.At(0), func(s *State) bool { return s.values[0] == 1 }}, - {"breadcrumb", "default", breadcrumbLink.At(0), func(s *State) bool { return s.values[0] == 1 }}, - {"bubble", "conversation", bubbleReaction, func(s *State) bool { return s.flags == 1 }}, - {"button-group", "horizontal", buttonGroupItem.At(2), func(s *State) bool { return s.values[0] == 2 }}, - {"calendar", "month", calendarNext, func(s *State) bool { return s.values[0] == 1 }}, - {"carousel", "horizontal", carouselNext, func(s *State) bool { return s.values[0] == 1 }}, - {"carousel", "vertical", carouselNext, func(s *State) bool { return s.values[0] == 1 }}, - {"collapsible", "default", collapsibleTrigger, func(s *State) bool { return s.flags == 0 }}, - {"combobox", "default", comboboxOption.At(1), func(s *State) bool { return s.values[0] == 2 && s.flags&comboboxOpenFlag == 0 }}, - {"combobox", "default", comboboxInput, func(s *State) bool { return s.flags&comboboxOpenFlag == 0 }}, + {"accordion", "default", gfx.ID{}, "状态由谁持有?", func(s *State) bool { return s.flags == 3 }}, + {"accordion", "disabled", gfx.ID{}, "状态由谁持有?", func(s *State) bool { return s.flags == 1 }}, + {"alert-dialog", "default", alertDialogAction, "", func(s *State) bool { return s.flags&alertDialogOpenFlag == 0 }}, + {"alert-dialog", "media", alertDialogCancel, "", func(s *State) bool { return s.flags&alertDialogOpenFlag == 0 }}, + {"attachment", "default", attachmentItem.At(0), "", func(s *State) bool { return s.values[0] == 1 }}, + {"breadcrumb", "default", breadcrumbLink.At(0), "", func(s *State) bool { return s.values[0] == 1 }}, + {"bubble", "conversation", bubbleReaction, "", func(s *State) bool { return s.flags == 1 }}, + {"button-group", "horizontal", buttonGroupItem.At(2), "", func(s *State) bool { return s.values[0] == 2 }}, + {"calendar", "month", calendarNext, "", func(s *State) bool { return s.values[0] == 1 }}, + {"carousel", "horizontal", carouselNext, "", func(s *State) bool { return s.values[0] == 1 }}, + {"carousel", "vertical", carouselNext, "", func(s *State) bool { return s.values[0] == 1 }}, + {"collapsible", "default", gfx.ID{}, "3 个构建产物", func(s *State) bool { return s.flags == 0 }}, } for _, test := range cases { t.Run(test.component+"/"+test.example, func(t *testing.T) { state := newTestState(t, test.component, test.example) var canvas gfx.Canvas paintFrame(&canvas, state, testSize, time.Second, true) - findHit(t, &canvas, test.target) - click(&canvas, state, test.target) + target := test.target + if test.label != "" { + target = findHitByLabel(t, &canvas, test.label) + } + findHit(t, &canvas, target) + click(&canvas, state, target) if !test.changed(state) { - t.Fatalf("clicking %v did not change the state: flags %b values %v", test.target, state.flags, state.values) + t.Fatalf("clicking %v did not change the state: flags %b values %v", target, state.flags, state.values) } }) } + // The page-first Combobox starts closed: opening the field and choosing an + // option are two clicks through the page's own identities. + t.Run("combobox/default", func(t *testing.T) { + state := newTestState(t, "combobox", "default") + var canvas gfx.Canvas + paintFrame(&canvas, state, testSize, time.Second, true) + field := findHitByLabel(t, &canvas, "框架") + click(&canvas, state, field) + paintFrame(&canvas, state, testSize, time.Second, true) + option := findHitByLabel(t, &canvas, "WebGPU") + click(&canvas, state, option) + if state.values[0] != 2 { + t.Fatalf("choosing WebGPU left values[0]=%d", state.values[0]) + } + }) } diff --git a/internal/componentdemo/catalog_b_test.go b/internal/componentdemo/catalog_b_test.go index b141bf24..9062d858 100644 --- a/internal/componentdemo/catalog_b_test.go +++ b/internal/componentdemo/catalog_b_test.go @@ -113,23 +113,40 @@ func TestGroupBClicksChangeState(t *testing.T) { for _, test := range []struct { component, example string id gfx.ID + label string changed func(*State) bool }{ - {"command", "default", commandItem.At(2), func(s *State) bool { return s.values[0] == 2 }}, - {"dropdown-menu", "default", dropdownMenuToggle, func(s *State) bool { return s.flags&1 != 0 }}, - {"item", "default", itemRow.At(0), func(s *State) bool { return s.flags&1 != 0 }}, - {"native-select", "default", nativeSelectTrigger.At(0), func(s *State) bool { return s.flags&1 != 0 }}, - {"message-scroller", "default", messageScrollerEnd, func(s *State) bool { return s.values[0] == 72 }}, - {"menubar", "default", menubarFile, func(s *State) bool { return s.flags&1 != 0 }}, - {"input-otp", "default", inputOTPField, func(s *State) bool { return s.values[0] == 4 }}, - {"input-group", "default", inputGroupClear, func(s *State) bool { return s.flags&1 == 0 }}, - {"drawer", "default", drawerClose, func(s *State) bool { return s.flags&1 == 0 }}, + {"command", "default", commandItem.At(2), "", func(s *State) bool { return s.values[0] == 2 }}, + {"dropdown-menu", "default", gfx.ID{}, "Compact mode", func(s *State) bool { return s.flags&1 != 0 }}, + {"item", "default", itemRow.At(0), "", func(s *State) bool { return s.flags&1 != 0 }}, + {"message-scroller", "default", messageScrollerEnd, "", func(s *State) bool { return s.values[0] == 72 }}, + {"menubar", "default", menubarFile, "", func(s *State) bool { return s.flags&1 != 0 }}, + {"input-otp", "default", inputOTPField, "", func(s *State) bool { return s.values[0] == 4 }}, + {"input-group", "default", inputGroupClear, "", func(s *State) bool { return s.flags&1 == 0 }}, + {"drawer", "default", gfx.ID{}, "Close drawer", func(s *State) bool { return s.flags&1 == 0 }}, } { state := newTestState(t, test.component, test.example) paintFrame(&canvas, state, testSize, time.Second, true) - click(&canvas, state, test.id) + target := test.id + if test.label != "" { + target = findHitByLabel(t, &canvas, test.label) + } + click(&canvas, state, target) if !test.changed(state) { t.Errorf("%s: clicking its control did not change the state", test.component) } } + // The page-first Select starts closed: open the trigger, then choose. + t.Run("native-select/default", func(t *testing.T) { + state := newTestState(t, "native-select", "default") + paintFrame(&canvas, state, testSize, time.Second, true) + trigger := findHitByLabel(t, &canvas, "Environment") + click(&canvas, state, trigger) + paintFrame(&canvas, state, testSize, time.Second, true) + option := findHitByLabel(t, &canvas, "Staging") + click(&canvas, state, option) + if state.values[0] != 2 { + t.Fatalf("choosing Staging left values[0]=%d", state.values[0]) + } + }) } diff --git a/internal/componentdemo/checkbox.go b/internal/componentdemo/checkbox.go index 2453d074..15058929 100644 --- a/internal/componentdemo/checkbox.go +++ b/internal/componentdemo/checkbox.go @@ -61,35 +61,54 @@ type checkboxState struct { } func (state *State) paintCheckbox(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + if state.exampleID == "states" { + state.paintCheckboxStates(canvas, theme, size) + return + } labels := []string{state.Text("接受使用条款", "Accept terms of use")} - switch state.exampleID { - case "selection": + if state.exampleID == "selection" { labels = []string{ state.Text("显示行号", "Show line numbers"), state.Text("保存时格式化", "Format on save"), state.Text("恢复上次窗口", "Restore last window"), } - case "states": - labels = []string{ - state.Text("必选:接受使用条款", "Required: accept terms of use"), - state.Text("禁用 · 未选择", "Disabled · Unchecked"), - state.Text("禁用 · 已选择", "Disabled · Checked"), + } + caption := state.Text("点击方框,或用 Tab / Space 切换。", "Click the box, or press Tab / Space to toggle.") + if state.exampleID == "default" && state.checkbox.boxes[0] { + caption = state.Text("已接受使用条款。", "Terms accepted.") + } + state.drawPage(canvas, theme, size, 480, state.Text("Checkbox · 显式选择", "Checkbox · Explicit selection"), func(c ui.C) { + for index, label := range labels { + ui.Row(c).Gap(12).Items(ui.Center).Children(func() { + ui.Checkbox(c, &state.checkbox.boxes[index], "").Hit(checkboxBox.At(index), label) + ui.Text(c, label).FontSize(theme.Metrics.FontSizeM) + }) } + ui.Text(c, caption).FontSize(theme.Metrics.FontSizeS).Muted() + }) +} + +// paintCheckboxStates keeps the validation example on the canvas API: the page +// Checkbox has no invalid option, and the components checkbox paints a required +// box that is still empty in its invalid look into a Slot. +func (state *State) paintCheckboxStates(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + labels := []string{ + state.Text("必选:接受使用条款", "Required: accept terms of use"), + state.Text("禁用 · 未选择", "Disabled · Unchecked"), + state.Text("禁用 · 已选择", "Disabled · Checked"), } - // A required box that is still empty is drawn invalid, which ui's checkbox - // has no option for: its square is a Slot the component paints into. var invalid ui.Box hasInvalid := false state.drawPage(canvas, theme, size, 480, state.Text("Checkbox · 显式选择", "Checkbox · Explicit selection"), func(c ui.C) { for index, label := range labels { checked := state.checkbox.selected&(1< 0 + disabled := index > 0 if disabled { checked = index == 2 } ui.Row(c).Gap(12).Items(ui.Center).PadX(12).MarginY(2).Children(func() { state.checkbox.boxes[index] = checked - if state.exampleID == "states" && index == 0 && !checked { + if index == 0 && !checked { side := components.CheckboxExtent(theme) invalid, hasInvalid = ui.Slot(c).Size(side, side), true } else if ui.Checkbox(c, &state.checkbox.boxes[index], "").Hit(checkboxBox.At(index), label).Disabled(disabled).Clicked() { @@ -102,11 +121,8 @@ func (state *State) paintCheckbox(canvas *gfx.Canvas, theme gfx.Theme, size gfx. ui.Text(c, label).FontSize(theme.Metrics.FontSizeM).Color(color) }) } - caption := state.Text("点击方框,或用 Tab / Space 切换。", "Click the box, or press Tab / Space to toggle.") - if state.exampleID == "default" && state.checkbox.selected != 0 { - caption = state.Text("已接受使用条款。", "Terms accepted.") - } - ui.Text(c, caption).FontSize(theme.Metrics.FontSizeS).Muted() + ui.Text(c, state.Text("点击方框,或用 Tab / Space 切换。", "Click the box, or press Tab / Space to toggle.")). + FontSize(theme.Metrics.FontSizeS).Muted() }) if hasInvalid { bounds := invalid.Rect() diff --git a/internal/componentdemo/collapsible.go b/internal/componentdemo/collapsible.go index beb07117..b8c87800 100644 --- a/internal/componentdemo/collapsible.go +++ b/internal/componentdemo/collapsible.go @@ -1,7 +1,6 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -60,40 +59,50 @@ ui.Collapsible(c, &m.builds, "3 个构建产物", func() { }, } -var ( - collapsibleUI = tree.Feature("collapsible") - collapsibleTrigger = tree.ID(collapsibleUI, "trigger") -) - func initializeCollapsible(state *State) { state.flags = 1 } +// collapsibleDemo is one example's page disclosure state, title and fixed body. +// It is kept beside the State so a warm paint declares no new closures. +type collapsibleDemo struct { + state ui.CollapsibleState + title string + lines [3]string + c ui.C +} + +var collapsibleDemos = map[*State]*collapsibleDemo{} + +func collapsibleDemoFor(state *State) *collapsibleDemo { + if demo := collapsibleDemos[state]; demo != nil { + return demo + } + demo := &collapsibleDemo{ + title: state.Text("3 个构建产物", "3 build artifacts"), + lines: [3]string{ + "viva-darwin-arm64 3.8 MiB", + "viva-windows-amd64 4.1 MiB", + "viva-linux-amd64 3.9 MiB", + }, + } + collapsibleDemos[state] = demo + return demo +} + func (state *State) paintCollapsible(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - open := state.flags&1 != 0 - const contentHeight = 112 - var slot ui.Box + demo := collapsibleDemoFor(state) + demo.state.Open = state.flags&1 != 0 + demo.state.Disabled = state.exampleID == "disabled" state.drawPage(canvas, theme, size, 520, state.Text("Collapsible · 构建输出", "Collapsible · Build output"), func(c ui.C) { - height := theme.Metrics.ControlHeight - if open { - height += contentHeight - } - slot = ui.Slot(c).FillWidth().Height(height) + demo.c = c + ui.Collapsible(c, &demo.state, demo.title, func() { + for _, line := range demo.lines { + ui.Text(demo.c, line).Mono().Muted() + } + }) }) - collapsible := components.BeginCollapsible(canvas, theme, collapsibleTrigger, slot.Rect()) - disabled := state.exampleID == "disabled" - if disabled { - collapsible = collapsible.Disabled() - } - content := collapsible.Paint(state.Text("3 个构建产物", "3 build artifacts"), open, contentHeight) - if !disabled && canvas.Clicked(collapsibleTrigger) { - state.flags ^= 1 - } - if content.Height == 0 { - return - } - canvas.Rounded(content, theme.Metrics.RadiusSurface, theme.Muted) - for index, line := range [...]string{ - "viva-darwin-arm64 3.8 MiB", "viva-windows-amd64 4.1 MiB", "viva-linux-amd64 3.9 MiB", - } { - canvas.Label(line, gfx.Rect{X: content.X + 14, Y: content.Y + 12 + float32(index)*30, Width: content.Width - 28, Height: 22}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.Foreground}) + if demo.state.Open { + state.flags |= 1 + } else { + state.flags &^= 1 } } diff --git a/internal/componentdemo/color_picker.go b/internal/componentdemo/color_picker.go index 322f96e6..c838db62 100644 --- a/internal/componentdemo/color_picker.go +++ b/internal/componentdemo/color_picker.go @@ -4,18 +4,24 @@ import ( "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" ) var colorPickerComponent = Component{ ID: "color-picker", Title: "Color Picker", Category: "Forms", Summary: "应用持有 HSV 草稿,支持拖动、方向键、HEX 输入和确认取消。", paint: (*State).paintColorPicker, pointer: (*State).pointerColorPicker, key: (*State).keyColorPicker, initialize: func(s *State) { - s.picker = &colorPickerDemoState{hex: "#3B82F6"} - c, _ := components.ParseColorHex(s.picker.hex, false) - s.picker.saved = components.ColorPickerValue{}.WithColor(c) - s.picker.draft = s.picker.saved + p := &colorPickerDemoState{hex: "#3B82F6"} + c, _ := components.ParseColorHex(p.hex, false) + p.savedValue = components.ColorPickerValue{}.WithColor(c) + p.draftValue = p.savedValue + p.color, p.saved = c, c + s.picker = p }, - editable: func(string) (editableField, bool) { + editable: func(exampleID string) (editableField, bool) { + if exampleID != "alpha" { + return editableField{}, false + } return editableField{ID: demoPickerIDs.Hex, Initial: "#3B82F6"}, true }, Examples: []Example{{ID: "default", Title: "选择颜色", Description: "拖动色相与饱和度/亮度,或输入 HEX。确认后应用,取消保留原色。", Height: 460, Snippet: `layout := components.BeginColorPicker(canvas, theme, trigger, components.ColorPickerOptions{ @@ -57,15 +63,21 @@ var demoPickerIDs = components.ColorPickerIDs{ } type colorPickerDemoState struct { - saved, draft components.ColorPickerValue - layout components.ColorPickerLayout - hex, seen string - open, empty, invalid bool + // The page-first picker and the color it writes on Apply. + picker ui.ColorPickerState + color ui.Color + saved ui.Color + + // The alpha example's canvas picker: the page API has no alpha option. + savedValue, draftValue components.ColorPickerValue + layout components.ColorPickerLayout + hex, seen string + open, empty, invalid bool } func (s *State) pickerSetValue(v components.ColorPickerValue) { p := s.picker - p.draft = v + p.draftValue = v var buf [9]byte p.hex = string(v.AppendHex(buf[:0], s.exampleID == "alpha")) p.seen = p.hex @@ -77,11 +89,21 @@ func (s *State) pickerSetValue(v components.ColorPickerValue) { } func (s *State) paintColorPicker(c *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + if s.exampleID != "alpha" { + s.drawPage(c, theme, size, 460, s.Text("Color Picker · 自定义颜色", "Color Picker · Custom color"), func(page ui.C) { + p := s.picker + ui.ColorPicker(page, &p.picker, &p.color, s.Text("自定义颜色", "Custom color")) + if p.picker.Applied() { + p.saved = p.color + } + }) + return + } p := s.picker if c.Clicked(demoPickerIDs.Trigger) { p.open = !p.open if p.open { - s.pickerSetValue(p.saved) + s.pickerSetValue(p.savedValue) } } value := s.fieldValue(p.hex) @@ -90,7 +112,7 @@ func (s *State) paintColorPicker(c *gfx.Canvas, theme gfx.Theme, size gfx.Size) parsed, ok := components.ParseColorHex(value, s.exampleID == "alpha") p.invalid = !ok if ok { - p.draft = p.draft.WithColor(parsed) + p.draftValue = p.draftValue.WithColor(parsed) } } if c.Clicked(demoPickerIDs.Cancel) || c.Clicked(demoPickerIDs.Dismiss) { @@ -103,7 +125,7 @@ func (s *State) paintColorPicker(c *gfx.Canvas, theme gfx.Theme, size gfx.Size) c.RequestFocus(demoPickerIDs.Trigger) } if c.Clicked(demoPickerIDs.Apply) && !p.invalid { - p.saved = p.draft + p.savedValue = p.draftValue p.empty = false p.open = false c.RequestFocus(demoPickerIDs.Trigger) @@ -111,10 +133,10 @@ func (s *State) paintColorPicker(c *gfx.Canvas, theme gfx.Theme, size gfx.Size) c.Label(s.Text("自定义颜色", "Custom color"), gfx.Rect{X: 24, Y: 20, Width: 300, Height: 24}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.Foreground}) hex := components.InputSnapshot{Value: value, Focused: c.Focused() == demoPickerIDs.Hex, Invalid: p.invalid} s.paintEditable(c, demoPickerIDs.Hex, value, &hex) - o := components.ColorPickerOptions{IDs: demoPickerIDs, Value: p.saved, Open: p.open, Empty: p.empty, ShowAlpha: s.exampleID == "alpha", Viewport: gfx.Rect{Width: size.Width, Height: size.Height}, Layer: 3, Scope: demoPickerScope, + o := components.ColorPickerOptions{IDs: demoPickerIDs, Value: p.savedValue, Open: p.open, Empty: p.empty, ShowAlpha: s.exampleID == "alpha", Viewport: gfx.Rect{Width: size.Width, Height: size.Height}, Layer: 3, Scope: demoPickerScope, Hex: hex} if p.open { - o.Value = p.draft + o.Value = p.draftValue } if p.invalid { o.Error = s.Text("请输入有效的十六进制色值", "Enter a valid hex color") @@ -124,20 +146,20 @@ func (s *State) paintColorPicker(c *gfx.Canvas, theme gfx.Theme, size gfx.Size) } func (s *State) pointerColorPicker(e gfx.PointerEvent) gfx.EventResult { - if !s.picker.open { + if s.exampleID != "alpha" || !s.picker.open { return gfx.EventResult{} } - v, r := s.picker.layout.Pointer(e, s.picker.draft) + v, r := s.picker.layout.Pointer(e, s.picker.draftValue) if r.Repaint { s.pickerSetValue(v) } return r } func (s *State) keyColorPicker(e gfx.KeyEvent) gfx.EventResult { - if !s.picker.open { + if s.exampleID != "alpha" || !s.picker.open { return gfx.EventResult{} } - v, r := s.picker.layout.Key(e, s.picker.draft) + v, r := s.picker.layout.Key(e, s.picker.draftValue) if r.Repaint { s.pickerSetValue(v) } diff --git a/internal/componentdemo/color_swatch.go b/internal/componentdemo/color_swatch.go index d9817191..3d0e0674 100644 --- a/internal/componentdemo/color_swatch.go +++ b/internal/componentdemo/color_swatch.go @@ -59,6 +59,9 @@ func (state *State) keyColorSwatch(event gfx.KeyEvent) gfx.EventResult { return gfx.EventResult{Focus: next, FocusVisible: true, Handled: true, Repaint: changed} } +// paintColorSwatch stays on the canvas API: ui.ColorSwatch paints the same +// swatches, but Box.Disabled is not forwarded to components.ColorSwatch, so the +// disabled choice would neither dim nor become inert. func (state *State) paintColorSwatch(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { var slots [4]ui.Box state.drawPage(canvas, theme, size, 360, state.Text("连接颜色", "Connection color"), func(c ui.C) { diff --git a/internal/componentdemo/combobox.go b/internal/componentdemo/combobox.go index 4ba736e7..96349cc7 100644 --- a/internal/componentdemo/combobox.go +++ b/internal/componentdemo/combobox.go @@ -89,7 +89,11 @@ var ( const comboboxOpenFlag uint64 = 1 -func initializeCombobox(state *State) { state.flags |= comboboxOpenFlag } +func initializeCombobox(state *State) { + if state.exampleID != "default" { + state.flags |= comboboxOpenFlag + } +} // comboboxChipRemove's item i removes the i-th chip of the chips example. var comboboxChipRemove = tree.Sub(comboboxUI, tree.Name("chip-remove")) @@ -121,11 +125,46 @@ func (state *State) paintComboboxChips(canvas *gfx.Canvas, theme gfx.Theme, size } } +// comboboxDemo is the caller-owned value of the page-first Combobox. +type comboboxDemo struct { + target string +} + +func comboboxValueIndex(target string) int32 { + switch target { + case "Viva Native": + return 1 + case "WebGPU": + return 2 + case "Headless tests": + return 3 + default: + return 0 + } +} + func (state *State) paintCombobox(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { if state.exampleID == "chips" { state.paintComboboxChips(canvas, theme, size) return } + if state.exampleID == "default" { + targets := []string{"Viva Native", "WebGPU", "Headless tests"} + hints := []string{state.Text("原生桌面", "Native desktop"), state.Text("可选 Web 目标", "Optional web target"), state.Text("无窗口测试", "Windowless testing")} + state.drawPage(canvas, theme, size, 420, state.Text("Combobox · 框架", "Combobox · Framework"), func(c ui.C) { + demo := ui.State[comboboxDemo](c, "combobox-demo") + ui.Combobox(c, &demo.target, targets, nil, state.Text("框架", "Framework")).Clearable(). + Describe(func(index int) ui.ComboboxOption { + return ui.ComboboxOption{Detail: hints[index]} + }) + state.values[0] = comboboxValueIndex(demo.target) + ui.Text(c, state.Text("点击输入区域打开选项。", "Click the input to open the options.")).FontSize(theme.Metrics.FontSizeS).Muted() + }) + return + } + // The empty, invalid and chips examples stay on the canvas API: the page + // Combobox starts closed with no caller-owned query, has no invalid state, + // and is single-select. values := [...]string{"", "Viva Native", "WebGPU", "Headless tests"} selected := int(state.values[0]) query := "" diff --git a/internal/componentdemo/context_menu.go b/internal/componentdemo/context_menu.go index 1786d32d..3d5a9599 100644 --- a/internal/componentdemo/context_menu.go +++ b/internal/componentdemo/context_menu.go @@ -1,14 +1,13 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) var contextMenuComponent = Component{ ID: "context-menu", Title: "Context Menu", Category: "Overlays", Summary: "调用方定位的上下文菜单与多种菜单项语义。", - paint: (*State).paintContextMenu, pointer: (*State).pointerContextMenu, initialize: (*State).initializeContextMenu, + paint: (*State).paintContextMenu, Examples: []Example{ {ID: "default", Title: "文件操作", Description: "动作、快捷键和子菜单由生产 ContextMenu 绘制。", Snippet: `menu := components.BeginContextMenu(canvas, theme, at, components.ContextMenuOptions{Layer: 1}) menu.AddItem(components.ContextMenuItem{ID: tree.ID(page, "open"), Label: "Open", Shortcut: "⌘O"}) @@ -65,68 +64,32 @@ ui.ContextMenu(c, area, func(menu *ui.MenuItems) { }, } -const contextMenuOpenMask uint64 = 1 << 1 - -var ( - contextMenuUI = tree.Feature("context-menu") - contextMenuToggle = tree.ID(contextMenuUI, "details") - contextMenuSurface = tree.ID(contextMenuUI, "surface") - // contextMenuItem's item i is the i-th plain item of the example. - contextMenuItem = tree.Sub(contextMenuUI, tree.Name("item")) -) - -func (state *State) initializeContextMenu() { - state.flags |= contextMenuOpenMask -} - -func (state *State) pointerContextMenu(event gfx.PointerEvent) gfx.EventResult { - if event.Kind != gfx.PointerDown || event.Button != gfx.PointerButtonSecondary || event.Target != contextMenuSurface { - return gfx.EventResult{} - } - changed := state.flags&contextMenuOpenMask == 0 || state.points[0] != event.X || state.points[1] != event.Y - state.flags |= contextMenuOpenMask - state.points[0], state.points[1] = event.X, event.Y - return gfx.EventResult{Handled: true, Repaint: changed} -} - func (state *State) paintContextMenu(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var area ui.Box state.drawPage(canvas, theme, size, 1000, state.Text("Context Menu · 上下文菜单", "Context Menu · Pointer actions"), func(c ui.C) { ui.Text(c, state.Text("在空白区域按次要按钮打开菜单。", "Right-click the empty area to open the menu.")).FontSize(theme.Metrics.FontSizeS).Muted() - area = ui.Slot(c).FillWidth().Height(max(size.Height-124, 120)) + area := ui.Row(c).FillWidth().Height(max(size.Height-124, 120)). + Radius(theme.Metrics.RadiusSurface).Background(theme.Muted). + Hit(ui.ID(c), state.Text("上下文菜单区域", "Context menu area")) + ui.ContextMenu(c, area, func(menu *ui.MenuItems) { + if state.exampleID != "default" { + menu.Label("Sort by") + if menu.Item("Name").Chosen(state.values[0] == 0).Clicked() { + state.values[0] = 0 + } + if menu.Item("Modified").Chosen(state.values[0] == 1).Clicked() { + state.values[0] = 1 + } + menu.Separator() + menu.Item("Unavailable action").Disabled(true) + return + } + menu.Item("Open").Keys(ui.Primary, "O") + if menu.Item("Show details").Checked(state.flags&1 != 0).Clicked() { + state.flags ^= 1 + } + menu.Sub("Open with", func(sub *ui.MenuItems) {}) + menu.Separator() + menu.Item("Move to trash").Destructive() + }) }) - surface := area.Rect() - canvas.RoundedBorder(surface, theme.Metrics.RadiusSurface, 1, theme.Border, theme.Muted) - canvas.PushFocusScope(contextMenuSurface) - canvas.HitWithOptions(contextMenuSurface, surface, "Context menu surface", gfx.HitOptions{SkipFocus: true}) - canvas.PopFocusScope() - if state.flags&contextMenuOpenMask == 0 { - return - } - menuWidth := min(size.Width-48, float32(260)) - menuX, menuY := (size.Width-menuWidth)/2, surface.Y+4 - if state.points[0] != 0 || state.points[1] != 0 { - menuX = min(max(state.points[0], float32(8)), max(size.Width-menuWidth-8, 8)) - menuY = min(max(state.points[1], surface.Y), max(size.Height-266, surface.Y)) - } - // Four 32px rows, a separator, and the surface's 4px top and bottom padding. - menuHeight := float32(4*32 + 9 + 2*4) - menu := components.BeginContextMenu(canvas, theme, gfx.Rect{X: menuX, Y: menuY, Width: menuWidth, Height: min(menuHeight, size.Height-menuY-8)}, components.ContextMenuOptions{Layer: 1}) - if state.exampleID == "default" { - menu.AddItem(components.ContextMenuItem{ID: contextMenuItem.At(0), Label: "Open", Shortcut: "⌘O"}) - menu.AddItem(components.ContextMenuItem{ID: contextMenuToggle, Label: "Show details", Kind: components.ContextMenuCheckbox, Checked: state.flags&1 != 0}) - menu.AddItem(components.ContextMenuItem{ID: contextMenuItem.At(1), Label: "Open with", Kind: components.ContextMenuSubmenu, Expanded: true}) - menu.AddSeparator() - menu.AddItem(components.ContextMenuItem{ID: contextMenuItem.At(2), Label: "Move to trash", Variant: components.ContextMenuItemDestructive}) - } else { - menu.AddLabel("Sort by", true) - menu.AddItem(components.ContextMenuItem{ID: contextMenuItem.At(3), Label: "Name", Kind: components.ContextMenuRadio, Selected: true}) - menu.AddItem(components.ContextMenuItem{ID: contextMenuItem.At(4), Label: "Modified", Kind: components.ContextMenuRadio}) - menu.AddSeparator() - menu.AddItem(components.ContextMenuItem{ID: contextMenuItem.At(5), Label: "Unavailable action", Disabled: true}) - } - menu.End() - if canvas.Clicked(contextMenuToggle) { - state.flags ^= 1 - } } diff --git a/internal/componentdemo/drawer.go b/internal/componentdemo/drawer.go index 58654dd3..8e6a249b 100644 --- a/internal/componentdemo/drawer.go +++ b/internal/componentdemo/drawer.go @@ -1,7 +1,6 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -19,9 +18,14 @@ canvas.Label("Native settings.", layout.Body, labelStyle) drawer.Actions(layout, components.ButtonAction{ID: saveID, Label: "Save"}) drawer.End() if canvas.Clicked(saveID) || canvas.Clicked(closeID) { open = false }`, PageSnippet: `open := true +if !open { + if ui.Button(c, "Open drawer").Clicked() { + open = true + } +} ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ Side: ui.DrawerBottom, Size: 248, - Description: "Applies immediately.", Swipe: true, + Description: "Applies immediately.", }, func() { ui.Text(c, "Native settings.") }, func() { @@ -29,13 +33,18 @@ ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ open = false } })`, PageSnippetZh: `open := true -ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ +if !open { + if ui.Button(c, "打开抽屉").Clicked() { + open = true + } +} +ui.Drawer(c, &open, "工作区设置", ui.DrawerSpec{ Side: ui.DrawerBottom, Size: 248, - Description: "Applies immediately.", Swipe: true, + Description: "立即生效。", }, func() { - ui.Text(c, "Native settings.") + ui.Text(c, "原生设置。") }, func() { - if ui.Button(c, "Save changes").Clicked() { + if ui.Button(c, "保存更改").Clicked() { open = false } })`}, @@ -48,6 +57,11 @@ canvas.Label("Native settings.", layout.Body, labelStyle) drawer.Actions(layout, components.ButtonAction{ID: saveID, Label: "Save changes"}) drawer.End() if canvas.Clicked(saveID) || canvas.Clicked(closeID) { open = false }`, PageSnippet: `open := true +if !open { + if ui.Button(c, "Open drawer").Clicked() { + open = true + } +} ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ Side: ui.DrawerRight, Size: 300, Description: "Same modal contract on the right edge.", @@ -58,13 +72,18 @@ ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ open = false } })`, PageSnippetZh: `open := true -ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ +if !open { + if ui.Button(c, "打开抽屉").Clicked() { + open = true + } +} +ui.Drawer(c, &open, "工作区设置", ui.DrawerSpec{ Side: ui.DrawerRight, Size: 300, - Description: "Same modal contract on the right edge.", + Description: "右侧边缘使用相同的模态契约。", }, func() { - ui.Text(c, "Native settings.") + ui.Text(c, "原生设置。") }, func() { - if ui.Button(c, "Save changes").Clicked() { + if ui.Button(c, "保存更改").Clicked() { open = false } })`}, @@ -74,16 +93,22 @@ ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ layout := drawer.Begin("Workspace settings", "Structure remains visible; interaction is off.") drawer.Actions(layout, components.ButtonAction{ID: saveID, Label: "Save changes"}) drawer.End()`, PageSnippet: `open := true +if !open { + ui.Button(c, "Open drawer").Disabled(true) +} ui.Drawer(c, &open, "Workspace settings", ui.DrawerSpec{ - Side: ui.DrawerBottom, Disabled: true, + Side: ui.DrawerBottom, Size: 248, Disabled: true, Description: "Structure remains visible; interaction is off.", }, func() { ui.Text(c, "Native settings.") }, func() { ui.Button(c, "Save changes").Disabled(true) })`, PageSnippetZh: `open := true +if !open { + ui.Button(c, "打开抽屉").Disabled(true) +} ui.Drawer(c, &open, "工作区设置", ui.DrawerSpec{ - Side: ui.DrawerBottom, Disabled: true, + Side: ui.DrawerBottom, Size: 248, Disabled: true, Description: "结构保持可见,交互已关闭。", }, func() { ui.Text(c, "原生设置。") @@ -94,42 +119,60 @@ ui.Drawer(c, &open, "工作区设置", ui.DrawerSpec{ } var ( - drawerUI = tree.Feature("drawer") - drawerOpen = tree.ID(drawerUI, "open") - drawerClose = tree.ID(drawerUI, "close") - drawerFocus = tree.ID(drawerUI, "focus") - drawerSave = tree.ID(drawerUI, "save") + drawerUI = tree.Feature("drawer") + drawerOpen = tree.ID(drawerUI, "open") + drawerSave = tree.ID(drawerUI, "save") ) func (state *State) initializeDrawer() { state.flags |= 1 } func (state *State) paintDrawer(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - open := state.flags&1 != 0 state.drawPage(canvas, theme, size, 480, state.Text("Drawer · 边缘模态", "Drawer · Edge modal"), func(c ui.C) { - // The page behind an open drawer is just its title. - if !open && ui.Button(c, "Open drawer").Self(ui.Start).Hit(drawerOpen, "Open drawer").Clicked() { + // The drawer's open state lives on the page; the demo's flag mirrors it so + // the surrounding state stays inspectable. + open := ui.State[bool](c, "open") + seeded := ui.State[bool](c, "seeded") + if !*seeded { + *open = state.flags&1 != 0 + *seeded = true + } + if !*open { + label := state.Text("打开抽屉", "Open drawer") + if state.exampleID == "disabled" { + ui.Button(c, label).Self(ui.Start).Hit(drawerOpen, label).Disabled(true) + } else if ui.Button(c, label).Self(ui.Start).Hit(drawerOpen, label).Clicked() { + *open = true + } + } + spec := ui.DrawerSpec{ + Side: ui.DrawerBottom, Size: 248, + Description: state.Text("立即生效。", "Applies immediately."), + } + title, body := state.Text("工作区设置", "Workspace settings"), state.Text("原生设置。", "Native settings.") + switch state.exampleID { + case "sides": + spec.Side, spec.Size = ui.DrawerRight, 300 + spec.Description = state.Text("右侧边缘使用相同的模态契约。", "Same modal contract on the right edge.") + case "disabled": + spec.Disabled = true + spec.Description = state.Text("结构保持可见,交互已关闭。", "Structure remains visible; interaction is off.") + } + ui.Drawer(c, open, title, spec, func() { + ui.Text(c, body) + }, func() { + save := state.Text("保存更改", "Save changes") + if state.exampleID == "disabled" { + ui.Button(c, save).Hit(drawerSave, save).Disabled(true) + return + } + if ui.Button(c, save).Hit(drawerSave, save).Clicked() { + *open = false + } + }) + if *open { state.flags |= 1 + } else { + state.flags &^= 1 } }) - if !open { - return - } - side := components.DrawerBottom - extent := min(float32(248), size.Height*0.72) - if state.exampleID == "sides" { - side = components.DrawerRight - extent = min(float32(300), size.Width*0.78) - } - viewport := gfx.Rect{Width: size.Width, Height: size.Height} - drawer := components.BeginDrawer(canvas, theme, viewport, components.DrawerOptions{Layer: 2, Scope: drawerFocus, CloseID: drawerClose, Side: side, ContentExtent: extent}).WithHandle() - if state.exampleID == "disabled" { - drawer = drawer.Disabled() - } - layout := drawer.Begin("Workspace settings", "Applies immediately.") - canvas.Label("Native settings.", layout.Body, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.Foreground}) - drawer.Actions(layout, components.ButtonAction{ID: drawerSave, Label: "Save changes"}) - drawer.End() - if canvas.Clicked(drawerSave) || canvas.Clicked(drawerClose) { - state.flags &^= 1 - } } diff --git a/internal/componentdemo/dropdown_menu.go b/internal/componentdemo/dropdown_menu.go index bae4a8c6..48d82664 100644 --- a/internal/componentdemo/dropdown_menu.go +++ b/internal/componentdemo/dropdown_menu.go @@ -1,7 +1,6 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -82,38 +81,45 @@ ui.Menu(c, trigger, &open, func(menu *ui.MenuItems) { }, } -var ( - dropdownMenuUI = tree.Feature("dropdown-menu") - dropdownMenuToggle = tree.ID(dropdownMenuUI, "compact") - // dropdownMenuItem's item i is the i-th plain item of the example. - dropdownMenuItem = tree.Sub(dropdownMenuUI, tree.Name("item")) -) +// dropdownMenuDemo is the caller-owned state of the page-first Menu. +type dropdownMenuDemo struct { + open, compact, ready bool +} func (state *State) paintDropdownMenu(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - // Label (32), three rows (96), separator (9), and the surface's 4px padding. - height := float32(32 + 3*32 + 9 + 2*4) + label := "Account" if state.exampleID != "default" { - height = 4*32 + 2*4 + label = "Team" } - var panel ui.Box state.drawPage(canvas, theme, size, 260, "Dropdown Menu · Account", func(c ui.C) { - panel = ui.Slot(c).FillWidth().Height(min(height, max(size.Height-84, 120))) + demo := ui.State[dropdownMenuDemo](c, "dropdown-menu-demo") + if !demo.ready { + demo.ready, demo.open = true, true + } + trigger := ui.Button(c, label).Outline() + if trigger.Clicked() { + demo.open = !demo.open + } + ui.Menu(c, trigger, &demo.open, func(menu *ui.MenuItems) { + if state.exampleID == "default" { + menu.Label("skyler@example.com") + menu.Item("Profile").Keys(ui.Primary|ui.Shift, "P") + if menu.Item("Compact mode").Checked(demo.compact).Clicked() { + demo.compact = !demo.compact + } + menu.Separator() + menu.Item("Sign out").Destructive() + return + } + menu.Sub("Team", func(sub *ui.MenuItems) { + sub.Item("Personal").Chosen(true) + sub.Item("Organization").Chosen(false) + }) + menu.Item("Unavailable").Disabled(true) + }) + state.flags &^= 1 + if demo.compact { + state.flags |= 1 + } }) - menu := components.BeginDropdownMenu(canvas, theme, panel.Rect(), components.DropdownMenuOptions{Layer: 1}) - if state.exampleID == "default" { - menu.AddLabel("skyler@example.com", false) - menu.AddItem(components.DropdownMenuItem{ID: dropdownMenuItem.At(0), Label: "Profile", Shortcut: "⇧⌘P"}) - menu.AddItem(components.DropdownMenuItem{ID: dropdownMenuToggle, Label: "Compact mode", Kind: components.DropdownMenuCheckbox, Checked: state.flags&1 != 0}) - menu.AddSeparator() - menu.AddItem(components.DropdownMenuItem{ID: dropdownMenuItem.At(1), Label: "Sign out", Variant: components.DropdownMenuItemDestructive}) - } else { - menu.AddItem(components.DropdownMenuItem{ID: dropdownMenuItem.At(2), Label: "Team", Kind: components.DropdownMenuSubmenu, Expanded: true}) - menu.AddItem(components.DropdownMenuItem{ID: dropdownMenuItem.At(3), Label: "Personal", Kind: components.DropdownMenuRadio, Selected: true}) - menu.AddItem(components.DropdownMenuItem{ID: dropdownMenuItem.At(4), Label: "Organization", Kind: components.DropdownMenuRadio}) - menu.AddItem(components.DropdownMenuItem{ID: dropdownMenuItem.At(5), Label: "Unavailable", Disabled: true}) - } - menu.End() - if canvas.Clicked(dropdownMenuToggle) { - state.flags ^= 1 - } } diff --git a/internal/componentdemo/empty.go b/internal/componentdemo/empty.go index 453a17bb..3f0a004d 100644 --- a/internal/componentdemo/empty.go +++ b/internal/componentdemo/empty.go @@ -1,13 +1,10 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) -var emptyCreate = tree.ID(tree.Feature("empty"), "create") - var emptyComponent = Component{ ID: "empty", Title: "Empty", Category: "Feedback", Summary: "无数据时的居中图形、标题与说明。", paint: (*State).paintEmpty, @@ -55,22 +52,19 @@ components.BeginButton(canvas, theme, tree.ID(page, "create"), gfx.Rect{Height: } func (state *State) paintEmpty(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var stage ui.Box - state.drawPage(canvas, theme, size, 560, state.Text("Empty · 空状态", "Empty · No data"), func(c ui.C) { - stage = ui.Slot(c).FillWidth().Height(max(size.Height-110, 180)) + icon := state.exampleID == "icon" + state.drawStage(canvas, theme, size, func(c ui.C) { + ui.Column(c).Fill().Center().Gap(6).Children(func() { + if icon { + ui.Column(c).Size(56, 56).Center().Radius(28).Background(theme.Muted).Children(func() { + ui.Icon(c, folderIcon).Size(24, 24).Muted() + }) + } else { + ui.Icon(c, folderIcon).Size(40, 40).Muted() + } + ui.Text(c, "No projects yet").FontSize(18).Bold() + ui.Text(c, "Create a project to get started.").FontSize(13).Muted() + ui.Button(c, "Create project").Self(ui.Start) + }) }) - data := components.EmptyData{ - Icon: folderIcon, Title: "No projects yet", Description: "Create a project to get started.", ContentHeight: 32, - } - if state.exampleID == "icon" { - data.Media = components.EmptyMediaIcon - } - // The centered text needs more than the page column on a narrow stage, so the - // recipe is given the page's side margin too. - bounds := stage.Rect() - bounds.X, bounds.Width = bounds.X-16, bounds.Width+32 - content := components.Empty(canvas, theme, bounds, data) - const label = "Create project" - components.BeginButton(canvas, theme, emptyCreate, gfx.Rect{Height: content.Height}). - SizeToFit(label).CenterIn(content).Default(label) } diff --git a/internal/componentdemo/field.go b/internal/componentdemo/field.go index a8e9175d..3d705f4b 100644 --- a/internal/componentdemo/field.go +++ b/internal/componentdemo/field.go @@ -90,32 +90,43 @@ func fieldInitial(exampleID string) string { } func (state *State) paintField(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + if state.exampleID == "orientations" { + state.paintFieldResponsive(canvas, theme, size) + return + } + initial := fieldInitial(state.exampleID) + state.drawPage(canvas, theme, size, 600, state.Text("Field · 结构化字段", "Field · Structured field"), func(c ui.C) { + field := ui.State[ui.Field](c, "email") + form := ui.State[ui.FormFieldState](c, "field") + state.bindPageField(field, initial) + form.Description = "Used only for release notifications." + if state.exampleID == "invalid" { + field.Invalid = !strings.Contains(field.Text(), "@") + form.Invalid = field.Invalid + form.Error = "" + if field.Invalid { + form.Error = "Enter a valid work email." + } + } + ui.FormField(c, form, "Work email").Children(func() { + ui.TextFieldID(c, fieldInput, field, "Work email", "") + }) + }) +} + +// paintFieldResponsive keeps the orientation example on the canvas API: the +// page FormField has no responsive orientation option. +func (state *State) paintFieldResponsive(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { var slot ui.Box state.drawPage(canvas, theme, size, 600, state.Text("Field · 结构化字段", "Field · Structured field"), func(c ui.C) { slot = ui.Slot(c).FillWidth().Height(136) }) - field := components.BeginField(canvas, theme, slot.Rect()).For(fieldInput) - if state.exampleID == "orientations" { - field = field.Orientation(components.FieldResponsive) - } + field := components.BeginField(canvas, theme, slot.Rect()).For(fieldInput).Orientation(components.FieldResponsive) value := state.fieldValue(fieldInitial(state.exampleID)) - required := state.exampleID == "invalid" - invalid := required && !strings.Contains(value, "@") - if required { - field = field.Required() - } - if invalid { - field = field.Invalid() - } - errorText := "" - if invalid { - errorText = "Enter a valid work email." - } - control := field.Paint("Work email", "Used only for release notifications.", errorText) input := components.InputSnapshot{ - ID: fieldInput, Label: "Work email", Value: value, Hint: "Used only for release notifications", Invalid: invalid, + ID: fieldInput, Label: "Work email", Value: value, Hint: "Used only for release notifications", ReadOnly: !state.editing, } state.paintEditable(canvas, fieldInput, value, &input) - components.PaintInput(canvas, theme, control, input) + components.PaintInput(canvas, theme, field.Paint("Work email", "Used only for release notifications.", ""), input) } diff --git a/internal/componentdemo/form.go b/internal/componentdemo/form.go index d6ea36a1..edaa330a 100644 --- a/internal/componentdemo/form.go +++ b/internal/componentdemo/form.go @@ -101,22 +101,45 @@ func formInitial(exampleID string) string { } func (state *State) paintForm(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + if state.exampleID == "message" { + state.paintFormMessage(canvas, theme, size) + return + } + initial := formInitial(state.exampleID) + state.drawPage(canvas, theme, size, 560, state.Text("Form · 显式字段状态", "Form · Explicit field state"), func(c ui.C) { + field := ui.State[ui.Field](c, "username") + form := ui.State[ui.FormFieldState](c, "field") + state.bindPageField(field, initial) + form.Description = "This name is visible to collaborators." + if state.exampleID == "invalid" { + field.Invalid = utf8.RuneCountInString(field.Text()) < 3 + form.Invalid = field.Invalid + form.Error = "" + if field.Invalid { + form.Error = "Use at least three characters." + } + } + ui.FormField(c, form, "Username").Children(func() { + ui.TextFieldID(c, formInput, field, "Username", "") + }) + }) +} + +// paintFormMessage keeps the message example on the canvas API: the page +// FormField has no separate non-error message line. +func (state *State) paintFormMessage(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { var slot ui.Box state.drawPage(canvas, theme, size, 560, state.Text("Form · 显式字段状态", "Form · Explicit field state"), func(c ui.C) { slot = ui.Slot(c).FillWidth().Height(150) }) value := state.fieldValue(formInitial(state.exampleID)) - snapshot := components.FormFieldSnapshot{Label: "Username", Description: "This name is visible to collaborators.", Required: true, ControlID: formInput} - if state.exampleID == "message" { - snapshot.Message = "Username is available." - } - if state.exampleID == "invalid" && utf8.RuneCountInString(value) < 3 { - snapshot.Invalid = true - snapshot.Error = "Use at least three characters." + snapshot := components.FormFieldSnapshot{ + Label: "Username", Description: "This name is visible to collaborators.", + Message: "Username is available.", Required: true, ControlID: formInput, } layout := components.PaintFormField(canvas, theme, slot.Rect(), snapshot) input := components.InputSnapshot{ - ID: formInput, Label: layout.Semantics.Label, Value: value, Hint: layout.Semantics.AssistiveText(), Invalid: layout.Semantics.Invalid, + ID: formInput, Label: layout.Semantics.Label, Value: value, Hint: layout.Semantics.AssistiveText(), ReadOnly: !state.editing, } state.paintEditable(canvas, formInput, value, &input) diff --git a/internal/componentdemo/group_c_test.go b/internal/componentdemo/group_c_test.go index f1c5d4f3..d809e64e 100644 --- a/internal/componentdemo/group_c_test.go +++ b/internal/componentdemo/group_c_test.go @@ -37,11 +37,10 @@ func TestGroupCClicksUpdateCallerState(t *testing.T) { {id: questionnaireNext, want: func(s *State) bool { return s.values[1] == 1 }}, }}, {"radio-group", "vertical", []step{{id: radioGroupItem.At(0), want: func(s *State) bool { return s.values[0] == 0 }}}}, - {"scroll-area", "both-axes", []step{{id: scrollAreaHorizontal, want: func(s *State) bool { return s.values[1] == 72 }}}}, - {"segmented-control", "default", []step{{id: segmentedControlView.At(2), want: func(s *State) bool { return s.values[0] == 2 }}}}, + {"segmented-control", "default", []step{{label: "Timeline", want: func(s *State) bool { return s.values[0] == 2 }}}}, {"select", "default", []step{ - {id: selectTrigger, want: func(s *State) bool { return s.flags&1 != 0 }}, - {id: selectItem.At(1), want: func(s *State) bool { return s.values[0] == 2 && s.flags&1 == 0 }}, + {label: "Renderer", want: func(s *State) bool { return s.values[0] == 0 }}, + {label: "Direct3D", want: func(s *State) bool { return s.values[0] == 2 }}, }}, {"sheet", "right", []step{ {id: sheetTrigger, want: func(s *State) bool { return s.flags&1 != 0 }}, @@ -52,23 +51,18 @@ func TestGroupCClicksUpdateCallerState(t *testing.T) { {id: sidebarCollapse, want: func(s *State) bool { return s.flags&1 != 0 }}, }}, {"slider", "default", []step{{id: sliderPrimary, want: func(s *State) bool { return s.values[0] == 50 }}}}, - {"sonner", "stack", []step{{id: sonnerDismiss.At(1), want: func(s *State) bool { return s.flags&0b010 == 0 && s.flags&0b101 == 0b101 }}}}, + {"sonner", "stack", []step{{label: "Close toast", want: func(s *State) bool { return s.flags == 0b011 }}}}, {"table", "selection", []step{ - {id: tableRow.At(1), want: func(s *State) bool { return s.flags&2 != 0 }}, - {id: tableRow.At(1), want: func(s *State) bool { return s.flags&2 == 0 }}, + {label: "桌面构建", want: func(s *State) bool { return s.flags&2 != 0 }}, + {label: "性能审计", want: func(s *State) bool { return s.flags&4 != 0 }}, }}, {"tabs", "line", []step{{label: "活动", want: func(s *State) bool { return s.values[0] == 1 }}}}, {"toast", "types", []step{ - {id: toastAction, want: func(s *State) bool { return s.values[0] == 1 }}, - {id: toastDismiss, want: func(s *State) bool { return s.flags&1 == 0 }}, + {label: "切换", want: func(s *State) bool { return s.values[0] == 1 }}, + {label: "Close toast", want: func(s *State) bool { return s.flags == 0 }}, }}, {"toggle", "default", []step{{id: toggleItem.At(2), want: func(s *State) bool { return s.flags&4 != 0 }}}}, {"toggle-group", "single", []step{{id: toggleGroupItem.At(2), want: func(s *State) bool { return s.flags == 4 }}}}, - {"tooltip", "default", []step{{id: tooltipTrigger, want: func(s *State) bool { return s.flags&1 != 0 }}}}, - {"tree", "selection", []step{ - {id: treeLeaf.At(2), want: func(s *State) bool { return s.values[0] == 2 }}, - {id: treeGroupDisclosure, want: func(s *State) bool { return s.flags&1 == 0 }}, - }}, } for _, test := range tests { t.Run(test.component+"/"+test.example, func(t *testing.T) { @@ -97,6 +91,46 @@ func TestGroupCClicksUpdateCallerState(t *testing.T) { } }) } + // The page Tree owns its row identities: choose a leaf by label, then collapse + // the branch through the disclosure identity the state reports. + t.Run("tree/selection", func(t *testing.T) { + state := newTestState(t, "tree", "selection") + var canvas gfx.Canvas + canvas.SetMeasurer(measureTestText) + paintFrame(&canvas, state, testSize, 0, true) + click(&canvas, state, findHitByLabel(t, &canvas, "Worker")) + if state.values[0] != 2 { + t.Fatalf("choosing Worker left values[0]=%d", state.values[0]) + } + paintFrame(&canvas, state, testSize, 0, true) + click(&canvas, state, treeDemoFor(state).state.DisclosureID(0)) + if state.flags&1 != 0 { + t.Fatalf("collapsing Production left flags=%b", state.flags) + } + }) + // The page Scroll owns its offset: a sideways wheel over the area moves it and + // the demo mirrors the settled offset back into its values. + t.Run("scroll-area/both-axes", func(t *testing.T) { + state := newTestState(t, "scroll-area", "both-axes") + var canvas gfx.Canvas + canvas.SetMeasurer(measureTestText) + paintFrame(&canvas, state, testSize, 0, true) + demo := scrollAreaDemoFor(state) + if demo.scroller == nil || demo.bounds.Width <= 0 { + t.Fatal("the scroll area was not declared") + } + result := state.Scroll(gfx.ScrollEvent{ + X: demo.bounds.X + demo.bounds.Width/2, Y: demo.bounds.Y + demo.bounds.Height/2, + DeltaX: 72, Precise: true, Target: scrollAreaViewport, + }) + if !result.Handled || !result.Repaint || demo.scroller.OffsetX != 72 { + t.Fatalf("wheel result=%+v offsetX=%.0f", result, demo.scroller.OffsetX) + } + paintFrame(&canvas, state, testSize, 0, true) + if state.values[1] != 72 { + t.Fatalf("mirrored offsetX=%d, want 72", state.values[1]) + } + }) } // findHitByLabel finds the control of the canvas with the accessibility label, diff --git a/internal/componentdemo/input.go b/internal/componentdemo/input.go index 9952538b..284d9174 100644 --- a/internal/componentdemo/input.go +++ b/internal/componentdemo/input.go @@ -223,71 +223,126 @@ func (state *State) paintInput(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Siz if state.editing { mode = state.Text("平台文本服务 · 支持输入、选区与 IME", "Platform text service · typing, selection and IME") } - if state.exampleID == "states" { + switch state.exampleID { + case "states": mode = state.Text("禁用与只读 · 不连接编辑器", "Disabled and read-only · no editor") - } - if state.exampleID == "custom" { + state.paintInputStates(canvas, theme, size, mode) + case "custom": state.paintCustomInputs(canvas, theme, size, mode) - return + default: + state.paintInputPage(canvas, theme, size, mode) } - var samples [2]inputSample - caption := state.Text("Web 与原生预览均连接同一个 Go Editor。", "The Web and native previews connect the same Go Editor.") - if state.exampleID == "states" { - samples[0] = inputSample{ - id: inputDisabled, label: "Disabled", value: state.Text("不可编辑", "Not editable"), - disabled: true, themeRadius: true, - } - samples[1] = inputSample{ - id: inputReadOnly, label: "Read-only", value: state.Text("Viva · 只读文本", "Viva · read-only text"), - readOnly: true, themeRadius: true, - } - caption = state.Text("禁用与只读字段均不连接编辑器。", "Disabled and read-only fields do not connect an editor.") - } else { - value := state.fieldValue(state.initialInputValue()) - label, placeholder := "Name", state.Text("输入中文或 English…", "Type in Chinese or English…") - invalid := false - if state.exampleID == "invalid" { - label, placeholder = "Email", "name@example.com" - invalid = value == "" || !strings.Contains(value, "@") - } - samples[0] = inputSample{ - id: inputEditable, label: label, value: value, placeholder: placeholder, hint: mode, - invalid: invalid, readOnly: !state.editing, themeRadius: true, +} + +// paintInputPage is the page TextField of the examples whose single field the +// platform edits: the value lives in the Field the page paints, so the preview +// and the snippet connect the same editor. +func (state *State) paintInputPage(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size, mode string) { + initial := state.initialInputValue() + label, placeholder := "Name", state.Text("输入中文或 English…", "Type in Chinese or English…") + invalidExample := state.exampleID == "invalid" + if invalidExample { + label, placeholder = "Email", "name@example.com" + } + captionText := state.Text("Web 与原生预览均连接同一个 Go Editor。", "The Web and native previews connect the same Go Editor.") + invalid := false + if invalidExample { + invalid = initial == "" || !strings.Contains(initial, "@") + captionText = state.Text("演示校验通过。", "The demo validation passes.") + if invalid { + captionText = state.Text("请输入含 @ 的非空文本。", "Enter non-empty text containing @.") } - if state.exampleID == "invalid" { - caption = state.Text("演示校验通过。", "The demo validation passes.") - if invalid { - caption = state.Text("请输入含 @ 的非空文本。", "Enter non-empty text containing @.") + } + if !state.editing { + // Without a platform text service the demo keeps its read-only + // snapshot: the page TextField has no read-only state. + state.paintInputSnapshot(canvas, theme, size, mode, label, placeholder, initial, invalid, captionText) + return + } + state.drawPage(canvas, theme, size, 440, state.Text("Input · 文本输入", "Input · Text input"), func(c ui.C) { + field := ui.State[ui.Field](c, "input") + state.bindPageField(field, initial) + field.Hint = mode + if invalidExample { + field.Invalid = field.Text() == "" || !strings.Contains(field.Text(), "@") + captionText = state.Text("演示校验通过。", "The demo validation passes.") + if field.Invalid { + captionText = state.Text("请输入含 @ 的非空文本。", "Enter non-empty text containing @.") } } + ui.Text(c, mode).FontSize(theme.Metrics.FontSizeS).Muted() + ui.Column(c).Gap(6).Children(func() { + ui.Text(c, label).FontSize(theme.Metrics.FontSizeM) + ui.TextFieldID(c, inputEditable, field, label, placeholder) + }) + ui.Text(c, captionText).FontSize(theme.Metrics.FontSizeS).Muted() + }) +} + +// paintInputSnapshot is the disconnected preview of one input: a read-only +// snapshot painted by the component, which keeps the demo's rule that a preview +// without a platform text service never looks editable. +func (state *State) paintInputSnapshot(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size, mode, label, placeholder, value string, invalid bool, captionText string) { + sample := inputSample{ + id: inputEditable, label: label, value: value, placeholder: placeholder, + hint: mode, invalid: invalid, readOnly: true, themeRadius: true, } state.drawPage(canvas, theme, size, 440, state.Text("Input · 文本输入", "Input · Text input"), func(c ui.C) { ui.Text(c, mode).FontSize(theme.Metrics.FontSizeS).Muted() - if state.exampleID == "states" { - ui.Column(c).Gap(6).Children(func() { - ui.Text(c, "Disabled").FontSize(theme.Metrics.FontSizeM) - samples[0].box = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) - }) - ui.Column(c).Gap(6).Children(func() { - ui.Text(c, "Read-only").FontSize(theme.Metrics.FontSizeM) - samples[1].box = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) - }) - } else { - ui.Column(c).Gap(6).Children(func() { - ui.Text(c, samples[0].label).FontSize(theme.Metrics.FontSizeM) - samples[0].box = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) - }) - } - ui.Text(c, caption).FontSize(theme.Metrics.FontSizeS).Muted() + ui.Column(c).Gap(6).Children(func() { + ui.Text(c, label).FontSize(theme.Metrics.FontSizeM) + sample.box = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) + }) + ui.Text(c, captionText).FontSize(theme.Metrics.FontSizeS).Muted() + }) + state.paintInputSample(canvas, theme, &sample) +} + +// paintInputStates keeps the disabled and read-only samples on the canvas API: +// the page TextField has no read-only state. +func (state *State) paintInputStates(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size, mode string) { + var samples [2]inputSample + samples[0] = inputSample{ + id: inputDisabled, label: "Disabled", value: state.Text("不可编辑", "Not editable"), + disabled: true, themeRadius: true, + } + samples[1] = inputSample{ + id: inputReadOnly, label: "Read-only", value: state.Text("Viva · 只读文本", "Viva · read-only text"), + readOnly: true, themeRadius: true, + } + state.drawPage(canvas, theme, size, 440, state.Text("Input · 文本输入", "Input · Text input"), func(c ui.C) { + ui.Text(c, mode).FontSize(theme.Metrics.FontSizeS).Muted() + ui.Column(c).Gap(6).Children(func() { + ui.Text(c, "Disabled").FontSize(theme.Metrics.FontSizeM) + samples[0].box = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) + }) + ui.Column(c).Gap(6).Children(func() { + ui.Text(c, "Read-only").FontSize(theme.Metrics.FontSizeM) + samples[1].box = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) + }) + ui.Text(c, state.Text("禁用与只读字段均不连接编辑器。", "Disabled and read-only fields do not connect an editor.")). + FontSize(theme.Metrics.FontSizeS).Muted() }) for index := range samples { - if samples[index].id.IsZero() { - continue - } state.paintInputSample(canvas, theme, &samples[index]) } } +// bindPageField binds the demo's platform editor to a page Field, or seeds the +// Field's own editor with the example's initial text when no platform text +// service is attached. +func (state *State) bindPageField(field *ui.Field, initial string) { + if state.editing && state.editor != nil { + if field.GetEditor() != state.editor { + field.Bind(state.editor) + } + return + } + if field.GetEditor() == nil { + field.SetText(initial) + } +} + // paintCustomInputs shows three fields in one column: a pill with larger text, a // squarer one with smaller text, and one with the theme's own radius and size. // Only the first is connected to the editor; the others are read-only samples. diff --git a/internal/componentdemo/item.go b/internal/componentdemo/item.go index 727a9aab..90ff2e59 100644 --- a/internal/componentdemo/item.go +++ b/internal/componentdemo/item.go @@ -1,7 +1,6 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -27,12 +26,14 @@ if m.selected { trailing = "Selected" } row := ui.Row(c).FillWidth().Pad(12).Gap(12).Items(ui.Center).Hit(ui.ID(c), "Release notes") -ui.Row(c).Size(24, 24).Radius(6).Background(look.Primary) -ui.Column(c).Grow(1).Gap(2).Children(func() { - ui.Text(c, "Release notes").Bold() - ui.Text(c, "Latest runtime changes.").Muted() +row.Children(func() { + ui.Row(c).Size(24, 24).Radius(6).Background(look.Primary) + ui.Column(c).Grow(1).Gap(2).Children(func() { + ui.Text(c, "Release notes").Bold() + ui.Text(c, "Latest runtime changes.").Muted() + }) + ui.Text(c, trailing) }) -ui.Text(c, trailing) if row.Clicked() { m.selected = !m.selected }`, PageSnippetZh: `look := c.Theme() @@ -41,12 +42,14 @@ if m.selected { trailing = "Selected" } row := ui.Row(c).FillWidth().Pad(12).Gap(12).Items(ui.Center).Hit(ui.ID(c), "Release notes") -ui.Row(c).Size(24, 24).Radius(6).Background(look.Primary) -ui.Column(c).Grow(1).Gap(2).Children(func() { - ui.Text(c, "Release notes").Bold() - ui.Text(c, "Latest runtime changes.").Muted() +row.Children(func() { + ui.Row(c).Size(24, 24).Radius(6).Background(look.Primary) + ui.Column(c).Grow(1).Gap(2).Children(func() { + ui.Text(c, "Release notes").Bold() + ui.Text(c, "Latest runtime changes.").Muted() + }) + ui.Text(c, trailing) }) -ui.Text(c, trailing) if row.Clicked() { m.selected = !m.selected }`}, @@ -106,30 +109,46 @@ var ( ) func (state *State) paintItem(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var rows [3]ui.Box + selected := state.flags&1 != 0 + trailing := "Open" + if selected { + trailing = "Selected" + } state.drawPage(canvas, theme, size, 560, state.Text("Item · 生产列表行", "Item · Production list rows"), func(c ui.C) { if state.exampleID == "default" { - rows[0] = ui.Slot(c).FillWidth().Height(72) + row := ui.Row(c).FillWidth().Pad(12).Gap(12).Items(ui.Center).Hit(itemRow.At(0), "Release notes") + row.Children(func() { + ui.Row(c).Size(24, 24).Radius(6).Background(theme.Primary) + ui.Column(c).Grow(1).Gap(2).Children(func() { + ui.Text(c, "Release notes").Bold() + ui.Text(c, "Latest runtime changes.").Muted() + }) + ui.Text(c, trailing) + }) + if row.Clicked() { + state.flags ^= 1 + } return } - rows[0] = ui.Slot(c).FillWidth().Height(68) - rows[1] = ui.Slot(c).FillWidth().Height(54) - rows[2] = ui.Slot(c).FillWidth().Height(42) + ui.Row(c).FillWidth().Pad(12).Gap(12).Items(ui.Center).Children(func() { + ui.Column(c).Grow(1).Children(func() { + ui.Text(c, "Outline") + ui.Text(c, "Default density").Muted() + }) + ui.Text(c, "⌘1") + }) + ui.Row(c).FillWidth().Pad(8).Gap(8).Items(ui.Center).Children(func() { + ui.Column(c).Grow(1).Children(func() { + ui.Text(c, "Muted") + ui.Text(c, "Small density").Muted() + }) + ui.Text(c, "⌘2") + }) + ui.Row(c).FillWidth().Pad(6).Gap(6).Items(ui.Center).Disabled(true).Children(func() { + ui.Column(c).Grow(1).Children(func() { + ui.Text(c, "Disabled") + }) + ui.Text(c, "Unavailable").Muted() + }) }) - if state.exampleID == "default" { - trailing := "Open" - if state.flags&1 != 0 { - trailing = "Selected" - } - bounds := rows[0].Rect() - components.BeginItem(canvas, theme, itemRow.At(0), bounds).Variant(components.ItemOutline).LeadingSpace(28).Paint("Release notes", "Latest runtime changes.", trailing) - canvas.Rounded(gfx.Rect{X: bounds.X + 12, Y: bounds.Y + (bounds.Height-24)/2, Width: 24, Height: 24}, 6, theme.Primary) - if canvas.Clicked(itemRow.At(0)) { - state.flags ^= 1 - } - return - } - components.BeginItem(canvas, theme, itemRow.At(0), rows[0].Rect()).Variant(components.ItemOutline).Paint("Outline", "Default density", "⌘1") - components.BeginItem(canvas, theme, itemRow.At(1), rows[1].Rect()).Variant(components.ItemMuted).Size(components.ItemSizeSmall).Paint("Muted", "Small density", "⌘2") - components.BeginItem(canvas, theme, itemRow.At(2), rows[2].Rect()).Size(components.ItemSizeExtraSmall).Disabled().Paint("Disabled", "", "Unavailable") } diff --git a/internal/componentdemo/multi_select.go b/internal/componentdemo/multi_select.go index 28d3a229..13081f2e 100644 --- a/internal/componentdemo/multi_select.go +++ b/internal/componentdemo/multi_select.go @@ -3,20 +3,22 @@ package componentdemo import ( "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/text" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/multiselect" ) var ( multiSelectUI = tree.Feature("multi-select") - multiSelectInput = tree.ID(multiSelectUI, "input") - multiSelectTrigger = tree.ID(multiSelectUI, "trigger") - multiSelectDismiss = tree.ID(multiSelectUI, "dismiss") - multiSelectScope = tree.ID(multiSelectUI, "scope") multiSelectOptions = tree.Sub(multiSelectUI, tree.Name("option")) multiSelectRemove = tree.Sub(multiSelectUI, tree.Name("remove")) ) +// multiSelectDemo is the page-owned picker of one example, made once so a warm +// paint reuses it instead of building a new control every frame. +type multiSelectDemo struct { + picker *multiselect.Picker +} + var multiSelectComponent = Component{ ID: "multi-select", Title: "Multi Select", Category: "Forms", Summary: "可搜索、多选并创建条目,已选项可逐个删除。", initialize: func(state *State) { @@ -24,22 +26,6 @@ var multiSelectComponent = Component{ state.multiSelect.SetOptions([]components.MultiSelectOption{{Value: state.Text("开发", "Development")}, {Value: state.Text("测试", "Testing")}, {Value: state.Text("生产", "Production")}}) state.multiSelect.SetValues([]string{state.Text("开发", "Development")}) }, - editable: func(example string) (editableField, bool) { - return editableField{ID: multiSelectInput}, example != "disabled" - }, - editor: func(state *State) *text.Editor { return &state.multiSelect.Query }, - key: func(state *State, event gfx.KeyEvent) gfx.EventResult { - if state.exampleID == "disabled" { - return gfx.EventResult{} - } - if event.Target != multiSelectInput && (!state.multiSelect.Open || event.Key != gfx.KeyEscape && event.Key != gfx.KeyTab) { - return gfx.EventResult{} - } - return state.multiSelect.Key(event) - }, - scroll: func(state *State, event gfx.ScrollEvent) gfx.EventResult { - return gfx.EventResult{Handled: state.multiSelect.Open, Repaint: state.multiSelect.Open && state.multiSelect.Wheel(event)} - }, paint: (*State).paintMultiSelect, Examples: []Example{ {ID: "default", Title: "多选与创建", Description: "选择多个已有选项,或输入新条目后回车创建;点击空白处收起。", Height: 400, Snippet: `selection := components.MultiSelectState{AllowCreate: true} @@ -74,7 +60,7 @@ picker.View(c, multiselect.Spec{ EmptyLabel: "没有匹配项", CreatePrefix: "创建:", }).FillWidth()`}, {ID: "disabled", Title: "禁用", Description: "保留已选项,禁止编辑、展开或删除。", Height: 280, Snippet: `options.Disabled = true -components.PaintMultiSelect(canvas, theme, bounds, &selection, options)`, PageSnippet: `tags := &multiselect.State{AllowCreate: true, MatchCaseInsensitive: true} +components.PaintMultiSelect(canvas, theme, bounds, &selection, options)`, PageSnippet: `tags := &multiselect.State{AllowCreate: true, MatchCaseInsensitive: true, Open: true} tags.SetOptions([]multiselect.Option{ {Value: "development", Label: "Development"}, {Value: "testing", Label: "Testing"}, @@ -85,7 +71,7 @@ picker := multiselect.New(tags) picker.View(c, multiselect.Spec{ Label: "Tags", Placeholder: "Select or create tags", EmptyLabel: "No matching options", CreatePrefix: "Create: ", -}).FillWidth().Disabled(true)`, PageSnippetZh: `tags := &multiselect.State{AllowCreate: true, MatchCaseInsensitive: true} +}).FillWidth().Disabled(true)`, PageSnippetZh: `tags := &multiselect.State{AllowCreate: true, MatchCaseInsensitive: true, Open: true} tags.SetOptions([]multiselect.Option{ {Value: "开发", Label: "开发"}, {Value: "测试", Label: "测试"}, @@ -101,33 +87,16 @@ picker.View(c, multiselect.Spec{ } func (state *State) paintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var field ui.Box state.drawPage(canvas, theme, size, 420, state.Text("Multi Select · 多选标签", "Multi Select · Tags"), func(c ui.C) { ui.Text(c, state.Text("输入筛选,回车创建,支持中文输入法。", "Type to filter, press Enter to create. Native IME supported.")).Muted().FontSize(theme.Metrics.FontSizeS) - field = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) - }) - components.PaintMultiSelect(canvas, theme, field.Rect(), state.multiSelect, components.MultiSelectOptions{ - InputID: multiSelectInput, TriggerID: multiSelectTrigger, DismissID: multiSelectDismiss, Scope: multiSelectScope, - OptionIDs: multiSelectOptions, RemoveIDs: multiSelectRemove, Label: state.Text("标签", "Tags"), Placeholder: state.Text("选择或输入标签", "Select or create tags"), - EmptyLabel: state.Text("没有匹配项", "No matching options"), CreatePrefix: state.Text("创建:", "Create: "), Disabled: state.exampleID == "disabled", - Viewport: gfx.Rect{Width: size.Width, Height: size.Height}, Layer: 6, - }) - if state.exampleID == "disabled" { - return - } - switch { - case canvas.Clicked(multiSelectInput): - state.multiSelect.Open = true - case canvas.Clicked(multiSelectTrigger): - state.multiSelect.Open = !state.multiSelect.Open - case canvas.Clicked(multiSelectDismiss): - state.multiSelect.Open = false - default: - if i, ok := canvas.ClickedIn(multiSelectOptions); ok { - state.multiSelect.Choose(i) - } - if i, ok := canvas.ClickedIn(multiSelectRemove); ok { - state.multiSelect.Remove(i) + demo := ui.State[multiSelectDemo](c, "multi-select-picker") + if demo.picker == nil { + demo.picker = multiselect.New(state.multiSelect) } - } + demo.picker.View(c, multiselect.Spec{ + Label: state.Text("标签", "Tags"), Placeholder: state.Text("选择或输入标签", "Select or create tags"), + EmptyLabel: state.Text("没有匹配项", "No matching options"), CreatePrefix: state.Text("创建:", "Create: "), + Options: multiSelectOptions, Removes: multiSelectRemove, + }).FillWidth().Disabled(state.exampleID == "disabled") + }) } diff --git a/internal/componentdemo/native_select.go b/internal/componentdemo/native_select.go index 38d495f6..602fc37b 100644 --- a/internal/componentdemo/native_select.go +++ b/internal/componentdemo/native_select.go @@ -57,26 +57,50 @@ var ( nativeSelectTrigger = tree.Sub(nativeSelectUI, tree.Name("trigger")) ) +// nativeSelectDemo is the caller-owned value of the page-first Select. +type nativeSelectDemo struct { + environment string + ready bool +} + func (state *State) paintNativeSelect(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + if state.exampleID == "default" { + environments := []string{"Development", "Staging", "Production"} + state.drawPage(canvas, theme, size, 560, state.Text("Native Select · 系统弹窗", "Native Select · System popup"), func(c ui.C) { + demo := ui.State[nativeSelectDemo](c, "native-select-demo") + if !demo.ready { + demo.ready, demo.environment = true, "Production" + } + ui.Select(c, &demo.environment, environments, nil). + Label("Environment").Hint("Choose environment").FillWidth() + state.values[0] = nativeSelectValueIndex(demo.environment) + ui.Text(c, state.Text("平台适配器负责系统弹窗。", "The platform adapter owns the system popup.")).FontSize(theme.Metrics.FontSizeS).Muted() + }) + return + } + + // The states example stays on the canvas API: the page Select has no + // invalid-trigger state for the "No team" row. var rows [3]ui.Box state.drawPage(canvas, theme, size, 560, state.Text("Native Select · 系统弹窗", "Native Select · System popup"), func(c ui.C) { - if state.exampleID == "default" { - rows[0] = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) - ui.Text(c, state.Text("平台适配器负责系统弹窗。", "The platform adapter owns the system popup.")).FontSize(theme.Metrics.FontSizeS).Muted() - return - } rows[0] = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight - 4) rows[1] = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) rows[2] = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) }) - if state.exampleID == "default" { - components.PaintNativeSelect(canvas, theme, rows[0].Rect(), components.NativeSelectSnapshot{ID: nativeSelectTrigger.At(0), Label: "Environment", Value: "production", Display: "Production", Hint: "Choose environment", Open: state.flags&1 != 0}) - if canvas.Clicked(nativeSelectTrigger.At(0)) { - state.flags ^= 1 - } - return - } components.PaintNativeSelect(canvas, theme, rows[0].Rect(), components.NativeSelectSnapshot{ID: nativeSelectTrigger.At(0), Label: "Region", Placeholder: "Select a region", Size: components.NativeSelectSmall}) components.PaintNativeSelect(canvas, theme, rows[1].Rect(), components.NativeSelectSnapshot{ID: nativeSelectTrigger.At(1), Label: "Team", Value: "none", Display: "No team", Invalid: true}) components.PaintNativeSelect(canvas, theme, rows[2].Rect(), components.NativeSelectSnapshot{ID: nativeSelectTrigger.At(2), Label: "Plan", Value: "enterprise", Display: "Enterprise", Disabled: true}) } + +func nativeSelectValueIndex(value string) int32 { + switch value { + case "Development": + return 1 + case "Staging": + return 2 + case "Production": + return 3 + default: + return 0 + } +} diff --git a/internal/componentdemo/pagination.go b/internal/componentdemo/pagination.go index 14a4685c..2634c002 100644 --- a/internal/componentdemo/pagination.go +++ b/internal/componentdemo/pagination.go @@ -1,7 +1,6 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -95,40 +94,53 @@ func (state *State) initializePagination() { func (state *State) paintPagination(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { page := state.values[0] - var bar ui.Box + compact := size.Width-48 < 430 state.drawPage(canvas, theme, size, 620, "Results", func(c ui.C) { ui.Text(c, paginationPageStatus(page)).FontSize(theme.Metrics.FontSizeS).Muted() - bar = ui.Slot(c).Height(theme.Metrics.ControlHeight) - caption(c, state.Text("窄视口自动减少页码;当前页保持非交互。", "Narrow viewports show fewer pages; the current page stays non-interactive.")) - }) - - bounds := bar.Rect() - pagination := components.BeginPagination(canvas, theme, bounds) - compact := bounds.Width < 430 - pagination.AddPrevious(paginationPrevious, "Previous", page == 1) - if compact { - pagination.AddPage(paginationCurrent, paginationPageLabel(page), true) - } else { - for visiblePage := int32(1); visiblePage <= 3; visiblePage++ { - pagination.AddPage(paginationPage.At(int(visiblePage-1)), paginationPageLabel(visiblePage), page == visiblePage) + var items [7]ui.PaginationItem + count := 0 + items[count] = ui.PaginationItem{ID: paginationPrevious, Label: "Previous", Kind: ui.PaginationPrevious, Disabled: page == 1} + count++ + if compact { + items[count] = ui.PaginationItem{ID: paginationCurrent, Label: paginationPageLabel(page), Kind: ui.PaginationPage, Current: true} + count++ + } else { + for visiblePage := int32(1); visiblePage <= 3; visiblePage++ { + items[count] = ui.PaginationItem{ + ID: paginationPage.At(int(visiblePage - 1)), Label: paginationPageLabel(visiblePage), + Kind: ui.PaginationPage, Current: page == visiblePage, + } + count++ + } + items[count] = ui.PaginationItem{Kind: ui.PaginationEllipsis} + count++ + items[count] = ui.PaginationItem{ID: paginationPage.At(4), Label: "8", Kind: ui.PaginationPage, Current: page == 8} + count++ } - pagination.AddEllipsis() - pagination.AddPage(paginationPage.At(4), "8", page == 8) - } - pagination.AddNext(paginationNext, "Next", page == 8) - - if canvas.Clicked(paginationPrevious) && page > 1 { - state.values[0]-- - } - if canvas.Clicked(paginationNext) && page < 8 { - state.values[0]++ - } - if index, ok := canvas.ClickedIn(paginationPage); ok { - state.values[0] = int32(index) + 1 - if index == 4 { - state.values[0] = 8 + items[count] = ui.PaginationItem{ID: paginationNext, Label: "Next", Kind: ui.PaginationNext, Disabled: page == 8} + count++ + bar := ui.Pagination(c, items[:count]) + caption(c, state.Text("窄视口自动减少页码;当前页保持非交互。", "Narrow viewports show fewer pages; the current page stays non-interactive.")) + if id, ok := bar.Chosen(); ok { + switch id { + case paginationPrevious: + if page > 1 { + state.values[0]-- + } + case paginationNext: + if page < 8 { + state.values[0]++ + } + default: + if index, ok := id.In(paginationPage); ok { + state.values[0] = int32(index) + 1 + if index == 4 { + state.values[0] = 8 + } + } + } } - } + }) } func paginationPageLabel(page int32) string { diff --git a/internal/componentdemo/popover.go b/internal/componentdemo/popover.go index b0139eb0..6f17a8f2 100644 --- a/internal/componentdemo/popover.go +++ b/internal/componentdemo/popover.go @@ -1,7 +1,6 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -99,51 +98,48 @@ var ( ) func (state *State) paintPopover(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - open := state.flags&1 != 0 - var anchor ui.Box state.drawPage(canvas, theme, size, 560, "Popover", func(c ui.C) { - label := "Open details" - if open { - label = "Close details" + demo := ui.State[popoverDemo](c, "popover-demo") + label := state.Text("打开详情", "Open details") + if demo.open { + label = state.Text("关闭详情", "Close details") } - anchor = ui.Button(c, label).Outline().Self(ui.Start).Hit(popoverTrigger, label) - if anchor.Clicked() { - state.flags ^= 1 + trigger := ui.Button(c, label).Outline().Self(ui.Start).Hit(popoverTrigger, label) + if trigger.Clicked() { + demo.open = !demo.open } - if !open { + title, description := "Native surface", "Clamped to the current viewport without timers." + if state.exampleID == "custom-body" { + title, description = "Build status", "The stable host owns this overlay state." + } + ui.PopoverWith(c, trigger, ui.PopoverSpec{ + Title: title, Description: description, + Scope: popoverScope, DismissID: popoverDismiss, + }, &demo.open, func() { + if state.exampleID != "custom-body" { + return + } + status := "Diagnostics disabled" + if demo.enabled { + status = "Diagnostics enabled" + } + if ui.Button(c, status).Secondary().Hit(popoverAction, status).Clicked() { + demo.enabled = !demo.enabled + } + }) + if !demo.open { caption(c, state.Text("点击触发器打开锚定浮层。", "Click the trigger to open the anchored popover.")) } - }) - if !open { - return - } - - contentWidth := min(size.Width-48, float32(288)) - bodyHeight := float32(0) - if state.exampleID == "custom-body" { - bodyHeight = 34 - } - popover := components.BeginPopover(canvas, theme, gfx.Rect{Width: size.Width, Height: size.Height}, anchor.Rect(), components.PopoverOptions{ - Layer: 3, Scope: popoverScope, DismissID: popoverDismiss, - Side: components.PopoverBottom, Align: components.PopoverAlignStart, SideOffset: 8, - AnchorDismiss: true, - ContentSize: gfx.Size{Width: contentWidth}, BodyHeight: bodyHeight, - }) - if state.exampleID == "custom-body" { - layout := popover.Begin("Build status", "The stable host owns this overlay state.") - status := "Diagnostics disabled" - if state.flags&2 != 0 { - status = "Diagnostics enabled" + state.flags &^= 1 + if demo.open { + state.flags |= 1 } - bounds := gfx.Rect{X: layout.Body.X, Y: layout.Body.Y, Width: layout.Body.Width, Height: 34} - if components.BeginButton(canvas, theme, popoverAction, bounds).Secondary(status).Clicked() { - state.flags ^= 2 + state.flags &^= 2 + if demo.enabled { + state.flags |= 2 } - popover.End() - } else { - popover.Paint("Native surface", "Clamped to the current viewport without timers.") - } - if canvas.Clicked(popoverDismiss) { - state.flags &^= 1 - } + }) } + +// popoverDemo is the caller-owned open and body state of the page-first Popover. +type popoverDemo struct{ open, enabled bool } diff --git a/internal/componentdemo/radio_group.go b/internal/componentdemo/radio_group.go index bf64178b..605f604a 100644 --- a/internal/componentdemo/radio_group.go +++ b/internal/componentdemo/radio_group.go @@ -115,25 +115,61 @@ func (state *State) keyRadioGroup(event gfx.KeyEvent) gfx.EventResult { return gfx.EventResult{Focus: next, FocusVisible: true, Handled: true, Repaint: changed} } +// radioPageState is the page RadioGroup's model: the chosen plan, and whether +// the demo has seeded it from State.values. +type radioPageState struct { + plan string + init bool +} + func (state *State) paintRadioGroup(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + if state.exampleID == "states" { + state.paintRadioGroupStates(canvas, theme, size) + return + } horizontal := state.exampleID == "horizontal" && min(size.Width-48, float32(520)) >= 360 - // Three control-height rows plus the group's 12px gaps; a horizontal group - // keeps the single-row default. - height := theme.Metrics.ControlHeight*3 + 24 - if horizontal { - height = theme.Metrics.ControlHeight + plans := [...]string{"Personal", "Team", "Enterprise"} + state.drawPage(canvas, theme, size, 520, "Workspace plan", func(c ui.C) { + page := ui.State[radioPageState](c, "plan") + if !page.init { + page.plan, page.init = plans[state.values[0]], true + } + radios := func() { + for index, plan := range plans { + ui.RadioID(c, radioGroupItem.At(index), &page.plan, plan, plan) + } + } + if horizontal { + ui.Row(c).Gap(12).FocusGroup(ui.FocusHorizontal).Children(radios) + } else { + ui.RadioGroup(c).Children(radios) + } + if index := radioPlanIndex(plans[:], page.plan); index >= 0 { + state.values[0] = int32(index) + } + caption(c, state.Text("方向键移动焦点并更新调用方选中值。", "Arrow keys move focus and update the caller's selection.")) + }) +} + +func radioPlanIndex(plans []string, plan string) int { + for index, option := range plans { + if option == plan { + return index + } } + return -1 +} + +// paintRadioGroupStates keeps the invalid example on the canvas API: the page +// Radio has no per-option invalid state. +func (state *State) paintRadioGroupStates(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { var slot ui.Box state.drawPage(canvas, theme, size, 520, "Workspace plan", func(c ui.C) { - slot = ui.Slot(c).Height(height) + slot = ui.Slot(c).Height(theme.Metrics.ControlHeight*3 + 24) caption(c, state.Text("方向键移动焦点并更新调用方选中值。", "Arrow keys move focus and update the caller's selection.")) }) - options := state.radioGroupOptionsFor() group := components.BeginRadioGroup(canvas, theme, slot.Rect(), options[:], radioGroupItem.At(int(state.values[0]))) - if horizontal { - group = group.Horizontal() - } group.Paint() if index, ok := canvas.ClickedIn(radioGroupItem); ok { state.values[0] = int32(index) diff --git a/internal/componentdemo/reorder_list.go b/internal/componentdemo/reorder_list.go index 39d3eb5b..a766892e 100644 --- a/internal/componentdemo/reorder_list.go +++ b/internal/componentdemo/reorder_list.go @@ -1,56 +1,97 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) var reorderDemoHandles = tree.Sub(tree.Feature("reorder-list"), tree.Name("handle")) +// reorderGripIcon is Lucide's grip-vertical: six dots. +var reorderGripIcon = lucide( + gfx.MoveTo(9, 5), gfx.LineTo(9.01, 5), gfx.MoveTo(9, 12), gfx.LineTo(9.01, 12), gfx.MoveTo(9, 19), gfx.LineTo(9.01, 19), + gfx.MoveTo(15, 5), gfx.LineTo(15.01, 5), gfx.MoveTo(15, 12), gfx.LineTo(15.01, 12), gfx.MoveTo(15, 19), gfx.LineTo(15.01, 19)) + type reorderDemoState struct { - list components.ReorderListState - order [4]int + list ui.ListState + order [4]int + labels [4]string + hitLabels [4]string + rowFn func(ui.ListRow) } -func (state *reorderDemoState) move(move components.ReorderMove) { - if !move.Valid() || move.From >= len(state.order) || move.To >= len(state.order) { +// key names a row by the item it shows, so focus and state follow the item as +// the rows are reordered. +func (demo *reorderDemoState) key(row int) int { return demo.order[row] } + +// label is row i's text, from the item the row shows. +func (demo *reorderDemoState) label(row int) string { return demo.labels[demo.order[row]] } + +// move puts rows, ascending, before row to, as the List's Reorder reports them. +func (demo *reorderDemoState) move(rows []int, to int) { + if len(rows) == 0 { return } - value := state.order[move.From] - if move.From < move.To { - copy(state.order[move.From:move.To], state.order[move.From+1:move.To+1]) - } else { - copy(state.order[move.To+1:move.From+1], state.order[move.To:move.From]) + var moving, kept [4]int + nm, nk := 0, 0 + for index, item := range demo.order { + moved := false + for _, row := range rows { + if row == index { + moved = true + break + } + } + if moved { + moving[nm], nm = item, nm+1 + } else { + kept[nk], nk = item, nk+1 + } } - state.order[move.To] = value + to = min(max(to, 0), nk) + var next [4]int + copy(next[:to], kept[:to]) + copy(next[to:], moving[:nm]) + copy(next[to+nm:], kept[to:nk]) + demo.order = next +} + +// row declares one item: its grip starts the drag and its name fills the row. +func (demo *reorderDemoState) row(row ui.ListRow) { + item := demo.order[row.Index] + label := demo.labels[item] + row.Element.Height(48).PadX(12).Gap(12).Items(ui.Center).Children(func() { + ui.Icon(row.C, reorderGripIcon).Size(16, 16). + Hit(reorderDemoHandles.At(item), demo.hitLabels[item]) + ui.Text(row.C, label).Grow(1) + }) } var reorderListComponent = Component{ ID: "reorder-list", Title: "Reorder List", Category: "Layout", Summary: "拖动手柄或键盘排序,列表数据由调用方持有。", - initialize: func(state *State) { state.reorder = &reorderDemoState{order: [4]int{0, 1, 2, 3}} }, + initialize: func(state *State) { + demo := &reorderDemoState{order: [4]int{0, 1, 2, 3}} + demo.labels = [4]string{ + state.Text("主机", "Hosts"), + state.Text("文件传输", "File transfer"), + state.Text("AI 助手", "AI assistant"), + state.Text("设置", "Settings"), + } + for index, label := range demo.labels { + demo.hitLabels[index] = state.Text("重新排序 ", "Reorder ") + label + } + demo.list.Key = demo.key + demo.list.Label = demo.label + demo.list.Reorder = demo.move + demo.list.Handle = reorderDemoHandles + demo.rowFn = demo.row + state.reorder = demo + }, paint: func(state *State, canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var slot ui.Box state.drawPage(canvas, theme, size, 440, state.Text("Reorder List · 入口顺序", "Reorder List · Shortcut order"), func(c ui.C) { - slot = ui.Slot(c).FillWidth().Height(188) + ui.List(c, &state.reorder.list, len(state.reorder.order), state.reorder.rowFn). + Label(state.Text("快捷入口", "Shortcuts")).Height(192) }) - list := components.BeginReorderList(canvas, theme, slot.Rect(), &state.reorder.list) - labels := [4]string{state.Text("主机", "Hosts"), state.Text("文件传输", "File transfer"), state.Text("AI 助手", "AI assistant"), state.Text("设置", "Settings")} - for _, index := range state.reorder.order { - row := list.Row(reorderDemoHandles.At(index), labels[index], false) - canvas.Label(labels[index], row.Content, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.Foreground}) - } - list.End() - }, - pointer: func(state *State, event gfx.PointerEvent) gfx.EventResult { - move, result := state.reorder.list.Pointer(event) - state.reorder.move(move) - return result - }, - key: func(state *State, event gfx.KeyEvent) gfx.EventResult { - move, result := state.reorder.list.Key(event) - state.reorder.move(move) - return result }, Examples: []Example{{ID: "default", Title: "入口排序", Description: "只有左侧手柄启动拖动;方向键也可移动条目,Escape 取消尚未放下的拖动。", Height: 280, Snippet: `list := components.BeginReorderList(canvas, theme, bounds, &dragState) for _, item := range items { diff --git a/internal/componentdemo/resizable.go b/internal/componentdemo/resizable.go index 73a40656..1b12545a 100644 --- a/internal/componentdemo/resizable.go +++ b/internal/componentdemo/resizable.go @@ -1,14 +1,13 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) var resizableComponent = Component{ ID: "resizable", Title: "Resizable", Category: "Layout", Summary: "返回精确面板几何的横向与纵向分隔器。", - paint: (*State).paintResizable, pointer: (*State).pointerResizable, initialize: (*State).initializeResizable, + paint: (*State).paintResizable, Examples: []Example{ {ID: "horizontal", Title: "横向分栏", Description: "捕获主指针拖动分隔器,激活仍可循环调用方持有的分栏比例。", Snippet: `bounds := stage.Rect() handle := tree.ID(page, "split") @@ -93,105 +92,59 @@ var ( resizableHandle = tree.ID(resizableUI, "handle") ) -func (state *State) initializeResizable() { - state.values[0] = 50 - state.bag() -} +var resizableDemos = map[*State]*resizableDemo{} -func (state *State) pointerResizable(event gfx.PointerEvent) gfx.EventResult { - if event.Target != resizableHandle || state.exampleID == "disabled" { - return gfx.EventResult{} - } - if event.Kind != gfx.PointerDown && !(event.Kind == gfx.PointerMove && event.Captured) { - return gfx.EventResult{Handled: event.Kind == gfx.PointerUp} - } - if event.Kind == gfx.PointerDown && event.Button != gfx.PointerButtonPrimary { - return gfx.EventResult{} - } - resizable := state.previewResizable() - position := event.X - if state.exampleID == "vertical" { - position = event.Y - } - value := int32(resizable.FractionAt(position)*100 + 0.5) - changed := state.values[0] != value - state.values[0] = value - return gfx.EventResult{Focus: resizableHandle, Handled: true, Repaint: changed} +type resizableDemo struct { + state ui.SplitterState } -// previewResizable is the splitter as the last paint placed it, for the pointer to -// turn a coordinate into a fraction. -func (state *State) previewResizable() components.Resizable { - resizable := components.BeginResizable(nil, gfx.Theme{}, resizableHandle, state.bag().placed, resizableFraction(state.values[0])).Limits(0.2, 0.8) +func resizableDemoFor(state *State) *resizableDemo { + if demo := resizableDemos[state]; demo != nil { + return demo + } + demo := &resizableDemo{} if state.exampleID == "vertical" { - resizable = resizable.Vertical() + demo.state.Pos = 100 + } else { + demo.state.Pos = 260 } - return resizable + resizableDemos[state] = demo + return demo } func (state *State) paintResizable(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var stage ui.Box + demo := resizableDemoFor(state) + vertical := state.exampleID == "vertical" + disabled := state.exampleID == "disabled" + label := state.Text("调整编辑器面板", "Resize editor panels") state.drawPage(canvas, theme, size, 600, "Editor layout", func(c ui.C) { - stage = ui.Slot(c).Height(200) - caption(c, state.Text("拖动抓手精确调整;激活循环 30% / 50% / 70%。", "Drag the handle to resize precisely; clicking cycles 30% / 50% / 70%.")) - }) - - bounds := stage.Rect() - if bag := state.slider; bag != nil { - bag.placed = bounds - } - fraction := resizableFraction(state.values[0]) - resizable := components.BeginResizable(canvas, theme, resizableHandle, bounds, fraction). - Limits(0.2, 0.8). - HandleSize(12). - WithHandle(). - ValueText(resizableValueText(state.values[0])) - if state.exampleID == "vertical" { - resizable = resizable.Vertical() - } - if state.exampleID == "disabled" { - resizable = resizable.Disabled() - } - layout := resizable.Paint("Resize editor panels") - - canvas.Rounded(layout.First.Inset(gfx.All(8)), 6, theme.Muted) - canvas.Rounded(layout.Second.Inset(gfx.All(8)), 6, theme.CardElevated) - canvas.LabelCenter("Navigator", layout.First.Inset(gfx.All(16)), gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.Foreground}) - canvas.LabelCenter("Preview", layout.Second.Inset(gfx.All(16)), gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.Foreground}) - - if canvas.Clicked(resizableHandle) { - switch state.values[0] { - case 30: - state.values[0] = 50 - case 50: - state.values[0] = 70 - default: - state.values[0] = 30 + splitter := func(minsFirst, minsSecond float32) ui.Box { + box := ui.Splitter(c, &demo.state).Mins(minsFirst, minsSecond).Hit(resizableHandle, label) + if disabled { + box = box.Disabled(true) + } + return box } - } -} - -func resizableFraction(value int32) float32 { - return float32(value) / 100 -} - -func resizableValueText(value int32) string { - switch value { - case 50: - return "50 percent" - case 30: - return "30 percent" - case 70: - return "70 percent" - case 20: - return "20 percent" - case 40: - return "40 percent" - case 60: - return "60 percent" - case 80: - return "80 percent" - default: - return "custom split" - } + if vertical { + ui.Column(c).Height(200).Children(func() { + ui.Row(c).Height(demo.state.Pos).Background(theme.Muted).Children(func() { + ui.Text(c, "Navigator") + }) + splitter(40, 40) + ui.Row(c).Grow(1).Basis(0).Background(theme.CardElevated).Children(func() { + ui.Text(c, "Preview") + }) + }) + return + } + ui.Row(c).Height(200).Children(func() { + ui.Column(c).Width(demo.state.Pos).Background(theme.Muted).Children(func() { + ui.Text(c, "Navigator") + }) + splitter(120, 200) + ui.Column(c).Grow(1).Basis(0).Background(theme.CardElevated).Children(func() { + ui.Text(c, "Preview") + }) + }) + }) } diff --git a/internal/componentdemo/scroll_area.go b/internal/componentdemo/scroll_area.go index b4ac87a0..13110c23 100644 --- a/internal/componentdemo/scroll_area.go +++ b/internal/componentdemo/scroll_area.go @@ -1,14 +1,13 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) var scrollAreaComponent = Component{ ID: "scroll-area", Title: "Scroll Area", Category: "Layout", Summary: "调用方提供偏移量的裁剪内容与原生滚动条几何。", - paint: (*State).paintScrollArea, scroll: (*State).scrollScrollArea, + paint: (*State).paintScrollArea, Examples: []Example{ {ID: "vertical", Title: "纵向内容", Description: "目标区域滚动更新调用方偏移,点击滚动条仍可循环。", Snippet: `contentSize := gfx.Size{Width: viewport.Width, Height: 420} area := components.BeginScrollArea(canvas, theme, viewport, contentSize). @@ -17,7 +16,7 @@ area := components.BeginScrollArea(canvas, theme, viewport, contentSize). geometry := area.BeginContent() canvas.Label("Window created", geometry.Content, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.Foreground}) -area.EndContent()`, PageSnippet: `ui.Scroll(c).Height(220).Scrollbars().Children(func() { +area.EndContent()`, PageSnippet: `ui.Scroll(c).Height(220).Scrollbars().Label("Scrollable activity").Children(func() { for _, label := range [...]string{ "Window created", "Scene retained", "Layout cache hit", "Text shaped", "Input routed", "Frame submitted", "GPU idle", "Resources released", @@ -26,7 +25,7 @@ area.EndContent()`, PageSnippet: `ui.Scroll(c).Height(220).Scrollbars().Children ui.Text(c, label) }) } -})`, PageSnippetZh: `ui.Scroll(c).Height(220).Scrollbars().Children(func() { +})`, PageSnippetZh: `ui.Scroll(c).Height(220).Scrollbars().Label("Scrollable activity").Children(func() { for _, label := range [...]string{ "Window created", "Scene retained", "Layout cache hit", "Text shaped", "Input routed", "Frame submitted", "GPU idle", "Resources released", @@ -44,7 +43,7 @@ area := components.BeginScrollArea(canvas, theme, viewport, contentSize). geometry := area.BeginContent() canvas.Label("Window created", geometry.Content, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.Foreground}) -area.EndContent()`, PageSnippet: `ui.Scroll(c).Height(220).Sideways().Scrollbars().Children(func() { +area.EndContent()`, PageSnippet: `ui.Scroll(c).Height(220).Sideways().Scrollbars().Label("Scrollable activity").Children(func() { for _, label := range [...]string{ "Window created", "Scene retained", "Layout cache hit", "Text shaped", "Input routed", "Frame submitted", "GPU idle", "Resources released", @@ -53,7 +52,7 @@ area.EndContent()`, PageSnippet: `ui.Scroll(c).Height(220).Sideways().Scrollbars ui.Text(c, label) }) } -})`, PageSnippetZh: `ui.Scroll(c).Height(220).Sideways().Scrollbars().Children(func() { +})`, PageSnippetZh: `ui.Scroll(c).Height(220).Sideways().Scrollbars().Label("Scrollable activity").Children(func() { for _, label := range [...]string{ "Window created", "Scene retained", "Layout cache hit", "Text shaped", "Input routed", "Frame submitted", "GPU idle", "Resources released", @@ -73,130 +72,54 @@ var ( scrollAreaViewport = tree.ID(scrollAreaUI, "viewport") ) -func (state *State) scrollScrollArea(event gfx.ScrollEvent) gfx.EventResult { - if event.Target != scrollAreaViewport && event.Target != scrollAreaVertical && event.Target != scrollAreaHorizontal { - return gfx.EventResult{} - } - previousX, previousY := state.values[1], state.values[0] - state.values[0] = clampInt32(state.values[0]+int32(event.DeltaY), 0, 180) - if state.exampleID == "both-axes" { - state.values[1] = clampInt32(state.values[1]+int32(event.DeltaX), 0, 180) - } - return gfx.EventResult{Handled: true, Repaint: previousX != state.values[1] || previousY != state.values[0]} +// scrollAreaDemo remembers the page scroll area's state and its last bounds for +// the keyboard/wheel tests; the page owns the offsets themselves. +type scrollAreaDemo struct { + scroller *ui.ScrollState + bounds gfx.Rect } -func clampInt32(value, minimum, maximum int32) int32 { - if value < minimum { - return minimum - } - if value > maximum { - return maximum +var scrollAreaDemos = map[*State]*scrollAreaDemo{} + +func scrollAreaDemoFor(state *State) *scrollAreaDemo { + if demo := scrollAreaDemos[state]; demo != nil { + return demo } - return value + demo := &scrollAreaDemo{} + scrollAreaDemos[state] = demo + return demo } func (state *State) paintScrollArea(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var stage ui.Box - state.drawPage(canvas, theme, size, 560, "Recent activity", func(c ui.C) { - stage = ui.Slot(c).Height(220) - caption(c, state.Text("偏移量由应用持有。", "The offset is caller-owned.")) - }) - - viewport := stage.Rect() - contentWidth := viewport.Width - if state.exampleID == "both-axes" { - contentWidth += 180 - } - contentHeight := float32(420) - area := components.BeginScrollArea(canvas, theme, viewport, gfx.Size{Width: contentWidth, Height: contentHeight}). - Offset(scrollAreaHorizontalOffset(state.values[1]), scrollAreaVerticalOffset(state.values[0])). - VerticalScrollbar(scrollAreaVertical, "Scroll activity", scrollAreaVerticalValue(state.values[0])) - if state.exampleID == "both-axes" { - area = area.HorizontalScrollbar(scrollAreaHorizontal, "Scroll columns", scrollAreaHorizontalValue(state.values[1])) + both := state.exampleID == "both-axes" + labels := [8]string{ + "Window created", "Scene retained", "Layout cache hit", "Text shaped", + "Input routed", "Frame submitted", "GPU idle", "Resources released", } - geometry := area.BeginContent() - canvas.PushFocusScope(scrollAreaViewport) - canvas.HitWithOptions(scrollAreaViewport, geometry.Viewport, "Scrollable activity", gfx.HitOptions{SkipFocus: true}) - canvas.PopFocusScope() - - canvas.RoundedBorder(geometry.Bounds, 6, 1, theme.Border, theme.Card) - for index := 0; index < 8; index++ { - y := geometry.Content.Y + float32(index)*50 + 10 - if y+38 <= geometry.Viewport.Y || y >= geometry.Viewport.Y+geometry.Viewport.Height { - continue + demo := scrollAreaDemoFor(state) + var area ui.Box + state.drawPage(canvas, theme, size, 560, "Recent activity", func(c ui.C) { + scroll := ui.Scroll(c).Height(220).Scrollbars().Hit(scrollAreaViewport, "Scrollable activity").ScrollbarIDs(scrollAreaVertical, scrollAreaHorizontal) + if both { + scroll = scroll.Sideways() } - row := gfx.Rect{X: geometry.Viewport.X + 12, Y: max(y, geometry.Viewport.Y), Width: max(geometry.Viewport.Width-36, 0), Height: min(y+38, geometry.Viewport.Y+geometry.Viewport.Height) - max(y, geometry.Viewport.Y)} - canvas.Rounded(row, 5, theme.CardElevated) - canvas.Label(scrollAreaRowLabel(index), gfx.Rect{X: row.X + 12, Y: row.Y, Width: max(row.Width-24, 0), Height: row.Height}, gfx.TextStyle{ - Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.Foreground, + area = scroll + demo.scroller = scroll.ScrollState() + scroll.Children(func() { + for _, label := range labels { + row := ui.Row(c).Height(50).PadX(12).Items(ui.Center) + if both { + row = row.Width(c.Bounds().Width + 180) + } + row.Children(func() { + ui.Text(c, label) + }) + } }) - } - area.EndContent() - - // A click on a scrollbar steps its offset. - if canvas.Clicked(scrollAreaVertical) { - state.values[0] += 72 - if state.values[0] > 216 { - state.values[0] = 0 - } - } - if canvas.Clicked(scrollAreaHorizontal) { - state.values[1] += 72 - if state.values[1] > 144 { - state.values[1] = 0 - } - } -} - -func scrollAreaVerticalOffset(value int32) float32 { - return float32(value) -} - -func scrollAreaHorizontalOffset(value int32) float32 { - return float32(value) -} - -func scrollAreaVerticalValue(value int32) string { - switch value { - case 72: - return "72 pixels" - case 144: - return "144 pixels" - case 216: - return "216 pixels" - default: - return "Scrolled" - } -} - -func scrollAreaHorizontalValue(value int32) string { - switch value { - case 72: - return "72 pixels" - case 144: - return "144 pixels" - default: - return "Scrolled" - } -} - -func scrollAreaRowLabel(index int) string { - switch index { - case 0: - return "Window created" - case 1: - return "Scene retained" - case 2: - return "Layout cache hit" - case 3: - return "Text shaped" - case 4: - return "Input routed" - case 5: - return "Frame submitted" - case 6: - return "GPU idle" - default: - return "Resources released" + }) + demo.bounds = area.Rect() + if demo.scroller != nil { + state.values[0] = int32(demo.scroller.Offset) + state.values[1] = int32(demo.scroller.OffsetX) } } diff --git a/internal/componentdemo/segmented_control.go b/internal/componentdemo/segmented_control.go index 74968037..6cce35d8 100644 --- a/internal/componentdemo/segmented_control.go +++ b/internal/componentdemo/segmented_control.go @@ -91,25 +91,46 @@ func (state *State) keySegmentedControl(event gfx.KeyEvent) gfx.EventResult { return gfx.EventResult{Focus: next, FocusVisible: true, Handled: true, Repaint: changed} } +// segmentedPageState is the page Choice's model: the chosen view, and whether +// the demo has seeded it from State.values. +type segmentedPageState struct { + view string + init bool +} + func (state *State) paintSegmentedControl(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - options := segmentedControlOptions[:] if state.exampleID == "states" { - options = segmentedControlStateOptions[:] + state.paintSegmentedControlStates(canvas, theme, size) + return } + views := [...]string{"List", "Board", "Timeline"} + state.drawPage(canvas, theme, size, 520, "View", func(c ui.C) { + page := ui.State[segmentedPageState](c, "view") + if !page.init { + page.view, page.init = views[state.values[0]], true + } + ui.Choice(c, &page.view, views[:], nil) + if index := radioPlanIndex(views[:], page.view); index >= 0 { + state.values[0] = int32(index) + } + caption(c, state.Text("方向键通过 typed helper 更新焦点与选择。", "Arrow keys update focus and selection through the typed helper.")) + }) +} + +// paintSegmentedControlStates keeps the per-option disabled example on the +// canvas API: the page Choice has no per-option disabled state. +func (state *State) paintSegmentedControlStates(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + options := segmentedControlStateOptions[:] var live, disabled ui.Box state.drawPage(canvas, theme, size, 520, "View", func(c ui.C) { live = ui.Slot(c).FillWidth().MaxWidth(420).Height(theme.Metrics.ControlHeight) - if state.exampleID == "states" { - // The component paints a whole-control disabled specimen in a slot: - // it declares its own (inert) hits beside the live control's. - disabled = ui.Slot(c).FillWidth().MaxWidth(420).Height(theme.Metrics.ControlHeight) - } + // The component paints a whole-control disabled specimen in a slot: + // it declares its own (inert) hits beside the live control's. + disabled = ui.Slot(c).FillWidth().MaxWidth(420).Height(theme.Metrics.ControlHeight) caption(c, state.Text("方向键通过 typed helper 更新焦点与选择。", "Arrow keys update focus and selection through the typed helper.")) }) if id, ok := components.BeginSegmentedControl(canvas, theme, live.Rect(), options, segmentedControlView.At(int(state.values[0]))).Paint().Clicked(); ok { state.values[0] = int32(listIndex(id, segmentedControlView)) } - if state.exampleID == "states" { - components.BeginSegmentedControl(canvas, theme, disabled.Rect(), segmentedControlLockedOptions[:], segmentedControlLocked.At(1)).Disabled().Paint() - } + components.BeginSegmentedControl(canvas, theme, disabled.Rect(), segmentedControlLockedOptions[:], segmentedControlLocked.At(1)).Disabled().Paint() } diff --git a/internal/componentdemo/select.go b/internal/componentdemo/select.go index 9f633b62..a17429f3 100644 --- a/internal/componentdemo/select.go +++ b/internal/componentdemo/select.go @@ -65,14 +65,30 @@ var ( selectItem = tree.Sub(selectUI, tree.Name("item")) ) +// selectDemo is the caller-owned value of the page-first Select. +type selectDemo struct{ value string } + func (state *State) paintSelect(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + if state.exampleID != "states" { + backends := []string{"Metal", "Direct3D", "Vulkan"} + state.drawPage(canvas, theme, size, 520, "Renderer", func(c ui.C) { + demo := ui.State[selectDemo](c, "select-demo") + ui.Select(c, &demo.value, backends, nil). + Label("Renderer").Placeholder("Select a backend"). + FillWidth().MaxWidth(280) + state.values[0] = selectValueIndex(demo.value) + caption(c, state.Text("选中值与开合由应用持有。", "The application owns the selection and open state.")) + }) + return + } + + // The states example stays on the canvas API: the page Select has no + // invalid-trigger state to paint beside the disabled one. var trigger, unavailable ui.Box open := state.flags&1 != 0 state.drawPage(canvas, theme, size, 520, "Renderer", func(c ui.C) { trigger = ui.Slot(c).FillWidth().MaxWidth(280).Height(theme.Metrics.ControlHeight) - if state.exampleID == "states" { - unavailable = ui.Slot(c).FillWidth().MaxWidth(280).Height(theme.Metrics.ControlHeight) - } + unavailable = ui.Slot(c).FillWidth().MaxWidth(280).Height(theme.Metrics.ControlHeight) caption(c, state.Text("选中值与开合由应用持有。", "The application owns the selection and open state.")) }) @@ -86,7 +102,7 @@ func (state *State) paintSelect(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Si } selectControl := components.BeginSelect(canvas, theme, bounds, components.SelectOptions{ TriggerID: selectTrigger, Label: "Renderer", Value: selectValueLabel(state.values[0]), Placeholder: "Select a backend", - Open: open, Invalid: state.exampleID == "states" && state.values[0] == 0, + Open: open, Invalid: state.values[0] == 0, Content: gfx.Rect{X: bounds.X, Y: contentY, Width: bounds.Width, Height: contentHeight}, Layer: 4, Scope: selectScope, DismissID: selectDismiss, }) @@ -96,7 +112,7 @@ func (state *State) paintSelect(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Si selectControl.AddItem(components.SelectItem{ID: selectItem.At(2), Label: "Vulkan", Value: "vulkan", Selected: state.values[0] == 3}) selectControl.End() - if state.exampleID == "states" && !open { + if !open { components.BeginSelect(canvas, theme, unavailable.Rect(), components.SelectOptions{ TriggerID: selectDisabled, Label: "Unavailable", Placeholder: "Backend unavailable", Disabled: true, Size: components.SelectSizeSmall, }).TriggerBounds() @@ -113,6 +129,19 @@ func (state *State) paintSelect(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Si } } +func selectValueIndex(value string) int32 { + switch value { + case "Metal": + return 1 + case "Direct3D": + return 2 + case "Vulkan": + return 3 + default: + return 0 + } +} + func selectValueLabel(value int32) string { switch value { case 1: diff --git a/internal/componentdemo/sheet.go b/internal/componentdemo/sheet.go index e3a9a92a..c7b16da0 100644 --- a/internal/componentdemo/sheet.go +++ b/internal/componentdemo/sheet.go @@ -1,7 +1,6 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -18,7 +17,13 @@ layout := sheet.Begin("Project settings", "Changes remain caller-owned until Sav canvas.Label("Rendering backend", layout.Body, labelStyle) sheet.Actions(layout, components.ButtonAction{ID: saveID, Label: "Save"}) sheet.End() -if canvas.Clicked(saveID) || canvas.Clicked(closeID) || canvas.Clicked(dismissID) { open = false }`, PageSnippet: `open := true +if canvas.Clicked(saveID) || canvas.Clicked(closeID) || canvas.Clicked(dismissID) { open = false }`, PageSnippet: `m.backend = "Native GPU" +open := false +if !open { + if ui.Button(c, "Open settings").Clicked() { + open = true + } +} ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ Side: ui.DrawerRight, Size: 360, Description: "Changes remain caller-owned until Save.", @@ -28,14 +33,20 @@ ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ if ui.Button(c, "Save changes").Clicked() { open = false } -})`, PageSnippetZh: `open := true -ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ +})`, PageSnippetZh: `m.backend = "原生 GPU" +open := false +if !open { + if ui.Button(c, "打开设置").Clicked() { + open = true + } +} +ui.Drawer(c, &open, "项目设置", ui.DrawerSpec{ Side: ui.DrawerRight, Size: 360, - Description: "Changes remain caller-owned until Save.", + Description: "保存前更改由调用方持有。", }, func() { - ui.TextField(c, &m.backend, "Rendering backend", "") + ui.TextField(c, &m.backend, "渲染后端", "") }, func() { - if ui.Button(c, "Save changes").Clicked() { + if ui.Button(c, "保存更改").Clicked() { open = false } })`}, @@ -47,7 +58,13 @@ layout := sheet.Begin("Project settings", "Same API, bottom edge.") canvas.Label("Native GPU", layout.Body, labelStyle) sheet.Actions(layout, components.ButtonAction{ID: saveID, Label: "Save changes"}) sheet.End() -if canvas.Clicked(saveID) || canvas.Clicked(closeID) || canvas.Clicked(dismissID) { open = false }`, PageSnippet: `open := true +if canvas.Clicked(saveID) || canvas.Clicked(closeID) || canvas.Clicked(dismissID) { open = false }`, PageSnippet: `m.backend = "Native GPU" +open := false +if !open { + if ui.Button(c, "Open settings").Clicked() { + open = true + } +} ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ Side: ui.DrawerBottom, Size: 230, Description: "Same API, bottom edge.", @@ -57,14 +74,20 @@ ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ if ui.Button(c, "Save changes").Clicked() { open = false } -})`, PageSnippetZh: `open := true -ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ +})`, PageSnippetZh: `m.backend = "原生 GPU" +open := false +if !open { + if ui.Button(c, "打开设置").Clicked() { + open = true + } +} +ui.Drawer(c, &open, "项目设置", ui.DrawerSpec{ Side: ui.DrawerBottom, Size: 230, - Description: "Same API, bottom edge.", + Description: "同一 API,底部边缘。", }, func() { - ui.TextField(c, &m.backend, "Rendering backend", "") + ui.TextField(c, &m.backend, "渲染后端", "") }, func() { - if ui.Button(c, "Save changes").Clicked() { + if ui.Button(c, "保存更改").Clicked() { open = false } })`}, @@ -74,41 +97,47 @@ ui.Drawer(c, &open, "Project settings", ui.DrawerSpec{ var ( sheetUI = tree.Feature("sheet") sheetTrigger = tree.ID(sheetUI, "trigger") - sheetDismiss = tree.ID(sheetUI, "dismiss") - sheetClose = tree.ID(sheetUI, "close") sheetSave = tree.ID(sheetUI, "save") - sheetScope = tree.ID(sheetUI, "content") ) func (state *State) paintSheet(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { state.drawPage(canvas, theme, size, 560, "Project settings", func(c ui.C) { - ui.Text(c, "Edit without leaving this view.").FontSize(theme.Metrics.FontSizeS).Muted() - if ui.Button(c, "Open settings").Self(ui.Start).Hit(sheetTrigger, "Open settings").Clicked() { + ui.Text(c, state.Text("留在当前视图编辑。", "Edit without leaving this view.")).FontSize(theme.Metrics.FontSizeS).Muted() + open := ui.State[bool](c, "open") + seeded := ui.State[bool](c, "seeded") + backend := ui.State[string](c, "backend") + if !*seeded { + *open = state.flags&1 != 0 + *backend = state.Text("原生 GPU", "Native GPU") + *seeded = true + } + if !*open { + label := state.Text("打开设置", "Open settings") + if ui.Button(c, label).Self(ui.Start).Hit(sheetTrigger, label).Clicked() { + *open = true + } + } + spec := ui.DrawerSpec{ + Side: ui.DrawerRight, Size: 360, + Description: state.Text("保存前更改由调用方持有。", "Changes remain caller-owned until Save."), + } + title := state.Text("项目设置", "Project settings") + if state.exampleID == "bottom" { + spec.Side, spec.Size = ui.DrawerBottom, 230 + spec.Description = state.Text("同一 API,底部边缘。", "Same API, bottom edge.") + } + ui.Drawer(c, open, title, spec, func() { + ui.TextField(c, backend, state.Text("渲染后端", "Rendering backend"), "") + }, func() { + save := state.Text("保存更改", "Save changes") + if ui.Button(c, save).Hit(sheetSave, save).Clicked() { + *open = false + } + }) + if *open { state.flags |= 1 + } else { + state.flags &^= 1 } }) - - if state.flags&1 == 0 { - return - } - side := components.SheetRight - extent := min(size.Width*0.78, float32(360)) - if state.exampleID == "bottom" { - side = components.SheetBottom - extent = min(size.Height*0.62, float32(230)) - } - sheet := components.BeginSheet(canvas, theme, gfx.Rect{Width: size.Width, Height: size.Height}, components.SheetOptions{ - Layer: 5, Scope: sheetScope, DismissID: sheetDismiss, CloseID: sheetClose, Side: side, ContentExtent: extent, - }) - layout := sheet.Begin("Project settings", "Changes remain caller-owned until Save.") - canvas.Label("Rendering backend", gfx.Rect{X: layout.Body.X, Y: layout.Body.Y, Width: layout.Body.Width, Height: 22}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.Foreground}) - field := gfx.Rect{X: layout.Body.X, Y: layout.Body.Y + 30, Width: layout.Body.Width, Height: theme.Metrics.ControlHeight} - canvas.RoundedBorder(field, theme.Metrics.RadiusControl, 1, theme.Border, theme.Input) - canvas.Label("Native GPU", gfx.Rect{X: field.X + 12, Y: field.Y, Width: max(field.Width-24, 0), Height: field.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: theme.Foreground}) - sheet.Actions(layout, components.ButtonAction{ID: sheetSave, Label: "Save changes"}) - sheet.End() - - if canvas.Clicked(sheetDismiss) || canvas.Clicked(sheetClose) || canvas.Clicked(sheetSave) { - state.flags &^= 1 - } } diff --git a/internal/componentdemo/single_select.go b/internal/componentdemo/single_select.go index a71101a0..75645352 100644 --- a/internal/componentdemo/single_select.go +++ b/internal/componentdemo/single_select.go @@ -1,43 +1,12 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/text" "github.com/vivaui/viva/ui" ) -var ( - singleSelectUI = tree.Feature("single-select") - singleSelectInput = tree.ID(singleSelectUI, "input") - singleSelectTrigger = tree.ID(singleSelectUI, "trigger") - singleSelectClear = tree.ID(singleSelectUI, "clear") - singleSelectDismiss = tree.ID(singleSelectUI, "dismiss") - singleSelectScope = tree.ID(singleSelectUI, "scope") - singleSelectScroll = tree.ID(singleSelectUI, "scroll") - singleSelectOptions = tree.Sub(singleSelectUI, tree.Name("option")) -) - var singleSelectComponent = Component{ - ID: "single-select", Title: "Single Select", Category: "Forms", Summary: "可搜索、单选并创建条目,选择后收起列表。", - initialize: func(state *State) { - state.singleSelect = &components.SingleSelectState{AllowCreate: true, Open: true} - state.singleSelect.SetOptions([]components.SingleSelectOption{{Value: state.Text("开发环境", "Development")}, {Value: state.Text("测试环境", "Testing")}, {Value: state.Text("生产环境", "Production")}}) - state.singleSelect.SetValue(state.Text("开发环境", "Development")) - }, - editable: func(example string) (editableField, bool) { - return editableField{ID: singleSelectInput}, example != "disabled" - }, - editor: func(state *State) *text.Editor { return &state.singleSelect.Query }, - key: func(state *State, event gfx.KeyEvent) gfx.EventResult { - if state.exampleID == "disabled" || event.Target != singleSelectInput && (!state.singleSelect.Open || event.Key != gfx.KeyEscape && event.Key != gfx.KeyTab) { - return gfx.EventResult{} - } - return state.singleSelect.Key(event) - }, - scroll: func(state *State, event gfx.ScrollEvent) gfx.EventResult { - return gfx.EventResult{Handled: state.singleSelect.Open, Repaint: state.singleSelect.Open && state.singleSelect.Wheel(event)} - }, + ID: "single-select", Title: "Single Select", Category: "Forms", Summary: "应用持有选中值的页面 Select 单选。", paint: (*State).paintSingleSelect, Examples: []Example{ {ID: "default", Title: "单选与创建", Description: "选择已有条目或输入新名称后回车创建;选中后收起,支持清空。", Height: 400, Snippet: `selection := components.SingleSelectState{AllowCreate: true} @@ -61,32 +30,25 @@ ui.Select(c, &group, []string{"开发环境", "测试环境", "生产环境"}, n }, } +// singleSelectDemo is the caller-owned value of the page-first Select. +type singleSelectDemo struct { + group string + ready bool +} + func (state *State) paintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var field ui.Box + groups := []string{state.Text("开发环境", "Development"), state.Text("测试环境", "Testing"), state.Text("生产环境", "Production")} state.drawPage(canvas, theme, size, 420, state.Text("Single Select · 单选分组", "Single Select · Groups"), func(c ui.C) { - ui.Text(c, state.Text("输入筛选,回车创建;每次保留一个选项。", "Type to filter or create; keep one selected value.")).Muted().FontSize(theme.Metrics.FontSizeS) - field = ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) - }) - components.PaintSingleSelect(canvas, theme, field.Rect(), state.singleSelect, components.SingleSelectOptions{ - InputID: singleSelectInput, TriggerID: singleSelectTrigger, ClearID: singleSelectClear, DismissID: singleSelectDismiss, Scope: singleSelectScope, ScrollID: singleSelectScroll, OptionIDs: singleSelectOptions, - Label: state.Text("分组", "Group"), Placeholder: state.Text("选择或创建分组", "Select or create a group"), EmptyLabel: state.Text("输入即可创建分组", "Type to create a group"), CreatePrefix: state.Text("创建分组:", "Create group: "), ClearLabel: state.Text("清空分组", "Clear group"), - Disabled: state.exampleID == "disabled", Viewport: gfx.Rect{Width: size.Width, Height: size.Height}, Layer: 6, - }) - if state.exampleID == "disabled" { - return - } - switch { - case canvas.Clicked(singleSelectInput): - state.singleSelect.Open = true - case canvas.Clicked(singleSelectTrigger): - state.singleSelect.Open = !state.singleSelect.Open - case canvas.Clicked(singleSelectClear): - state.singleSelect.Clear() - case canvas.Clicked(singleSelectDismiss): - state.singleSelect.Dismiss() - default: - if i, ok := canvas.ClickedIn(singleSelectOptions); ok { - state.singleSelect.Choose(i) + ui.Text(c, state.Text("选择一个分组;应用持有当前值。", "Choose a group; the application owns the value.")).Muted().FontSize(theme.Metrics.FontSizeS) + demo := ui.State[singleSelectDemo](c, "single-select-demo") + if !demo.ready { + demo.ready, demo.group = true, groups[0] + } + field := ui.Select(c, &demo.group, groups, nil). + Label(state.Text("分组", "Group")).Placeholder(state.Text("选择或创建分组", "Select or create a group")). + FillWidth() + if state.exampleID == "disabled" { + field.Disabled(true) } - } + }) } diff --git a/internal/componentdemo/slider.go b/internal/componentdemo/slider.go index b8a049c9..454177c4 100644 --- a/internal/componentdemo/slider.go +++ b/internal/componentdemo/slider.go @@ -190,49 +190,61 @@ func (state *State) sliderForExample() components.Slider { } func (state *State) paintSlider(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var track, disabled ui.Box + if state.exampleID == "range" { + state.paintSliderRange(canvas, theme, size) + return + } + var track, live ui.Box + var volume *ui.SliderState state.drawPage(canvas, theme, size, 520, state.Text("Slider · 显式数值", "Slider · Explicit values"), func(c ui.C) { - switch state.exampleID { - case "range": - track = ui.Slot(c).Height(16) - ui.Text(c, state.Text("下限 / 上限", "Lower / upper bound")).FontSize(theme.Metrics.FontSizeM) - caption(c, state.Text("分别激活两个圆形滑块,演示调用方更新范围。", "Activate each round thumb to see the caller update the range.")) - case "states": + volume = ui.State[ui.SliderState](c, "volume") + volume.Value = float32(state.values[0]) + if state.exampleID == "states" { ui.Row(c).Gap(40).Children(func() { ui.Column(c).Gap(10).Items(ui.Center).Children(func() { - track = ui.Slot(c).Size(24, 160) + live = ui.Slider(c, volume).Range(0, 100).Step(10).Vertical().Height(160).Label(state.Text("音量", "Volume")).Hit(sliderPrimary, state.Text("音量", "Volume")) ui.Text(c, state.Text("竖向", "Vertical")).FontSize(theme.Metrics.FontSizeM) }) ui.Column(c).Grow(1).Basis(0).Gap(10).Children(func() { - disabled = ui.Slot(c).Height(16) + fixed := ui.State[ui.SliderState](c, "fixed") + fixed.Value = 64 + ui.Slider(c, fixed).Range(0, 100).Disabled(true).Label(state.Text("禁用滑块", "Disabled slider")) ui.Text(c, state.Text("禁用", "Disabled")).FontSize(theme.Metrics.FontSizeM).Muted() }) }) - default: - track = ui.Slot(c).Height(16) - caption(c, state.Text("拖动滑块按十为步长更新;激活仍可循环。", "Dragging steps by ten; activating cycles the caller's value.")) + return } + track = ui.Slider(c, volume).Range(0, 100).Step(10).Label(state.Text("音量", "Volume")).Hit(sliderPrimary, state.Text("音量", "Volume")) + caption(c, state.Text("拖动滑块按十为步长更新;激活仍可循环。", "Dragging steps by ten; activating cycles the caller's value.")) }) + if state.exampleID == "states" { + state.values[0] = int32(volume.Value + 0.5) + state.bag().placed = live.Rect() + } else { + state.values[0] = int32(volume.Value + 0.5) + state.bag().placed = track.Rect() + } + if canvas.Clicked(sliderPrimary) { + state.values[0] = (state.values[0] + 10) % 110 + } +} +// paintSliderRange keeps the range example on the canvas API: the page +// RangeSlider paints no caller-supplied thumb labels or value text. +func (state *State) paintSliderRange(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + var track ui.Box + state.drawPage(canvas, theme, size, 520, state.Text("Slider · 显式数值", "Slider · Explicit values"), func(c ui.C) { + track = ui.Slot(c).Height(16) + ui.Text(c, state.Text("下限 / 上限", "Lower / upper bound")).FontSize(theme.Metrics.FontSizeM) + caption(c, state.Text("分别激活两个圆形滑块,演示调用方更新范围。", "Activate each round thumb to see the caller update the range.")) + }) bounds := track.Rect() if bag := state.slider; bag != nil { bag.placed = bounds } - switch state.exampleID { - case "range": - components.BeginRangeSlider(canvas, theme, bounds, state.bag().thumbs[:]).Step(5).Paint(state.Text("价格区间", "Price range")) - if canvas.Clicked(sliderLower) || canvas.Clicked(sliderUpper) { - state.toggleSliderRangePreset() - } - return - case "states": - components.BeginSlider(canvas, theme, sliderPrimary, bounds, float32(state.values[0])).Vertical().Step(10).Paint(state.Text("音量", "Volume")) - components.BeginSlider(canvas, theme, sliderDisabled, disabled.Rect(), 64).Disabled().Paint(state.Text("禁用滑块", "Disabled slider")) - default: - components.BeginSlider(canvas, theme, sliderPrimary, bounds, float32(state.values[0])).Step(10).ValueText(sliderDemoValueText(state.values[0])).Paint(state.Text("音量", "Volume")) - } - if canvas.Clicked(sliderPrimary) { - state.values[0] = (state.values[0] + 10) % 110 + components.BeginRangeSlider(canvas, theme, bounds, state.bag().thumbs[:]).Step(5).Paint(state.Text("价格区间", "Price range")) + if canvas.Clicked(sliderLower) || canvas.Clicked(sliderUpper) { + state.toggleSliderRangePreset() } } diff --git a/internal/componentdemo/sonner.go b/internal/componentdemo/sonner.go index d76c6cd2..c1275adf 100644 --- a/internal/componentdemo/sonner.go +++ b/internal/componentdemo/sonner.go @@ -6,6 +6,13 @@ import ( "github.com/vivaui/viva/ui" ) +// sonnerDemo is the page-owned toaster of one example, made once so a warm +// paint reuses the stack and its identities. +type sonnerDemo struct { + toaster ui.Toaster + seeded bool +} + var sonnerComponent = Component{ ID: "sonner", Title: "Sonner", Category: "Feedback", Summary: "调用方管理生命周期的通知堆栈。", paint: (*State).paintSonner, initialize: (*State).initializeSonner, @@ -18,10 +25,18 @@ toasts := [...]components.SonnerToast{{ Scope: toast, DismissID: tree.ID(page, "dismiss"), ActionID: tree.ID(page, "action"), ActionLabel: "View", }} -components.PaintSonner(canvas, theme, viewport, toasts[:], components.SonnerOptions{Layer: 40})`, PageSnippet: `if ui.Button(c, "Save project").Clicked() { +components.PaintSonner(canvas, theme, viewport, toasts[:], components.SonnerOptions{Layer: 40})`, PageSnippet: `if !m.notified { m.toaster.ShowAction("Project saved", "All local changes are written.", ui.ToastSuccess, "View") + m.notified = true } -ui.Toasts(c, &m.toaster)`, PageSnippetZh: `if ui.Button(c, "保存项目").Clicked() { +if ui.Button(c, "Save project").Clicked() { + m.toaster.ShowAction("Project saved", "All local changes are written.", ui.ToastSuccess, "View") +} +ui.Toasts(c, &m.toaster)`, PageSnippetZh: `if !m.notified { + m.toaster.ShowAction("项目已保存", "所有本地更改均已写入。", ui.ToastSuccess, "查看") + m.notified = true +} +if ui.Button(c, "保存项目").Clicked() { m.toaster.ShowAction("项目已保存", "所有本地更改均已写入。", ui.ToastSuccess, "查看") } ui.Toasts(c, &m.toaster)`}, @@ -35,15 +50,15 @@ toasts := [...]components.SonnerToast{ Scope: toast.At(2)}, } components.PaintSonner(canvas, theme, viewport, toasts[:], components.SonnerOptions{Layer: 40})`, PageSnippet: `if !m.notified { - m.toaster.Show("Project saved", "", ui.ToastSuccess) - m.toaster.Show("Update available", "", ui.ToastInfo) - m.toaster.Show("Connection lost", "", ui.ToastError) + m.toaster.Show("Project saved", "All local changes are written.", ui.ToastSuccess) + m.toaster.Show("Update available", "Takes effect after the app restarts.", ui.ToastInfo) + m.toaster.Show("Connection lost", "Waiting for the network to recover.", ui.ToastError) m.notified = true } ui.Toasts(c, &m.toaster)`, PageSnippetZh: `if !m.notified { - m.toaster.Show("项目已保存", "", ui.ToastSuccess) - m.toaster.Show("有可用更新", "", ui.ToastInfo) - m.toaster.Show("连接已中断", "", ui.ToastError) + m.toaster.Show("项目已保存", "所有本地更改均已写入。", ui.ToastSuccess) + m.toaster.Show("有可用更新", "重启应用后生效。", ui.ToastInfo) + m.toaster.Show("连接已中断", "正在等待网络恢复。", ui.ToastError) m.notified = true } ui.Toasts(c, &m.toaster)`}, @@ -60,17 +75,20 @@ toasts := [...]components.SonnerToast{ components.PaintSonner(canvas, theme, viewport, toasts[:], components.SonnerOptions{ Layer: 40, Expanded: true, })`, PageSnippet: `// The stack expands while the pointer rests on it or focus is inside it. +// A static page cannot hold that hover, so the preview stays on the canvas +// painter to show the expanded geometry exactly. if !m.notified { - m.toaster.ShowAction("Project saved", "", ui.ToastSuccess, "View") - m.toaster.ShowAction("Update available", "", ui.ToastInfo, "Later") - m.toaster.Show("Connection lost", "", ui.ToastError) + m.toaster.ShowAction("Project saved", "All local changes are written.", ui.ToastSuccess, "View") + m.toaster.ShowAction("Update available", "Takes effect after the app restarts.", ui.ToastInfo, "Later") + m.toaster.Show("Connection lost", "Waiting for the network to recover.", ui.ToastError) m.notified = true } ui.Toasts(c, &m.toaster)`, PageSnippetZh: `// 指针停留或焦点在通知堆栈内时,堆栈会展开。 +// 静态页面无法保持悬停,因此该示例保留 canvas 绘制以如实展示展开几何。 if !m.notified { - m.toaster.ShowAction("项目已保存", "", ui.ToastSuccess, "查看") - m.toaster.ShowAction("有可用更新", "", ui.ToastInfo, "稍后") - m.toaster.Show("连接已中断", "", ui.ToastError) + m.toaster.ShowAction("项目已保存", "所有本地更改均已写入。", ui.ToastSuccess, "查看") + m.toaster.ShowAction("有可用更新", "重启应用后生效。", ui.ToastInfo, "稍后") + m.toaster.Show("连接已中断", "正在等待网络恢复。", ui.ToastError) m.notified = true } ui.Toasts(c, &m.toaster)`}, @@ -88,6 +106,45 @@ var ( func (state *State) initializeSonner() { state.flags = 0b111 } func (state *State) paintSonner(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + if state.exampleID == "expanded" { + state.paintSonnerExpanded(canvas, theme, size) + return + } + state.drawPage(canvas, theme, size, 520, state.Text("Sonner · 通知堆栈", "Sonner · Notification stack"), func(c ui.C) { + demo := ui.State[sonnerDemo](c, "sonner-demo") + ui.Text(c, state.Text("生命周期、过期与动画由调用方持有。", "Lifecycle, expiry, and animation belong to the caller.")).FontSize(theme.Metrics.FontSizeS).Muted() + if !demo.seeded { + demo.seeded = true + if state.exampleID == "default" { + demo.toaster.ShowAction(state.Text("项目已保存", "Project saved"), state.Text("所有本地更改均已写入。", "All local changes are written."), ui.ToastSuccess, state.Text("查看", "View")) + } else { + demo.toaster.Show(state.Text("项目已保存", "Project saved"), state.Text("所有本地更改均已写入。", "All local changes are written."), ui.ToastSuccess) + demo.toaster.Show(state.Text("有可用更新", "Update available"), state.Text("重启应用后生效。", "Takes effect after the app restarts."), ui.ToastInfo) + demo.toaster.Show(state.Text("连接已中断", "Connection lost"), state.Text("正在等待网络恢复。", "Waiting for the network to recover."), ui.ToastError) + } + } + if state.exampleID == "default" { + label := state.Text("保存项目", "Save project") + if ui.Button(c, label).Self(ui.Start).Hit(sonnerAction.At(0), label).Clicked() { + demo.toaster.ShowAction(state.Text("项目已保存", "Project saved"), state.Text("所有本地更改均已写入。", "All local changes are written."), ui.ToastSuccess, state.Text("查看", "View")) + } + } + if demo.toaster.Len() == 0 { + ui.Text(c, state.Text("通知已全部关闭。", "All notifications are dismissed.")).FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium).Muted() + } + ui.Toasts(c, &demo.toaster) + if demo.toaster.Len() == 0 { + state.flags = 0 + } else { + state.flags = 1< 0 && open { - status = state.Text("主操作已触发 · 菜单:展开", "Primary triggered · Menu: open") - } else if state.values[0] > 0 { - status = state.Text("主操作已触发 · 菜单:收起", "Primary triggered · Menu: closed") - } else if open { - status = state.Text("主操作:保存 · 菜单:展开", "Primary: Save · Menu: open") + if state.values[0] > 0 { + status = state.Text("主操作已触发", "Primary triggered") + } + if open { + status += state.Text(" · 菜单:展开", " · Menu: open") } - ui.Text(c, status). - FontSize(theme.Metrics.FontSizeS).Muted() + ui.Text(c, status).FontSize(theme.Metrics.FontSizeS).Muted() ui.Wrap(c, state.Text( "主操作与菜单热区各自支持键盘焦点和独立可访问名称。", "The primary and menu targets have separate keyboard focus and accessible names.", diff --git a/internal/componentdemo/state_test.go b/internal/componentdemo/state_test.go index 770ea2b6..ddecb6db 100644 --- a/internal/componentdemo/state_test.go +++ b/internal/componentdemo/state_test.go @@ -227,6 +227,13 @@ func TestPaintDeterministicResponsiveAndIdle(t *testing.T) { // seconds later it is in, and paints what reduced motion did. paintFrame(&canvas, state, size, 5*time.Second, false) paintFrame(&canvas, state, size, 10*time.Second, false) + if component.ID == "toast" || component.ID == "sonner" { + // The page toast stack takes a toast down five seconds after it + // appears, so by 10s the example has settled into its dismissed + // state. That state is itself stable and asks for no frame. + expected = snapshot(&canvas) + paintFrame(&canvas, state, size, 11*time.Second, false) + } assertSamePaint(t, expected, &canvas) if canvas.Animating() { t.Fatal("unchanged example requested another frame") @@ -284,7 +291,7 @@ func assertLayout(t *testing.T, canvas *gfx.Canvas, size gfx.Size) { t.Fatalf("text outside viewport: %+v; measured %+v", label, ink) } } - seen := make(map[gfx.ID]bool) + seen := make(map[gfx.ID]gfx.Rect) for index, hit := range canvas.Hits() { if hit.Block || hit.Container { // An occluder or a semantic container has no ID and may sit under @@ -294,11 +301,17 @@ func assertLayout(t *testing.T, canvas *gfx.Canvas, size gfx.Size) { } continue } - // A label shares the identity of the control it labels, by design. - if hit.ID.IsZero() || seen[hit.ID] && !hit.IsLabel || !inside(hit.Bounds) || hit.Bounds.Width <= 0 || hit.Bounds.Height <= 0 { + // A label shares the identity of the control it labels, by design. A + // control that names an inner region with its own identity (a picker's + // input inside its control) is a nested region, and the later hit wins. + previous, duplicate := seen[hit.ID] + nested := duplicate && contains(previous, hit.Bounds) + if hit.ID.IsZero() || duplicate && !hit.IsLabel && !nested || !inside(hit.Bounds) || hit.Bounds.Width <= 0 || hit.Bounds.Height <= 0 { t.Fatalf("invalid, duplicate, or clipped hit: %+v", hit) } - seen[hit.ID] = seen[hit.ID] || !hit.IsLabel + if !hit.IsLabel { + seen[hit.ID] = hit.Bounds + } for _, previous := range canvas.Hits()[:index] { // A hit declared on top of another and wholly inside it is an overlay by design // (an attachment's action over its trigger): the later hit wins its own area. diff --git a/internal/componentdemo/table.go b/internal/componentdemo/table.go index 6b34dfe1..73c04da6 100644 --- a/internal/componentdemo/table.go +++ b/internal/componentdemo/table.go @@ -3,6 +3,7 @@ package componentdemo import ( "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" "github.com/vivaui/viva/ui" ) @@ -79,7 +80,8 @@ if row, ok := table.RowClicked(); ok { } if row := m.table.Selected(); row >= 0 { ui.Text(c, "Selected: "+bills[row][0]).Muted() -}`, PageSnippetZh: `bills := ui.TableRows{ +} +ui.Text(c, "Total · 3 items · ¥ 4,540").Muted()`, PageSnippetZh: `bills := ui.TableRows{ {"设计系统", "已支付", "¥ 2,400"}, {"桌面构建", "处理中", "¥ 860"}, {"性能审计", "待付款", "¥ 1,280"}, @@ -99,7 +101,8 @@ if row, ok := table.RowClicked(); ok { } if row := m.table.Selected(); row >= 0 { ui.Text(c, "Selected: "+bills[row][0]).Muted() -}`}, +} +ui.Text(c, "合计 · 3 项 · ¥ 4,540").Muted()`}, {ID: "alignment", Title: "列对齐", Description: "左、中、右三种列内文字对齐。", Snippet: `columns := []components.TableColumn{ {Width: 112, Alignment: components.TableAlignLeft}, {Width: 88, Alignment: components.TableAlignCenter}, @@ -187,24 +190,100 @@ var tableColumns = [...]components.TableColumn{ {Width: 0, Alignment: components.TableAlignRight}, } +// tableDemo keeps the page Table's selection, row scope and the data the table +// reads each paint. The slices live here because the page retains the spec, so a +// warm paint allocates nothing. +type tableDemo struct { + state ui.TableState + rows [3][3]string + source ui.TableRows + columns []style.TableColumn + headers []string + footer string + caption string +} + +var tableDemos = map[*State]*tableDemo{} + +func tableDemoFor(state *State) *tableDemo { + if demo := tableDemos[state]; demo != nil { + return demo + } + demo := &tableDemo{ + rows: [3][3]string{ + {state.Text("设计系统", "Design system"), state.Text("已支付", "Paid"), "¥ 2,400"}, + {state.Text("桌面构建", "Desktop build"), state.Text("处理中", "Processing"), "¥ 860"}, + {state.Text("性能审计", "Performance audit"), state.Text("待付款", "Unpaid"), "¥ 1,280"}, + }, + columns: []style.TableColumn{ + {Width: 112, Alignment: style.TableAlignLeft}, + {Width: 88, Alignment: style.TableAlignCenter}, + {Width: 0, Alignment: style.TableAlignRight}, + }, + headers: []string{ + state.Text("项目", "Item"), + state.Text("状态", "Status"), + state.Text("金额", "Amount"), + }, + footer: state.Text("合计 · 3 项 · ¥ 4,540", "Total · 3 items · ¥ 4,540"), + caption: state.Text("点击任意数据行以查看交互反馈。", "Click any data row to see its interactive feedback."), + } + demo.source = ui.TableRows{demo.rows[0][:], demo.rows[1][:], demo.rows[2][:]} + if state.exampleID == "alignment" { + demo.caption = state.Text("项目左对齐,状态居中,金额右对齐。", "Item is left-aligned, status centered, amount right-aligned.") + } + tableDemos[state] = demo + return demo +} + // The demo paints the component table (with footer and caption, and a selection -// bit per row the caller owns) in a slot: ui.Table is the selectable, sortable, -// scrolling one. +// bit per row the caller owns) in a slot. ui.Table is the selectable, sortable, +// scrolling one; the overflow example still needs the component's heading fit, +// which the page API does not expose. func (state *State) paintTable(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + if state.exampleID == "overflow" { + state.paintTableOverflow(canvas, theme, size) + return + } + demo := tableDemoFor(state) + state.drawPage(canvas, theme, size, 620, state.Text("Table · 账单", "Table · Bills"), func(c ui.C) { + table := ui.Table(c, &demo.state, ui.TableSpec{ + Columns: demo.columns, + Headers: demo.headers, + Source: &demo.source, + }) + if state.exampleID == "selection" { + if row, ok := table.RowClicked(); ok { + demo.state.Select(row) + } + state.flags = 0 + if selected := demo.state.Selected(); selected >= 0 { + state.flags = 1 << selected + ui.Text(c, "Selected: "+demo.rows[selected][0]).Muted() + } + ui.Text(c, demo.footer).Muted() + return + } + ui.Text(c, demo.footer).Muted() + ui.Text(c, demo.caption).Muted() + }) +} + +// paintTableOverflow keeps the component table for the heading-fit example: the +// page Table takes explicit column widths and does not measure headings. +func (state *State) paintTableOverflow(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { var slot ui.Box state.drawPage(canvas, theme, size, 620, state.Text("Table · 账单", "Table · Bills"), func(c ui.C) { slot = ui.Slot(c).Height(220) }) columns := tableColumns + columns[0].Width, columns[1].Width = 96, 40 header := [...]string{ state.Text("项目", "Item"), state.Text("状态", "Status"), state.Text("金额", "Amount"), } - if state.exampleID == "overflow" { - columns[0].Width, columns[1].Width = 96, 40 - components.FitTableHeadings(canvas, theme, columns[:], header[:]) - } + components.FitTableHeadings(canvas, theme, columns[:], header[:]) table := components.BeginTable(canvas, theme, slot.Rect(), columns[:]) table.Header(header[:]) rows := [...][3]string{ @@ -213,23 +292,12 @@ func (state *State) paintTable(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Siz {state.Text("性能审计", "Performance audit"), state.Text("待付款", "Unpaid"), "¥ 1,280"}, } for index := range rows { - selected := state.exampleID == "selection" && state.flags&(1< 0 { + state.flags |= 1 + } else { + state.flags &^= 1 + } + }) +} + +// paintToastSwipe draws the caller's horizontal offset, which the page stack +// cannot carry yet: the toast component takes the snapshot as-is. +func (state *State) paintToastSwipe(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { open := state.flags&1 != 0 state.drawPage(canvas, theme, size, 520, state.Text("Toast · 调用方生命周期", "Toast · Caller lifecycle"), func(c ui.C) { ui.Text(c, state.Text("关闭后重新进入示例可恢复初始快照。", "Re-entering the example after dismissal restores the initial snapshot.")).FontSize(theme.Metrics.FontSizeS).Muted() @@ -102,37 +163,15 @@ func (state *State) paintToast(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Siz return } snapshot := components.ToastSnapshot{ - Title: state.Text("项目已保存", "Project saved"), Description: state.Text("更改已安全写入本地。", "Changes are safely written locally."), - Type: components.ToastSuccess, - } - actionLabel := state.Text("查看", "View") - if state.exampleID == "types" { - actionLabel = state.Text("切换", "Switch") - types := [...]components.ToastType{components.ToastInfo, components.ToastWarning, components.ToastError} - titles := [...]string{ - state.Text("有可用更新", "Update available"), - state.Text("磁盘空间不足", "Low disk space"), - state.Text("构建失败", "Build failed"), - } - index := int(state.values[0]) - snapshot.Type = types[index] - snapshot.Title = titles[index] - snapshot.Description = state.Text("激活操作按钮查看下一个语义类型。", "Activate the action button to see the next semantic type.") - } else if state.exampleID == "swipe" { - snapshot.Type = components.ToastInfo - snapshot.Title = state.Text("下载即将完成", "Download almost complete") - snapshot.Description = state.Text("横向位移来自调用方快照。", "The horizontal offset comes from the caller's snapshot.") - snapshot.SwipeX = -8 - actionLabel = state.Text("继续", "Continue") + Title: state.Text("下载即将完成", "Download almost complete"), + Description: state.Text("横向位移来自调用方快照。", "The horizontal offset comes from the caller's snapshot."), + Type: components.ToastInfo, + SwipeX: -8, } components.PaintToast(canvas, theme, gfx.Rect{Width: size.Width, Height: size.Height}, snapshot, components.ToastOptions{ - Layer: 52, Scope: toastScope, DismissID: toastDismiss, ActionID: toastAction, ActionLabel: actionLabel, + Layer: 52, Scope: toastScope, DismissID: toastDismiss, ActionID: toastAction, ActionLabel: state.Text("继续", "Continue"), }) - if canvas.Clicked(toastDismiss) { state.flags &^= 1 } - if canvas.Clicked(toastAction) { - state.values[0] = (state.values[0] + 1) % 3 - } } diff --git a/internal/componentdemo/toggle.go b/internal/componentdemo/toggle.go index 90cf576c..753d009f 100644 --- a/internal/componentdemo/toggle.go +++ b/internal/componentdemo/toggle.go @@ -73,59 +73,71 @@ type toggleSpecimen struct { invalid, disabled bool } +// togglePageState is the page Toggle's model: the active bits of the toggles a +// caller keeps (the fixed specimens are seeded each paint). +type togglePageState struct { + values [4]bool +} + func (state *State) paintToggle(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - var specimens [6]toggleSpecimen - count := 0 - height := theme.Metrics.ControlHeight // default size; small and large adjust below - add := func(c ui.C, specimen toggleSpecimen, width, extra float32) { - specimen.slot = ui.Slot(c).Size(width, height+extra) - specimens[count] = specimen - count++ + if state.exampleID == "states" { + state.paintToggleStates(canvas, theme, size) + return } state.drawPage(canvas, theme, size, 500, state.Text("Toggle · 双态操作", "Toggle · Two-state action"), func(c ui.C) { - ui.Row(c).Gap(12).Children(func() { - for index, label := range [...]string{"B", "I", "U"} { - add(c, toggleSpecimen{id: toggleItem.At(index), label: label, outline: true, active: state.flags&(1< 0 { m.selected = i - 1 }`, PageSnippetZh: `labels := []string{"Production", "Gateway", "Database", "Worker"} +addresses := []string{"gw.example.com", "db.example.com", "worker.example.com"} m.tree.Node = func(i int) ui.TreeNode { if i == 0 { - return ui.TreeNode{Branch: true, Expanded: true} + return ui.TreeNode{Branch: true, Expanded: true, Height: 44} } - return ui.TreeNode{Depth: 1, Selected: i-1 == m.selected} + return ui.TreeNode{Depth: 1, Selected: i-1 == m.selected, Height: 44} } -ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, nil).Grow(1) -if i, ok := m.tree.Chosen(); ok { +ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, func(i int) { + if i == 0 { + ui.Column(c).Grow(1).Children(func() { + ui.Text(c, labels[0]).Weight(gfx.WeightSemibold) + }) + ui.Text(c, "3 hosts").Muted() + return + } + ui.Column(c).Grow(1).Gap(1).Children(func() { + ui.Text(c, labels[i]).Weight(gfx.WeightMedium) + ui.Text(c, addresses[i-1]).Muted() + }) +}).Height(4 * 44) +if i, ok := m.tree.Chosen(); ok && i > 0 { m.selected = i - 1 }`}, {ID: "disabled", Title: "禁用分支", Description: "保留层级和语义,但分组与叶子均不可交互。", Snippet: `hosts := components.BeginTree(canvas, theme, bounds) @@ -92,79 +143,140 @@ for _, name := range [...]string{"Gateway", "Database", "Worker"} { ID: tree.ID(page, name), Label: name, Depth: 1, Disabled: true, }) }`, PageSnippet: `labels := []string{"Production", "Gateway", "Database", "Worker"} +addresses := []string{"gw.example.com", "db.example.com", "worker.example.com"} m.tree.Node = func(i int) ui.TreeNode { if i == 0 { - return ui.TreeNode{Branch: true, Expanded: true, Disabled: true} + return ui.TreeNode{Branch: true, Expanded: true, Disabled: true, Height: 44} } - return ui.TreeNode{Depth: 1, Disabled: true} + return ui.TreeNode{Depth: 1, Disabled: true, Height: 44} } -ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, nil).Grow(1)`, PageSnippetZh: `labels := []string{"Production", "Gateway", "Database", "Worker"} +ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, func(i int) { + if i == 0 { + ui.Column(c).Grow(1).Children(func() { + ui.Text(c, labels[0]).Weight(gfx.WeightSemibold) + }) + ui.Text(c, "3 hosts").Muted() + return + } + ui.Column(c).Grow(1).Gap(1).Children(func() { + ui.Text(c, labels[i]).Weight(gfx.WeightMedium) + ui.Text(c, addresses[i-1]).Muted() + }) +}).Height(4 * 44)`, PageSnippetZh: `labels := []string{"Production", "Gateway", "Database", "Worker"} +addresses := []string{"gw.example.com", "db.example.com", "worker.example.com"} m.tree.Node = func(i int) ui.TreeNode { if i == 0 { - return ui.TreeNode{Branch: true, Expanded: true, Disabled: true} + return ui.TreeNode{Branch: true, Expanded: true, Disabled: true, Height: 44} } - return ui.TreeNode{Depth: 1, Disabled: true} + return ui.TreeNode{Depth: 1, Disabled: true, Height: 44} } -ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, nil).Grow(1)`}, +ui.Tree(c, &m.tree, len(labels), func(i int) string { return labels[i] }, func(i int) { + if i == 0 { + ui.Column(c).Grow(1).Children(func() { + ui.Text(c, labels[0]).Weight(gfx.WeightSemibold) + }) + ui.Text(c, "3 hosts").Muted() + return + } + ui.Column(c).Grow(1).Gap(1).Children(func() { + ui.Text(c, labels[i]).Weight(gfx.WeightMedium) + ui.Text(c, addresses[i-1]).Muted() + }) +}).Height(4 * 44)`}, }, } -var ( - treeUI = tree.Feature("tree") - treeGroupRow = tree.ID(treeUI, "group") - treeGroupDisclosure = tree.ID(treeUI, "disclosure") - // treeLeaf's item i is the i-th host. - treeLeaf = tree.Sub(treeUI, tree.Name("host")) -) - func initializeTree(state *State) { state.flags = 1 state.values[0] = 1 } -func (state *State) paintTree(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - // The demo draws a two-line row; the extra 12px is its own content, not - // the tree's default single-line row height. - rowHeight := theme.Metrics.ControlHeight + 12 - var stage ui.Box - state.drawPage(canvas, theme, size, 600, state.Text("Tree · 主机目录", "Tree · Host directory"), func(c ui.C) { - stage = ui.Slot(c).Height(rowHeight * 4) - }) - disabled := state.exampleID == "disabled" - expanded := state.flags&1 != 0 - hosts := components.BeginTree(canvas, theme, stage.Rect()).RowHeight(rowHeight).Indent(22) - group := components.TreeItem{ - ID: treeGroupRow, DisclosureID: treeGroupDisclosure, Label: "Production", Branch: true, - Expanded: expanded, Disabled: disabled, +// treeDemo keeps the page Tree's expanded and selected rows and the stable +// callbacks that describe and paint them. +type treeDemo struct { + state ui.TreeState + labels [4]string + address [3]string + node func(int) ui.TreeNode + label func(int) string + content func(int) + c ui.C + expanded bool + disabled bool + selected int32 + choose bool + height float32 +} + +var treeDemos = map[*State]*treeDemo{} + +func treeDemoFor(state *State) *treeDemo { + if demo := treeDemos[state]; demo != nil { + return demo } - row := hosts.Item(group) - canvas.Label("Production", gfx.Rect{X: row.Content.X + 2, Y: row.Content.Y + 10, Width: row.Content.Width - 80, Height: 24}, gfx.TextStyle{ - Size: theme.Metrics.FontSizeM, Weight: gfx.WeightSemibold, Color: theme.Foreground, - }) - canvas.Label("3 hosts", gfx.Rect{X: row.Bounds.X + row.Bounds.Width - 72, Y: row.Bounds.Y + 11, Width: 64, Height: 22}, gfx.TextStyle{ - Size: theme.Metrics.FontSizeS, Color: theme.MutedForeground, - }) - if canvas.Clicked(treeGroupRow) || canvas.Clicked(treeGroupDisclosure) { - state.flags ^= 1 + demo := &treeDemo{ + labels: [4]string{"Production", "Gateway", "Database", "Worker"}, + address: [3]string{ + "gw.example.com", + "db.example.com", + "worker.example.com", + }, } - if !expanded { - return + demo.node = demo.describe + demo.label = demo.nameOf + demo.content = demo.paintContent + demo.state.Node = demo.node + treeDemos[state] = demo + return demo +} + +func (demo *treeDemo) nameOf(i int) string { return demo.labels[i] } + +func (demo *treeDemo) describe(i int) ui.TreeNode { + node := ui.TreeNode{Height: demo.height, Disabled: demo.disabled} + if i == 0 { + node.Branch, node.Expanded = true, demo.expanded + return node } - names := [...]string{"Gateway", "Database", "Worker"} - addresses := [...]string{"gw.example.com", "db.example.com", "worker.example.com"} - for index := range names { - selected := state.exampleID == "selection" && state.values[0] == int32(index) - row = hosts.Item(components.TreeItem{ - ID: treeLeaf.At(index), Label: names[index], Depth: 1, Selected: selected, Disabled: disabled, - }) - canvas.Label(names[index], gfx.Rect{X: row.Content.X + 10, Y: row.Content.Y + 4, Width: 120, Height: 20}, gfx.TextStyle{ - Size: theme.Metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.Foreground, - }) - canvas.Label(addresses[index], gfx.Rect{X: row.Content.X + 10, Y: row.Content.Y + 23, Width: row.Content.Width - 20, Height: 18}, gfx.TextStyle{ - Size: theme.Metrics.FontSizeS, Color: theme.MutedForeground, + node.Depth = 1 + node.Selected = demo.choose && demo.selected == int32(i-1) + return node +} + +func (demo *treeDemo) paintContent(i int) { + if i == 0 { + ui.Column(demo.c).Grow(1).Children(func() { + ui.Text(demo.c, demo.labels[0]).Weight(gfx.WeightSemibold) }) + ui.Text(demo.c, "3 hosts").Muted() + return + } + ui.Column(demo.c).Grow(1).Gap(1).Children(func() { + ui.Text(demo.c, demo.labels[i]).Weight(gfx.WeightMedium) + ui.Text(demo.c, demo.address[i-1]).Muted() + }) +} + +func (state *State) paintTree(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := treeDemoFor(state) + demo.expanded = state.flags&1 != 0 + demo.disabled = state.exampleID == "disabled" + demo.choose = state.exampleID == "selection" + demo.selected = state.values[0] + demo.height = theme.Metrics.ControlHeight + 12 + rows := 1 + if demo.expanded { + rows = 4 + } + state.drawPage(canvas, theme, size, 600, state.Text("Tree · 主机目录", "Tree · Host directory"), func(c ui.C) { + demo.c = c + demo.state.Node = demo.node + ui.Tree(c, &demo.state, rows, demo.label, demo.content).Height(float32(rows) * demo.height) + }) + if i, ok := demo.state.Toggled(); ok && i == 0 { + state.flags ^= 1 } - if index, ok := canvas.ClickedIn(treeLeaf); ok { - state.values[0] = int32(index) + if i, ok := demo.state.Chosen(); ok && i > 0 { + state.values[0] = int32(i - 1) } } diff --git a/internal/componentdemo/typed_events_test.go b/internal/componentdemo/typed_events_test.go index 45e29d4a..b7d25877 100644 --- a/internal/componentdemo/typed_events_test.go +++ b/internal/componentdemo/typed_events_test.go @@ -102,13 +102,8 @@ func TestPointerGeometryUsesResponsiveViewport(t *testing.T) { resizable := newTestState(t, "resizable", "horizontal") paintAt(&canvas, resizable, narrow) - split := resizable.slider.placed - result = resizable.Pointer(gfx.PointerEvent{ - Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: split.X + split.Width, - Viewport: narrow, Target: resizableHandle, - }) - if !result.Handled || resizable.values[0] != 80 { - t.Fatalf("responsive resizable result=%+v value=%d", result, resizable.values[0]) + if position := resizableDemoFor(resizable).state.Pos; position > narrow.Width { + t.Fatalf("responsive splitter position %.0f is wider than the window", position) } } @@ -131,48 +126,59 @@ func TestResizableUsesCapturedPointerDrag(t *testing.T) { state := newTestState(t, "resizable", "horizontal") var canvas gfx.Canvas paintAt(&canvas, state, testSize) - split := state.slider.placed - at := func(fraction float32) float32 { return split.X + split.Width*fraction } - result := state.Pointer(gfx.PointerEvent{Kind: gfx.PointerMove, X: at(0.7), Target: resizableHandle}) - if result != (gfx.EventResult{}) || state.values[0] != 50 { - t.Fatalf("uncaptured move result=%+v value=%d", result, state.values[0]) - } - result = state.Pointer(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: at(0.7), Target: resizableHandle}) - if !result.Handled || !result.Repaint || result.Focus != resizableHandle || state.values[0] != 70 { - t.Fatalf("down result=%+v value=%d", result, state.values[0]) - } - result = state.Pointer(gfx.PointerEvent{Kind: gfx.PointerMove, X: at(0.2), Target: resizableHandle, Captured: true}) - if !result.Handled || !result.Repaint || state.values[0] != 20 { - t.Fatalf("captured move result=%+v value=%d", result, state.values[0]) - } - click(&canvas, state, resizableHandle) - if state.values[0] != 30 { - t.Fatalf("click value=%d", state.values[0]) + demo := resizableDemoFor(state) + split := findHit(t, &canvas, resizableHandle).Bounds + center := split.X + split.Width/2 + pointer := func(event gfx.PointerEvent) { + canvas.BeginPointerPass(event) + paintAt(&canvas, state, testSize) + canvas.EndPointerPass() + } + // A move without a press does not start a drag. + pointer(gfx.PointerEvent{Kind: gfx.PointerMove, X: center + 40, Viewport: testSize, Target: resizableHandle}) + if demo.state.Dragging() || demo.state.Pos != 260 { + t.Fatalf("uncaptured move dragged=%t position=%.0f", demo.state.Dragging(), demo.state.Pos) + } + pointer(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: center, Viewport: testSize, Target: resizableHandle}) + if !demo.state.Dragging() { + t.Fatal("a press on the divider did not start a drag") + } + pointer(gfx.PointerEvent{Kind: gfx.PointerMove, X: center + 40, Viewport: testSize, Target: resizableHandle, Captured: true}) + if demo.state.Pos <= 260 { + t.Fatalf("captured move left position=%.0f", demo.state.Pos) + } + pointer(gfx.PointerEvent{Kind: gfx.PointerUp, X: center + 40, Viewport: testSize, Target: resizableHandle, Captured: true}) + if demo.state.Dragging() { + t.Fatal("the drag did not stop on release") } } func TestScrollAreaHandlesOnlyTargetedScroll(t *testing.T) { state := newTestState(t, "scroll-area", "both-axes") + var canvas gfx.Canvas + paintAt(&canvas, state, testSize) + demo := scrollAreaDemoFor(state) + if demo.scroller == nil || demo.bounds.Width <= 0 { + t.Fatal("the scroll area was not declared") + } if result := state.Scroll(gfx.ScrollEvent{DeltaX: 40, DeltaY: 60, Target: gfx.Item(999)}); result != (gfx.EventResult{}) { - t.Fatalf("untargeted result=%+v", result) + t.Fatalf("wheel outside the area result=%+v", result) } - result := state.Scroll(gfx.ScrollEvent{DeltaX: 40, DeltaY: 60, Target: scrollAreaViewport, Precise: true}) - if !result.Handled || !result.Repaint || state.values[1] != 40 || state.values[0] != 60 { - t.Fatalf("targeted result=%+v offsets=(%d,%d)", result, state.values[1], state.values[0]) + inside := func(event gfx.ScrollEvent) gfx.ScrollEvent { + event.X, event.Y = demo.bounds.X+demo.bounds.Width/2, demo.bounds.Y+demo.bounds.Height/2 + return event } - result = state.Scroll(gfx.ScrollEvent{DeltaX: 500, DeltaY: 500, Target: scrollAreaVertical}) - if !result.Handled || !result.Repaint || state.values[1] != 180 || state.values[0] != 180 { - t.Fatalf("clamped result=%+v offsets=(%d,%d)", result, state.values[1], state.values[0]) + result := state.Scroll(inside(gfx.ScrollEvent{DeltaX: 40, DeltaY: 60, Target: scrollAreaViewport, Precise: true})) + if !result.Handled || !result.Repaint || demo.scroller.OffsetX != 40 || demo.scroller.Offset != 60 { + t.Fatalf("wheel inside result=%+v offsets=(%.0f,%.0f)", result, demo.scroller.OffsetX, demo.scroller.Offset) } - result = state.Scroll(gfx.ScrollEvent{DeltaX: 10, DeltaY: 10, Target: scrollAreaViewport}) - if !result.Handled || result.Repaint { - t.Fatalf("bounded result=%+v", result) + result = state.Scroll(inside(gfx.ScrollEvent{DeltaX: 500, DeltaY: 500, Target: scrollAreaVertical})) + if !result.Handled || !result.Repaint || demo.scroller.OffsetX != demo.scroller.MaxX() || demo.scroller.Offset != demo.scroller.Max() { + t.Fatalf("clamped result=%+v offsets=(%.0f,%.0f) max=(%.0f,%.0f)", result, demo.scroller.OffsetX, demo.scroller.Offset, demo.scroller.MaxX(), demo.scroller.Max()) } - var canvas gfx.Canvas - paintAt(&canvas, state, testSize) - click(&canvas, state, scrollAreaVertical) - if state.values[0] != 0 { - t.Fatalf("vertical click offset=%d", state.values[0]) + result = state.Scroll(inside(gfx.ScrollEvent{DeltaX: 10, DeltaY: 10, Target: scrollAreaViewport})) + if result.Repaint { + t.Fatalf("bounded result=%+v", result) } } @@ -243,44 +249,48 @@ func TestStandardTabsRouteKeysThroughThePage(t *testing.T) { func TestContextMenuOpensAtSecondaryPointer(t *testing.T) { state := newTestState(t, "context-menu", "default") - state.flags &^= contextMenuOpenMask - if result := state.Pointer(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, Target: contextMenuSurface}); result != (gfx.EventResult{}) { - t.Fatalf("primary result=%+v", result) - } - result := state.Pointer(gfx.PointerEvent{ - Kind: gfx.PointerDown, Button: gfx.PointerButtonSecondary, - X: 420, Y: 180, Target: contextMenuSurface, - }) - if !result.Handled || !result.Repaint || state.flags&contextMenuOpenMask == 0 || state.points[0] != 420 || state.points[1] != 180 { - t.Fatalf("secondary result=%+v flags=%d point=%v", result, state.flags, state.points[:2]) - } var canvas gfx.Canvas - click(&canvas, state, contextMenuToggle) - if state.flags&1 == 0 || state.flags&contextMenuOpenMask == 0 { + paintFrame(&canvas, state, testSize, time.Second, true) + area := findHitByLabel(t, &canvas, "上下文菜单区域") + deliver := func(button gfx.PointerButton, kind gfx.PointerEventKind) { + canvas.DeliverPointer(gfx.PointerEvent{ + Kind: kind, Button: button, X: 120, Y: 180, Target: area, + }, testSize, state.Paint) + paintFrame(&canvas, state, testSize, time.Second, true) + } + deliver(gfx.PointerButtonPrimary, gfx.PointerDown) + if hasText(&canvas, "Show details") { + t.Fatal("a primary press opened the context menu") + } + deliver(gfx.PointerButtonSecondary, gfx.PointerDown) + if !hasText(&canvas, "Show details") { + t.Fatal("a secondary press did not open the context menu") + } + row := findHitByLabel(t, &canvas, "Show details") + click(&canvas, state, row) + if state.flags&1 == 0 { t.Fatalf("toggle click flags=%d", state.flags) } } func TestTooltipAndHoverCardUseSynchronousEnterLeave(t *testing.T) { tooltip := newTestState(t, "tooltip", "default") - result := tooltip.Pointer(gfx.PointerEvent{Kind: gfx.PointerMove, Target: tooltipTrigger}) - if !result.Handled || !result.Repaint || tooltip.flags&2 == 0 { - t.Fatalf("tooltip enter result=%+v flags=%d", result, tooltip.flags) - } - result = tooltip.Pointer(gfx.PointerEvent{Kind: gfx.PointerExit}) - if !result.Handled || !result.Repaint || tooltip.flags&2 != 0 { - t.Fatalf("tooltip leave result=%+v flags=%d", result, tooltip.flags) - } var canvas gfx.Canvas - click(&canvas, tooltip, tooltipTrigger) - tooltip.Pointer(gfx.PointerEvent{Kind: gfx.PointerMove, Target: tooltipTrigger}) - tooltip.Pointer(gfx.PointerEvent{Kind: gfx.PointerExit}) - if tooltip.flags&1 == 0 { - t.Fatal("pointer leave cleared click-owned tooltip state") + paintFrame(&canvas, tooltip, testSize, time.Second, true) + findHit(t, &canvas, tooltipTrigger) + canvas.SetInteraction(tooltipTrigger, gfx.ID{}, gfx.ID{}, false) + paintFrame(&canvas, tooltip, testSize, time.Second, true) + if !hasText(&canvas, "原生同步提示,无后台延时器") { + t.Fatal("hovering the trigger did not show its tooltip") + } + canvas.SetInteraction(gfx.ID{}, gfx.ID{}, gfx.ID{}, false) + paintFrame(&canvas, tooltip, testSize, time.Second, true) + if hasText(&canvas, "原生同步提示,无后台延时器") { + t.Fatal("moving the pointer away did not hide the tooltip") } hover := newTestState(t, "hover-card", "default") - result = hover.Pointer(gfx.PointerEvent{Kind: gfx.PointerMove, Target: hoverCardAnchor}) + result := hover.Pointer(gfx.PointerEvent{Kind: gfx.PointerMove, Target: hoverCardAnchor}) if !result.Handled || !result.Repaint || hover.flags&1 == 0 { t.Fatalf("hover enter result=%+v flags=%d", result, hover.flags) } diff --git a/internal/componentdemo/typography.go b/internal/componentdemo/typography.go index d88b59b4..674c33a1 100644 --- a/internal/componentdemo/typography.go +++ b/internal/componentdemo/typography.go @@ -113,8 +113,8 @@ var ( } ) -// The specimens are the component's roles themselves, painted in slots: ui.Text -// would only imitate their size and weight. +// The specimens are the component's roles, declared with the page's text calls: +// Paragraph wraps, Text does not, and the role decides size, weight and color. func (state *State) paintTypography(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { lines := typographyHierarchy[:] switch state.exampleID { @@ -123,15 +123,31 @@ func (state *State) paintTypography(canvas *gfx.Canvas, theme gfx.Theme, size gf case "muted": lines = typographyMuted[:] } - var slots [len(typographyHierarchy)]ui.Box state.drawPage(canvas, theme, size, 600, state.Text("Typography · 文字角色", "Typography · Text roles"), func(c ui.C) { ui.Column(c).Gap(6).Children(func() { - for index, line := range lines { - slots[index] = ui.Slot(c).Height(line.height) + for _, line := range lines { + text := state.Text(line.text, line.english) + switch line.role { + case components.TypographyH1: + ui.Text(c, text).FontSize(theme.Metrics.FontSizeL * 1.5).Weight(gfx.WeightBold) + case components.TypographyH2: + ui.Text(c, text).FontSize(theme.Metrics.FontSizeL + 6).Weight(gfx.WeightSemibold) + case components.TypographyH3: + ui.Text(c, text).FontSize(theme.Metrics.FontSizeL).Weight(gfx.WeightSemibold) + case components.TypographyH4: + ui.Text(c, text).FontSize(theme.Metrics.FontSizeM + 7).Weight(gfx.WeightSemibold) + case components.TypographyLead: + ui.Paragraph(c, text, 0).FontSize(theme.Metrics.FontSizeM + 7).Muted() + case components.TypographyParagraph: + ui.Paragraph(c, text, 0).FontSize(theme.Metrics.FontSizeM + 3) + case components.TypographyLarge: + ui.Text(c, text).FontSize(theme.Metrics.FontSizeM + 5).Weight(gfx.WeightSemibold) + case components.TypographySmall: + ui.Text(c, text).FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium) + default: + ui.Text(c, text).FontSize(theme.Metrics.FontSizeM).Muted() + } } }) }) - for index, line := range lines { - components.Typography(canvas, theme, slots[index].Rect(), line.role, state.Text(line.text, line.english)) - } } diff --git a/internal/gallery/gallery.go b/internal/gallery/gallery.go index b8c33eb6..900802ea 100644 --- a/internal/gallery/gallery.go +++ b/internal/gallery/gallery.go @@ -184,8 +184,12 @@ func (state *State) openPage(page int) { // and owns the offset itself. func (state *State) Scroll(event gfx.ScrollEvent) gfx.EventResult { if slot, local, ok := state.decodeExample(event.Target); ok && slot < len(state.live) { + view := &state.live[slot] + event.X -= view.origin.X + event.Y -= view.origin.Y + event.Viewport = view.size event.Target = local - if result := state.live[slot].demo.Scroll(event); result.Handled { + if result := view.demo.Scroll(event); result.Handled { return liftResult(result, slot) } } diff --git a/internal/gallery/gallery_test.go b/internal/gallery/gallery_test.go index 7deca84a..7d251ca6 100644 --- a/internal/gallery/gallery_test.go +++ b/internal/gallery/gallery_test.go @@ -240,12 +240,12 @@ func TestExamplesNeverPaintAboveTheToolbar(t *testing.T) { state.density, state.lightMode = density, light canvas := paintTall(state, DefaultWidth) for _, rectangle := range canvas.Rectangles() { - if rectangle.Layer >= toolbarLayer && rectangle.Bounds.Y >= toolbarHeight { + if rectangle.Layer > toolbarLayer && rectangle.Bounds.Y < toolbarHeight && rectangle.Bounds.Y+rectangle.Bounds.Height > 0 { t.Fatalf("%s: a rectangle on layer %d at %+v would cover the toolbar", catalog[index].ID, rectangle.Layer, rectangle.Bounds) } } for _, text := range canvas.Texts() { - if text.Layer >= toolbarLayer && text.Bounds.Y >= toolbarHeight { + if text.Layer > toolbarLayer && text.Bounds.Y < toolbarHeight && text.Bounds.Y+text.Bounds.Height > 0 { t.Fatalf("%s: text %q on layer %d would cover the toolbar", catalog[index].ID, text.Value, text.Layer) } } From 93f917f9529075637bd0d9a24237d37ce14a1e97 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 18:34:36 +0800 Subject: [PATCH 40/66] feat(web): render with WebGL2 and fall back to Canvas2D Share the native frame builder with the browser, draw labels as retained textures and tile them beyond the GPU texture limit, draw images in both renderers, and build the docs previews through the public web deployment path. --- .github/workflows/ci.yml | 16 +- .github/workflows/website.yml | 7 + README.md | 13 +- README.zh-CN.md | 6 +- app/app.go | 6 + app/driver.go | 4 +- app/driver_test.go | 3 +- app/interface_font_test.go | 6 +- app/key_traversal_frame_test.go | 8 +- app/label_replace_test.go | 33 - app/painter.go | 1050 +-------------- app/painter_bitmap_test.go | 31 +- app/painter_leak_test.go | 16 +- app/painter_origin_test.go | 12 +- app/painter_presence_test.go | 6 +- app/painter_test.go | 54 +- app/quad_clip_test.go | 8 +- app/run_canvas.go | 4 +- app/run_canvas_js.go | 4 +- app/run_canvas_js_test.go | 13 +- app/store_consistency_test.go | 33 +- cmd/component-preview/main_web.go | 26 +- cmd/viva/build.go | 99 +- .../2026-11-19-web-renderers-darwin-arm64.md | 80 ++ docs/conformance.md | 10 +- docs/web-deployment.md | 91 +- internal/framebuild/framebuild.go | 1138 +++++++++++++++++ internal/framebuild/framebuild_test.go | 285 +++++ internal/platform/web/glpack.go | 60 + internal/platform/web/glpack_test.go | 81 ++ internal/platform/web/painter.go | 33 +- internal/platform/web/painter_test.go | 4 +- internal/platform/web/render.go | 450 +++++-- internal/platform/web/render_gl_js.go | 608 +++++++++ internal/platform/web/render_warp_js.go | 187 +++ internal/platform/web/shaders/scene.frag.glsl | 154 +++ internal/platform/web/shaders/scene.vert.glsl | 126 ++ internal/platform/web/shaders/text.frag.glsl | 16 + internal/platform/web/shaders/text.vert.glsl | 31 + internal/platform/web/shaders_js.go | 45 + internal/platform/web/trace.go | 10 +- internal/platform/web/web.go | 111 +- internal/render/plan.go | 112 ++ internal/render/plan_test.go | 97 ++ internal/webbuild/webbuild.go | 191 +++ tools/docs/content.go | 2 +- tools/docs/main.go | 38 +- tools/webcheck/check.mjs | 52 +- tools/webcheck/fixture/main.go | 23 +- tools/webcheck/package-lock.json | 12 +- tools/webcheck/package.json | 3 +- tools/webcheck/safari.mjs | 142 ++ website/content/guides/en/platforms.md | 8 +- website/content/guides/zh/platforms.md | 4 +- website/src/lib/home.ts | 4 +- website/src/lib/i18n.ts | 2 +- 56 files changed, 4219 insertions(+), 1449 deletions(-) create mode 100644 docs/benchmarks/2026-11-19-web-renderers-darwin-arm64.md create mode 100644 internal/framebuild/framebuild.go create mode 100644 internal/framebuild/framebuild_test.go create mode 100644 internal/platform/web/glpack.go create mode 100644 internal/platform/web/glpack_test.go create mode 100644 internal/platform/web/render_gl_js.go create mode 100644 internal/platform/web/render_warp_js.go create mode 100644 internal/platform/web/shaders/scene.frag.glsl create mode 100644 internal/platform/web/shaders/scene.vert.glsl create mode 100644 internal/platform/web/shaders/text.frag.glsl create mode 100644 internal/platform/web/shaders/text.vert.glsl create mode 100644 internal/platform/web/shaders_js.go create mode 100644 internal/render/plan.go create mode 100644 internal/render/plan_test.go create mode 100644 internal/webbuild/webbuild.go create mode 100644 tools/webcheck/safari.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2584e2b8..926747fc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -169,6 +169,12 @@ jobs: GOOS=js GOARCH=wasm go build \ ./cmd/component-preview ./cmd/gallery-web \ ./examples/guides/hello ./examples/guides/webview + # The docs previews and the gallery build through the same public command + # an application uses, so a break in the deployment path fails here. + - name: build the public web entry points + run: | + go run ./cmd/viva build --target web ./cmd/component-preview -o build/component-preview-web + go run ./cmd/viva build --target web ./cmd/gallery-web -o build/gallery-web # The real browser gate. It builds the fixture and drives it through the # three engines in parallel with the wasm tests above; most of its elapsed @@ -197,12 +203,14 @@ jobs: tools/webcheck/node_modules/.bin/playwright install --with-deps chromium firefox webkit # Each engine gets its own step so a failure names the engine that broke # and the others still report their own result. - - name: drive the browser verification page (chromium) - run: node tools/webcheck/check.mjs --dir build/webcheck --browser chromium + - name: drive the browser verification page (chromium, WebGL2) + run: node tools/webcheck/check.mjs --dir build/webcheck --browser chromium --renderer webgl2 + - name: drive the browser verification page (chromium, Canvas2D fallback) + run: node tools/webcheck/check.mjs --dir build/webcheck --browser chromium --renderer canvas2d - name: drive the browser verification page (firefox) - run: node tools/webcheck/check.mjs --dir build/webcheck --browser firefox + run: node tools/webcheck/check.mjs --dir build/webcheck --browser firefox --renderer auto - name: drive the browser verification page (webkit) - run: node tools/webcheck/check.mjs --dir build/webcheck --browser webkit + run: node tools/webcheck/check.mjs --dir build/webcheck --browser webkit --renderer auto # The whole test suite except the packages that carry darwin-only files, split # over several runners. .github/scripts/test-packages.sh decides what this diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml index 9536c3a5..327f730a 100644 --- a/.github/workflows/website.yml +++ b/.github/workflows/website.yml @@ -11,8 +11,15 @@ on: - "website/**" - "components/**" - "internal/componentdemo/**" + - "internal/framebuild/**" + - "internal/platform/web/**" + - "internal/previewmeasure/**" + - "internal/render/**" + - "internal/scene/**" + - "internal/webbuild/**" - "tools/docs/**" - "cmd/component-preview/**" + - "cmd/viva/**" - "ui/**" - "app/**" - "text/**" diff --git a/README.md b/README.md index a9c615ff..f8f0f705 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,8 @@ and how to work on the framework rather than with it. ## Scope Viva targets native desktop applications on macOS, Windows, and Linux, and -treats WebAssembly/Canvas2D as a supported web deployment target. Both targets +treats WebAssembly as a supported web deployment target, rendered with WebGL2 +and falling back to Canvas2D when WebGL2 is unavailable. Both targets share components, input, text, focus and accessibility semantics; capabilities the browser does not have are reported through explicit asynchronous APIs and `Capability`, never faked. The web target must not add cost to native builds. @@ -210,8 +211,9 @@ without changing build commands. Unconfigured windows keep the ordinary renderer limits, fallback behavior and the platforms actually verified. Native label renderers draw single-line labels. The browser target runs the same -components on the Canvas2D backend; see [Web deployment](docs/web-deployment.md) -for its capability matrix and hosting requirements. +components on the WebGL2 backend, with Canvas2D as its fallback; see +[Web deployment](docs/web-deployment.md) for its capability matrix and hosting +requirements. ## Run the repository @@ -224,8 +226,9 @@ tools/build_web.sh # viva build --target web, then serves http://127.0 go run ./tools/docs -check # the API and component data the website generates from ``` -The browser build paints the same Go components through the Canvas2D -WebAssembly backend. It is a deployment target, not only a gallery: file +The browser build paints the same Go components through WebGL2, falling back to +the Canvas2D WebAssembly backend when WebGL2 is unavailable or a context is +lost. It is a deployment target, not only a gallery: file pickers, drops, clipboard, notifications, encrypted secret storage and embedded fonts have typed asynchronous APIs. Its visual direction and measured costs are recorded in `docs/benchmarks/m3-gallery-style-darwin-arm64.md`. diff --git a/README.zh-CN.md b/README.zh-CN.md index 33bf0a24..be2b6a3c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -40,7 +40,7 @@ viva dev . # hot reload: save a file, the window updates and keeps its st ## 范围 -Viva 面向 macOS、Windows 和 Linux 上的原生桌面应用,同时把 WebAssembly/Canvas2D 作为正式的 Web 发布目标:两个目标共享组件、输入、文本、焦点和无障碍语义,浏览器缺失的能力通过显式异步 API 和 `Capability` 报告,而不是伪造原生行为。Web 目标不得给原生构建增加成本。iOS、iPadOS、Android、移动端打包,以及以触摸为主的移动运行时,明确不在范围内。不会为了保留假设中的未来移动兼容性而削弱桌面性能与原生集成。 +Viva 面向 macOS、Windows 和 Linux 上的原生桌面应用,同时把 WebAssembly 作为正式的 Web 发布目标:浏览器构建优先使用 WebGL2,WebGL2 不可用时回退 Canvas2D。两个目标共享组件、输入、文本、焦点和无障碍语义,浏览器缺失的能力通过显式异步 API 和 `Capability` 报告,而不是伪造原生行为。Web 目标不得给原生构建增加成本。iOS、iPadOS、Android、移动端打包,以及以触摸为主的移动运行时,明确不在范围内。不会为了保留假设中的未来移动兼容性而削弱桌面性能与原生集成。 三个后端都直接使用操作系统自己的窗口和 GPU API,没有 WebView,也不捆绑渲染运行时。 @@ -83,7 +83,7 @@ Viva 面向 macOS、Windows 和 Linux 上的原生桌面应用,同时把 WebAs Windows 后端支持 amd64 和 arm64 交叉构建,并在 Wine/DXVK 下通过平台测试以及 Gallery 的启动、指针和键盘冒烟测试。平台测试、conformance 场景,以及输入、拖放和设备丢失路径,在一台 Windows 11 虚拟机(WARP)和一台 Debian KDE/X11 机器(lavapipe)上运行;`docs/conformance.md` 记录了需要真实硬件的场景。UI Automation 在一台真实的 Windows 11 机器上由外部客户端检查(见 docs/accessibility.md),AT-SPI 在 KDE/X11 机器上针对 libatspi 检查。Linux 后端通过 Ubuntu arm64 Xvfb/llvmpipe 的 M0 和 Debian amd64 X11/Lavapipe 的保留式场景冒烟测试,包括中英混排文本和局部场景更新。macOS 运行时测试和基准在 arm64 上运行。 -原生标签渲染器绘制单行标签。浏览器目标运行在 Canvas2D 后端;能力矩阵、生命周期与静态托管要求见 [Web 部署](docs/web-deployment.md)。 +原生标签渲染器绘制单行标签。浏览器目标运行在 WebGL2 后端,WebGL2 不可用时回退 Canvas2D;能力矩阵、生命周期与静态托管要求见 [Web 部署](docs/web-deployment.md)。 ## 运行这个仓库 @@ -96,7 +96,7 @@ tools/build_web.sh # viva build --target web,然后服务 http://127 go run ./tools/docs -check # 网站生成的 API 与组件数据 ``` -浏览器构建通过 Canvas2D WebAssembly 后端绘制相同的 Go 组件,并且是正式发布目标:文件选择、拖放、剪贴板、通知、加密密钥存储和内置字体都有类型化的异步 API。视觉方向与测量成本记录在 `docs/benchmarks/m3-gallery-style-darwin-arm64.md`。 +浏览器构建通过 WebGL2(不可用时回退 Canvas2D)WebAssembly 后端绘制相同的 Go 组件,并且是正式发布目标:文件选择、拖放、剪贴板、通知、加密密钥存储和内置字体都有类型化的异步 API。视觉方向与测量成本记录在 `docs/benchmarks/m3-gallery-style-darwin-arm64.md`。 ## 文档网站 diff --git a/app/app.go b/app/app.go index 3bf0e8b1..6e04008d 100644 --- a/app/app.go +++ b/app/app.go @@ -161,6 +161,12 @@ type Config struct { // OnScroll receives normalized pixel deltas and the hovered hit target. // Handled suppresses the window's default canvas scroll offset. OnScroll func(event gfx.ScrollEvent) gfx.EventResult + // ForwardWheel, when set, receives a wheel gesture the application did not + // use, so an embedding page can scroll instead. Setting it makes the page + // own the default scroll: only a gesture the application handled scrolls + // the canvas. It is a browser deployment option and is ignored on native + // platforms. + ForwardWheel func(deltaX, deltaY float32) // OnFileDrop receives files dragged from the system over this window: the // pointer entering and moving with them (FileDropOver), leaving // (FileDropLeave), and the drop. Each event carries the hit under the point; diff --git a/app/driver.go b/app/driver.go index 8e243db9..c2581960 100644 --- a/app/driver.go +++ b/app/driver.go @@ -1195,7 +1195,7 @@ func (driver *Driver) Snapshot() Snapshot { } snapshot.TextWidths[index] = painter.canvas.TextWidthStyle(text.Value, text.Style) } - for _, rectangle := range painter.renderer.Rectangles() { + for _, rectangle := range painter.frame.Rectangles() { primitive := Primitive{ Bounds: gfx.Rect{X: rectangle.Bounds.X, Y: rectangle.Bounds.Y, Width: rectangle.Bounds.Width, Height: rectangle.Bounds.Height}, Color: gfx.Color{Red: rectangle.Color.Red, Green: rectangle.Color.Green, Blue: rectangle.Color.Blue, Alpha: rectangle.Color.Alpha}, @@ -1224,7 +1224,7 @@ func (driver *Driver) Snapshot() Snapshot { } snapshot.Primitives = append(snapshot.Primitives, primitive) } - for _, label := range painter.labels { + for _, label := range painter.frame.Labels() { captured := Label{ Value: label.Value, Bounds: gfx.Rect{X: label.X, Y: label.Y, Width: label.Width, Height: label.Height}, diff --git a/app/driver_test.go b/app/driver_test.go index 109d68ac..160a0f5c 100644 --- a/app/driver_test.go +++ b/app/driver_test.go @@ -11,6 +11,7 @@ import ( "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/framebuild" "github.com/vivaui/viva/text" ) @@ -200,7 +201,7 @@ func TestDriverEditsAFocusedTextFieldThroughTheTextSystem(t *testing.T) { break } } - if fieldText.Bounds == (gfx.Rect{}) || !containsRect(field.Bounds, fieldText.Bounds) { + if fieldText.Bounds == (gfx.Rect{}) || !framebuild.ContainsRect(field.Bounds, fieldText.Bounds) { t.Fatalf("field declared no text line inside its control: %+v", field) } if snapshot.Editor.Bounds != fieldText.Bounds { diff --git a/app/interface_font_test.go b/app/interface_font_test.go index 2e3be3e3..3d75e8bf 100644 --- a/app/interface_font_test.go +++ b/app/interface_font_test.go @@ -143,10 +143,10 @@ func TestAFamilyChangeSendsTheSameTextToTheRendererAgain(t *testing.T) { t.Fatal(err) } generation := func() (interfaceText, fixedPitch uint32) { - if len(painter.labels) != 2 { - t.Fatalf("labels = %+v", painter.labels) + if len(painter.frame.Labels()) != 2 { + t.Fatalf("labels = %+v", painter.frame.Labels()) } - return painter.labels[0].FontGeneration, painter.labels[1].FontGeneration + return painter.frame.Labels()[0].FontGeneration, painter.frame.Labels()[1].FontGeneration } before, _ := generation() frame, err := painter.repaint() diff --git a/app/key_traversal_frame_test.go b/app/key_traversal_frame_test.go index 89b9233f..b0d7f49d 100644 --- a/app/key_traversal_frame_test.go +++ b/app/key_traversal_frame_test.go @@ -47,12 +47,12 @@ func TestContinueTraversalKeyPublishesOneConsistentFrame(t *testing.T) { } painter := newTestPainter(t, &canvas, config) - base := len(painter.renderer.Rectangles()) + base := len(painter.frame.Rectangles()) frame, err := painter.key(platform.KeyEvent{Key: input.KeyTab}) if err != nil { t.Fatal(err) } - count := len(painter.renderer.Rectangles()) + count := len(painter.frame.Rectangles()) if count >= base { t.Fatalf("the popup did not close: %d -> %d", base, count) } @@ -115,12 +115,12 @@ func TestContinueTraversalKeyPublishesOneFrameWhenThePageGrows(t *testing.T) { } painter := newTestPainter(t, &canvas, config) - base := len(painter.renderer.Rectangles()) + base := len(painter.frame.Rectangles()) frame, err := painter.key(platform.KeyEvent{Key: input.KeyTab}) if err != nil { t.Fatal(err) } - count := len(painter.renderer.Rectangles()) + count := len(painter.frame.Rectangles()) if count <= base { t.Fatalf("the page did not grow: %d -> %d", base, count) } diff --git a/app/label_replace_test.go b/app/label_replace_test.go index 6151c1eb..fe64ee72 100644 --- a/app/label_replace_test.go +++ b/app/label_replace_test.go @@ -6,39 +6,6 @@ import ( "github.com/vivaui/viva/gfx" ) -// The memo hands a line that arrives unchanged back as it replaced it, and a -// line whose runs changed — a recolour keeps the value — gets a replacement -// built for the new runs, not the remembered one. -func TestReplaceCellGlyphsMemoFollowsItsInput(t *testing.T) { - painter := &painter{} - value := "┌──┐ ok" - runs := []gfx.TextRun{{Bytes: int32(len(value)), Cells: 6, Color: gfx.Color{Alpha: 1}}} - firstValue, firstRuns := painter.replaceCellGlyphs(value, runs) - if firstValue == value { - t.Fatalf("a line with cell glyphs came back unchanged: %q", firstValue) - } - againValue, againRuns := painter.replaceCellGlyphs(value, runs) - if againValue != firstValue || &againRuns[0] != &firstRuns[0] { - t.Fatal("the same line was replaced again instead of remembered") - } - - recolored := []gfx.TextRun{{Bytes: int32(len(value)), Cells: 6, Color: gfx.Color{Red: 1, Alpha: 1}}} - recValue, recRuns := painter.replaceCellGlyphs(value, recolored) - if recRuns[0].Color != recolored[0].Color { - t.Fatalf("a recoloured line got the remembered colour %+v", recRuns[0].Color) - } - if recValue != firstValue { - t.Fatalf("the replacement text changed with the colour: %q and %q", recValue, firstValue) - } - - plain := "plain line" - plainRuns := []gfx.TextRun{{Bytes: int32(len(plain)), Cells: 10, Color: gfx.Color{Alpha: 1}}} - outValue, outRuns := painter.replaceCellGlyphs(plain, plainRuns) - if outValue != plain || &outRuns[0] != &plainRuns[0] { - t.Fatal("a line without cell glyphs was copied or remembered") - } -} - // A keystroke in a grid-shaped page re-sends every row's label; the rows that // did not change reach the label sync with the same value and runs, and their // cell glyph replacement is remembered rather than rebuilt. diff --git a/app/painter.go b/app/painter.go index 5e2d5ca1..7392667b 100644 --- a/app/painter.go +++ b/app/painter.go @@ -12,11 +12,10 @@ import ( "unsafe" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/framebuild" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/interaction" "github.com/vivaui/viva/internal/platform" - "github.com/vivaui/viva/internal/render" - "github.com/vivaui/viva/internal/scene" "github.com/vivaui/viva/internal/semantic" "github.com/vivaui/viva/keymap" "github.com/vivaui/viva/text" @@ -63,52 +62,22 @@ type painter struct { size gfx.Size focus interaction.Focus pointer interaction.Pointer - graph *scene.Scene - renderer render.Store + frame *framebuild.Builder semantics *semantic.Tree semanticIDs []semantic.ID accessibility []platform.AccessibilityNode lastAccess []platform.AccessibilityNode - changes []scene.Change semanticChanges []semantic.Change - resyncs int // times the renderer had to be rebuilt after a failed batch - reusedHits int // publishes that kept the previous regions and semantics - shapeIDs []scene.ID // one scene node per entry of order, in paint order - labels []platform.TextLabel - lastTexts []gfx.Text - lastRuns []gfx.TextRun // the runs lastTexts refer to, copied out of the application's memory - // lastFontGeneration is the canvas's font generation at the labels last sent: text - // that has not changed still needs sending when the fonts have, so the renderer - // draws it again. - lastFontGeneration uint32 - lastImages []gfx.Image - // labelImage names, for each label of this frame, the image it was drawn - // from (an index into clippedImages, -1 for a text label); lastLabelImage is - // the same for the labels last sent. A bitmap needs its pixels again unless - // the label in its place showed the same picture: the platform hands a - // label its predecessor's texture when both are at the same index and carry - // the same content. - labelImage []int32 - lastLabelImage []int32 - lastTextBefores []uint32 // clippedTextBefores last sent - lastImageBefores []uint32 // clippedImageBefores last sent - views []platform.NativeView // the native views of this publish - lastViews []platform.NativeView // the ones last sent - covers []gfx.Rect // backing of the views' Covers - stateBySlot []instanceState - // layerShift is 1 while the frame has a backdrop, which takes platform layer - // zero; every canvas layer then travels one higher. It is 0 otherwise. - layerShift uint16 - hitScratch []gfx.Hit + reusedHits int // publishes that kept the previous regions and semantics + views []platform.NativeView // the native views of this publish + lastViews []platform.NativeView // the ones last sent + covers []gfx.Rect // backing of the views' Covers + hitScratch []gfx.Hit // publishedHits is the hit list the regions and the semantic tree were last // built from. Comparing it byte for byte (the strings keep the previous // 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 - // cellReplace remembers the font-ready form of lines that hold cell glyphs; - // a frame that changed one row of a grid-shaped page sends every row again, - // and the rows that did not change rebuild no string and runs. - cellReplace []cellReplaceMemo + publishedHits []gfx.Hit publishedFocus gfx.ID publishedTrap gfx.ID publishedInitial gfx.ID @@ -124,20 +93,6 @@ type painter struct { semanticsDirty bool labelNames map[gfx.ID]string labelNamePeak int - clipRects [4]gfx.Rect - clipped []gfx.Rectangle - clippedPaths []gfx.Triangle - clippedSoft []gfx.Shadow - order []shapeRef // clipped, clippedPaths and clippedSoft interleaved in paint order - blocks []gfx.Rectangle // scratch for appendCellGlyphs - strokes []gfx.Triangle // scratch for appendCellGlyphs - clippedTexts []gfx.Text - clippedImages []gfx.Image - // clippedTextBefores and clippedImageBefores are how many shapes the frame - // paints before each of those labels: the place a renderer puts the label - // back among the shapes. - clippedTextBefores []uint32 - clippedImageBefores []uint32 // controls draws the window buttons of a custom titlebar, on platforms where // Viva does; it is nil otherwise. controls *windowControls @@ -196,13 +151,11 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D textInput: config.TextInput, canvas: canvas, size: gfx.Size{Width: float32(config.Width), Height: float32(config.Height)}, - graph: scene.NewWithCapacity(len(canvas.Rectangles()) + len(canvas.Triangles()) + len(canvas.Shadows()) + 1), + frame: framebuild.New(canvas), semantics: semantic.NewWithCapacity("Viva", len(canvas.Hits())+1), semanticIDs: make([]semantic.ID, 0, len(canvas.Hits())+1), accessibility: make([]platform.AccessibilityNode, 0, len(canvas.Hits())+1), lastAccess: make([]platform.AccessibilityNode, 0, len(canvas.Hits())+1), - shapeIDs: make([]scene.ID, 0, len(canvas.Rectangles())+len(canvas.Triangles())+len(canvas.Shadows())), - labels: make([]platform.TextLabel, 0, len(canvas.Texts())+len(canvas.Images())+1), } painter.onTextEvent = painter.applyTextEvent painter.clipboardText = func() string { @@ -234,10 +187,7 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D return nil, err } } - for index := range painter.labels { - painter.labels[index].BitmapUpload = len(painter.labels[index].Bitmap) > 0 - } - painter.saveContent() + painter.frame.MarkInitialBitmapUploads() painter.lastAccess = append(painter.lastAccess[:0], painter.accessibility...) return painter, nil } @@ -986,28 +936,9 @@ func (painter *painter) scheduleIfAnimating() { // publish reconciles the canvas with the scene, router, and label list and // returns the resulting renderer frame. func (painter *painter) publish() (platform.Frame, error) { - painter.applyClipping() - painter.syncShapes() - painter.changes = painter.graph.DrainChanges(painter.changes[:0]) - update, err := painter.renderer.Apply(painter.changes) + frame, err := painter.frame.Build() if err != nil { - // The scene has already absorbed this frame, so the failed batch will - // never be sent again: leaving the store as it is would freeze every - // node it skipped at its old value for good. Rebuild both from the - // canvas instead. - if update, err = painter.resyncRenderer(); err != nil { - return platform.Frame{}, fmt.Errorf("app: render state is inconsistent: %w", err) - } - } - if painter.stampState() && !update.Rebuild { - update = render.Update{Count: len(painter.renderer.Rectangles()), Rebuild: true} - } - - frame := platform.Frame{Update: update, Rectangles: painter.renderer.Rectangles()} - if !painter.sameAsLastContent() { - painter.syncLabels() - painter.saveContent() - frame.TextLabels = painter.labels + return platform.Frame{}, fmt.Errorf("app: render state is inconsistent: %w", err) } if views, changed := painter.syncNativeViews(); changed { @@ -1068,7 +999,7 @@ func (painter *painter) syncNativeViews() ([]platform.NativeView, bool) { } bounds = gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top} } - native := platform.NativeView{ID: uint32(view.ID), Bounds: bounds, Layer: painter.platformLayer(view.Layer)} + native := platform.NativeView{ID: uint32(view.ID), Bounds: bounds, Layer: painter.frame.PlatformLayer(view.Layer)} start := len(painter.covers) painter.covers = painter.coversOf(view.Layer, bounds, painter.covers) native.Covers = painter.covers[start:len(painter.covers):len(painter.covers)] @@ -1118,15 +1049,8 @@ func (painter *painter) trim() { // for a page that stays large, but after a large page is replaced by a // small one the slots are pure retention. Rebuild both from the small // frame instead of carrying the peak for the rest of the session. + painter.frame.Trim() const trimAt, trimRatio = 4096, 4 - if slots := painter.graph.Slots(); slots > trimAt && painter.graph.Len()*trimRatio < slots { - if _, err := painter.resyncRenderer(); err == nil { - painter.stateBySlot = nil - } - // A page the scene rebuilt wholesale shows other lines; its memoized - // replacements are stale retention. - painter.cellReplace = painter.cellReplace[:0] - } if slots := painter.semantics.Slots(); slots > trimAt && painter.semantics.Len()*trimRatio < slots { painter.semantics = semantic.NewWithCapacity("Viva", len(painter.hitScratch)+1) painter.semanticIDs = painter.semanticIDs[:0] @@ -1135,52 +1059,19 @@ func (painter *painter) trim() { } painter.canvas.Trim() painter.focus.Trim() - painter.shapeIDs = trimPainterCapacity(painter.shapeIDs) - painter.labels = trimPainterCapacity(painter.labels) - painter.lastTexts = trimPainterCapacity(painter.lastTexts) - painter.lastRuns = trimPainterCapacity(painter.lastRuns) - painter.lastImages = trimPainterCapacity(painter.lastImages) - painter.labelImage = trimPainterCapacity(painter.labelImage) - painter.lastLabelImage = trimPainterCapacity(painter.lastLabelImage) - painter.hitScratch = trimPainterCapacity(painter.hitScratch) - painter.publishedHits = trimPainterCapacity(painter.publishedHits) - painter.publishedReturns = trimPainterCapacity(painter.publishedReturns) - painter.clipped = trimPainterCapacity(painter.clipped) - painter.clippedPaths = trimPainterCapacity(painter.clippedPaths) - painter.clippedSoft = trimPainterCapacity(painter.clippedSoft) - painter.order = trimPainterCapacity(painter.order) - painter.blocks = trimPainterCapacity(painter.blocks) - painter.strokes = trimPainterCapacity(painter.strokes) - painter.clippedTexts = trimPainterCapacity(painter.clippedTexts) - painter.clippedImages = trimPainterCapacity(painter.clippedImages) - painter.clippedTextBefores = trimPainterCapacity(painter.clippedTextBefores) - painter.clippedImageBefores = trimPainterCapacity(painter.clippedImageBefores) - painter.lastTextBefores = trimPainterCapacity(painter.lastTextBefores) - painter.lastImageBefores = trimPainterCapacity(painter.lastImageBefores) - painter.accessibility = trimPainterCapacity(painter.accessibility) - painter.lastAccess = trimPainterCapacity(painter.lastAccess) - painter.changes = trimPainterCapacity(painter.changes) - painter.semanticChanges = trimPainterCapacity(painter.semanticChanges) - painter.semanticIDs = trimPainterCapacity(painter.semanticIDs) + painter.hitScratch = framebuild.TrimCapacity(painter.hitScratch) + painter.publishedHits = framebuild.TrimCapacity(painter.publishedHits) + painter.publishedReturns = framebuild.TrimCapacity(painter.publishedReturns) + painter.accessibility = framebuild.TrimCapacity(painter.accessibility) + painter.lastAccess = framebuild.TrimCapacity(painter.lastAccess) + painter.semanticChanges = framebuild.TrimCapacity(painter.semanticChanges) + painter.semanticIDs = framebuild.TrimCapacity(painter.semanticIDs) if painter.labelNamePeak > 4096 && len(painter.labelNames)*4 < painter.labelNamePeak { painter.labelNames = nil painter.labelNamePeak = 0 } } -// trimPainterCapacity is trimCapacity for the painter's buffers. The same -// threshold is used so a page that stays near its capacity never reallocates. -func trimPainterCapacity[T any](items []T) []T { - const minCapacity = 4096 - const ratio = 4 - if cap(items) <= minCapacity || len(items)*ratio >= cap(items) { - return items - } - next := make([]T, len(items), max(len(items)*2, minCapacity/64)) - copy(next, items) - return next -} - func (painter *painter) syncCursor() error { next := CursorArrow var image *gfx.CursorImage @@ -1254,18 +1145,6 @@ func cursorFromHit(cursor gfx.PointerCursor) Cursor { } } -// resyncRenderer discards the retained scene and render store and rebuilds -// both from the current canvas, returning the full-rebuild update. -func (painter *painter) resyncRenderer() (render.Update, error) { - painter.resyncs++ - painter.graph = scene.NewWithCapacity(len(painter.clipped) + len(painter.clippedPaths) + len(painter.clippedSoft) + 1) - painter.renderer = render.Store{} - painter.shapeIDs = painter.shapeIDs[:0] - painter.syncShapes() - painter.changes = painter.graph.DrainChanges(painter.changes[:0]) - return painter.renderer.Apply(painter.changes) -} - // focusedTextField describes the focused text field of the last paint, and how // it places its caret when it lays its rows out itself. func (painter *painter) focusedTextField() (TextInputContext, gfx.TextPlacement, int) { @@ -1323,7 +1202,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { } } if transformed, moving := painter.canvas.HitPresenceRect(hitIndex, bounds); moving { - bounds = roundPresenceRect(transformed) + bounds = framebuild.RoundPresenceRect(transformed) } if fontSize == 0 { fontSize = context.FontSize @@ -1343,7 +1222,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { fontSize = gfx.DefaultMetrics().FontSizeM } if bounds.Width <= 0 || bounds.Height <= 0 || - roundPixel(bounds.Width) <= 0 || roundPixel(bounds.Height) <= 0 { + framebuild.RoundPixel(bounds.Width) <= 0 || framebuild.RoundPixel(bounds.Height) <= 0 { return painter.disableTextInput() } var cellWidth, baseline float32 @@ -1363,7 +1242,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { X: bounds.X, Y: bounds.Y, Width: bounds.Width, Height: bounds.Height, FontSize: fontSize, Weight: weight, FontGeneration: painter.canvas.FontGeneration(), - Alignment: alignment, Layer: painter.platformLayer(context.Layer), Multiline: context.Multiline, Secure: context.Secure, Terminal: context.Terminal || context.TypeAhead, + Alignment: alignment, Layer: painter.frame.PlatformLayer(context.Layer), Multiline: context.Multiline, Secure: context.Secure, Terminal: context.Terminal || context.TypeAhead, AltSendsEscape: input.AltSendsEscape, KeyReleases: context.Terminal && input.KeyReleases, DisableIME: input.DisableIME, MonoFace: input.MonoFace, CellWidth: cellWidth, Baseline: baseline, NavigationKeys: input.NavigationKeys || context.NavigationKeys, CopyOverride: input.CopyOverride, @@ -1381,7 +1260,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { native.Placed = true if caret, ok := placement.CaretBounds(); ok { if transformed, moving := painter.canvas.HitPresenceRect(hitIndex, caret); moving { - caret = roundPresenceRect(transformed) + caret = framebuild.RoundPresenceRect(transformed) } native.CaretX, native.CaretY, native.CaretWidth, native.CaretHeight = caret.X, caret.Y, caret.Width, caret.Height } @@ -1524,410 +1403,6 @@ func samePlatformTextInput(left, right platform.TextInput) bool { left.Color == right.Color && left.State == right.State } -// shapeRef names one clipped shape: an entry of painter.clippedPaths when -// triangle is set, of painter.clippedSoft when shadow is set, of painter.clipped -// otherwise. -type shapeRef struct { - index int32 - triangle bool - shadow bool -} - -// applyClipping drops every shape, image and text its canvas clip hides and -// notes, on the others, whether the clip cuts them: a shape left with HasClip -// set is drawn through a scissor rectangle by the renderer, which is how a -// partial shape is cut, so no geometry is cut here. It also merges rectangles, -// triangles, shadows, texts and images back into the order they were painted -// in: each primitive carries the paint order the canvas gave it. -func (painter *painter) applyClipping() { - painter.clipped = painter.clipped[:0] - painter.clippedPaths = painter.clippedPaths[:0] - painter.clippedSoft = painter.clippedSoft[:0] - painter.clippedTexts = painter.clippedTexts[:0] - painter.clippedImages = painter.clippedImages[:0] - painter.clippedTextBefores = painter.clippedTextBefores[:0] - painter.clippedImageBefores = painter.clippedImageBefores[:0] - painter.order = painter.order[:0] - painter.layerShift = 0 - rectangles := painter.canvas.Rectangles() - triangles := painter.canvas.Triangles() - shadows := painter.canvas.Shadows() - texts := painter.canvas.Texts() - images := painter.canvas.Images() - // Walk the five lists as one paint order. A primitive with a smaller Order - // is painted first; on a tie (a border ring shares its backing rectangle's - // order, cell glyphs share their line's) shapes come before images and - // images before text. - ri, ti, si, xi, ii := 0, 0, 0, 0, 0 - for ri < len(rectangles) || ti < len(triangles) || si < len(shadows) || xi < len(texts) || ii < len(images) { - kind, best := 0, ^uint32(0) - if ri < len(rectangles) && rectangles[ri].Order < best { - kind, best = 1, rectangles[ri].Order - } - if ti < len(triangles) && triangles[ti].Order < best { - kind, best = 2, triangles[ti].Order - } - if si < len(shadows) && shadows[si].Order < best { - kind, best = 3, shadows[si].Order - } - if ii < len(images) && images[ii].Order < best { - kind, best = 4, images[ii].Order - } - if xi < len(texts) && texts[xi].Order < best { - kind = 5 - } - switch kind { - case 1: - painter.appendRectangle(rectangles[ri]) - ri++ - case 2: - painter.appendTriangle(triangles[ti]) - ti++ - case 3: - painter.appendShadow(shadows[si]) - si++ - case 4: - painter.appendImage(images[ii]) - ii++ - case 5: - painter.appendText(texts[xi]) - xi++ - } - } -} - -// appendImage adds image to the frame's label list unless its clip hides it or -// it has no area, cutting its source to the visible part. A backdrop is kept -// apart: its layer moves the rest of the frame above it. -func (painter *painter) appendImage(image gfx.Image) { - if roundPixel(image.Bounds.Width) <= 0 || roundPixel(image.Bounds.Height) <= 0 { - return - } - if image.Backdrop { - // A backdrop is beneath every layer, before any shape: it carries no - // place among them. - painter.layerShift = 1 - painter.clippedImages = append(painter.clippedImages, image) - painter.clippedImageBefores = append(painter.clippedImageBefores, 0) - return - } - if !image.HasClip { - painter.clippedImages = append(painter.clippedImages, image) - painter.clippedImageBefores = append(painter.clippedImageBefores, uint32(len(painter.order))) - return - } - visible, ok := intersectVisible(image.Bounds, image.ClipOf) - if !ok { - return - } - if image.DevicePixels { - // The clip may end between device pixels; the picture is cut at one. - scale := painter.canvas.PixelScale() - if visible = deviceBounds(visible, scale); visible.Width <= 0 || visible.Height <= 0 { - return - } - } - if visible != image.Bounds { - sx := image.Source.Width / image.Bounds.Width - sy := image.Source.Height / image.Bounds.Height - image.Source.X += (visible.X - image.Bounds.X) * sx - image.Source.Y += (visible.Y - image.Bounds.Y) * sy - image.Source.Width = visible.Width * sx - image.Source.Height = visible.Height * sy - image.Bounds = visible - if image.DevicePixels { - image.Source = wholePixels(image.Source) - } - } - painter.clippedImages = append(painter.clippedImages, image) - painter.clippedImageBefores = append(painter.clippedImageBefores, uint32(len(painter.order))) -} - -// appendText adds text to the frame's label list and paints the cell glyph -// geometry that belongs to it, unless the text paints nothing. -func (painter *painter) appendText(text gfx.Text) { - // A label with no area or no font size paints nothing, and the native label - // backends require positive values. Transient layouts (a closing drawer, a - // pane squeezed to nothing) can produce one; drop it here rather than failing - // the whole frame. - if roundPixel(text.Bounds.Width) <= 0 || roundPixel(text.Bounds.Height) <= 0 || text.Style.Size <= 0 { - return - } - if text.HasClip && !textClipVisible(text) { - return - } - painter.clippedTexts = append(painter.clippedTexts, text) - if text.RunCount > 0 { - painter.appendCellGlyphs(text) - } - // The cell glyph geometry is part of the line: it is painted before the - // glyphs, so the label comes after the shapes just appended. - painter.clippedTextBefores = append(painter.clippedTextBefores, uint32(len(painter.order))) -} - -// appendShadow puts shadow in the frame's order after cutting it to its clip, -// and drops it when nothing of it is inside. -func (painter *painter) appendShadow(shadow gfx.Shadow) { - if shadow.HasClip { - visible, cut := clipVisibility(shadowBounds(shadow), shadow.ClipOf) - if !visible { - return - } - shadow.HasClip = cut - } - painter.order = append(painter.order, shapeRef{index: int32(len(painter.clippedSoft)), shadow: true}) - painter.clippedSoft = append(painter.clippedSoft, shadow) -} - -// appendCellGlyphs paints the geometry of a fixed-pitch line's cell glyphs — the Block Elements, -// Box Drawing, Braille, the corner shapes of Geometric Shapes, the Powerline separators and the -// Symbols for Legacy Computing — after the canvas's own, as the line's text is drawn after them -// (see gfx.Canvas.CellGlyphGeometry). -func (painter *painter) appendCellGlyphs(text gfx.Text) { - shapes := painter.canvas.CellGlyphGeometry(gfx.CellGlyphShapes{ - Rectangles: painter.blocks[:0], - Triangles: painter.strokes[:0], - }, text) - painter.blocks, painter.strokes = shapes.Rectangles, shapes.Triangles - for _, rectangle := range painter.blocks { - painter.appendRectangle(rectangle) - } - for _, triangle := range painter.strokes { - painter.appendTriangle(triangle) - } -} - -// appendRectangle puts rectangle in the frame's order after cutting it to its clip, and drops it -// when nothing of it is inside. -func (painter *painter) appendRectangle(rectangle gfx.Rectangle) { - if rectangle.HasClip { - visible, cut := clipVisibility(rectangle.Bounds, rectangle.ClipOf) - if !visible { - return - } - rectangle.HasClip = cut - } - painter.order = append(painter.order, shapeRef{index: int32(len(painter.clipped))}) - painter.clipped = append(painter.clipped, rectangle) -} - -// appendTriangle is appendRectangle for the triangles a renderer feathers: their scissor keeps the -// half device pixel the edge reaches past the silhouette. -func (painter *painter) appendTriangle(triangle gfx.Triangle) { - if triangle.HasClip { - bounds := triangleBounds(triangle.Points) - if triangle.EdgeMask != 0 { - half := 0.5 / painter.canvas.PixelScale() - bounds.X -= half - bounds.Y -= half - bounds.Width += 2 * half - bounds.Height += 2 * half - } - visible, cut := clipVisibility(bounds, triangle.ClipOf) - if !visible { - return - } - triangle.HasClip = cut - } - painter.order = append(painter.order, shapeRef{index: int32(len(painter.clippedPaths)), triangle: true}) - painter.clippedPaths = append(painter.clippedPaths, triangle) -} - -// clipVisibility reports whether any of bounds lies inside clip and whether the -// clip cuts it, that is, whether part of bounds lies outside. -func clipVisibility(bounds, clip gfx.Rect) (visible, cut bool) { - if bounds.X+bounds.Width <= clip.X || bounds.Y+bounds.Height <= clip.Y || - bounds.X >= clip.X+clip.Width || bounds.Y >= clip.Y+clip.Height { - return false, false - } - return true, !containsRect(clip, bounds) -} - -// shadowBounds is the region a shadow paints in: the rectangle that casts it -// grown by how far its blur, spread and offset reach. -func shadowBounds(shadow gfx.Shadow) gfx.Rect { - extent := shadow.Style.Extent() - return gfx.Rect{ - X: shadow.Bounds.X - extent, Y: shadow.Bounds.Y - extent, - Width: shadow.Bounds.Width + 2*extent, Height: shadow.Bounds.Height + 2*extent, - } -} - -func triangleBounds(points [3]gfx.Point) gfx.Rect { - left := min32(points[0].X, min32(points[1].X, points[2].X)) - top := min32(points[0].Y, min32(points[1].Y, points[2].Y)) - right := max32(points[0].X, max32(points[1].X, points[2].X)) - bottom := max32(points[0].Y, max32(points[1].Y, points[2].Y)) - return gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top} -} - -func quadBounds(points [4]gfx.Point) gfx.Rect { - left := min32(min32(points[0].X, points[1].X), min32(points[2].X, points[3].X)) - top := min32(min32(points[0].Y, points[1].Y), min32(points[2].Y, points[3].Y)) - right := max32(max32(points[0].X, points[1].X), max32(points[2].X, points[3].X)) - bottom := max32(max32(points[0].Y, points[1].Y), max32(points[2].Y, points[3].Y)) - return gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top} -} - -func textClipVisible(text gfx.Text) bool { - _, visible := intersectVisible(text.Bounds, text.ClipOf) - if text.HasQuad { - _, warped := intersectVisible(quadBounds(text.Quad), text.ClipOf) - visible = visible || warped - } - return visible -} - -func textClipCuts(text gfx.Text) bool { - return !containsRect(text.ClipOf, text.Bounds) || - text.HasQuad && !containsRect(text.ClipOf, quadBounds(text.Quad)) -} - -func intersectVisible(bounds, clip gfx.Rect) (gfx.Rect, bool) { - left := max32(bounds.X, clip.X) - top := max32(bounds.Y, clip.Y) - right := min32(bounds.X+bounds.Width, clip.X+clip.Width) - bottom := min32(bounds.Y+bounds.Height, clip.Y+clip.Height) - if right <= left || bottom <= top { - return gfx.Rect{}, false - } - return gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top}, true -} - -func max32(a, b float32) float32 { - if a > b { - return a - } - return b -} - -func min32(a, b float32) float32 { - if a < b { - return a - } - return b -} - -// drawnBy reports whether a stored instance already draws a clipped shape. -// Both sides are compared field by field, as the scene stores them. -func (painter *painter) drawnBy(stored *render.Rectangle, ref shapeRef) bool { - if ref.triangle { - triangle := &painter.clippedPaths[ref.index] - return stored.Kind == scene.KindTriangle && stored.Color == scene.Color(triangle.Color) && - stored.EdgeMask == triangle.EdgeMask && stored.Shade == sceneShade(*triangle) && - stored.Points[0] == scene.Point(triangle.Points[0]) && - stored.Points[1] == scene.Point(triangle.Points[1]) && - stored.Points[2] == scene.Point(triangle.Points[2]) - } - if ref.shadow { - shadow := &painter.clippedSoft[ref.index] - return stored.Kind == scene.KindShadow && stored.Radius == shadow.Radius && - stored.Color == scene.Color(shadow.Color) && stored.Bounds == scene.Rect(shadow.Bounds) && - stored.Shadow == scene.Shadow(shadow.Style) - } - rectangle := &painter.clipped[ref.index] - return stored.Kind == scene.KindRectangle && stored.Radius == rectangle.Radius && - stored.Color == scene.Color(rectangle.Color) && stored.Bounds == scene.Rect(rectangle.Bounds) -} - -// syncShapes aligns the scene's nodes with the clipped shapes, rectangles and -// triangles together in paint order, so the render store, which paints in node -// order, always equals the canvas. -// -// A repaint usually changes one stretch of the shapes: a highlight appears, a -// tab closes, a page swaps. The shapes before and after that stretch are left -// alone; inside it the nodes are rewritten in place (a node that held a -// rectangle may become a triangle and keeps its place), and the difference in -// length is inserted or removed at the end of the stretch. Cost follows the -// size of the change, not of the page, and no node is ever painted out of -// order. -func (painter *painter) syncShapes() { - root := painter.graph.Root() - stored := painter.renderer.Rectangles() // what the previous frame painted - oldCount, newCount := len(painter.shapeIDs), len(painter.order) - if len(stored) != oldCount { - // Not reachable while the store follows the scene; if it ever does not, - // rewrite every node rather than trust the comparison below. - stored = nil - } - - prefix := 0 - for prefix < min(len(stored), newCount) && painter.drawnBy(&stored[prefix], painter.order[prefix]) { - prefix++ - } - suffix := 0 - for suffix < min(oldCount, newCount)-prefix && len(stored) == oldCount && - painter.drawnBy(&stored[oldCount-1-suffix], painter.order[newCount-1-suffix]) { - suffix++ - } - oldMiddle, newMiddle := oldCount-prefix-suffix, newCount-prefix-suffix - - for index := prefix; index < prefix+min(oldMiddle, newMiddle); index++ { - painter.setShape(painter.shapeIDs[index], painter.order[index]) - } - switch { - case newMiddle > oldMiddle: - at := prefix + oldMiddle - add := newMiddle - oldMiddle - var previous scene.ID - if at > 0 { - previous = painter.shapeIDs[at-1] - } - for range add { - painter.shapeIDs = append(painter.shapeIDs, 0) - } - copy(painter.shapeIDs[at+add:], painter.shapeIDs[at:oldCount]) - for index := at; index < at+add; index++ { - previous = painter.insertShape(root, previous, painter.order[index]) - painter.shapeIDs[index] = previous - } - case oldMiddle > newMiddle: - from := prefix + newMiddle - for _, id := range painter.shapeIDs[from : prefix+oldMiddle] { - painter.graph.Remove(id) - } - painter.shapeIDs = slices.Delete(painter.shapeIDs, from, prefix+oldMiddle) - } -} - -// setShape makes an existing node draw a shape, whatever it drew before. -func (painter *painter) setShape(id scene.ID, ref shapeRef) { - if ref.triangle { - value := sceneTriangle(painter.clippedPaths[ref.index]) - painter.graph.SetTriangle(id, value.Points, value.Color, value.EdgeMask, value.Shade) - return - } - if ref.shadow { - shadow := &painter.clippedSoft[ref.index] - painter.graph.SetShadow(id, scene.Rect(shadow.Bounds), scene.Color(shadow.Color), shadow.Radius, scene.Shadow(shadow.Style)) - return - } - painter.setRectangle(id, painter.clipped[ref.index]) -} - -// insertShape adds a node drawing a shape right after previous. -func (painter *painter) insertShape(root, previous scene.ID, ref shapeRef) scene.ID { - if ref.triangle { - value := sceneTriangle(painter.clippedPaths[ref.index]) - id, _ := painter.graph.InsertTriangle(root, previous, value.Points, value.Color, value.EdgeMask, value.Shade) - return id - } - if ref.shadow { - shadow := &painter.clippedSoft[ref.index] - id, _ := painter.graph.InsertShadow(root, previous, scene.Rect(shadow.Bounds), scene.Color(shadow.Color), shadow.Radius, scene.Shadow(shadow.Style)) - return id - } - rectangle := painter.clipped[ref.index] - value := sceneRectangle(rectangle) - id, _ := painter.graph.InsertRoundedRectangle(root, previous, value.Bounds, value.Color, rectangle.Radius) - return id -} - -func (painter *painter) setRectangle(id scene.ID, rectangle gfx.Rectangle) { - value := sceneRectangle(rectangle) - painter.graph.SetRoundedRectangle(id, value.Bounds, value.Color, rectangle.Radius) -} - // hitStructuresUnchanged reports whether the paint produced exactly the input // the semantic tree and the accessibility payload were last built from, so both // can be kept. It compares every field those structures read, plus the focus, @@ -2336,463 +1811,6 @@ func semanticRole(role gfx.Role) semantic.Role { } } -// syncLabels rebuilds the label list. A bitmap label carries its pixels across -// the native boundary only when that bitmap is not exactly what the same place -// in the previous frame showed, so a picture made of many bitmaps (see -// gfx.Surface) stages just the ones that changed. -func (painter *painter) syncLabels() { - painter.labels = painter.labels[:0] - painter.labelImage = painter.labelImage[:0] - images := painter.clippedImages - texts := painter.clippedTexts - fontGeneration := painter.canvas.FontGeneration() - // Images and texts are each in paint order; merge them back into one order, - // because a label and a bitmap are both platform text labels. A backdrop is - // beneath everything whatever its own paint order, so it goes first. Each - // label carries how many shapes the frame painted before it, which is where - // the renderers put it back among them. - for ii := range images { - if images[ii].Backdrop { - painter.appendImageLabel(ii, painter.clippedImageBefores[ii]) - } - } - for ii, ti := 0, 0; ii < len(images) || ti < len(texts); { - for ii < len(images) && images[ii].Backdrop { - ii++ - } - if ti >= len(texts) || (ii < len(images) && images[ii].Order <= texts[ti].Order) { - painter.appendImageLabel(ii, painter.clippedImageBefores[ii]) - ii++ - continue - } - painter.appendTextLabel(texts[ti], fontGeneration, painter.clippedTextBefores[ti]) - ti++ - } -} - -// appendImageLabel adds image number index of painter.clippedImages to the -// frame's labels, after shapesBefore shapes. -func (painter *painter) appendImageLabel(index int, shapesBefore uint32) { - image := painter.clippedImages[index] - bitmap := image.Bitmap - left := max(int(image.Source.X), 0) - top := max(int(image.Source.Y), 0) - right := min(int(math.Ceil(float64(image.Source.X+image.Source.Width))), bitmap.Width) - bottom := min(int(math.Ceil(float64(image.Source.Y+image.Source.Height))), bitmap.Height) - if left >= right || top >= bottom { - return - } - offset := top*bitmap.Stride + left*4 - length := (bottom-top-1)*bitmap.Stride + (right-left)*4 - if offset < 0 || length <= 0 || offset > len(bitmap.Pix) || length > len(bitmap.Pix)-offset { - return - } - width := roundPixel(image.Bounds.Width) - height := roundPixel(image.Bounds.Height) - if width <= 0 || height <= 0 { - return - } - layer := painter.platformLayer(image.Layer) - if image.Backdrop { - layer = 0 - } - // Rounded to logical pixels, unless the image is laid out in device pixels. - x, y, w, h := float32(roundPosition(image.Bounds.X)), float32(roundPosition(image.Bounds.Y)), float32(width), float32(height) - if image.DevicePixels { - x, y, w, h = image.Bounds.X, image.Bounds.Y, image.Bounds.Width, image.Bounds.Height - } - painter.labels = append(painter.labels, platform.TextLabel{ - X: x, Y: y, - Width: w, Height: h, - Layer: layer, - ShapesBefore: shapesBefore, - Bitmap: bitmap.Pix[offset : offset+length], BitmapWidth: right - left, BitmapHeight: bottom - top, - BitmapStride: bitmap.Stride, BitmapID: bitmap.ID, BitmapVersion: bitmap.Version, - BitmapUpload: painter.bitmapUpload(image, index), - }) - painter.labelImage = append(painter.labelImage, int32(index)) -} - -// bitmapUpload reports whether image number index must carry its pixels to the -// platform. It may omit them only when the label it is about to become showed -// the same picture in the frame last sent: the platform then reuses that -// label's texture. Another draw of the same bitmap elsewhere is no substitute, -// because the platform decides which label takes which old texture by position -// first. -func (painter *painter) bitmapUpload(image gfx.Image, index int) bool { - label := len(painter.labels) - if image.Bitmap.ID == 0 || label >= len(painter.lastLabelImage) { - return true - } - previous := int(painter.lastLabelImage[label]) - if previous < 0 || previous >= len(painter.lastImages) { - return true - } - return !sameImageBitmap(image, painter.lastImages[previous]) -} - -// appendTextLabel adds one canvas text to the frame's labels. -func (painter *painter) appendTextLabel(label gfx.Text, fontGeneration uint32, shapesBefore uint32) { - width := roundPixel(label.Bounds.Width) - height := roundPixel(label.Bounds.Height) - if width <= 0 || height <= 0 { - return - } - // Integer logical-pixel bounds keep the texture exactly one texel per - // physical pixel so linear sampling stays crisp on scaled displays. - entry := platform.TextLabel{ - Value: label.Value, - Identity: label.Identity, - X: float32(roundPosition(label.Bounds.X)), Y: float32(roundPosition(label.Bounds.Y)), - Width: float32(width), Height: float32(height), - OriginX: roundingRemainder(label.Bounds.X), OriginY: roundingRemainder(label.Bounds.Y), - FontSize: label.Style.Size, Weight: label.Style.Weight, Italic: label.Style.Italic, - Color: platform.Color{ - Red: float64(label.Style.Color.Red), Green: float64(label.Style.Color.Green), - Blue: float64(label.Style.Color.Blue), Alpha: float64(label.Style.Color.Alpha), - }, - Layer: painter.platformLayer(label.Layer), - ShapesBefore: shapesBefore, - Mono: label.Style.Mono, MonoFace: label.Style.MonoFace, CellWidth: label.CellWidth, Baseline: label.Baseline, Runs: painter.canvas.TextRuns(label), - } - if !label.Style.Mono && label.RunCount == 0 { - // Only text in the interface font follows its generation. - entry.FontGeneration = fontGeneration - } - if label.RunCount > 0 { - // The font does not draw the cell glyphs; appendCellGlyphs did. - entry.Value, entry.Runs = painter.replaceCellGlyphs(entry.Value, entry.Runs) - } - if label.HasClip { - if textClipCuts(label) { - // The clip cuts the label partway: the renderers scissor to it. - entry.Clip, entry.Clipped = label.ClipOf, true - } - } - if label.HasQuad { - // A warped line keeps its rasterisation box and moves only where the - // picture lands, so the platform draws the same texture as a quad. - entry.Quad, entry.HasQuad = label.Quad, true - for corner, tint := range label.Tint { - entry.Tint[corner] = platform.Color{ - Red: float64(tint.Red), Green: float64(tint.Green), - Blue: float64(tint.Blue), Alpha: float64(tint.Alpha), - } - } - } - painter.labels = append(painter.labels, entry) - painter.labelImage = append(painter.labelImage, -1) -} - -// cellReplaceLimit bounds the memoized cell glyph replacements: a screen holds -// its grid's rows and a little slack, and past the limit the memo starts over -// rather than keeping every line a session ever showed. -const cellReplaceLimit = 256 - -// cellReplaceMemo is one line's font-ready form: out is what ReplaceCellGlyphs -// built for in, kept while the same value and runs keep arriving. -type cellReplaceMemo struct { - inValue, outValue string - inRuns, outRuns []gfx.TextRun -} - -// replaceCellGlyphs is gfx.ReplaceCellGlyphs with a memory. A label sync that -// one changed row opened sends every row again; the rows that kept their value -// and runs get the replacement they already have instead of a fresh copy of the -// line and its runs, which is most of the garbage a keystroke in a bordered -// grid page otherwise makes. -func (painter *painter) replaceCellGlyphs(value string, runs []gfx.TextRun) (string, []gfx.TextRun) { - for i := range painter.cellReplace { - if memo := &painter.cellReplace[i]; memo.inValue == value && slices.Equal(memo.inRuns, runs) { - return memo.outValue, memo.outRuns - } - } - outValue, outRuns := gfx.ReplaceCellGlyphs(value, runs) - // A line without cell glyphs comes back as it went in; it has nothing to - // remember, and its runs are the caller's own slice. - if len(outRuns) == 0 || len(runs) == 0 || &outRuns[0] == &runs[0] { - return outValue, outRuns - } - if len(painter.cellReplace) >= cellReplaceLimit { - painter.cellReplace = painter.cellReplace[:0] - } - painter.cellReplace = append(painter.cellReplace, cellReplaceMemo{ - inValue: value, inRuns: append([]gfx.TextRun(nil), runs...), - outValue: outValue, outRuns: outRuns, - }) - return outValue, outRuns -} - -// deviceBounds rounds the edges of bounds to whole device pixels of scale. -func deviceBounds(bounds gfx.Rect, scale float32) gfx.Rect { - edge := func(value float32) float32 { return float32(math.Floor(float64(value)*float64(scale) + 0.5)) } - left, top := edge(bounds.X), edge(bounds.Y) - right, bottom := edge(bounds.X+bounds.Width), edge(bounds.Y+bounds.Height) - return gfx.Rect{X: left / scale, Y: top / scale, Width: (right - left) / scale, Height: (bottom - top) / scale} -} - -// wholePixels rounds the edges of a bitmap region to whole bitmap pixels. -func wholePixels(region gfx.Rect) gfx.Rect { - left, top := math.Floor(float64(region.X)+0.5), math.Floor(float64(region.Y)+0.5) - right, bottom := math.Floor(float64(region.X+region.Width)+0.5), math.Floor(float64(region.Y+region.Height)+0.5) - return gfx.Rect{X: float32(left), Y: float32(top), Width: float32(right - left), Height: float32(bottom - top)} -} - -// containsRect reports whether inner lies wholly inside outer. -func containsRect(outer, inner gfx.Rect) bool { - return inner.X >= outer.X && inner.Y >= outer.Y && - inner.X+inner.Width <= outer.X+outer.Width && inner.Y+inner.Height <= outer.Y+outer.Height -} - -// roundingRemainder is what roundPosition took off value: the sub-pixel position -// backends that place text at device pixels draw it at (platform.TextLabel.OriginX). -func roundingRemainder(value float32) float32 { - return value - float32(roundPosition(value)) -} - -func roundPixel(value float32) int32 { - if value < 0 { - return 0 - } - return int32(value + 0.5) -} - -// roundPosition rounds a coordinate to the nearest logical pixel. Unlike a -// size, a position may be negative: a leaving drawer and its text move past the -// window edge together, and clamping either to zero would stop it at the edge. -func roundPosition(value float32) int32 { - return int32(math.Floor(float64(value) + 0.5)) -} - -// roundPresenceRect puts a native overlay on the same whole logical pixels as -// the moving label it covers. Presence rounds a text label's origin so its -// texture is not rebuilt every frame; the platform editor next to it has to -// land on the same pixel. -func roundPresenceRect(rect gfx.Rect) gfx.Rect { - return gfx.Rect{ - X: float32(roundPosition(rect.X)), Y: float32(roundPosition(rect.Y)), - Width: float32(roundPixel(rect.Width)), Height: float32(roundPixel(rect.Height)), - } -} - -func sceneRectangle(rectangle gfx.Rectangle) render.Rectangle { - return render.Rectangle{ - Kind: scene.KindRectangle, - Bounds: scene.Rect{ - X: rectangle.Bounds.X, Y: rectangle.Bounds.Y, - Width: rectangle.Bounds.Width, Height: rectangle.Bounds.Height, - }, - Color: scene.Color{ - Red: rectangle.Color.Red, Green: rectangle.Color.Green, - Blue: rectangle.Color.Blue, Alpha: rectangle.Color.Alpha, - }, - Radius: rectangle.Radius, - Layer: rectangle.Layer, - } -} - -func sceneTriangle(triangle gfx.Triangle) render.Rectangle { - return render.Rectangle{ - Kind: scene.KindTriangle, - Points: [3]scene.Point{ - {X: triangle.Points[0].X, Y: triangle.Points[0].Y}, - {X: triangle.Points[1].X, Y: triangle.Points[1].Y}, - {X: triangle.Points[2].X, Y: triangle.Points[2].Y}, - }, - EdgeMask: triangle.EdgeMask, - Color: scene.Color{ - Red: triangle.Color.Red, Green: triangle.Color.Green, - Blue: triangle.Color.Blue, Alpha: triangle.Color.Alpha, - }, - Shade: sceneShade(triangle), - Layer: triangle.Layer, - } -} - -// sceneShade is the vertex colors of a shaded triangle, and the zero Shade for a -// flat one, whatever stale colors its Shade array holds. -func sceneShade(triangle gfx.Triangle) scene.Shade { - if !triangle.Shaded { - return scene.Shade{} - } - return scene.Shade{On: true, Colors: [2]scene.Color{scene.Color(triangle.Shade[0]), scene.Color(triangle.Shade[1])}} -} - -// instanceState is what a render instance knows about its place on screen that -// the scene does not carry: the layer it composes in and the clip that cuts it. -type instanceState struct { - layer uint16 - clipped bool - clip scene.Rect -} - -// stampState copies each primitive's canvas layer and clip onto its render -// instance and reports whether either changed anywhere, which a partial update -// would not carry to the GPU. Instances are listed by the scene's tree order, -// which syncShapes keeps equal to paint order, so the shape at index i is the -// instance at index i; should the store ever disagree, the state travels with -// the node's storage slot instead. -func (painter *painter) stampState() (changed bool) { - instances := painter.renderer.Rectangles() - if len(instances) != len(painter.shapeIDs) { - return painter.stampBySlot() - } - for index, id := range painter.shapeIDs { - instance := &instances[index] - if instance.ID != id { - return painter.stampBySlot() - } - state := painter.shapeState(painter.order[index]) - if instance.Layer != state.layer || instance.Clipped != state.clipped || instance.Clip != state.clip { - instance.Layer, instance.Clipped, instance.Clip = state.layer, state.clipped, state.clip - changed = true - } - } - return changed -} - -// stampBySlot is stampState for a store whose order is not the paint order. -func (painter *painter) stampBySlot() (changed bool) { - for index, id := range painter.shapeIDs { - slot, ok := id.Slot() - if !ok { - continue - } - for int(slot) >= len(painter.stateBySlot) { - painter.stateBySlot = append(painter.stateBySlot, instanceState{}) - } - painter.stateBySlot[slot] = painter.shapeState(painter.order[index]) - } - instances := painter.renderer.Rectangles() - for index := range instances { - slot, _ := instances[index].ID.Slot() - state := painter.stateBySlot[slot] - if instances[index].Layer != state.layer || instances[index].Clipped != state.clipped || instances[index].Clip != state.clip { - instances[index].Layer, instances[index].Clipped, instances[index].Clip = state.layer, state.clipped, state.clip - changed = true - } - } - return changed -} - -// shapeState is the layer and clip the platform draws a shape with. -func (painter *painter) shapeState(ref shapeRef) instanceState { - var state instanceState - if ref.shadow { - shadow := &painter.clippedSoft[ref.index] - state = instanceState{layer: shadow.Layer, clipped: shadow.HasClip} - if shadow.HasClip { - state.clip = scene.Rect(shadow.ClipOf) - } - } else if ref.triangle { - triangle := &painter.clippedPaths[ref.index] - state = instanceState{layer: triangle.Layer, clipped: triangle.HasClip} - if triangle.HasClip { - state.clip = scene.Rect(triangle.ClipOf) - } - } else { - rectangle := &painter.clipped[ref.index] - state = instanceState{layer: rectangle.Layer, clipped: rectangle.HasClip} - if rectangle.HasClip { - state.clip = scene.Rect(rectangle.ClipOf) - } - } - state.layer = painter.platformLayer(state.layer) - return state -} - -// platformLayer is the layer a canvas layer takes on the platform. The topmost -// layer stays topmost. -func (painter *painter) platformLayer(layer uint16) uint16 { - if painter.layerShift == 0 || layer == math.MaxUint16 { - return layer - } - return layer + painter.layerShift -} - -// sameAsLastTexts reports whether the texts to draw are exactly those last -// sent to the platform. -func (painter *painter) sameAsLastContent() bool { - if painter.canvas.FontGeneration() != painter.lastFontGeneration || !sameImages(painter.clippedImages, painter.lastImages) { - return false - } - // A label's place among the shapes can move while the label itself does - // not: a shape before it can drop out of the clip, or paint nothing, and - // then the renderers must be told where the label goes. - if !slices.Equal(painter.clippedTextBefores, painter.lastTextBefores) || - !slices.Equal(painter.clippedImageBefores, painter.lastImageBefores) { - return false - } - left, right := painter.clippedTexts, painter.lastTexts - if len(left) != len(right) { - return false - } - for index := range left { - a, b := left[index], right[index] - if a.Value != b.Value || a.Style != b.Style || a.Identity != b.Identity || a.Layer != b.Layer || a.Order != b.Order { - return false - } - if a.Bounds != b.Bounds || a.CellWidth != b.CellWidth || a.Baseline != b.Baseline || a.RunCount != b.RunCount { - return false - } - if a.HasClip != b.HasClip || a.HasClip && a.ClipOf != b.ClipOf { - return false - } - // Where a warped line lands changes every frame of an animation while - // its picture stays the same: the platform must still see the new quad. - if a.HasQuad != b.HasQuad { - return false - } - if a.HasQuad && (a.Quad != b.Quad || a.Tint != b.Tint) { - return false - } - if a.RunCount == 0 { - continue - } - current := painter.canvas.TextRuns(a) - if len(current) != int(a.RunCount) || b.RunFirst < 0 || b.RunCount < 0 || int(b.RunFirst+b.RunCount) > len(painter.lastRuns) { - return false - } - saved := painter.lastRuns[b.RunFirst : b.RunFirst+b.RunCount] - for run := range current { - if current[run] != saved[run] { - return false - } - } - } - return true -} - -func sameImages(left, right []gfx.Image) bool { - if len(left) != len(right) { - return false - } - for index := range left { - a, b := left[index], right[index] - if a.Bounds != b.Bounds || a.Source != b.Source || a.Layer != b.Layer || a.Order != b.Order || a.Backdrop != b.Backdrop || a.Bitmap.Width != b.Bitmap.Width || - a.Bitmap.Height != b.Bitmap.Height || a.Bitmap.Stride != b.Bitmap.Stride || a.Bitmap.ID != b.Bitmap.ID || - a.Bitmap.Version != b.Bitmap.Version || len(a.Bitmap.Pix) != len(b.Bitmap.Pix) { - return false - } - if len(a.Bitmap.Pix) > 0 && &a.Bitmap.Pix[0] != &b.Bitmap.Pix[0] { - return false - } - } - return true -} - -// sameImageBitmap reports whether two draws show the very same pixels: the same -// identity and version, source region and storage. A bitmap with no identity -// (ID 0) is never the same: nothing says its pixels did not change. -func sameImageBitmap(a, b gfx.Image) bool { - if a.Source != b.Source || a.Bitmap.Width != b.Bitmap.Width || a.Bitmap.Height != b.Bitmap.Height || - a.Bitmap.Stride != b.Bitmap.Stride || a.Bitmap.ID != b.Bitmap.ID || a.Bitmap.Version != b.Bitmap.Version || - len(a.Bitmap.Pix) != len(b.Bitmap.Pix) || a.Bitmap.ID == 0 { - return false - } - return len(a.Bitmap.Pix) == 0 || &a.Bitmap.Pix[0] == &b.Bitmap.Pix[0] -} - func sameAccessibility(left, right []platform.AccessibilityNode) bool { if len(left) != len(right) { return false @@ -2805,24 +1823,6 @@ func sameAccessibility(left, right []platform.AccessibilityNode) bool { return true } -// saveTexts remembers this frame's texts for the next comparison. Their runs -// live in the canvas, which is rewritten by the next paint, so they are copied. -func (painter *painter) saveContent() { - painter.lastFontGeneration = painter.canvas.FontGeneration() - painter.lastImages = append(painter.lastImages[:0], painter.clippedImages...) - painter.lastLabelImage = append(painter.lastLabelImage[:0], painter.labelImage...) - painter.lastTexts = append(painter.lastTexts[:0], painter.clippedTexts...) - painter.lastTextBefores = append(painter.lastTextBefores[:0], painter.clippedTextBefores...) - painter.lastImageBefores = append(painter.lastImageBefores[:0], painter.clippedImageBefores...) - painter.lastRuns = painter.lastRuns[:0] - for index := range painter.lastTexts { - text := &painter.lastTexts[index] - runs := painter.canvas.TextRuns(*text) - text.RunFirst = int32(len(painter.lastRuns)) - painter.lastRuns = append(painter.lastRuns, runs...) - } -} - // windowActions makes the set of operations the window buttons need, for the // platform adapter to fill, or nil when the system draws the buttons. func (painter *painter) windowActions() *platform.WindowActions { diff --git a/app/painter_bitmap_test.go b/app/painter_bitmap_test.go index 376c6124..407ccd40 100644 --- a/app/painter_bitmap_test.go +++ b/app/painter_bitmap_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/framebuild" "github.com/vivaui/viva/internal/platform" ) @@ -25,10 +26,10 @@ func TestBitmapPaintIsRetainedAndClippedWithoutPixelCopies(t *testing.T) { if err != nil { t.Fatal(err) } - if len(painter.labels) != 2 || !painter.labels[0].BitmapUpload { - t.Fatalf("labels = %+v", painter.labels) + if len(painter.frame.Labels()) != 2 || !painter.frame.Labels()[0].BitmapUpload { + t.Fatalf("labels = %+v", painter.frame.Labels()) } - label := painter.labels[0] + label := painter.frame.Labels()[0] if label.X != 10 || label.Y != 10 || label.Width != 20 || label.Height != 20 || label.BitmapWidth != 2 || label.BitmapHeight != 2 { t.Fatalf("clipped bitmap label = %+v", label) } @@ -89,8 +90,8 @@ func TestBitmapPixelsFollowTheLabelAndNotThePictureOrder(t *testing.T) { if _, err := painter.repaint(); err != nil { t.Fatal(err) } - previous := append([]int32(nil), painter.lastLabelImage...) - previousImages := append([]gfx.Image(nil), painter.lastImages...) + previous := append([]int32(nil), painter.frame.LastLabelImages()...) + previousImages := append([]gfx.Image(nil), painter.frame.LastImages()...) // The icon is gone and the page's copy is whole again: both pictures move up // one image place, while the labels keep the places the text gives them. showIcon = false @@ -102,14 +103,14 @@ func TestBitmapPixelsFollowTheLabelAndNotThePictureOrder(t *testing.T) { if frame.TextLabels == nil { t.Fatal("the clipped picture changed but no labels were sent") } - current := append([]int32(nil), painter.labelImage...) - currentImages := append([]gfx.Image(nil), painter.clippedImages...) + current := append([]int32(nil), painter.frame.LabelImages()...) + currentImages := append([]gfx.Image(nil), painter.frame.ClippedImages()...) for index, label := range frame.TextLabels { if len(label.Bitmap) == 0 || label.BitmapUpload { continue } if index >= len(previous) || previous[index] < 0 || int(previous[index]) >= len(previousImages) || - !sameImageBitmap(currentImages[current[index]], previousImages[previous[index]]) { + !framebuild.SameImageBitmap(currentImages[current[index]], previousImages[previous[index]]) { t.Fatalf("label %d at %v,%v omits its pixels though the label in its place showed no such picture", index, label.X, label.Y) } @@ -155,7 +156,7 @@ func TestInitialBitmapUploadAfterPreparationPaint(test *testing.T) { test.Fatal(err) } found := false - for _, label := range painter.labels { + for _, label := range painter.frame.Labels() { if label.BitmapID == bitmap.ID { found = true if !label.BitmapUpload { @@ -242,10 +243,10 @@ func TestBackdropIsBeneathEveryLayerAndShiftsThemOnlyWhilePresent(t *testing.T) t.Fatal(err) } layers := func() (rectangles, labels []uint16) { - for _, rectangle := range painter.renderer.Rectangles() { + for _, rectangle := range painter.frame.Rectangles() { rectangles = append(rectangles, rectangle.Layer) } - for _, label := range painter.labels { + for _, label := range painter.frame.Labels() { labels = append(labels, label.Layer) } return @@ -254,8 +255,8 @@ func TestBackdropIsBeneathEveryLayerAndShiftsThemOnlyWhilePresent(t *testing.T) if !slices.Equal(rectangles, []uint16{1, 601, math.MaxUint16}) || !slices.Equal(labels, []uint16{0, 1}) { t.Fatalf("with a backdrop: rectangles %v, labels %v", rectangles, labels) } - if painter.labels[0].BitmapID != 7 || painter.labels[0].BitmapWidth != 4 { - t.Fatalf("backdrop label = %+v", painter.labels[0]) + if painter.frame.Labels()[0].BitmapID != 7 || painter.frame.Labels()[0].BitmapWidth != 4 { + t.Fatalf("backdrop label = %+v", painter.frame.Labels()[0]) } backdrop = false @@ -324,7 +325,7 @@ func TestOnlyChangedBitmapsCrossTheNativeBoundary(t *testing.T) { } return count } - if got := uploads(painter.labels); got != 6 { + if got := uploads(painter.frame.Labels()); got != 6 { t.Fatalf("first frame uploads %d bitmaps, want all 6", got) } // A patch inside the first tile: one upload, the other five stay on the GPU. @@ -373,7 +374,7 @@ func TestDevicePixelBitmapsKeepTheirDevicePixelsAtFractionalScales(t *testing.T) t.Fatal(err) } covered := 0 - for _, label := range painter.labels { + for _, label := range painter.frame.Labels() { if len(label.Bitmap) == 0 { continue } diff --git a/app/painter_leak_test.go b/app/painter_leak_test.go index caf5898a..dfd64cb6 100644 --- a/app/painter_leak_test.go +++ b/app/painter_leak_test.go @@ -34,20 +34,20 @@ func TestAPageThatIsRemovedLeavesNothingRetained(t *testing.T) { } settle(0) - scenes, semantics, rectangles := painter.graph.Len(), painter.semantics.Len(), len(painter.renderer.Rectangles()) + scenes, semantics, rectangles := painter.frame.Graph().Len(), painter.semantics.Len(), len(painter.frame.Rectangles()) for round := 0; round < 5; round++ { settle(12) - if painter.graph.Len() <= scenes || painter.semantics.Len() <= semantics { + if painter.frame.Graph().Len() <= scenes || painter.semantics.Len() <= semantics { t.Fatal("the busy page retained nothing; the test is not exercising what it claims") } settle(0) - if got := painter.graph.Len(); got != scenes { + if got := painter.frame.Graph().Len(); got != scenes { t.Fatalf("round %d: the scene holds %d nodes after the page was removed, %d before it was shown", round, got, scenes) } if got := painter.semantics.Len(); got != semantics { t.Fatalf("round %d: the semantic tree holds %d nodes after the page was removed, %d before", round, got, semantics) } - if got := len(painter.renderer.Rectangles()); got != rectangles { + if got := len(painter.frame.Rectangles()); got != rectangles { t.Fatalf("round %d: the renderer holds %d rectangles after the page was removed, %d before", round, got, rectangles) } } @@ -72,11 +72,11 @@ func TestALargePageThenASmallOneReleasesSlots(t *testing.T) { } } settle(5000) - if painter.graph.Slots() < 5000 || painter.semantics.Slots() < 5000 { - t.Fatalf("the large page did not allocate its slots: graph=%d semantics=%d", painter.graph.Slots(), painter.semantics.Slots()) + if painter.frame.Graph().Slots() < 5000 || painter.semantics.Slots() < 5000 { + t.Fatalf("the large page did not allocate its slots: graph=%d semantics=%d", painter.frame.Graph().Slots(), painter.semantics.Slots()) } settle(1) - if painter.graph.Slots() > 64 || painter.semantics.Slots() > 64 { - t.Fatalf("the small page kept the large page's slots: graph=%d semantics=%d", painter.graph.Slots(), painter.semantics.Slots()) + if painter.frame.Graph().Slots() > 64 || painter.semantics.Slots() > 64 { + t.Fatalf("the small page kept the large page's slots: graph=%d semantics=%d", painter.frame.Graph().Slots(), painter.semantics.Slots()) } } diff --git a/app/painter_origin_test.go b/app/painter_origin_test.go index 5b10c864..c503534e 100644 --- a/app/painter_origin_test.go +++ b/app/painter_origin_test.go @@ -1,17 +1,21 @@ package app -import "testing" +import ( + "testing" + + "github.com/vivaui/viva/internal/framebuild" +) // A label's frame is on whole logical pixels, and the text keeps the rest of its position: // the two add up to where layout put it, so a backend that places glyphs at device pixels // loses nothing to the rounding. func TestLabelOriginIsWhatRoundingTookOff(t *testing.T) { for _, value := range []float32{-99.9, -20.75, -10.3, -3.49, -0.5, -0.25, 0, 0.25, 0.5, 3.49, 10.3, 20.75, 99.9} { - got := float32(roundPosition(value)) + roundingRemainder(value) + got := float32(framebuild.RoundPosition(value)) + framebuild.RoundingRemainder(value) if diff := got - value; diff > 1e-4 || diff < -1e-4 { - t.Errorf("%v: frame %d + origin %v = %v", value, roundPosition(value), roundingRemainder(value), got) + t.Errorf("%v: frame %d + origin %v = %v", value, framebuild.RoundPosition(value), framebuild.RoundingRemainder(value), got) } - if r := roundingRemainder(value); r < -0.5 || r > 0.5 { + if r := framebuild.RoundingRemainder(value); r < -0.5 || r > 0.5 { t.Errorf("%v: origin %v is further than half a pixel from the frame", value, r) } } diff --git a/app/painter_presence_test.go b/app/painter_presence_test.go index 1a39b583..9d4e0d38 100644 --- a/app/painter_presence_test.go +++ b/app/painter_presence_test.go @@ -44,8 +44,8 @@ func TestPresenceExitPublishesLabelsPastTheWindowEdge(t *testing.T) { if _, err := painter.repaint(); err != nil { t.Fatal(err) } - startPanelX := painter.clipped[0].Bounds.X - startLabelX := painter.labels[0].X + startPanelX := painter.frame.ClippedRectangles()[0].Bounds.X + startLabelX := painter.frame.Labels()[0].X show = false now += 16 * time.Millisecond if _, err := painter.repaint(); err != nil { @@ -62,7 +62,7 @@ func TestPresenceExitPublishesLabelsPastTheWindowEdge(t *testing.T) { if frame.TextLabels[0].OriginX != 0 || frame.TextLabels[0].OriginY != 0 { t.Fatalf("moving label kept sub-pixel origin %v,%v", frame.TextLabels[0].OriginX, frame.TextLabels[0].OriginY) } - movedPanelX, movedLabelX := painter.clipped[0].Bounds.X, frame.TextLabels[0].X + movedPanelX, movedLabelX := painter.frame.ClippedRectangles()[0].Bounds.X, frame.TextLabels[0].X if movedPanelX >= startPanelX || movedLabelX >= startLabelX { t.Fatalf("leaving panel %v->%v and label %v->%v did not move left", startPanelX, movedPanelX, startLabelX, movedLabelX) } diff --git a/app/painter_test.go b/app/painter_test.go index 33e2a186..9956167f 100644 --- a/app/painter_test.go +++ b/app/painter_test.go @@ -410,11 +410,11 @@ func TestPainterInitialSyncPublishesCanvas(t *testing.T) { canvas.Label("Viva", gfx.Rect{X: 2, Y: 2, Width: 40, Height: 12}, gfx.TextStyle{Size: 12}) painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 100, Height: 100}) - if len(painter.renderer.Rectangles()) != 1 { - t.Fatalf("renderer rectangles = %+v", painter.renderer.Rectangles()) + if len(painter.frame.Rectangles()) != 1 { + t.Fatalf("renderer rectangles = %+v", painter.frame.Rectangles()) } - if len(painter.labels) != 1 || painter.labels[0].Value != "Viva" { - t.Fatalf("labels = %+v", painter.labels) + if len(painter.frame.Labels()) != 1 || painter.frame.Labels()[0].Value != "Viva" { + t.Fatalf("labels = %+v", painter.frame.Labels()) } } @@ -716,8 +716,8 @@ func TestRepaintShrinkingListRemovesSceneNodes(t *testing.T) { if !frame.Update.Empty() { t.Fatalf("resize after initial shrink produced work: %+v", frame.Update) } - if len(painter.renderer.Rectangles()) != 1 { - t.Fatalf("renderer kept %d rectangles", len(painter.renderer.Rectangles())) + if len(painter.frame.Rectangles()) != 1 { + t.Fatalf("renderer kept %d rectangles", len(painter.frame.Rectangles())) } } @@ -1158,8 +1158,8 @@ func TestScrollClampsAtZeroAndRepaints(t *testing.T) { if paints != 2 { t.Fatalf("productive scroll repainted %d times, want initial + 1", paints) } - if len(painter.clipped) != 1 || painter.clipped[0].Bounds.Y != -14 { - t.Fatalf("scrolled rectangle = %+v", painter.clipped) + if len(painter.frame.ClippedRectangles()) != 1 || painter.frame.ClippedRectangles()[0].Bounds.Y != -14 { + t.Fatalf("scrolled rectangle = %+v", painter.frame.ClippedRectangles()) } } @@ -1176,7 +1176,7 @@ func TestClipKeepsCutRectanglesWholeAndDropsHiddenShapesAndText(t *testing.T) { canvas.Fill(gfx.Rect{X: 80, Y: 40, Width: 10, Height: 10}, gfx.Color{Alpha: 1}) painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 100, Height: 100}) - instances := painter.renderer.Rectangles() + instances := painter.frame.Rectangles() if len(instances) != 3 { t.Fatalf("renderer holds %d rectangles, want the cut one, the inside one and the unclipped one: %+v", len(instances), instances) } @@ -1188,8 +1188,8 @@ func TestClipKeepsCutRectanglesWholeAndDropsHiddenShapesAndText(t *testing.T) { t.Errorf("rectangle %d carries a clip it does not need: %+v", index, instances[index]) } } - if len(painter.clippedTexts) != 1 || painter.clippedTexts[0].Value != "visible" { - t.Fatalf("clipped texts = %+v", painter.clippedTexts) + if len(painter.frame.ClippedTexts()) != 1 || painter.frame.ClippedTexts()[0].Value != "visible" { + t.Fatalf("clipped texts = %+v", painter.frame.ClippedTexts()) } } @@ -1209,7 +1209,7 @@ func TestPartlyClippedLabelsCarryTheirClipToThePlatform(t *testing.T) { painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 100, Height: 120}) got := map[string]platform.TextLabel{} - for _, label := range painter.labels { + for _, label := range painter.frame.Labels() { got[label.Value] = label } if _, sent := got["gone"]; sent || len(got) != 4 { @@ -1242,7 +1242,7 @@ func TestClippedStrokeReachesTheRendererWholeWithItsClip(t *testing.T) { painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 100, Height: 100}) painted := canvas.Triangles() - instances := painter.renderer.Rectangles() + instances := painter.frame.Rectangles() if len(painted) != 6 || len(instances) != 4 { t.Fatalf("canvas painted %d triangles and the renderer holds %d, want 6 and 4", len(painted), len(instances)) } @@ -1269,7 +1269,7 @@ func TestVectorFringeKeepsItsClip(t *testing.T) { canvas.DrawPath(gfx.NewPath(10, 10, gfx.MoveTo(x/scale, 2), gfx.LineTo(8, 2), gfx.LineTo(x/scale, 8), gfx.ClosePath()), clip, gfx.PathStyle{Fill: gfx.Color{Alpha: 1}}) canvas.Unclip() painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 10, Height: 10}) - instances := painter.renderer.Rectangles() + instances := painter.frame.Rectangles() if len(instances) == 0 { t.Fatal("visible fringe was culled") } @@ -1755,8 +1755,8 @@ func TestRepaintRecoloringRectanglesBehindShrinkingTrianglesRefreshesEverything( if len(canvas.Triangles()) >= trianglesBefore { t.Fatal("the triangle list did not shrink; the test is not exercising what it claims") } - if painter.resyncs != 0 { - t.Fatalf("the renderer rejected the batch and had to be rebuilt %d times", painter.resyncs) + if painter.frame.Resyncs() != 0 { + t.Fatalf("the renderer rejected the batch and had to be rebuilt %d times", painter.frame.Resyncs()) } want := scene.Color{Red: 0.1, Green: 0.1, Blue: 0.15, Alpha: 1} if len(frame.Rectangles) != len(canvas.Rectangles())+len(canvas.Triangles()) { @@ -1782,14 +1782,14 @@ func TestRepaintRebuildsRenderStateThatDisagreesWithTheScene(t *testing.T) { } painter := newTestPainter(t, &canvas, config) - painter.renderer = render.Store{} // forget every node the scene believes was published + *painter.frame.Store() = render.Store{} // forget every node the scene believes was published tint = gfx.Color{Red: 0.2, Green: 0.4, Blue: 0.6, Alpha: 1} frame, err := painter.repaint() if err != nil { t.Fatalf("repaint: %v", err) } - if painter.resyncs != 1 { - t.Fatalf("resyncs = %d, want exactly one rebuild", painter.resyncs) + if painter.frame.Resyncs() != 1 { + t.Fatalf("resyncs = %d, want exactly one rebuild", painter.frame.Resyncs()) } if !frame.Update.Rebuild || len(frame.Rectangles) != 2 { t.Fatalf("update=%+v instances=%d, want a full rebuild of both rectangles", frame.Update, len(frame.Rectangles)) @@ -2313,7 +2313,7 @@ func TestShadowsReachTheRendererAndRepaintWithoutChangePerformsNoWork(t *testing paint(&canvas, gfx.Size{}) painter := newTestPainter(t, &canvas, Config{Title: "test", Width: 100, Height: 100, Paint: paint}) - instances := painter.renderer.Rectangles() + instances := painter.frame.Rectangles() if len(instances) != 5 { t.Fatalf("renderer holds %d instances, want the page, the two layers of the large shadow, the surface and the shadow that reaches in: %+v", len(instances), instances) } @@ -2364,7 +2364,7 @@ func TestAShapeBecomingAShadowKeepsItsPlace(t *testing.T) { if err != nil { t.Fatal(err) } - instances := painter.renderer.Rectangles() + instances := painter.frame.Rectangles() if len(instances) != 3 || instances[1].Kind != want { t.Fatalf("instances = %+v, want the middle one to be kind %d", instances, want) } @@ -2502,8 +2502,8 @@ func TestPainterDropsLabelsWithoutAreaOrFontSize(t *testing.T) { canvas.Label("visible", gfx.Rect{Width: 40, Height: 12}, gfx.TextStyle{Size: 12}) } painter := newTestPainter(t, &canvas, config) - if len(painter.labels) != 1 || painter.labels[0].Value != "visible" { - t.Fatalf("labels = %+v, want only the visible one", painter.labels) + if len(painter.frame.Labels()) != 1 || painter.frame.Labels()[0].Value != "visible" { + t.Fatalf("labels = %+v, want only the visible one", painter.frame.Labels()) } if _, err := painter.repaint(); err != nil { t.Fatalf("repaint failed: %v", err) @@ -2531,11 +2531,11 @@ func TestPainterDropsSubpixelAndClippedImages(t *testing.T) { canvas.DrawBitmap(bitmap, gfx.Rect{X: 10, Y: 10, Width: 20, Height: 20}) } painter := newTestPainter(t, &canvas, config) - if len(painter.labels) != 1 { - t.Fatalf("labels count = %d, want 1; labels = %+v", len(painter.labels), painter.labels) + if len(painter.frame.Labels()) != 1 { + t.Fatalf("labels count = %d, want 1; labels = %+v", len(painter.frame.Labels()), painter.frame.Labels()) } - if painter.labels[0].Width <= 0 || painter.labels[0].Height <= 0 { - t.Fatalf("visible image label has non-positive dimensions: %+v", painter.labels[0]) + if painter.frame.Labels()[0].Width <= 0 || painter.frame.Labels()[0].Height <= 0 { + t.Fatalf("visible image label has non-positive dimensions: %+v", painter.frame.Labels()[0]) } if _, err := painter.repaint(); err != nil { t.Fatalf("repaint failed: %v", err) diff --git a/app/quad_clip_test.go b/app/quad_clip_test.go index 21330b2f..eca3f718 100644 --- a/app/quad_clip_test.go +++ b/app/quad_clip_test.go @@ -31,11 +31,11 @@ func TestQuadClippingPreservesBothBackendPlacements(t *testing.T) { Tint: [4]gfx.Color{white, white, white, white}, }, gfx.TextStyle{Size: 14, Color: white}) painter := newTestPainter(t, &canvas, Config{Title: "quad clip", Width: 200, Height: 100}) - if (len(painter.labels) != 0) != test.visible { - t.Fatalf("visible=%t, labels=%+v", test.visible, painter.labels) + if (len(painter.frame.Labels()) != 0) != test.visible { + t.Fatalf("visible=%t, labels=%+v", test.visible, painter.frame.Labels()) } - if test.visible && (painter.labels[0].Clipped != test.cut || test.cut && painter.labels[0].Clip != clip) { - t.Fatalf("clip cut=%t, label=%+v", test.cut, painter.labels[0]) + if test.visible && (painter.frame.Labels()[0].Clipped != test.cut || test.cut && painter.frame.Labels()[0].Clip != clip) { + t.Fatalf("clip cut=%t, label=%+v", test.cut, painter.frame.Labels()[0]) } }) } diff --git a/app/run_canvas.go b/app/run_canvas.go index 784dbe0e..385c6e2e 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -175,8 +175,8 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, }, Web: normalized.Web.bind(), NativeViews: slices.Clone(painter.lastViews), - Rectangles: painter.renderer.Rectangles(), - TextLabels: painter.labels, + Rectangles: painter.frame.Rectangles(), + TextLabels: painter.frame.Labels(), Accessibility: painter.accessibility, OnResize: resizeHandler, OnFrameChange: frameChangeHandler(normalized.OnFrameChange), diff --git a/app/run_canvas_js.go b/app/run_canvas_js.go index 1991db33..36f24254 100644 --- a/app/run_canvas_js.go +++ b/app/run_canvas_js.go @@ -42,8 +42,8 @@ func RunCanvas(config Config, canvas *gfx.Canvas) error { }, Paint: normalized.Paint, OnPointer: normalized.OnPointer, OnKey: normalized.OnKey, OnShortcut: normalized.OnShortcut, OnScroll: normalized.OnScroll, OnModifierTap: normalized.OnModifierTap, - OnFileDrop: normalized.OnFileDrop, - OnResize: normalized.OnResize, OnMinimize: normalized.OnMinimize, + OnFileDrop: normalized.OnFileDrop, ForwardWheel: normalized.ForwardWheel, + OnResize: normalized.OnResize, OnMinimize: normalized.OnMinimize, OnFullscreen: normalized.OnFullscreen, OnCloseRequest: normalized.OnCloseRequest, OnClosed: normalized.OnClosed, OnActivate: normalized.OnActivate, TextInput: webTextInput(normalized.TextInput), diff --git a/app/run_canvas_js_test.go b/app/run_canvas_js_test.go index f5b0578f..3d95a4db 100644 --- a/app/run_canvas_js_test.go +++ b/app/run_canvas_js_test.go @@ -26,10 +26,12 @@ func TestRunCanvasHandsTheApplicationToThePage(t *testing.T) { var invalidator Invalidator canvas := &gfx.Canvas{} woken := false + forwarded := [2]float32{} err := RunCanvas(Config{ Title: "Notes", Tree: &tree, Invalidator: &invalidator, OnWake: func() { woken = true }, - Paint: func(*gfx.Canvas, gfx.Size) {}, - TextInput: func(TextInputContext) *TextInput { return nil }, + Paint: func(*gfx.Canvas, gfx.Size) {}, + TextInput: func(TextInputContext) *TextInput { return nil }, + ForwardWheel: func(deltaX, deltaY float32) { forwarded = [2]float32{deltaX, deltaY} }, }, canvas) if err != nil { t.Fatal(err) @@ -43,6 +45,13 @@ func TestRunCanvasHandsTheApplicationToThePage(t *testing.T) { if got.Paint == nil || got.TextInput == nil { t.Error("Paint and TextInput must reach the page") } + if got.ForwardWheel == nil { + t.Fatal("ForwardWheel must reach the page") + } + got.ForwardWheel(1.5, -2.5) + if forwarded != [2]float32{1.5, -2.5} { + t.Errorf("the page forwarded %v, want the application's callback", forwarded) + } if got.Waker == nil { t.Fatal("an Invalidator must reach the page as its waker") } diff --git a/app/store_consistency_test.go b/app/store_consistency_test.go index 21882d27..7b2c7af0 100644 --- a/app/store_consistency_test.go +++ b/app/store_consistency_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/framebuild" "github.com/vivaui/viva/internal/scene" ) @@ -15,36 +16,36 @@ func storeMatchesCanvas(t *testing.T, painter *painter, painted []gfx.Color, ste t.Helper() var rects, triangles int var order []gfx.Color - for _, primitive := range painter.renderer.Rectangles() { + for _, primitive := range painter.frame.Rectangles() { var color gfx.Color if primitive.Kind == scene.KindTriangle { - if triangles >= len(painter.clippedPaths) { - t.Fatalf("step %d: the store holds more triangles than the canvas painted (%d)", step, len(painter.clippedPaths)) + if triangles >= len(painter.frame.ClippedTriangles()) { + t.Fatalf("step %d: the store holds more triangles than the canvas painted (%d)", step, len(painter.frame.ClippedTriangles())) } - want := sceneTriangle(painter.clippedPaths[triangles]) + want := framebuild.SceneTriangle(painter.frame.ClippedTriangles()[triangles]) if primitive.Points != want.Points || primitive.Color != want.Color { t.Fatalf("step %d: stored triangle %d = %+v, canvas painted %+v", step, triangles, primitive.Points, want.Points) } triangles++ - color = painter.clippedPaths[triangles-1].Color + color = painter.frame.ClippedTriangles()[triangles-1].Color } else { - if rects >= len(painter.clipped) { - t.Fatalf("step %d: the store holds more rectangles than the canvas painted (%d)", step, len(painter.clipped)) + if rects >= len(painter.frame.ClippedRectangles()) { + t.Fatalf("step %d: the store holds more rectangles than the canvas painted (%d)", step, len(painter.frame.ClippedRectangles())) } - want := sceneRectangle(painter.clipped[rects]) + want := framebuild.SceneRectangle(painter.frame.ClippedRectangles()[rects]) if primitive.Bounds != want.Bounds || primitive.Color != want.Color || primitive.Radius != want.Radius { t.Fatalf("step %d: stored rectangle %d = %+v, canvas painted %+v", step, rects, primitive.Bounds, want.Bounds) } rects++ - color = painter.clipped[rects-1].Color + color = painter.frame.ClippedRectangles()[rects-1].Color } if len(order) == 0 || order[len(order)-1] != color { order = append(order, color) } } - if rects != len(painter.clipped) || triangles != len(painter.clippedPaths) { + if rects != len(painter.frame.ClippedRectangles()) || triangles != len(painter.frame.ClippedTriangles()) { t.Fatalf("step %d: store has %d rectangles and %d triangles, canvas painted %d and %d", - step, rects, triangles, len(painter.clipped), len(painter.clippedPaths)) + step, rects, triangles, len(painter.frame.ClippedRectangles()), len(painter.frame.ClippedTriangles())) } // Every shape was painted in a color of its own, so the colors in store // order, one per run, are the shapes in store order. @@ -166,22 +167,22 @@ func TestInsertingAShapeMidPageTouchesOnlyThatShape(t *testing.T) { } } painter := newTestPainter(t, &canvas, config) - shapes := len(painter.order) + shapes := painter.frame.OrderLen() for _, want := range []bool{true, false, true} { highlighted = want if _, err := painter.resize(size(800, 600)); err != nil { t.Fatal(err) } - if len(painter.changes) != 1 { - t.Fatalf("highlighted=%v: %d scene changes for one shape among %d", want, len(painter.changes), shapes) + if len(painter.frame.Changes()) != 1 { + t.Fatalf("highlighted=%v: %d scene changes for one shape among %d", want, len(painter.frame.Changes()), shapes) } total := shapes if highlighted { total++ } - if len(painter.renderer.Rectangles()) != total { - t.Fatalf("highlighted=%v: renderer holds %d shapes, want %d", highlighted, len(painter.renderer.Rectangles()), total) + if len(painter.frame.Rectangles()) != total { + t.Fatalf("highlighted=%v: renderer holds %d shapes, want %d", highlighted, len(painter.frame.Rectangles()), total) } } } diff --git a/cmd/component-preview/main_web.go b/cmd/component-preview/main_web.go index e4fad3af..c5e19a46 100644 --- a/cmd/component-preview/main_web.go +++ b/cmd/component-preview/main_web.go @@ -7,9 +7,9 @@ import ( "strings" "syscall/js" + "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/componentdemo" - "github.com/vivaui/viva/internal/platform/web" "github.com/vivaui/viva/internal/previewmeasure" ) @@ -45,6 +45,19 @@ func main() { } state.SetDark(theme == "dark") state.EnableTextEditing() + appearance := gfx.LightTheme() + if theme == "dark" { + appearance = gfx.DarkTheme() + } + var previewInput app.TextInput + resolveInput := func(context app.TextInputContext) *app.TextInput { + editor, supported := state.Editor(context.ID) + if !supported { + return nil + } + previewInput = app.TextInput{Editor: editor} + return &previewInput + } ready := false lastHeight := 0 var forward func(deltaX, deltaY float32) @@ -52,8 +65,13 @@ func main() { if embedded { forward = forwardWheel } - err = web.Run(web.Config{ + err = app.RunCanvas(app.Config{ Title: "Viva · " + component + " · Web preview", Width: 760, Height: 380, + ClearColor: app.Color{ + Red: float64(appearance.Background.Red), Green: float64(appearance.Background.Green), + Blue: float64(appearance.Background.Blue), Alpha: 1, + }, + Tree: componentdemo.Tree(), Paint: func(canvas *gfx.Canvas, size gfx.Size) { state.Paint(canvas, size) if height := previewmeasure.Content(canvas, size); embedded && height > 0 && height != lastHeight { @@ -67,8 +85,8 @@ func main() { }, OnPointer: state.Pointer, OnKey: state.Key, OnScroll: state.Scroll, ForwardWheel: forward, - TextInput: web.EditorInputs(state.Editor), - }) + TextInput: resolveInput, + }, nil) if err != nil { reportPreview("viva-preview-error", err.Error()) } diff --git a/cmd/viva/build.go b/cmd/viva/build.go index 782e7388..9de3b919 100644 --- a/cmd/viva/build.go +++ b/cmd/viva/build.go @@ -1,13 +1,9 @@ package main import ( - "bytes" - "compress/gzip" - "encoding/json" "errors" "flag" "fmt" - "html" "io" "os" "os/exec" @@ -15,6 +11,7 @@ import ( "runtime" "strings" + "github.com/vivaui/viva/internal/webbuild" "github.com/vivaui/viva/tools/manifest" ) @@ -366,93 +363,29 @@ func formatSize(size int64) string { return fmt.Sprintf("%s B (%.2f MiB)", strings.Join(grouped, ","), float64(size)/mebibyte) } -// webPage renders the page that starts a WebAssembly program. The title is HTML -// text and the program's file name is a JavaScript string, so each is escaped -// for where it lands. -func webPage(title, wasm string) ([]byte, error) { - quoted, err := json.Marshal(wasm) - if err != nil { - return nil, err - } - var page bytes.Buffer - fmt.Fprintf(&page, ` - - - - - %s - - - - - - - -`, html.EscapeString(title), quoted, quoted, quoted) - return page.Bytes(), nil -} - // buildWeb writes the browser build: the wasm program, the Go runtime's loader // script and a page that starts it. func buildWeb(plan buildPlan, output, errorOutput io.Writer) error { - wasm := filepath.Join(plan.out, plan.executable+".wasm") - if err := plan.run(wasm, errorOutput); err != nil { - return err - } - root, err := exec.Command("go", "env", "GOROOT").Output() - if err != nil { - return fmt.Errorf("go env GOROOT: %w", err) - } - loader, err := os.ReadFile(filepath.Join(strings.TrimSpace(string(root)), "lib", "wasm", "wasm_exec.js")) - if err != nil { - return fmt.Errorf("reading wasm_exec.js from the Go installation: %w", err) - } - if err := os.WriteFile(filepath.Join(plan.out, "wasm_exec.js"), loader, 0o644); err != nil { - return err - } title := plan.manifest.App.Name if title == "" { title = plan.executable } - page, err := webPage(title, plan.executable+".wasm") + result, err := webbuild.Build(webbuild.Options{ + Dir: plan.manifest.Dir, + OutputDir: plan.out, + Executable: plan.executable, + Package: plan.pkg, + Flags: []string{"-trimpath", "-ldflags", plan.ldflags()}, + Tags: plan.tags, + Environment: os.Environ(), + Title: title, + Page: true, + Stdout: errorOutput, + Stderr: errorOutput, + }) if err != nil { return err } - if err := os.WriteFile(filepath.Join(plan.out, "index.html"), page, 0o644); err != nil { - return err - } - - program, err := os.ReadFile(wasm) - if err != nil { - return err - } - var compressed bytes.Buffer - writer, _ := gzip.NewWriterLevel(&compressed, gzip.BestCompression) - writer.Write(program) - writer.Close() - fmt.Fprintf(output, "built %s/\n", displayPath(plan.out)) fmt.Fprintf(output, " files %s.wasm, wasm_exec.js, index.html\n", plan.executable) if len(plan.tags) > 0 { @@ -462,7 +395,7 @@ func buildWeb(plan buildPlan, output, errorOutput io.Writer) error { if plan.debug { note = ", with symbols (not the release size)" } - fmt.Fprintf(output, " size %s%s\n", formatSize(int64(len(program))), note) - fmt.Fprintf(output, " gzip %s\n", formatSize(int64(compressed.Len()))) + fmt.Fprintf(output, " size %s%s\n", formatSize(result.WasmSize), note) + fmt.Fprintf(output, " gzip %s\n", formatSize(result.GzipSize)) return nil } diff --git a/docs/benchmarks/2026-11-19-web-renderers-darwin-arm64.md b/docs/benchmarks/2026-11-19-web-renderers-darwin-arm64.md new file mode 100644 index 00000000..5e4fa1d1 --- /dev/null +++ b/docs/benchmarks/2026-11-19-web-renderers-darwin-arm64.md @@ -0,0 +1,80 @@ +# Browser renderers: WebGL2 and Canvas2D + +Measured 2026-11-19 on Apple M2 Pro, 16 GiB RAM, macOS 15.5 (24F74), +darwin/arm64, Go 1.26.0. These are local observations, not budget-compliance +claims. The browser runs were headless Playwright builds on the same machine. + +## Scope + +The browser target now renders `platform.Frame` with WebGL2 and falls back to +Canvas2D at runtime. This report records the artifact sizes and the browser +behavior that were actually exercised. It does not claim a steady-state frame +time for a large application yet; that benchmark still needs a dedicated scene +with a large list, editor and charts. + +## Artifact size + +The fixture is the browser verification program +(`tools/webcheck/fixture`) built with: + +```sh +go run ./cmd/viva build --target web ./tools/webcheck/fixture -o +``` + +| Build | Stripped wasm | gzip | +| --- | ---: | ---: | +| Frame renderer with Canvas2D only (before WebGL2) | 5,504,604 B (5.25 MiB) | 1,557,350 B (1.49 MiB) | +| WebGL2 renderer plus Canvas2D fallback | 5,801,972 B (5.53 MiB) | 1,637,943 B (1.56 MiB) | +| Difference | +297,368 B (+0.28 MiB) | +80,593 B (+0.08 MiB) | + +The increase is the GLSL shaders, the WebGL2 renderer, per-label texture +management and the Canvas2D bitmap path. No new Go module dependency was +added. Native builds do not link any of it: the work is under `js && wasm` and +the shared frame builder is the same code moved out of `app/painter`. + +## Browser behavior + +`tools/webcheck/check.mjs` ran against Chromium 158.0.8127.18, Firefox 159.0 +and WebKit 27.2 in both forced renderers: + +```sh +go run ./cmd/viva build --target web ./tools/webcheck/fixture -o build/webcheck +node tools/webcheck/check.mjs --dir build/webcheck --browser all --renderer webgl2 +node tools/webcheck/check.mjs --dir build/webcheck --browser all --renderer canvas2d +``` + +All three engines passed the pointer, keyboard, focus, slider, text-editor, +IME composition, backdrop, pass-through and accessibility checks in both +renderers. The fixture also draws a solid bitmap, and the gate samples that +pixel from its screenshot in both renderers. The forced-WebGL2 run also lost +the context with `WEBGL_lose_context`; the page reported `canvas2d`, kept +pointer input working, and the subsequent click reached the application. + +The docs previews were built through the same `viva build --target web` +pipeline and rendered in WebGL2 and Canvas2D. Button, Image View, Code Editor, +Chart and Slider previews produced matching screenshots in both renderers, +including the Image View bitmap that the old Canvas2D renderer did not draw at +all. + +## Additional hardening + +- The fixture draws a warped label (`gfx.Canvas.LabelQuad`); both renderers + painted it. WebGL2 uses the four-corner quad and per-corner tint; Canvas2D + uses horizontal strip subdivision and a corner-to-corner tint gradient. +- WebGL2 labels wider than `MAX_TEXTURE_SIZE` are split into overlapping + horizontal tiles. A run with `window.vivaMaxTexture = 64` forced the fixture's + button and editor labels across several tiles and rendered without errors or + visible seams at 640×480. +- The browser fixture now also draws a solid bitmap; the gate samples its pixel + from the screenshot under both renderers. + +## Not measured + +- Steady-state frame time and GPU submission for a large application scene. +- Texture memory under a long scrolling session with thousands of labels. +- Native binary size and startup; the web renderer is excluded by build tags, + but a before/after native link measurement was not part of this run. +- Real Safari via `safaridriver`: `tools/webcheck/safari.mjs` is provided, but + remote automation is not enabled on this Mac. Playwright's WebKit is not the + same browser shell. +- Physical IME candidate windows; composition is synthesized at the DOM level. diff --git a/docs/conformance.md b/docs/conformance.md index dd02cf7f..d911334f 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -64,6 +64,14 @@ screenshot, when the code behind them changes: maximized window must stop at the taskbar; - where a panel and a new window are placed on a multi-monitor or scaled screen (Linux: not verified with more than one monitor or a real HiDPI display); +- an operating-system input method's candidate window: the browser gate and the + Go tests synthesize composition events, but the candidate window is the + system's own UI. Type through a real IME on macOS, Windows and Linux with the + Input example focused, and verify the candidate window sits at the caret and + that commit, cancel and selection update the Go editor exactly once; +- real Safari through `safaridriver` after one-time `sudo safaridriver --enable`: + `node tools/webcheck/safari.mjs --dir build/webcheck`. Playwright's WebKit is + not Safari's browser shell; - text, which each platform draws with its own engine and is not expected to match. ## Known differences @@ -98,7 +106,7 @@ mistakes an absence for an oversight. Items marked *measured* were tried or size | Native text events in `viva dev` | all | The worker protocol does not carry them; native Canvas examples do not run under `viva dev`. | | A flat accessibility tree | Windows, macOS | Every node hangs from the window; Linux derives parents from geometry. | | XIM input | Linux | Composition goes through IBus (IBus and Fcitx5's IBus frontend); XIM-only applications cannot compose. | -| Text in arbitrary quads | Windows, Linux, Web, headless | `Canvas.LabelQuad` warps a line into a general quad on macOS only; the other backends paint the line axis-aligned in its bounds, readable but unwarped. `Canvas.FillQuad` is two triangles and draws on every backend. | +| Text in arbitrary quads | Windows, Linux, Web, headless | `Canvas.LabelQuad` warps a line into a general quad on macOS and WebGL2. Canvas2D approximates it with horizontal strips and a corner-to-corner tint gradient. Windows, Linux and headless paint the line axis-aligned in its bounds, readable but unwarped. `Canvas.FillQuad` is two triangles and draws on every backend. | ## Test environments diff --git a/docs/web-deployment.md b/docs/web-deployment.md index a2e8f491..16dea2b7 100644 --- a/docs/web-deployment.md +++ b/docs/web-deployment.md @@ -2,8 +2,9 @@ `RunCanvas` on `GOOS=js GOARCH=wasm` is a deployment target, not a visual preview. It runs the same component tree, input router, text shaping and -accessibility model as the native applications, paints them through Canvas2D, -and keeps the browser event loop free by making every platform operation that +accessibility model as the native applications, paints them through WebGL2, +and falls back to Canvas2D when WebGL2 is unavailable or a context is lost. +It keeps the browser event loop free by making every platform operation that is asynchronous in the browser asynchronous in the API too. The page is the window. A web build has one document, one canvas and one @@ -67,6 +68,41 @@ Viva does not use `SharedArrayBuffer`. Add them only if an embedding page needs them, and verify that the application's own network integrations still work under the resulting isolation. +## Renderer + +The browser target draws with WebGL2 by default. Both renderers consume the +same `platform.Frame` from the shared frame builder, so component geometry, +paint order, text content, input routing and the accessibility mirror are the +same; they differ only in rasterization. + +- WebGL2 ports the analytic rounded-rectangle, triangle and shadow shaders used + by the native GPU backends, and draws text as whole-line textures rasterized + by the browser. It uses premultiplied alpha, no sRGB framebuffer conversion, + and grayscale text antialiasing (no dual-source LCD text). +- Canvas2D is the fallback. It is chosen when the browser has no WebGL2, shader + or buffer initialization fails, or a WebGL2 context is lost. It uses the + Canvas2D rasterizer and draws text with `fillText`. +- A page can force a renderer for diagnostics or tests with + `?viva-renderer=webgl2` or `?viva-renderer=canvas2d`; without it, WebGL2 is + preferred. +- `document.documentElement.dataset.vivaRenderer` reports `webgl2` or + `canvas2d`, and `window.vivaWebStats.renderer` does after the first frame. +- A lost WebGL2 context falls back to Canvas2D for the rest of the page's life, + following the same path as an initial WebGL2 failure. Input listeners live on + the window root, so the replacement canvas keeps pointer, wheel and keyboard + events. +- Images are `platform.TextLabel` bitmaps. Both renderers draw them, including + cropped surfaces; no separate image path exists. +- A warped label (`TextLabel.HasQuad`) is drawn with its per-corner tint in + WebGL2. Labels wider than `MAX_TEXTURE_SIZE` are split into overlapping + horizontal tiles. The Canvas2D fallback approximates the warp with horizontal + strips and a corner-to-corner tint gradient. + +Neither renderer promises pixel-identical output to macOS Metal, Windows +Direct3D 11 or Linux Vulkan: text shaping and font fallback belong to the +browser, and Canvas2D antialiasing differs from the GPU shaders. The shared +contract is the draw list and the semantic tree, not the pixels. + ## Capabilities Capabilities are static for the build target; a runtime permission can still @@ -179,12 +215,14 @@ engine. `FontFamilies` and `MonospaceFamilies` are empty because browsers do not expose the machine's installed fonts. Use `gfx.MonoSystem`, `gfx.MonoClassic`, or a family registered by the application. -Text is shaped and measured in CSS pixels through the document, and painted by -Canvas2D at `devicePixelRatio`. Widths, caret positions, selections and hits -therefore agree with the glyphs the browser draws. They are not promised to be -pixel-identical to macOS CoreText, Windows DirectWrite or Linux Pango: font -fallback, hinting and DPI rounding differ. A browser zoom change invalidates -measurements, as does a font that finishes loading. +Text is shaped and measured in CSS pixels through the document and painted at +`devicePixelRatio`: WebGL2 draws whole-line label textures rasterized by the +browser, and Canvas2D draws the same lines with `fillText`. Widths, caret +positions, selections and hits therefore agree with the glyphs the browser +draws. They are not promised to be pixel-identical to macOS CoreText, Windows +DirectWrite or Linux Pango: font fallback, hinting and DPI rounding differ. A +browser zoom change invalidates measurements, as does a font that finishes +loading. ## Lifecycle @@ -278,8 +316,8 @@ focus, autofocus, pending focus, Escape targets, held-key pairing, press capture, click completion, cursor selection and text-editor ownership — lives in `internal/interaction` and is used by both painters. The painters themselves remain platform implementations: the native one publishes to the retained -scene, renderer and native views, while the browser one paints Canvas2D and -drives the DOM accessibility mirror. The browser backend is still an +scene, renderer and native views, while the browser one paints WebGL2 or +Canvas2D and drives the DOM accessibility mirror. The browser backend is still an intentional subset where the document cannot supply a platform service. A behavior added to one painter must still be checked against the other and covered where it is observable without a real window. @@ -303,9 +341,9 @@ use rather than inventing a private browser runtime: Access, Clipboard, WebCrypto, IndexedDB and Fullscreen; - W3C ARIA Authoring Practices for the ARIA mirror and keyboard semantics. -These are design references, not dependencies. Viva keeps Canvas2D drawing, -the Go input router and the application-facing API under its own control; it -does not embed a browser engine in a native build. +These are design references, not dependencies. Viva keeps its WebGL2 and +Canvas2D drawing, the Go input router and the application-facing API under its +own control; it does not embed a browser engine in a native build. ## Verification @@ -359,9 +397,34 @@ The same gate runs locally with: npm ci --prefix tools/webcheck tools/webcheck/node_modules/.bin/playwright install chromium firefox webkit go run ./cmd/viva build --target web ./tools/webcheck/fixture -o build/webcheck -node tools/webcheck/check.mjs --dir build/webcheck --browser all +node tools/webcheck/check.mjs --dir build/webcheck --browser all --renderer webgl2 +node tools/webcheck/check.mjs --dir build/webcheck --browser all --renderer canvas2d ``` +The driver's `--renderer` chooses `auto`, `webgl2` or `canvas2d`; a forced +renderer is passed in the page's query string, and the gate asserts the +renderer the page reports. It checks the painted canvas from a Playwright +screenshot rather than a 2D `getImageData` call, so it covers both renderers. +In a forced-WebGL2 run it also loses the context through +`WEBGL_lose_context`, waits for the page to report `canvas2d`, and verifies that +a pointer click still reaches the application. CI runs Chromium with forced +WebGL2 and forced Canvas2D, and Firefox and WebKit with `auto`. + +The system Safari is not Playwright's WebKit. After one-time +`sudo safaridriver --enable` (or Safari Settings > Developer > Allow Remote +Automation), run: + +```sh +node tools/webcheck/safari.mjs --dir build/webcheck +``` + +That smoke gate checks the chosen renderer, a non-blank canvas, the bitmap +pixel and a trusted pointer click. The full interaction suite remains in +`check.mjs`. An operating-system IME candidate window still needs a person at +the target machine; the synthetic composition in `check.mjs` verifies the event +contract, not the candidate window's placement. `docs/conformance.md` records +that manual check. + A headless Chrome run served the generated `index.html`, `.wasm` and `wasm_exec.js` over HTTP, rendered the gallery, and then invoked the DOM `click` action on an ARIA component node. The application opened the component diff --git a/internal/framebuild/framebuild.go b/internal/framebuild/framebuild.go new file mode 100644 index 00000000..04ef159f --- /dev/null +++ b/internal/framebuild/framebuild.go @@ -0,0 +1,1138 @@ +// Package framebuild reconciles the immediate canvas paint with the retained +// scene, the render store and the platform's text labels. It is the +// platform-neutral half of a frame: the native and web shells keep input, +// focus, accessibility, text input, native views and the cursor. +package framebuild + +import ( + "math" + "slices" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +// Builder reconciles immediate canvas paints with the retained scene and the +// native label list, so an unchanged repaint performs no renderer work. +// +// A Builder owns the retained scene, render store and label state for one +// canvas. It is not safe for concurrent use: one goroutine calls Build once +// per frame, after the application's paint function has finished writing the +// canvas. The slices of the returned frame alias the builder's state and are +// valid until the next Build. +type Builder struct { + canvas *gfx.Canvas + graph *scene.Scene + renderer render.Store + changes []scene.Change + resyncs int // times the renderer had to be rebuilt after a failed batch + shapeIDs []scene.ID // one scene node per entry of order, in paint order + labels []platform.TextLabel + lastTexts []gfx.Text + lastRuns []gfx.TextRun // the runs lastTexts refer to, copied out of the application's memory + // lastFontGeneration is the canvas's font generation at the labels last sent: text + // that has not changed still needs sending when the fonts have, so the renderer + // draws it again. + lastFontGeneration uint32 + lastImages []gfx.Image + // labelImage names, for each label of this frame, the image it was drawn + // from (an index into clippedImages, -1 for a text label); lastLabelImage is + // the same for the labels last sent. A bitmap needs its pixels again unless + // the label in its place showed the same picture: the platform hands a + // label its predecessor's texture when both are at the same index and carry + // the same content. + labelImage []int32 + lastLabelImage []int32 + lastTextBefores []uint32 // clippedTextBefores last sent + lastImageBefores []uint32 // clippedImageBefores last sent + stateBySlot []instanceState + // layerShift is 1 while the frame has a backdrop, which takes platform layer + // zero; every canvas layer then travels one higher. It is 0 otherwise. + layerShift uint16 + // cellReplace remembers the font-ready form of lines that hold cell glyphs; + // a frame that changed one row of a grid-shaped page sends every row again, + // and the rows that did not change rebuild no string and runs. + cellReplace []cellReplaceMemo + clipRects [4]gfx.Rect + clipped []gfx.Rectangle + clippedPaths []gfx.Triangle + clippedSoft []gfx.Shadow + order []shapeRef // clipped, clippedPaths and clippedSoft interleaved in paint order + blocks []gfx.Rectangle // scratch for appendCellGlyphs + strokes []gfx.Triangle // scratch for appendCellGlyphs + clippedTexts []gfx.Text + clippedImages []gfx.Image + // clippedTextBefores and clippedImageBefores are how many shapes the frame + // paints before each of those labels: the place a renderer puts the label + // back among the shapes. + clippedTextBefores []uint32 + clippedImageBefores []uint32 +} + +// New returns a builder for the canvas's current primitives. +func New(canvas *gfx.Canvas) *Builder { + return &Builder{ + canvas: canvas, + graph: scene.NewWithCapacity(len(canvas.Rectangles()) + len(canvas.Triangles()) + len(canvas.Shadows()) + 1), + shapeIDs: make([]scene.ID, 0, len(canvas.Rectangles())+len(canvas.Triangles())+len(canvas.Shadows())), + labels: make([]platform.TextLabel, 0, len(canvas.Texts())+len(canvas.Images())+1), + } +} + +// Build reconciles the canvas with the scene and the label list and returns the +// resulting renderer frame. +func (builder *Builder) Build() (platform.Frame, error) { + builder.applyClipping() + builder.syncShapes() + builder.changes = builder.graph.DrainChanges(builder.changes[:0]) + update, err := builder.renderer.Apply(builder.changes) + if err != nil { + // The scene has already absorbed this frame, so the failed batch will + // never be sent again: leaving the store as it is would freeze every + // node it skipped at its old value for good. Rebuild both from the + // canvas instead. + if update, err = builder.Resync(); err != nil { + return platform.Frame{}, err + } + } + if builder.stampState() && !update.Rebuild { + update = render.Update{Count: len(builder.renderer.Rectangles()), Rebuild: true} + } + + frame := platform.Frame{Update: update, Rectangles: builder.renderer.Rectangles()} + if !builder.sameAsLastContent() { + builder.syncLabels() + builder.saveContent() + frame.TextLabels = builder.labels + } + return frame, nil +} + +// Rectangles returns the retained render instances in paint order. +func (builder *Builder) Rectangles() []render.Rectangle { + return builder.renderer.Rectangles() +} + +// Labels returns the labels of the last frame whose content changed. +func (builder *Builder) Labels() []platform.TextLabel { + return builder.labels +} + +// Graph returns the retained scene. +func (builder *Builder) Graph() *scene.Scene { + return builder.graph +} + +// Store returns the retained render store. +func (builder *Builder) Store() *render.Store { + return &builder.renderer +} + +// Resyncs reports how many times the render store had to be rebuilt after a +// failed batch. +func (builder *Builder) Resyncs() int { + return builder.resyncs +} + +// PlatformLayer is the layer a canvas layer takes on the platform. The topmost +// layer stays topmost. +func (builder *Builder) PlatformLayer(layer uint16) uint16 { + if builder.layerShift == 0 || layer == math.MaxUint16 { + return layer + } + return layer + builder.layerShift +} + +// MarkInitialBitmapUploads makes every bitmap label of the initial frame carry +// its pixels, and remembers that frame as the content last sent. +func (builder *Builder) MarkInitialBitmapUploads() { + for index := range builder.labels { + builder.labels[index].BitmapUpload = len(builder.labels[index].Bitmap) > 0 + } + builder.saveContent() +} + +// Trim gives back the backing arrays of the builder's per-frame buffers when +// they are far larger than the current frame, and rebuilds the scene and store +// when a large page was replaced by a small one. +func (builder *Builder) Trim() { + // A scene keeps its free slots for reuse. That is right for a page that + // stays large, but after a large page is replaced by a small one the slots + // are pure retention. Rebuild both from the small frame instead of carrying + // the peak for the rest of the session. + const trimAt, trimRatio = 4096, 4 + if slots := builder.graph.Slots(); slots > trimAt && builder.graph.Len()*trimRatio < slots { + if _, err := builder.Resync(); err == nil { + builder.stateBySlot = nil + } + // A page the scene rebuilt wholesale shows other lines; its memoized + // replacements are stale retention. + builder.cellReplace = builder.cellReplace[:0] + } + builder.shapeIDs = TrimCapacity(builder.shapeIDs) + builder.labels = TrimCapacity(builder.labels) + builder.lastTexts = TrimCapacity(builder.lastTexts) + builder.lastRuns = TrimCapacity(builder.lastRuns) + builder.lastImages = TrimCapacity(builder.lastImages) + builder.labelImage = TrimCapacity(builder.labelImage) + builder.lastLabelImage = TrimCapacity(builder.lastLabelImage) + builder.clipped = TrimCapacity(builder.clipped) + builder.clippedPaths = TrimCapacity(builder.clippedPaths) + builder.clippedSoft = TrimCapacity(builder.clippedSoft) + builder.order = TrimCapacity(builder.order) + builder.blocks = TrimCapacity(builder.blocks) + builder.strokes = TrimCapacity(builder.strokes) + builder.clippedTexts = TrimCapacity(builder.clippedTexts) + builder.clippedImages = TrimCapacity(builder.clippedImages) + builder.clippedTextBefores = TrimCapacity(builder.clippedTextBefores) + builder.clippedImageBefores = TrimCapacity(builder.clippedImageBefores) + builder.lastTextBefores = TrimCapacity(builder.lastTextBefores) + builder.lastImageBefores = TrimCapacity(builder.lastImageBefores) + builder.changes = TrimCapacity(builder.changes) +} + +// TrimCapacity gives back a slice's backing array when it is far larger than +// its contents. The contents are kept, so a frame already returned remains +// valid; its old array is released. +func TrimCapacity[T any](items []T) []T { + const minCapacity = 4096 + const ratio = 4 + if cap(items) <= minCapacity || len(items)*ratio >= cap(items) { + return items + } + next := make([]T, len(items), max(len(items)*2, minCapacity/64)) + copy(next, items) + return next +} + +// Resync discards the retained scene and render store and rebuilds both from +// the current canvas, returning the full-rebuild update. +func (builder *Builder) Resync() (render.Update, error) { + builder.resyncs++ + builder.graph = scene.NewWithCapacity(len(builder.clipped) + len(builder.clippedPaths) + len(builder.clippedSoft) + 1) + builder.renderer = render.Store{} + builder.shapeIDs = builder.shapeIDs[:0] + builder.syncShapes() + builder.changes = builder.graph.DrainChanges(builder.changes[:0]) + return builder.renderer.Apply(builder.changes) +} + +// Changes returns the scene changes of the last build. +func (builder *Builder) Changes() []scene.Change { + return builder.changes +} + +// ClippedRectangles returns the rectangles left by the canvas clip, in paint order. +func (builder *Builder) ClippedRectangles() []gfx.Rectangle { + return builder.clipped +} + +// ClippedTriangles returns the triangles left by the canvas clip, in paint order. +func (builder *Builder) ClippedTriangles() []gfx.Triangle { + return builder.clippedPaths +} + +// ClippedTexts returns the texts left by the canvas clip, in paint order. +func (builder *Builder) ClippedTexts() []gfx.Text { + return builder.clippedTexts +} + +// ClippedImages returns the images left by the canvas clip, in paint order. +func (builder *Builder) ClippedImages() []gfx.Image { + return builder.clippedImages +} + +// OrderLen reports how many shapes the frame paints. +func (builder *Builder) OrderLen() int { + return len(builder.order) +} + +// LabelImages names the image each label was drawn from, -1 for text. +func (builder *Builder) LabelImages() []int32 { + return builder.labelImage +} + +// LastLabelImages is LabelImages for the labels last sent. +func (builder *Builder) LastLabelImages() []int32 { + return builder.lastLabelImage +} + +// LastImages is the image list the labels last sent were built from. +func (builder *Builder) LastImages() []gfx.Image { + return builder.lastImages +} + +// shapeRef names one clipped shape: an entry of builder.clippedPaths when +// triangle is set, of builder.clippedSoft when shadow is set, of builder.clipped +// otherwise. +type shapeRef struct { + index int32 + triangle bool + shadow bool +} + +// applyClipping drops every shape, image and text its canvas clip hides and +// notes, on the others, whether the clip cuts them: a shape left with HasClip +// set is drawn through a scissor rectangle by the renderer, which is how a +// partial shape is cut, so no geometry is cut here. It also merges rectangles, +// triangles, shadows, texts and images back into the order they were painted +// in: each primitive carries the paint order the canvas gave it. +func (builder *Builder) applyClipping() { + builder.clipped = builder.clipped[:0] + builder.clippedPaths = builder.clippedPaths[:0] + builder.clippedSoft = builder.clippedSoft[:0] + builder.clippedTexts = builder.clippedTexts[:0] + builder.clippedImages = builder.clippedImages[:0] + builder.clippedTextBefores = builder.clippedTextBefores[:0] + builder.clippedImageBefores = builder.clippedImageBefores[:0] + builder.order = builder.order[:0] + builder.layerShift = 0 + rectangles := builder.canvas.Rectangles() + triangles := builder.canvas.Triangles() + shadows := builder.canvas.Shadows() + texts := builder.canvas.Texts() + images := builder.canvas.Images() + // Walk the five lists as one paint order. A primitive with a smaller Order + // is painted first; on a tie (a border ring shares its backing rectangle's + // order, cell glyphs share their line's) shapes come before images and + // images before text. + ri, ti, si, xi, ii := 0, 0, 0, 0, 0 + for ri < len(rectangles) || ti < len(triangles) || si < len(shadows) || xi < len(texts) || ii < len(images) { + kind, best := 0, ^uint32(0) + if ri < len(rectangles) && rectangles[ri].Order < best { + kind, best = 1, rectangles[ri].Order + } + if ti < len(triangles) && triangles[ti].Order < best { + kind, best = 2, triangles[ti].Order + } + if si < len(shadows) && shadows[si].Order < best { + kind, best = 3, shadows[si].Order + } + if ii < len(images) && images[ii].Order < best { + kind, best = 4, images[ii].Order + } + if xi < len(texts) && texts[xi].Order < best { + kind = 5 + } + switch kind { + case 1: + builder.appendRectangle(rectangles[ri]) + ri++ + case 2: + builder.appendTriangle(triangles[ti]) + ti++ + case 3: + builder.appendShadow(shadows[si]) + si++ + case 4: + builder.appendImage(images[ii]) + ii++ + case 5: + builder.appendText(texts[xi]) + xi++ + } + } +} + +// appendImage adds image to the frame's label list unless its clip hides it or +// it has no area, cutting its source to the visible part. A backdrop is kept +// apart: its layer moves the rest of the frame above it. +func (builder *Builder) appendImage(image gfx.Image) { + if RoundPixel(image.Bounds.Width) <= 0 || RoundPixel(image.Bounds.Height) <= 0 { + return + } + if image.Backdrop { + // A backdrop is beneath every layer, before any shape: it carries no + // place among them. + builder.layerShift = 1 + builder.clippedImages = append(builder.clippedImages, image) + builder.clippedImageBefores = append(builder.clippedImageBefores, 0) + return + } + if !image.HasClip { + builder.clippedImages = append(builder.clippedImages, image) + builder.clippedImageBefores = append(builder.clippedImageBefores, uint32(len(builder.order))) + return + } + visible, ok := intersectVisible(image.Bounds, image.ClipOf) + if !ok { + return + } + if image.DevicePixels { + // The clip may end between device pixels; the picture is cut at one. + scale := builder.canvas.PixelScale() + if visible = deviceBounds(visible, scale); visible.Width <= 0 || visible.Height <= 0 { + return + } + } + if visible != image.Bounds { + sx := image.Source.Width / image.Bounds.Width + sy := image.Source.Height / image.Bounds.Height + image.Source.X += (visible.X - image.Bounds.X) * sx + image.Source.Y += (visible.Y - image.Bounds.Y) * sy + image.Source.Width = visible.Width * sx + image.Source.Height = visible.Height * sy + image.Bounds = visible + if image.DevicePixels { + image.Source = wholePixels(image.Source) + } + } + builder.clippedImages = append(builder.clippedImages, image) + builder.clippedImageBefores = append(builder.clippedImageBefores, uint32(len(builder.order))) +} + +// appendText adds text to the frame's label list and paints the cell glyph +// geometry that belongs to it, unless the text paints nothing. +func (builder *Builder) appendText(text gfx.Text) { + // A label with no area or no font size paints nothing, and the native label + // backends require positive values. Transient layouts (a closing drawer, a + // pane squeezed to nothing) can produce one; drop it here rather than failing + // the whole frame. + if RoundPixel(text.Bounds.Width) <= 0 || RoundPixel(text.Bounds.Height) <= 0 || text.Style.Size <= 0 { + return + } + if text.HasClip && !textClipVisible(text) { + return + } + builder.clippedTexts = append(builder.clippedTexts, text) + if text.RunCount > 0 { + builder.appendCellGlyphs(text) + } + // The cell glyph geometry is part of the line: it is painted before the + // glyphs, so the label comes after the shapes just appended. + builder.clippedTextBefores = append(builder.clippedTextBefores, uint32(len(builder.order))) +} + +// appendShadow puts shadow in the frame's order after cutting it to its clip, +// and drops it when nothing of it is inside. +func (builder *Builder) appendShadow(shadow gfx.Shadow) { + if shadow.HasClip { + visible, cut := clipVisibility(shadowBounds(shadow), shadow.ClipOf) + if !visible { + return + } + shadow.HasClip = cut + } + builder.order = append(builder.order, shapeRef{index: int32(len(builder.clippedSoft)), shadow: true}) + builder.clippedSoft = append(builder.clippedSoft, shadow) +} + +// appendCellGlyphs paints the geometry of a fixed-pitch line's cell glyphs — the Block Elements, +// Box Drawing, Braille, the corner shapes of Geometric Shapes, the Powerline separators and the +// Symbols for Legacy Computing — after the canvas's own, as the line's text is drawn after them +// (see gfx.Canvas.CellGlyphGeometry). +func (builder *Builder) appendCellGlyphs(text gfx.Text) { + shapes := builder.canvas.CellGlyphGeometry(gfx.CellGlyphShapes{ + Rectangles: builder.blocks[:0], + Triangles: builder.strokes[:0], + }, text) + builder.blocks, builder.strokes = shapes.Rectangles, shapes.Triangles + for _, rectangle := range builder.blocks { + builder.appendRectangle(rectangle) + } + for _, triangle := range builder.strokes { + builder.appendTriangle(triangle) + } +} + +// appendRectangle puts rectangle in the frame's order after cutting it to its clip, and drops it +// when nothing of it is inside. +func (builder *Builder) appendRectangle(rectangle gfx.Rectangle) { + if rectangle.HasClip { + visible, cut := clipVisibility(rectangle.Bounds, rectangle.ClipOf) + if !visible { + return + } + rectangle.HasClip = cut + } + builder.order = append(builder.order, shapeRef{index: int32(len(builder.clipped))}) + builder.clipped = append(builder.clipped, rectangle) +} + +// appendTriangle is appendRectangle for the triangles a renderer feathers: their scissor keeps the +// half device pixel the edge reaches past the silhouette. +func (builder *Builder) appendTriangle(triangle gfx.Triangle) { + if triangle.HasClip { + bounds := triangleBounds(triangle.Points) + if triangle.EdgeMask != 0 { + half := 0.5 / builder.canvas.PixelScale() + bounds.X -= half + bounds.Y -= half + bounds.Width += 2 * half + bounds.Height += 2 * half + } + visible, cut := clipVisibility(bounds, triangle.ClipOf) + if !visible { + return + } + triangle.HasClip = cut + } + builder.order = append(builder.order, shapeRef{index: int32(len(builder.clippedPaths)), triangle: true}) + builder.clippedPaths = append(builder.clippedPaths, triangle) +} + +// clipVisibility reports whether any of bounds lies inside clip and whether the +// clip cuts it, that is, whether part of bounds lies outside. +func clipVisibility(bounds, clip gfx.Rect) (visible, cut bool) { + if bounds.X+bounds.Width <= clip.X || bounds.Y+bounds.Height <= clip.Y || + bounds.X >= clip.X+clip.Width || bounds.Y >= clip.Y+clip.Height { + return false, false + } + return true, !ContainsRect(clip, bounds) +} + +// shadowBounds is the region a shadow paints in: the rectangle that casts it +// grown by how far its blur, spread and offset reach. +func shadowBounds(shadow gfx.Shadow) gfx.Rect { + extent := shadow.Style.Extent() + return gfx.Rect{ + X: shadow.Bounds.X - extent, Y: shadow.Bounds.Y - extent, + Width: shadow.Bounds.Width + 2*extent, Height: shadow.Bounds.Height + 2*extent, + } +} + +func triangleBounds(points [3]gfx.Point) gfx.Rect { + left := min32(points[0].X, min32(points[1].X, points[2].X)) + top := min32(points[0].Y, min32(points[1].Y, points[2].Y)) + right := max32(points[0].X, max32(points[1].X, points[2].X)) + bottom := max32(points[0].Y, max32(points[1].Y, points[2].Y)) + return gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top} +} + +func quadBounds(points [4]gfx.Point) gfx.Rect { + left := min32(min32(points[0].X, points[1].X), min32(points[2].X, points[3].X)) + top := min32(min32(points[0].Y, points[1].Y), min32(points[2].Y, points[3].Y)) + right := max32(max32(points[0].X, points[1].X), max32(points[2].X, points[3].X)) + bottom := max32(max32(points[0].Y, points[1].Y), max32(points[2].Y, points[3].Y)) + return gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top} +} + +func textClipVisible(text gfx.Text) bool { + _, visible := intersectVisible(text.Bounds, text.ClipOf) + if text.HasQuad { + _, warped := intersectVisible(quadBounds(text.Quad), text.ClipOf) + visible = visible || warped + } + return visible +} + +func textClipCuts(text gfx.Text) bool { + return !ContainsRect(text.ClipOf, text.Bounds) || + text.HasQuad && !ContainsRect(text.ClipOf, quadBounds(text.Quad)) +} + +func intersectVisible(bounds, clip gfx.Rect) (gfx.Rect, bool) { + left := max32(bounds.X, clip.X) + top := max32(bounds.Y, clip.Y) + right := min32(bounds.X+bounds.Width, clip.X+clip.Width) + bottom := min32(bounds.Y+bounds.Height, clip.Y+clip.Height) + if right <= left || bottom <= top { + return gfx.Rect{}, false + } + return gfx.Rect{X: left, Y: top, Width: right - left, Height: bottom - top}, true +} + +func max32(a, b float32) float32 { + if a > b { + return a + } + return b +} + +func min32(a, b float32) float32 { + if a < b { + return a + } + return b +} + +// drawnBy reports whether a stored instance already draws a clipped shape. +// Both sides are compared field by field, as the scene stores them. +func (builder *Builder) drawnBy(stored *render.Rectangle, ref shapeRef) bool { + if ref.triangle { + triangle := &builder.clippedPaths[ref.index] + return stored.Kind == scene.KindTriangle && stored.Color == scene.Color(triangle.Color) && + stored.EdgeMask == triangle.EdgeMask && stored.Shade == sceneShade(*triangle) && + stored.Points[0] == scene.Point(triangle.Points[0]) && + stored.Points[1] == scene.Point(triangle.Points[1]) && + stored.Points[2] == scene.Point(triangle.Points[2]) + } + if ref.shadow { + shadow := &builder.clippedSoft[ref.index] + return stored.Kind == scene.KindShadow && stored.Radius == shadow.Radius && + stored.Color == scene.Color(shadow.Color) && stored.Bounds == scene.Rect(shadow.Bounds) && + stored.Shadow == scene.Shadow(shadow.Style) + } + rectangle := &builder.clipped[ref.index] + return stored.Kind == scene.KindRectangle && stored.Radius == rectangle.Radius && + stored.Color == scene.Color(rectangle.Color) && stored.Bounds == scene.Rect(rectangle.Bounds) +} + +// syncShapes aligns the scene's nodes with the clipped shapes, rectangles and +// triangles together in paint order, so the render store, which paints in node +// order, always equals the canvas. +// +// A repaint usually changes one stretch of the shapes: a highlight appears, a +// tab closes, a page swaps. The shapes before and after that stretch are left +// alone; inside it the nodes are rewritten in place (a node that held a +// rectangle may become a triangle and keeps its place), and the difference in +// length is inserted or removed at the end of the stretch. Cost follows the +// size of the change, not of the page, and no node is ever painted out of +// order. +func (builder *Builder) syncShapes() { + root := builder.graph.Root() + stored := builder.renderer.Rectangles() // what the previous frame painted + oldCount, newCount := len(builder.shapeIDs), len(builder.order) + if len(stored) != oldCount { + // Not reachable while the store follows the scene; if it ever does not, + // rewrite every node rather than trust the comparison below. + stored = nil + } + + prefix := 0 + for prefix < min(len(stored), newCount) && builder.drawnBy(&stored[prefix], builder.order[prefix]) { + prefix++ + } + suffix := 0 + for suffix < min(oldCount, newCount)-prefix && len(stored) == oldCount && + builder.drawnBy(&stored[oldCount-1-suffix], builder.order[newCount-1-suffix]) { + suffix++ + } + oldMiddle, newMiddle := oldCount-prefix-suffix, newCount-prefix-suffix + + for index := prefix; index < prefix+min(oldMiddle, newMiddle); index++ { + builder.setShape(builder.shapeIDs[index], builder.order[index]) + } + switch { + case newMiddle > oldMiddle: + at := prefix + oldMiddle + add := newMiddle - oldMiddle + var previous scene.ID + if at > 0 { + previous = builder.shapeIDs[at-1] + } + for range add { + builder.shapeIDs = append(builder.shapeIDs, 0) + } + copy(builder.shapeIDs[at+add:], builder.shapeIDs[at:oldCount]) + for index := at; index < at+add; index++ { + previous = builder.insertShape(root, previous, builder.order[index]) + builder.shapeIDs[index] = previous + } + case oldMiddle > newMiddle: + from := prefix + newMiddle + for _, id := range builder.shapeIDs[from : prefix+oldMiddle] { + builder.graph.Remove(id) + } + builder.shapeIDs = slices.Delete(builder.shapeIDs, from, prefix+oldMiddle) + } +} + +// setShape makes an existing node draw a shape, whatever it drew before. +func (builder *Builder) setShape(id scene.ID, ref shapeRef) { + if ref.triangle { + value := SceneTriangle(builder.clippedPaths[ref.index]) + builder.graph.SetTriangle(id, value.Points, value.Color, value.EdgeMask, value.Shade) + return + } + if ref.shadow { + shadow := &builder.clippedSoft[ref.index] + builder.graph.SetShadow(id, scene.Rect(shadow.Bounds), scene.Color(shadow.Color), shadow.Radius, scene.Shadow(shadow.Style)) + return + } + builder.setRectangle(id, builder.clipped[ref.index]) +} + +// insertShape adds a node drawing a shape right after previous. +func (builder *Builder) insertShape(root, previous scene.ID, ref shapeRef) scene.ID { + if ref.triangle { + value := SceneTriangle(builder.clippedPaths[ref.index]) + id, _ := builder.graph.InsertTriangle(root, previous, value.Points, value.Color, value.EdgeMask, value.Shade) + return id + } + if ref.shadow { + shadow := &builder.clippedSoft[ref.index] + id, _ := builder.graph.InsertShadow(root, previous, scene.Rect(shadow.Bounds), scene.Color(shadow.Color), shadow.Radius, scene.Shadow(shadow.Style)) + return id + } + rectangle := builder.clipped[ref.index] + value := SceneRectangle(rectangle) + id, _ := builder.graph.InsertRoundedRectangle(root, previous, value.Bounds, value.Color, rectangle.Radius) + return id +} + +func (builder *Builder) setRectangle(id scene.ID, rectangle gfx.Rectangle) { + value := SceneRectangle(rectangle) + builder.graph.SetRoundedRectangle(id, value.Bounds, value.Color, rectangle.Radius) +} + +// syncLabels rebuilds the label list. A bitmap label carries its pixels across +// the native boundary only when that bitmap is not exactly what the same place +// in the previous frame showed, so a picture made of many bitmaps (see +// gfx.Surface) stages just the ones that changed. +func (builder *Builder) syncLabels() { + builder.labels = builder.labels[:0] + builder.labelImage = builder.labelImage[:0] + images := builder.clippedImages + texts := builder.clippedTexts + fontGeneration := builder.canvas.FontGeneration() + // Images and texts are each in paint order; merge them back into one order, + // because a label and a bitmap are both platform text labels. A backdrop is + // beneath everything whatever its own paint order, so it goes first. Each + // label carries how many shapes the frame painted before it, which is where + // the renderers put it back among them. + for ii := range images { + if images[ii].Backdrop { + builder.appendImageLabel(ii, builder.clippedImageBefores[ii]) + } + } + for ii, ti := 0, 0; ii < len(images) || ti < len(texts); { + for ii < len(images) && images[ii].Backdrop { + ii++ + } + if ti >= len(texts) || (ii < len(images) && images[ii].Order <= texts[ti].Order) { + builder.appendImageLabel(ii, builder.clippedImageBefores[ii]) + ii++ + continue + } + builder.appendTextLabel(texts[ti], fontGeneration, builder.clippedTextBefores[ti]) + ti++ + } +} + +// appendImageLabel adds image number index of builder.clippedImages to the +// frame's labels, after shapesBefore shapes. +func (builder *Builder) appendImageLabel(index int, shapesBefore uint32) { + image := builder.clippedImages[index] + bitmap := image.Bitmap + left := max(int(image.Source.X), 0) + top := max(int(image.Source.Y), 0) + right := min(int(math.Ceil(float64(image.Source.X+image.Source.Width))), bitmap.Width) + bottom := min(int(math.Ceil(float64(image.Source.Y+image.Source.Height))), bitmap.Height) + if left >= right || top >= bottom { + return + } + offset := top*bitmap.Stride + left*4 + length := (bottom-top-1)*bitmap.Stride + (right-left)*4 + if offset < 0 || length <= 0 || offset > len(bitmap.Pix) || length > len(bitmap.Pix)-offset { + return + } + width := RoundPixel(image.Bounds.Width) + height := RoundPixel(image.Bounds.Height) + if width <= 0 || height <= 0 { + return + } + layer := builder.PlatformLayer(image.Layer) + if image.Backdrop { + layer = 0 + } + // Rounded to logical pixels, unless the image is laid out in device pixels. + x, y, w, h := float32(RoundPosition(image.Bounds.X)), float32(RoundPosition(image.Bounds.Y)), float32(width), float32(height) + if image.DevicePixels { + x, y, w, h = image.Bounds.X, image.Bounds.Y, image.Bounds.Width, image.Bounds.Height + } + builder.labels = append(builder.labels, platform.TextLabel{ + X: x, Y: y, + Width: w, Height: h, + Layer: layer, + ShapesBefore: shapesBefore, + Bitmap: bitmap.Pix[offset : offset+length], BitmapWidth: right - left, BitmapHeight: bottom - top, + BitmapStride: bitmap.Stride, BitmapID: bitmap.ID, BitmapVersion: bitmap.Version, + BitmapUpload: builder.bitmapUpload(image, index), + }) + builder.labelImage = append(builder.labelImage, int32(index)) +} + +// bitmapUpload reports whether image number index must carry its pixels to the +// platform. It may omit them only when the label it is about to become showed +// the same picture in the frame last sent: the platform then reuses that +// label's texture. Another draw of the same bitmap elsewhere is no substitute, +// because the platform decides which label takes which old texture by position +// first. +func (builder *Builder) bitmapUpload(image gfx.Image, index int) bool { + label := len(builder.labels) + if image.Bitmap.ID == 0 || label >= len(builder.lastLabelImage) { + return true + } + previous := int(builder.lastLabelImage[label]) + if previous < 0 || previous >= len(builder.lastImages) { + return true + } + return !SameImageBitmap(image, builder.lastImages[previous]) +} + +// appendTextLabel adds one canvas text to the frame's labels. +func (builder *Builder) appendTextLabel(label gfx.Text, fontGeneration uint32, shapesBefore uint32) { + width := RoundPixel(label.Bounds.Width) + height := RoundPixel(label.Bounds.Height) + if width <= 0 || height <= 0 { + return + } + // Integer logical-pixel bounds keep the texture exactly one texel per + // physical pixel so linear sampling stays crisp on scaled displays. + entry := platform.TextLabel{ + Value: label.Value, + Identity: label.Identity, + X: float32(RoundPosition(label.Bounds.X)), Y: float32(RoundPosition(label.Bounds.Y)), + Width: float32(width), Height: float32(height), + OriginX: RoundingRemainder(label.Bounds.X), OriginY: RoundingRemainder(label.Bounds.Y), + FontSize: label.Style.Size, Weight: label.Style.Weight, Italic: label.Style.Italic, + Color: platform.Color{ + Red: float64(label.Style.Color.Red), Green: float64(label.Style.Color.Green), + Blue: float64(label.Style.Color.Blue), Alpha: float64(label.Style.Color.Alpha), + }, + Layer: builder.PlatformLayer(label.Layer), + ShapesBefore: shapesBefore, + Mono: label.Style.Mono, MonoFace: label.Style.MonoFace, CellWidth: label.CellWidth, Baseline: label.Baseline, Runs: builder.canvas.TextRuns(label), + } + if !label.Style.Mono && label.RunCount == 0 { + // Only text in the interface font follows its generation. + entry.FontGeneration = fontGeneration + } + if label.RunCount > 0 { + // The font does not draw the cell glyphs; appendCellGlyphs did. + entry.Value, entry.Runs = builder.replaceCellGlyphs(entry.Value, entry.Runs) + } + if label.HasClip { + if textClipCuts(label) { + // The clip cuts the label partway: the renderers scissor to it. + entry.Clip, entry.Clipped = label.ClipOf, true + } + } + if label.HasQuad { + // A warped line keeps its rasterisation box and moves only where the + // picture lands, so the platform draws the same texture as a quad. + entry.Quad, entry.HasQuad = label.Quad, true + for corner, tint := range label.Tint { + entry.Tint[corner] = platform.Color{ + Red: float64(tint.Red), Green: float64(tint.Green), + Blue: float64(tint.Blue), Alpha: float64(tint.Alpha), + } + } + } + builder.labels = append(builder.labels, entry) + builder.labelImage = append(builder.labelImage, -1) +} + +// cellReplaceLimit bounds the memoized cell glyph replacements: a screen holds +// its grid's rows and a little slack, and past the limit the memo starts over +// rather than keeping every line a session ever showed. +const cellReplaceLimit = 256 + +// cellReplaceMemo is one line's font-ready form: out is what ReplaceCellGlyphs +// built for in, kept while the same value and runs keep arriving. +type cellReplaceMemo struct { + inValue, outValue string + inRuns, outRuns []gfx.TextRun +} + +// replaceCellGlyphs is gfx.ReplaceCellGlyphs with a memory. A label sync that +// one changed row opened sends every row again; the rows that kept their value +// and runs get the replacement they already have instead of a fresh copy of the +// line and its runs, which is most of the garbage a keystroke in a bordered +// grid page otherwise makes. +func (builder *Builder) replaceCellGlyphs(value string, runs []gfx.TextRun) (string, []gfx.TextRun) { + for i := range builder.cellReplace { + if memo := &builder.cellReplace[i]; memo.inValue == value && slices.Equal(memo.inRuns, runs) { + return memo.outValue, memo.outRuns + } + } + outValue, outRuns := gfx.ReplaceCellGlyphs(value, runs) + // A line without cell glyphs comes back as it went in; it has nothing to + // remember, and its runs are the caller's own slice. + if len(outRuns) == 0 || len(runs) == 0 || &outRuns[0] == &runs[0] { + return outValue, outRuns + } + if len(builder.cellReplace) >= cellReplaceLimit { + builder.cellReplace = builder.cellReplace[:0] + } + builder.cellReplace = append(builder.cellReplace, cellReplaceMemo{ + inValue: value, inRuns: append([]gfx.TextRun(nil), runs...), + outValue: outValue, outRuns: outRuns, + }) + return outValue, outRuns +} + +// deviceBounds rounds the edges of bounds to whole device pixels of scale. +func deviceBounds(bounds gfx.Rect, scale float32) gfx.Rect { + edge := func(value float32) float32 { return float32(math.Floor(float64(value)*float64(scale) + 0.5)) } + left, top := edge(bounds.X), edge(bounds.Y) + right, bottom := edge(bounds.X+bounds.Width), edge(bounds.Y+bounds.Height) + return gfx.Rect{X: left / scale, Y: top / scale, Width: (right - left) / scale, Height: (bottom - top) / scale} +} + +// wholePixels rounds the edges of a bitmap region to whole bitmap pixels. +func wholePixels(region gfx.Rect) gfx.Rect { + left, top := math.Floor(float64(region.X)+0.5), math.Floor(float64(region.Y)+0.5) + right, bottom := math.Floor(float64(region.X+region.Width)+0.5), math.Floor(float64(region.Y+region.Height)+0.5) + return gfx.Rect{X: float32(left), Y: float32(top), Width: float32(right - left), Height: float32(bottom - top)} +} + +// ContainsRect reports whether inner lies wholly inside outer. +func ContainsRect(outer, inner gfx.Rect) bool { + return inner.X >= outer.X && inner.Y >= outer.Y && + inner.X+inner.Width <= outer.X+outer.Width && inner.Y+inner.Height <= outer.Y+outer.Height +} + +// RoundingRemainder is what RoundPosition took off value: the sub-pixel position +// backends that place text at device pixels draw it at (platform.TextLabel.OriginX). +func RoundingRemainder(value float32) float32 { + return value - float32(RoundPosition(value)) +} + +// RoundPixel rounds a size to the nearest logical pixel, never below zero. +func RoundPixel(value float32) int32 { + if value < 0 { + return 0 + } + return int32(value + 0.5) +} + +// RoundPosition rounds a coordinate to the nearest logical pixel. Unlike a +// size, a position may be negative: a leaving drawer and its text move past the +// window edge together, and clamping either to zero would stop it at the edge. +func RoundPosition(value float32) int32 { + return int32(math.Floor(float64(value) + 0.5)) +} + +// RoundPresenceRect puts a native overlay on the same whole logical pixels as +// the moving label it covers. Presence rounds a text label's origin so its +// texture is not rebuilt every frame; the platform editor next to it has to +// land on the same pixel. +func RoundPresenceRect(rect gfx.Rect) gfx.Rect { + return gfx.Rect{ + X: float32(RoundPosition(rect.X)), Y: float32(RoundPosition(rect.Y)), + Width: float32(RoundPixel(rect.Width)), Height: float32(RoundPixel(rect.Height)), + } +} + +// SceneRectangle converts a canvas rectangle to its render instance shape. +func SceneRectangle(rectangle gfx.Rectangle) render.Rectangle { + return render.Rectangle{ + Kind: scene.KindRectangle, + Bounds: scene.Rect{ + X: rectangle.Bounds.X, Y: rectangle.Bounds.Y, + Width: rectangle.Bounds.Width, Height: rectangle.Bounds.Height, + }, + Color: scene.Color{ + Red: rectangle.Color.Red, Green: rectangle.Color.Green, + Blue: rectangle.Color.Blue, Alpha: rectangle.Color.Alpha, + }, + Radius: rectangle.Radius, + Layer: rectangle.Layer, + } +} + +// SceneTriangle converts a canvas triangle to its render instance shape. +func SceneTriangle(triangle gfx.Triangle) render.Rectangle { + return render.Rectangle{ + Kind: scene.KindTriangle, + Points: [3]scene.Point{ + {X: triangle.Points[0].X, Y: triangle.Points[0].Y}, + {X: triangle.Points[1].X, Y: triangle.Points[1].Y}, + {X: triangle.Points[2].X, Y: triangle.Points[2].Y}, + }, + EdgeMask: triangle.EdgeMask, + Color: scene.Color{ + Red: triangle.Color.Red, Green: triangle.Color.Green, + Blue: triangle.Color.Blue, Alpha: triangle.Color.Alpha, + }, + Shade: sceneShade(triangle), + Layer: triangle.Layer, + } +} + +// sceneShade is the vertex colors of a shaded triangle, and the zero Shade for a +// flat one, whatever stale colors its Shade array holds. +func sceneShade(triangle gfx.Triangle) scene.Shade { + if !triangle.Shaded { + return scene.Shade{} + } + return scene.Shade{On: true, Colors: [2]scene.Color{scene.Color(triangle.Shade[0]), scene.Color(triangle.Shade[1])}} +} + +// instanceState is what a render instance knows about its place on screen that +// the scene does not carry: the layer it composes in and the clip that cuts it. +type instanceState struct { + layer uint16 + clipped bool + clip scene.Rect +} + +// stampState copies each primitive's canvas layer and clip onto its render +// instance and reports whether either changed anywhere, which a partial update +// would not carry to the GPU. Instances are listed by the scene's tree order, +// which syncShapes keeps equal to paint order, so the shape at index i is the +// instance at index i; should the store ever disagree, the state travels with +// the node's storage slot instead. +func (builder *Builder) stampState() (changed bool) { + instances := builder.renderer.Rectangles() + if len(instances) != len(builder.shapeIDs) { + return builder.stampBySlot() + } + for index, id := range builder.shapeIDs { + instance := &instances[index] + if instance.ID != id { + return builder.stampBySlot() + } + state := builder.shapeState(builder.order[index]) + if instance.Layer != state.layer || instance.Clipped != state.clipped || instance.Clip != state.clip { + instance.Layer, instance.Clipped, instance.Clip = state.layer, state.clipped, state.clip + changed = true + } + } + return changed +} + +// stampBySlot is stampState for a store whose order is not the paint order. +func (builder *Builder) stampBySlot() (changed bool) { + for index, id := range builder.shapeIDs { + slot, ok := id.Slot() + if !ok { + continue + } + for int(slot) >= len(builder.stateBySlot) { + builder.stateBySlot = append(builder.stateBySlot, instanceState{}) + } + builder.stateBySlot[slot] = builder.shapeState(builder.order[index]) + } + instances := builder.renderer.Rectangles() + for index := range instances { + slot, _ := instances[index].ID.Slot() + state := builder.stateBySlot[slot] + if instances[index].Layer != state.layer || instances[index].Clipped != state.clipped || instances[index].Clip != state.clip { + instances[index].Layer, instances[index].Clipped, instances[index].Clip = state.layer, state.clipped, state.clip + changed = true + } + } + return changed +} + +// shapeState is the layer and clip the platform draws a shape with. +func (builder *Builder) shapeState(ref shapeRef) instanceState { + var state instanceState + if ref.shadow { + shadow := &builder.clippedSoft[ref.index] + state = instanceState{layer: shadow.Layer, clipped: shadow.HasClip} + if shadow.HasClip { + state.clip = scene.Rect(shadow.ClipOf) + } + } else if ref.triangle { + triangle := &builder.clippedPaths[ref.index] + state = instanceState{layer: triangle.Layer, clipped: triangle.HasClip} + if triangle.HasClip { + state.clip = scene.Rect(triangle.ClipOf) + } + } else { + rectangle := &builder.clipped[ref.index] + state = instanceState{layer: rectangle.Layer, clipped: rectangle.HasClip} + if rectangle.HasClip { + state.clip = scene.Rect(rectangle.ClipOf) + } + } + state.layer = builder.PlatformLayer(state.layer) + return state +} + +// sameAsLastContent reports whether the texts to draw are exactly those last +// sent to the platform. +func (builder *Builder) sameAsLastContent() bool { + if builder.canvas.FontGeneration() != builder.lastFontGeneration || !sameImages(builder.clippedImages, builder.lastImages) { + return false + } + // A label's place among the shapes can move while the label itself does + // not: a shape before it can drop out of the clip, or paint nothing, and + // then the renderers must be told where the label goes. + if !slices.Equal(builder.clippedTextBefores, builder.lastTextBefores) || + !slices.Equal(builder.clippedImageBefores, builder.lastImageBefores) { + return false + } + left, right := builder.clippedTexts, builder.lastTexts + if len(left) != len(right) { + return false + } + for index := range left { + a, b := left[index], right[index] + if a.Value != b.Value || a.Style != b.Style || a.Identity != b.Identity || a.Layer != b.Layer || a.Order != b.Order { + return false + } + if a.Bounds != b.Bounds || a.CellWidth != b.CellWidth || a.Baseline != b.Baseline || a.RunCount != b.RunCount { + return false + } + if a.HasClip != b.HasClip || a.HasClip && a.ClipOf != b.ClipOf { + return false + } + // Where a warped line lands changes every frame of an animation while + // its picture stays the same: the platform must still see the new quad. + if a.HasQuad != b.HasQuad { + return false + } + if a.HasQuad && (a.Quad != b.Quad || a.Tint != b.Tint) { + return false + } + if a.RunCount == 0 { + continue + } + current := builder.canvas.TextRuns(a) + if len(current) != int(a.RunCount) || b.RunFirst < 0 || b.RunCount < 0 || int(b.RunFirst+b.RunCount) > len(builder.lastRuns) { + return false + } + saved := builder.lastRuns[b.RunFirst : b.RunFirst+b.RunCount] + for run := range current { + if current[run] != saved[run] { + return false + } + } + } + return true +} + +func sameImages(left, right []gfx.Image) bool { + if len(left) != len(right) { + return false + } + for index := range left { + a, b := left[index], right[index] + if a.Bounds != b.Bounds || a.Source != b.Source || a.Layer != b.Layer || a.Order != b.Order || a.Backdrop != b.Backdrop || a.Bitmap.Width != b.Bitmap.Width || + a.Bitmap.Height != b.Bitmap.Height || a.Bitmap.Stride != b.Bitmap.Stride || a.Bitmap.ID != b.Bitmap.ID || + a.Bitmap.Version != b.Bitmap.Version || len(a.Bitmap.Pix) != len(b.Bitmap.Pix) { + return false + } + if len(a.Bitmap.Pix) > 0 && &a.Bitmap.Pix[0] != &b.Bitmap.Pix[0] { + return false + } + } + return true +} + +// SameImageBitmap reports whether two draws show the very same pixels: the same +// identity and version, source region and storage. A bitmap with no identity +// (ID 0) is never the same: nothing says its pixels did not change. +func SameImageBitmap(a, b gfx.Image) bool { + if a.Source != b.Source || a.Bitmap.Width != b.Bitmap.Width || a.Bitmap.Height != b.Bitmap.Height || + a.Bitmap.Stride != b.Bitmap.Stride || a.Bitmap.ID != b.Bitmap.ID || a.Bitmap.Version != b.Bitmap.Version || + len(a.Bitmap.Pix) != len(b.Bitmap.Pix) || a.Bitmap.ID == 0 { + return false + } + return len(a.Bitmap.Pix) == 0 || &a.Bitmap.Pix[0] == &b.Bitmap.Pix[0] +} + +// saveContent remembers this frame's texts for the next comparison. Their runs +// live in the canvas, which is rewritten by the next paint, so they are copied. +func (builder *Builder) saveContent() { + builder.lastFontGeneration = builder.canvas.FontGeneration() + builder.lastImages = append(builder.lastImages[:0], builder.clippedImages...) + builder.lastLabelImage = append(builder.lastLabelImage[:0], builder.labelImage...) + builder.lastTexts = append(builder.lastTexts[:0], builder.clippedTexts...) + builder.lastTextBefores = append(builder.lastTextBefores[:0], builder.clippedTextBefores...) + builder.lastImageBefores = append(builder.lastImageBefores[:0], builder.clippedImageBefores...) + builder.lastRuns = builder.lastRuns[:0] + for index := range builder.lastTexts { + text := &builder.lastTexts[index] + runs := builder.canvas.TextRuns(*text) + text.RunFirst = int32(len(builder.lastRuns)) + builder.lastRuns = append(builder.lastRuns, runs...) + } +} diff --git a/internal/framebuild/framebuild_test.go b/internal/framebuild/framebuild_test.go new file mode 100644 index 00000000..c28a47d6 --- /dev/null +++ b/internal/framebuild/framebuild_test.go @@ -0,0 +1,285 @@ +package framebuild + +import ( + "reflect" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/scene" +) + +func opaqueBitmap(id uint64, version uint32, width, height int) gfx.Bitmap { + pixels := make([]byte, width*height*4) + for index := 3; index < len(pixels); index += 4 { + pixels[index] = 255 + } + return gfx.Bitmap{Pix: pixels, Width: width, Height: height, Stride: width * 4, ID: id, Version: version} +} + +func platformColor(color gfx.Color) platform.Color { + return platform.Color{ + Red: float64(color.Red), Green: float64(color.Green), + Blue: float64(color.Blue), Alpha: float64(color.Alpha), + } +} + +// TestBuilderCharacterizesTheFrame paints a deterministic scene and checks the +// frame the builder reconciles: shape geometry, colors and order, the clips and +// layers stamped onto them, and every field of the labels that carry text and +// bitmaps to the platform. +func TestBuilderCharacterizesTheFrame(t *testing.T) { + sharp := gfx.Color{Red: 1, Alpha: 1} + round := gfx.Color{Green: 1, Alpha: 1} + shade := gfx.Color{Blue: 1, Alpha: 0.5} + cut := gfx.Color{Red: 0.2, Green: 0.4, Blue: 0.6, Alpha: 1} + layered := gfx.Color{Red: 0.9, Green: 0.8, Alpha: 1} + quadTint := [4]gfx.Color{ + {Red: 1, Alpha: 1}, {Green: 1, Alpha: 1}, + {Blue: 1, Alpha: 1}, {Red: 1, Green: 1, Alpha: 1}, + } + textColor := gfx.Color{Red: 0.5, Green: 0.5, Blue: 0.5, Alpha: 1} + + backdrop := opaqueBitmap(7, 1, 4, 4) + picture := opaqueBitmap(9, 3, 8, 4) + clip := gfx.Rect{X: 40, Y: 40, Width: 60, Height: 60} + sharpBounds := gfx.Rect{Width: 30, Height: 30} + roundBounds := gfx.Rect{X: 10, Y: 10, Width: 20, Height: 20} + shadowBounds := gfx.Rect{X: 15, Y: 15, Width: 20, Height: 20} + cutBounds := gfx.Rect{X: 50, Y: 50, Width: 100, Height: 100} + layerBounds := gfx.Rect{X: 60, Y: 10, Width: 10, Height: 10} + imageBounds := gfx.Rect{X: 70, Y: 10, Width: 16, Height: 8} + proportional := gfx.Rect{X: 4, Y: 4, Width: 60, Height: 14} + runsBounds := gfx.Rect{X: 4, Y: 100, Width: 56, Height: 12} + layerText := gfx.Rect{X: 4, Y: 120, Width: 60, Height: 14} + warpBounds := gfx.Rect{X: 4, Y: 140, Width: 60, Height: 14} + warpQuad := gfx.Quad{ + Points: [4]gfx.Point{{X: 4, Y: 140}, {X: 64, Y: 144}, {X: 6, Y: 154}, {X: 62, Y: 156}}, + Tint: quadTint, + } + runs := []gfx.TextRun{ + {Column: 0, Bytes: 1, Cells: 1, Color: textColor, Underline: true}, + {Column: 1, Bytes: 1, Cells: 1, Color: textColor, Strike: true}, + } + + var canvas gfx.Canvas + canvas.DrawBackdrop(backdrop, gfx.Rect{X: 0, Y: 0, Width: 4, Height: 4}, gfx.Rect{X: 0, Y: 0, Width: 20, Height: 20}) + canvas.Fill(sharpBounds, sharp) + canvas.Rounded(roundBounds, 8, round) + canvas.Shadow(shadowBounds, 4, gfx.ShadowStyle{OffsetY: 2, Blur: 6}, shade) + canvas.Label("proportional", proportional, gfx.TextStyle{Size: 12, Weight: 400, Color: textColor}) + canvas.Clip(clip) + canvas.Fill(cutBounds, cut) + canvas.Label("cut label", gfx.Rect{X: 30, Y: 40, Width: 60, Height: 12}, gfx.TextStyle{Size: 12, Color: textColor}) + canvas.FillQuad(gfx.Quad{ + Points: [4]gfx.Point{{X: 30, Y: 30}, {X: 70, Y: 30}, {X: 30, Y: 70}, {X: 70, Y: 70}}, + Tint: quadTint, + }) + canvas.Unclip() + canvas.LabelRuns("ab", runsBounds, gfx.TextStyle{Size: 10, Mono: true, Color: textColor}, 7, runs) + canvas.PushLayer(5) + canvas.Fill(layerBounds, layered) + canvas.DrawBitmap(picture, imageBounds) + canvas.Label("layered", layerText, gfx.TextStyle{Size: 12, Color: textColor}) + canvas.PopLayer() + canvas.LabelQuad("warped", warpBounds, warpQuad, gfx.TextStyle{Size: 12, Color: textColor}) + + canvasTriangles := append([]gfx.Triangle(nil), canvas.Triangles()...) + if len(canvasTriangles) != 2 { + t.Fatalf("canvas painted %d triangles, want 2", len(canvasTriangles)) + } + + builder := New(&canvas) + frame, err := builder.Build() + if err != nil { + t.Fatalf("Build: %v", err) + } + + // Shapes: the backdrop shifts every canvas layer one up, taking platform + // layer zero; the topmost layer stays topmost. + instances := frame.Rectangles + wantKinds := []scene.Kind{ + scene.KindRectangle, scene.KindRectangle, scene.KindShadow, + scene.KindRectangle, scene.KindTriangle, scene.KindTriangle, scene.KindRectangle, + } + if len(instances) != len(wantKinds) { + t.Fatalf("built %d instances, want %d: %+v", len(instances), len(wantKinds), instances) + } + for index, want := range wantKinds { + if instances[index].Kind != want { + t.Fatalf("instance %d kind = %d, want %d: %+v", index, instances[index].Kind, want, instances) + } + } + if got := instances[0]; got.Bounds != scene.Rect(sharpBounds) || got.Color != scene.Color(sharp) || got.Radius != 0 { + t.Errorf("sharp rectangle = %+v", got) + } + if got := instances[1]; got.Bounds != scene.Rect(roundBounds) || got.Color != scene.Color(round) || got.Radius != 8 { + t.Errorf("rounded rectangle = %+v", got) + } + if got := instances[2]; got.Bounds != scene.Rect(shadowBounds) || got.Color != scene.Color(shade) || + got.Radius != 4 || got.Shadow != (scene.Shadow{OffsetY: 2, Blur: 6}) { + t.Errorf("shadow = %+v", got) + } + if got := instances[3]; got.Bounds != scene.Rect(cutBounds) || !got.Clipped || got.Clip != scene.Rect(clip) { + t.Errorf("clipped rectangle = %+v, want its full bounds and the clip", got) + } + for index := range canvasTriangles { + got := instances[4+index] + want := SceneTriangle(canvasTriangles[index]) + if got.Points != want.Points || got.Color != want.Color || got.EdgeMask != want.EdgeMask { + t.Errorf("triangle %d = %+v, want %+v", index, got, want) + } + if got.EdgeMask == 0 || !got.Shade.On { + t.Errorf("triangle %d lost its edge mask or shading: %+v", index, got) + } + if !got.Clipped || got.Clip != scene.Rect(clip) { + t.Errorf("triangle %d did not keep its clip: %+v", index, got) + } + } + if got := instances[6]; got.Bounds != scene.Rect(layerBounds) || got.Color != scene.Color(layered) || got.Layer != 6 { + t.Errorf("layered rectangle = %+v, want platform layer 6", got) + } + for index, instance := range instances[:6] { + if instance.Layer != 1 { + t.Errorf("instance %d layer = %d, want 1 above the backdrop", index, instance.Layer) + } + } + + // Labels: the backdrop first, then images and text merged by paint order. + labels := builder.Labels() + if len(labels) != 7 { + t.Fatalf("labels = %d, want 7: %+v", len(labels), labels) + } + if got := labels[0]; got.BitmapID != backdrop.ID || !got.BitmapUpload || got.Layer != 0 || got.ShapesBefore != 0 || + got.BitmapWidth != 4 || got.BitmapHeight != 4 || got.BitmapStride != 16 { + t.Errorf("backdrop label = %+v", got) + } + if got := labels[1]; got.Value != "proportional" || got.Layer != 1 || got.ShapesBefore != 3 || + got.FontSize != 12 || got.Weight != 400 || got.Color != platformColor(textColor) || got.Mono { + t.Errorf("proportional label = %+v", got) + } + if got := labels[2]; got.Value != "cut label" || got.Layer != 1 || got.ShapesBefore != 4 || + !got.Clipped || got.Clip != clip { + t.Errorf("clipped label = %+v, want its clip and the shapes before it", got) + } + if got := labels[3]; got.Value != "ab" || !got.Mono || got.CellWidth != 7 || got.Layer != 1 || got.ShapesBefore != 6 { + t.Errorf("runs label = %+v", got) + } else if len(got.Runs) != 2 || !got.Runs[0].Underline || !got.Runs[1].Strike { + t.Errorf("runs label lost its decorations: %+v", got.Runs) + } + if got := labels[4]; got.BitmapID != picture.ID || got.BitmapVersion != picture.Version || got.Layer != 6 || + got.ShapesBefore != 7 || got.BitmapWidth != 8 || got.BitmapHeight != 4 || !got.BitmapUpload { + t.Errorf("image label = %+v", got) + } + if got := labels[5]; got.Value != "layered" || got.Layer != 6 || got.ShapesBefore != 7 { + t.Errorf("layered label = %+v", got) + } + if got := labels[6]; got.Value != "warped" || !got.HasQuad || got.Quad != warpQuad.Points || got.Layer != 1 || got.ShapesBefore != 7 { + t.Errorf("warped label = %+v", got) + } else { + for corner, tint := range warpQuad.Tint { + if got.Tint[corner] != platformColor(tint) { + t.Errorf("warped tint %d = %+v, want %+v", corner, got.Tint[corner], platformColor(tint)) + } + } + } + + // An unchanged repaint sends no labels, but still describes every instance. + again, err := builder.Build() + if err != nil { + t.Fatalf("unchanged Build: %v", err) + } + if again.TextLabels != nil { + t.Fatalf("unchanged repaint sent labels: %+v", again.TextLabels) + } + if !again.Update.Empty() { + t.Fatalf("unchanged repaint produced renderer work: %+v", again.Update) + } + if len(again.Rectangles) != len(wantKinds) { + t.Fatalf("unchanged repaint returned %d instances, want %d", len(again.Rectangles), len(wantKinds)) + } + if !reflect.DeepEqual(again.Rectangles, frame.Rectangles) { + t.Fatalf("unchanged repaint changed the instances") + } +} + +// TestBuilderRestagesOnlyChangedBitmaps checks that a changed tile carries its +// pixels again while an unchanged frame does not. +func TestBuilderRestagesOnlyChangedBitmaps(t *testing.T) { + bitmap := opaqueBitmap(11, 1, 4, 4) + tile := gfx.Rect{X: 4, Y: 4, Width: 8, Height: 8} + paint := func(canvas *gfx.Canvas) { + canvas.DrawBitmap(bitmap, tile) + } + uploads := func(labels []platform.TextLabel) (count int) { + for _, label := range labels { + if label.BitmapUpload { + count++ + } + } + return count + } + + var canvas gfx.Canvas + paint(&canvas) + builder := New(&canvas) + if _, err := builder.Build(); err != nil { + t.Fatalf("Build: %v", err) + } + if got := uploads(builder.Labels()); got != 1 { + t.Fatalf("first frame uploaded %d bitmaps, want 1", got) + } + + if frame, err := builder.Build(); err != nil { + t.Fatalf("unchanged Build: %v", err) + } else if frame.TextLabels != nil { + t.Fatalf("unchanged frame sent labels: %+v", frame.TextLabels) + } + + bitmap.Version++ + canvas.Reset() + paint(&canvas) + frame, err := builder.Build() + if err != nil { + t.Fatalf("changed Build: %v", err) + } + if frame.TextLabels == nil || len(frame.TextLabels) != 1 { + t.Fatalf("changed bitmap sent no labels: %+v", frame.TextLabels) + } + if !frame.TextLabels[0].BitmapUpload || frame.TextLabels[0].BitmapVersion != 2 { + t.Fatalf("changed bitmap label = %+v, want its pixels and version 2", frame.TextLabels[0]) + } +} + +// The memo hands a line that arrives unchanged back as it replaced it, and a +// line whose runs changed — a recolour keeps the value — gets a replacement +// built for the new runs, not the remembered one. +func TestReplaceCellGlyphsMemoFollowsItsInput(t *testing.T) { + builder := New(&gfx.Canvas{}) + value := "┌──┐ ok" + runs := []gfx.TextRun{{Bytes: int32(len(value)), Cells: 6, Color: gfx.Color{Alpha: 1}}} + firstValue, firstRuns := builder.replaceCellGlyphs(value, runs) + if firstValue == value { + t.Fatalf("a line with cell glyphs came back unchanged: %q", firstValue) + } + againValue, againRuns := builder.replaceCellGlyphs(value, runs) + if againValue != firstValue || &againRuns[0] != &firstRuns[0] { + t.Fatal("the same line was replaced again instead of remembered") + } + + recolored := []gfx.TextRun{{Bytes: int32(len(value)), Cells: 6, Color: gfx.Color{Red: 1, Alpha: 1}}} + recValue, recRuns := builder.replaceCellGlyphs(value, recolored) + if recRuns[0].Color != recolored[0].Color { + t.Fatalf("a recoloured line got the remembered colour %+v", recRuns[0].Color) + } + if recValue != firstValue { + t.Fatalf("the replacement text changed with the colour: %q and %q", recValue, firstValue) + } + + plain := "plain line" + plainRuns := []gfx.TextRun{{Bytes: int32(len(plain)), Cells: 10, Color: gfx.Color{Alpha: 1}}} + outValue, outRuns := builder.replaceCellGlyphs(plain, plainRuns) + if outValue != plain || &outRuns[0] != &plainRuns[0] { + t.Fatal("a line without cell glyphs was copied or remembered") + } +} diff --git a/internal/platform/web/glpack.go b/internal/platform/web/glpack.go new file mode 100644 index 00000000..ef813807 --- /dev/null +++ b/internal/platform/web/glpack.go @@ -0,0 +1,60 @@ +package web + +import ( + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +// tileRanges splits a label's device-pixel width into horizontal texture +// ranges no wider than maxTex, with a two-pixel overlap so linear sampling at +// a seam blends neighbouring texels instead of clamping. +func tileRanges(deviceWidth, maxTex int) [][2]int { + if deviceWidth <= 0 || maxTex <= 0 { + return nil + } + if deviceWidth <= maxTex { + return [][2]int{{0, deviceWidth}} + } + step := max(1, maxTex-2) + var ranges [][2]int + for left := 0; left < deviceWidth; left += step { + right := min(deviceWidth, left+maxTex) + if right <= left { + break + } + ranges = append(ranges, [2]int{left, right}) + } + return ranges +} + +// packInstance writes one render instance as the five vec4 slots the WebGL2 +// scene shader reads: bounds, color, style, Shade1 and Shade2. A rectangle uses +// Bounds and Style.x (radius); a triangle packs its three points and edge mask; +// a shadow packs its casting rectangle, blur, and offset/spread. +func packInstance(dst []float32, instance render.Rectangle) { + for index := 0; index < 20; index++ { + dst[index] = 0 + } + colors := instance.VertexColors() + setColor := func(at int, color scene.Color) { + dst[at], dst[at+1], dst[at+2], dst[at+3] = color.Red, color.Green, color.Blue, color.Alpha + } + switch instance.Kind { + case scene.KindTriangle: + points := instance.Points + dst[0], dst[1], dst[2], dst[3] = points[0].X, points[0].Y, points[1].X, points[1].Y + dst[8], dst[9], dst[10], dst[11] = points[2].X, float32(instance.Layer), points[2].Y, float32(instance.EdgeMask)+1 + setColor(4, colors[0]) + setColor(12, colors[1]) + setColor(16, colors[2]) + case scene.KindShadow: + dst[0], dst[1], dst[2], dst[3] = instance.Bounds.X, instance.Bounds.Y, instance.Bounds.Width, instance.Bounds.Height + dst[8], dst[9], dst[10], dst[11] = instance.Radius, 0, instance.Shadow.Blur, 0 + setColor(4, instance.Color) + dst[12], dst[13], dst[14], dst[15] = instance.Shadow.OffsetX, instance.Shadow.OffsetY, instance.Shadow.Spread, 0 + default: + dst[0], dst[1], dst[2], dst[3] = instance.Bounds.X, instance.Bounds.Y, instance.Bounds.Width, instance.Bounds.Height + dst[8] = instance.Radius + setColor(4, instance.Color) + } +} diff --git a/internal/platform/web/glpack_test.go b/internal/platform/web/glpack_test.go new file mode 100644 index 00000000..71206549 --- /dev/null +++ b/internal/platform/web/glpack_test.go @@ -0,0 +1,81 @@ +package web + +import ( + "reflect" + "testing" + + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +func TestTileRangesCoverTheWidthWithOverlap(t *testing.T) { + got := tileRanges(100, 40) + want := [][2]int{{0, 40}, {38, 78}, {76, 100}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("tile ranges = %v, want %v", got, want) + } + if single := tileRanges(30, 40); !reflect.DeepEqual(single, [][2]int{{0, 30}}) { + t.Fatalf("a label inside one texture = %v", single) + } + if empty := tileRanges(0, 40); len(empty) != 0 { + t.Fatalf("empty label = %v", empty) + } +} + +func TestPackInstanceRectangle(t *testing.T) { + dst := make([]float32, 20) + packInstance(dst, render.Rectangle{ + Kind: scene.KindRectangle, + Bounds: scene.Rect{X: 10, Y: 20, Width: 30, Height: 40}, + Color: scene.Color{Red: 1, Green: 2, Blue: 3, Alpha: 4}, + Radius: 6, + Layer: 2, + }) + want := make([]float32, 20) + want[0], want[1], want[2], want[3] = 10, 20, 30, 40 + want[4], want[5], want[6], want[7] = 1, 2, 3, 4 + want[8] = 6 + if !reflect.DeepEqual(dst, want) { + t.Fatalf("packed rectangle = %v, want %v", dst, want) + } +} + +func TestPackInstanceTriangle(t *testing.T) { + dst := make([]float32, 20) + packInstance(dst, render.Rectangle{ + Kind: scene.KindTriangle, + Points: [3]scene.Point{{X: 1, Y: 2}, {X: 3, Y: 4}, {X: 5, Y: 6}}, + Color: scene.Color{Red: 0.1, Green: 0.2, Blue: 0.3, Alpha: 1}, + Shade: scene.Shade{On: true, Colors: [2]scene.Color{{Red: 0.4, Green: 0.5, Blue: 0.6, Alpha: 1}, {Red: 0.7, Green: 0.8, Blue: 0.9, Alpha: 1}}}, + EdgeMask: 5, + Layer: 7, + }) + want := make([]float32, 20) + want[0], want[1], want[2], want[3] = 1, 2, 3, 4 + want[4], want[5], want[6], want[7] = 0.1, 0.2, 0.3, 1 + want[8], want[9], want[10], want[11] = 5, 7, 6, 6 + want[12], want[13], want[14], want[15] = 0.4, 0.5, 0.6, 1 + want[16], want[17], want[18], want[19] = 0.7, 0.8, 0.9, 1 + if !reflect.DeepEqual(dst, want) { + t.Fatalf("packed triangle = %v, want %v", dst, want) + } +} + +func TestPackInstanceShadow(t *testing.T) { + dst := make([]float32, 20) + packInstance(dst, render.Rectangle{ + Kind: scene.KindShadow, + Bounds: scene.Rect{X: 1, Y: 2, Width: 3, Height: 4}, + Color: scene.Color{Red: 0, Green: 0, Blue: 0, Alpha: 0.5}, + Radius: 5, + Shadow: scene.Shadow{OffsetX: 6, OffsetY: 7, Blur: 8, Spread: 9}, + }) + want := make([]float32, 20) + want[0], want[1], want[2], want[3] = 1, 2, 3, 4 + want[4], want[5], want[6], want[7] = 0, 0, 0, 0.5 + want[8], want[9], want[10], want[11] = 5, 0, 8, 0 + want[12], want[13], want[14], want[15] = 6, 7, 9, 0 + if !reflect.DeepEqual(dst, want) { + t.Fatalf("packed shadow = %v, want %v", dst, want) + } +} diff --git a/internal/platform/web/painter.go b/internal/platform/web/painter.go index a61d1032..384b9f88 100644 --- a/internal/platform/web/painter.go +++ b/internal/platform/web/painter.go @@ -7,6 +7,7 @@ import ( "unicode/utf8" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/framebuild" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/interaction" "github.com/vivaui/viva/internal/platform" @@ -23,6 +24,10 @@ type painter struct { width float32 height float32 clear gfx.Color + builder *framebuild.Builder + frame platform.Frame + labels []platform.TextLabel + frameErr error rectangles []gfx.Rectangle shadows []gfx.Shadow triangles []gfx.Triangle @@ -62,9 +67,10 @@ func newPainter(canvas *gfx.Canvas, config *Config) *painter { clear = config.ClearColor } return &painter{ - config: config, - canvas: canvas, - clear: clear, + config: config, + canvas: canvas, + clear: clear, + builder: framebuild.New(canvas), } } @@ -475,21 +481,24 @@ func (p *painter) deliverPointer(event gfx.PointerEvent) bool { func (p *painter) repaint() { for pass := 0; ; pass++ { p.paint() - p.rectangles = p.canvas.Rectangles() - p.shadows = p.canvas.Shadows() - p.triangles = p.canvas.Triangles() - p.texts = p.canvas.Texts() - p.layers = collectLayers(p.layers[:0], p.rectangles, p.triangles, p.texts) - for _, shadow := range p.shadows { - p.layers = insertLayer(p.layers, shadow.Layer) - } - before := p.focus.Focused() p.focus.Sync(p.canvas) if p.focus.Focused() == before || pass > 0 { break } } + if frame, err := p.builder.Build(); err != nil { + // Keep the last frame on screen rather than losing the page to one bad + // batch; the runtime reports the error to the console. + p.frameErr = err + } else { + p.frameErr = nil + p.frame = frame + if frame.TextLabels != nil { + p.labels = append(p.labels[:0], frame.TextLabels...) + } + p.builder.Trim() + } p.accessibility = describeAccessibility(p.accessibility[:0], p.canvas.Hits(), p.focus.Router().ActiveScope()) p.syncTextInput() p.syncCursor() diff --git a/internal/platform/web/painter_test.go b/internal/platform/web/painter_test.go index c6d50967..8cbe5c07 100644 --- a/internal/platform/web/painter_test.go +++ b/internal/platform/web/painter_test.go @@ -786,8 +786,8 @@ func TestPainterUsesTheCallersStaticCanvasWithoutPaint(t *testing.T) { painter := newPainter(&canvas, &Config{}) painter.width, painter.height = 40, 20 painter.repaint() - if len(painter.rectangles) != 1 { - t.Fatalf("static canvas rectangles = %d, want the caller's one", len(painter.rectangles)) + if len(painter.frame.Rectangles) != 1 { + t.Fatalf("static canvas rectangles = %d, want the caller's one", len(painter.frame.Rectangles)) } } diff --git a/internal/platform/web/render.go b/internal/platform/web/render.go index 9f180f23..39a44d9d 100644 --- a/internal/platform/web/render.go +++ b/internal/platform/web/render.go @@ -4,17 +4,26 @@ package web import ( "syscall/js" + "unicode/utf8" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/bidi" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" ) -// render repaints the canvas vocabulary into the 2D context. Each layer is -// drawn back to front, and within a layer every primitive is drawn in the order -// the application painted it: rectangles, triangles, shadows and text are kept -// in separate lists but each carries the paint order of the frame. +// bitmapKey identifies a retained bitmap picture. +type bitmapKey struct { + id uint64 + version uint32 + width, height int + stride int + hash uint64 +} + +// render repaints the frame the painter built into the 2D context. func (runtime *runtime) render() { - context := runtime.context clock := &runtime.clock clock.begin() runtime.paths.beginFrame() @@ -25,128 +34,171 @@ func (runtime *runtime) render() { runtime.a11y.text.sync(id, input, runtime.textInputChanged) } clock.lap(&clock.a11y) - context.Call("save") - context.Call("scale", runtime.dpr, runtime.dpr) - context.Set("fillStyle", cssColor(runtime.painter.clear)) - context.Call("fillRect", 0, 0, runtime.painter.width, runtime.painter.height) - for _, layer := range runtime.painter.layers { - runtime.drawLayer(layer) + if err := runtime.painter.frameErr; err != nil { + js.Global().Get("console").Call("error", "viva: frame: "+err.Error()) + runtime.painter.frameErr = nil + } + if runtime.gl != nil { + if err := runtime.gl.Draw(runtime.painter.frame, runtime.painter.labels, runtime.painter.clear); err != nil { + if err == errContextLost { + runtime.fallbackToCanvas2D(err.Error()) + } else { + js.Global().Get("console").Call("error", "viva: webgl2: "+err.Error()) + } + } + } else { + context := runtime.context + context.Call("save") + context.Call("scale", runtime.dpr, runtime.dpr) + context.Set("fillStyle", cssColor(runtime.painter.clear)) + context.Call("fillRect", 0, 0, runtime.painter.width, runtime.painter.height) + runtime.drawFrame() + context.Call("restore") } - context.Call("restore") runtime.paths.endFrame() - clock.end(runtime.painter, runtime.paths.built, runtime.paths.reused) + rectangles, triangles, texts := frameCounts(runtime.painter.frame, runtime.painter.labels) + clock.end(rectangles, triangles, texts, len(runtime.painter.accessibility), runtime.paths.built, runtime.paths.reused) if delay, ok := runtime.canvas.NextFrame(); ok { runtime.scheduleFrame(delay) } } -// drawLayer paints one layer's primitives in paint order. Each list is in -// paint order, so the layer is a merge of four sorted streams; a label painted -// between two shapes of the same style ends a triangle run. -func (runtime *runtime) drawLayer(layer uint16) { - context := runtime.context - clock := &runtime.clock - rectangles := runtime.painter.rectangles - shadows := runtime.painter.shadows - triangles := runtime.painter.triangles - texts := runtime.painter.texts - ri, si, ti, xi := 0, 0, 0, 0 - for { - for ri < len(rectangles) && rectangles[ri].Layer != layer { - ri++ - } - for si < len(shadows) && shadows[si].Layer != layer { - si++ - } - for ti < len(triangles) && triangles[ti].Layer != layer { - ti++ - } - for xi < len(texts) && texts[xi].Layer != layer { - xi++ - } - kind, best := 0, ^uint32(0) - if ri < len(rectangles) && rectangles[ri].Order < best { - kind, best = 1, rectangles[ri].Order - } - if ti < len(triangles) && triangles[ti].Order < best { - kind, best = 2, triangles[ti].Order - } - if si < len(shadows) && shadows[si].Order < best { - kind, best = 3, shadows[si].Order - } - if xi < len(texts) && texts[xi].Order < best { - kind = 4 - } - switch kind { - case 1: - drawRectangle(context, rectangles[ri]) - ri++ - clock.lap(&clock.rectangles) - case 2: - first := triangles[ti] - if first.Shaded { - runtime.drawShadedTriangle(first) - ti++ - } else { - start := ti - ti++ - for ti < len(triangles) && sameRun(first, triangles[ti]) { - due := si < len(shadows) && shadows[si].Order < triangles[ti].Order || - ri < len(rectangles) && rectangles[ri].Order < triangles[ti].Order || - xi < len(texts) && texts[xi].Order < triangles[ti].Order - if due { - break - } - ti++ - } - runtime.drawSolidRun(triangles[start:ti]) - } - clock.lap(&clock.triangles) - case 3: - drawShadow(context, shadows[si], runtime.dpr) - si++ - clock.lap(&clock.rectangles) - case 4: - runtime.drawText(texts[xi]) - xi++ - clock.lap(&clock.texts) +// frameCounts reports how many primitives the last frame carried, for the +// page's statistics. +func frameCounts(frame platform.Frame, labels []platform.TextLabel) (rectangles, triangles, texts int) { + for _, instance := range frame.Rectangles { + switch instance.Kind { + case scene.KindTriangle: + triangles++ default: - return + rectangles++ + } + } + for _, label := range labels { + if label.BitmapWidth <= 0 || label.BitmapHeight <= 0 || len(label.Bitmap) == 0 && label.BitmapID == 0 { + texts++ } } + return rectangles, triangles, texts } -// drawRectangle paints one rectangle. -func drawRectangle(context js.Value, rectangle gfx.Rectangle) { - if rectangle.HasClip { +// drawFrame interleaves the shape batches and labels in the order the +// application painted them. +func (runtime *runtime) drawFrame() { + frame := runtime.painter.frame + labels := runtime.painter.labels + batches := render.GroupBatches(runtime.batches[:0], frame.Rectangles) + runtime.batches = batches + order := runtime.labelOrder[:0] + for _, label := range labels { + order = append(order, render.LabelOrder{Layer: label.Layer, ShapesBefore: label.ShapesBefore}) + } + runtime.labelOrder = order + plan, scratch := render.PlanWithOrder(runtime.plan[:0], runtime.planOrder, batches, order) + runtime.plan, runtime.planOrder = plan, scratch + for _, op := range plan { + switch op.Kind { + case render.PlanShapes: + runtime.drawShapes(frame.Rectangles[op.First:op.First+op.Count], op.Clipped, op.Clip) + case render.PlanLabels: + if op.Label >= 0 && op.Label < len(labels) { + runtime.drawLabel(labels[op.Label]) + } + } + } +} + +// drawShapes paints one batch of instances, clipped to the batch's clip. +func (runtime *runtime) drawShapes(instances []render.Rectangle, clipped bool, clip scene.Rect) { + context := runtime.context + if clipped { context.Call("save") - clipRect(context, rectangle.ClipOf) + clipRect(context, gfx.Rect{X: clip.X, Y: clip.Y, Width: clip.Width, Height: clip.Height}) } - context.Set("fillStyle", cssColor(rectangle.Color)) - if rectangle.Radius > 0 { - traceRoundedRect(context, rectangle.Bounds, rectangle.Radius) - context.Call("fill") - } else { - context.Call("fillRect", rectangle.Bounds.X, rectangle.Bounds.Y, rectangle.Bounds.Width, rectangle.Bounds.Height) + for index := 0; index < len(instances); { + instance := instances[index] + switch instance.Kind { + case scene.KindShadow: + drawShadow(context, gfx.Shadow{ + Bounds: gfx.Rect{X: instance.Bounds.X, Y: instance.Bounds.Y, Width: instance.Bounds.Width, Height: instance.Bounds.Height}, + Radius: instance.Radius, + Color: gfxColor(instance.Color), + Style: gfx.ShadowStyle{ + OffsetX: instance.Shadow.OffsetX, OffsetY: instance.Shadow.OffsetY, + Blur: instance.Shadow.Blur, Spread: instance.Shadow.Spread, + }, + }, runtime.dpr) + index++ + case scene.KindTriangle: + if instance.Shade.On { + runtime.drawShadedTriangle(gfxTriangle(instance)) + index++ + continue + } + first := index + run := runtime.triangles[:0] + for index < len(instances) && instances[index].Kind == scene.KindTriangle && + !instances[index].Shade.On && instances[index].Color == instance.Color { + run = append(run, gfxTriangle(instances[index])) + index++ + } + runtime.triangles = run + if index > first { + runtime.drawSolidRun(run) + } + default: + drawRectangle(context, gfx.Rectangle{ + Bounds: gfx.Rect{X: instance.Bounds.X, Y: instance.Bounds.Y, Width: instance.Bounds.Width, Height: instance.Bounds.Height}, + Color: gfxColor(instance.Color), + Radius: instance.Radius, + }) + index++ + } } - if rectangle.HasClip { + if clipped { context.Call("restore") } } +func gfxColor(color scene.Color) gfx.Color { + return gfx.Color{Red: color.Red, Green: color.Green, Blue: color.Blue, Alpha: color.Alpha} +} + +func platformColor(color platform.Color) gfx.Color { + return gfx.Color{Red: float32(color.Red), Green: float32(color.Green), Blue: float32(color.Blue), Alpha: float32(color.Alpha)} +} + +func gfxTriangle(instance render.Rectangle) gfx.Triangle { + return gfx.Triangle{ + Points: [3]gfx.Point{{X: instance.Points[0].X, Y: instance.Points[0].Y}, {X: instance.Points[1].X, Y: instance.Points[1].Y}, {X: instance.Points[2].X, Y: instance.Points[2].Y}}, + Color: gfxColor(instance.Color), + Shade: [2]gfx.Color{gfxColor(instance.Shade.Colors[0]), gfxColor(instance.Shade.Colors[1])}, + Shaded: instance.Shade.On, + EdgeMask: instance.EdgeMask, + } +} + // sameRun reports whether next continues the run that first began. func sameRun(first, next gfx.Triangle) bool { return next.Layer == first.Layer && !next.Shaded && next.Color == first.Color && next.HasClip == first.HasClip && next.ClipOf == first.ClipOf } +// drawRectangle paints one rectangle. +func drawRectangle(context js.Value, rectangle gfx.Rectangle) { + context.Set("fillStyle", cssColor(rectangle.Color)) + if rectangle.Radius > 0 { + traceRoundedRect(context, rectangle.Bounds, rectangle.Radius) + context.Call("fill") + } else { + context.Call("fillRect", rectangle.Bounds.X, rectangle.Bounds.Y, rectangle.Bounds.Width, rectangle.Bounds.Height) + } +} + func (runtime *runtime) drawSolidRun(run []gfx.Triangle) { context := runtime.context first := run[0] context.Call("save") - if first.HasClip { - clipRect(context, first.ClipOf) - } context.Call("translate", first.Points[0].X, first.Points[0].Y) context.Set("fillStyle", cssColor(first.Color)) context.Call("fill", runtime.paths.path(run)) @@ -155,10 +207,6 @@ func (runtime *runtime) drawSolidRun(run []gfx.Triangle) { func (runtime *runtime) drawShadedTriangle(triangle gfx.Triangle) { context := runtime.context - if triangle.HasClip { - context.Call("save") - clipRect(context, triangle.ClipOf) - } context.Set("fillStyle", triangleFill(context, triangle)) context.Call("beginPath") context.Call("moveTo", triangle.Points[0].X, triangle.Points[0].Y) @@ -166,16 +214,189 @@ func (runtime *runtime) drawShadedTriangle(triangle gfx.Triangle) { context.Call("lineTo", triangle.Points[2].X, triangle.Points[2].Y) context.Call("closePath") context.Call("fill") - if triangle.HasClip { - context.Call("restore") +} + +// drawLabel paints one platform text label: a bitmap, a fixed-pitch run line, +// or proportional text. +func (runtime *runtime) drawLabel(label platform.TextLabel) { + if label.HasQuad { + runtime.drawWarpedLabel(label) + return + } + if label.BitmapWidth > 0 && label.BitmapHeight > 0 && (len(label.Bitmap) > 0 || label.BitmapID != 0) { + runtime.drawBitmapLabel(label) + return } + if len(label.Runs) > 0 { + runtime.drawLabelRuns(label) + return + } + runtime.drawText(gfx.Text{ + Value: label.Value, + Bounds: gfx.Rect{ + X: label.X + label.OriginX, Y: label.Y + label.OriginY, + Width: label.Width, Height: label.Height, + }, + Style: gfx.TextStyle{ + Size: label.FontSize, Weight: label.Weight, Italic: label.Italic, + Color: platformColor(label.Color), Mono: label.Mono, MonoFace: label.MonoFace, + }, + Baseline: label.Baseline, + HasClip: label.Clipped, ClipOf: gfx.Rect(label.Clip), + }) +} + +// drawLabelRuns paints a fixed-pitch grid line from the labels a frame carries. +func (runtime *runtime) drawLabelRuns(label platform.TextLabel) { + runtime.drawLabelRunsContext(runtime.context, label) +} + +// drawLabelRunsContext is drawLabelRuns into an explicit 2D context, which the +// WebGL2 renderer uses to rasterize a grid label texture. +func (runtime *runtime) drawLabelRunsContext(context js.Value, label platform.TextLabel) { + context.Call("save") + defer context.Call("restore") + if label.Clipped { + clipRect(context, gfx.Rect(label.Clip)) + } + clipRect(context, gfx.Rect{X: label.X + label.OriginX, Y: label.Y + label.OriginY, Width: label.Width, Height: label.Height}) + metrics := monoBaseline(context, label.FontSize, label.MonoFace) + baseline := label.Y + label.OriginY + label.Baseline + if label.Baseline <= 0 { + baseline = label.Y + label.OriginY + (label.Height-metrics.Ascent-metrics.Descent)*0.5 + metrics.Ascent + } + context.Set("textBaseline", "alphabetic") + offset := 0 + for _, run := range label.Runs { + end := offset + int(run.Bytes) + if run.Bytes < 0 || end > len(label.Value) { + break + } + piece := label.Value[offset:end] + offset = end + left := label.X + label.OriginX + float32(run.Column)*label.CellWidth + span := float32(run.Cells) * label.CellWidth + context.Set("fillStyle", cssColor(run.Color)) + context.Set("font", cssMonoFont(label.FontSize, run.Weight, run.Italic, label.MonoFace)) + x := left + if run.Cells > 0 && utf8.RuneCountInString(piece) == 1 { + x = left + (span-float32(context.Call("measureText", piece).Get("width").Float()))/2 + } + if run.Ligatures && printableASCII(piece) && len(piece) > 1 { + if width := float32(context.Call("measureText", piece).Get("width").Float()); width > 0 && span > 0 { + context.Call("save") + context.Call("translate", left, 0) + context.Call("scale", span/width, 1) + context.Call("fillText", piece, 0, baseline) + context.Call("restore") + } + } else if printableASCII(piece) && len(piece) > 1 { + for index := range len(piece) { + context.Call("fillText", piece[index:index+1], left+float32(index)*label.CellWidth, baseline) + } + } else { + context.Call("fillText", piece, x, baseline) + } + if span > 0 { + thickness := max(1, label.FontSize/14) + if run.Underline { + context.Call("fillRect", left, baseline+thickness, span, thickness) + } + if run.Strike { + context.Call("fillRect", left, baseline-metrics.Ascent*0.35, span, thickness) + } + } + } +} + +// drawBitmapLabel paints an image label from its retained premultiplied BGRA +// pixels, converted once into an offscreen canvas. +func (runtime *runtime) drawBitmapLabel(label platform.TextLabel) { + key := bitmapKey{id: label.BitmapID, version: label.BitmapVersion, width: label.BitmapWidth, height: label.BitmapHeight, stride: label.BitmapStride} + if key.id == 0 { + key.hash = fnvBytes(label.Bitmap) + } + canvas, ok := runtime.bitmaps[key] + if !ok { + if len(label.Bitmap) == 0 { + return + } + canvas = runtime.bitmapCanvas(label) + if canvas.IsUndefined() || canvas.IsNull() { + return + } + if runtime.bitmaps == nil { + runtime.bitmaps = make(map[bitmapKey]js.Value) + } + if len(runtime.bitmaps) > 64 { + runtime.bitmaps = make(map[bitmapKey]js.Value) + } + runtime.bitmaps[key] = canvas + } + context := runtime.context + context.Call("drawImage", canvas, label.X+label.OriginX, label.Y+label.OriginY, label.Width, label.Height) +} + +// bitmapCanvas converts a label's premultiplied BGRA pixels into an offscreen +// canvas holding straight RGBA, which Canvas2D composites as it drew the source. +func (runtime *runtime) bitmapCanvas(label platform.TextLabel) js.Value { + width, height := label.BitmapWidth, label.BitmapHeight + if width <= 0 || height <= 0 || label.BitmapStride < width*4 { + return js.Undefined() + } + rgba := make([]byte, width*height*4) + for y := 0; y < height; y++ { + source := label.Bitmap[y*label.BitmapStride:] + target := rgba[y*width*4:] + for x := 0; x < width; x++ { + b, g, r, a := source[x*4], source[x*4+1], source[x*4+2], source[x*4+3] + if a == 255 { + target[x*4], target[x*4+1], target[x*4+2], target[x*4+3] = r, g, b, 255 + continue + } + if a == 0 { + continue + } + target[x*4] = byte(int(r) * 255 / int(a)) + target[x*4+1] = byte(int(g) * 255 / int(a)) + target[x*4+2] = byte(int(b) * 255 / int(a)) + target[x*4+3] = a + } + } + canvas := runtime.document.Call("createElement", "canvas") + canvas.Set("width", width) + canvas.Set("height", height) + context := canvas.Call("getContext", "2d") + bytes := js.Global().Get("Uint8ClampedArray").New(len(rgba)) + js.CopyBytesToJS(bytes, rgba) + image := js.Global().Get("ImageData").New(bytes, width, height) + context.Call("putImageData", image, 0, 0) + return canvas +} + +func fnvBytes(data []byte) uint64 { + const ( + offset = 14695981039346656037 + prime = 1099511628211 + ) + hash := uint64(offset) + for _, b := range data { + hash ^= uint64(b) + hash *= prime + } + return hash } // drawText paints one text line. A line that cannot overflow its box (no outer // clip, left to right, narrower and no taller than the box) is drawn directly; // any other line is clipped to its box inside its own saved state. func (runtime *runtime) drawText(text gfx.Text) { - context := runtime.context + runtime.drawTextContext(runtime.context, text) +} + +// drawTextContext is drawText into an explicit 2D context, which the WebGL2 +// renderer uses to rasterize a label texture. +func (runtime *runtime) drawTextContext(context js.Value, text gfx.Text) { context.Call("save") defer context.Call("restore") context.Set("textBaseline", "alphabetic") @@ -188,6 +409,13 @@ func (runtime *runtime) drawText(text gfx.Text) { var style textStyleState metrics := runtime.metrics.baseline(text.Style.Size) baseline := runtime.canvas.LabelBaseline(gfx.Rect{Height: text.Bounds.Height}, gfx.TextStyle{Size: text.Style.Size}) + if text.Style.Mono { + baseline = text.Baseline + if baseline <= 0 { + mono := monoBaseline(context, text.Style.Size, text.Style.MonoFace) + baseline = (text.Bounds.Height-mono.Ascent-mono.Descent)*0.5 + mono.Ascent + } + } y := text.Bounds.Y + baseline // The line is drawn whole, in the font and direction the text engine measured it // with. The base direction of a right-to-left paragraph puts the @@ -207,7 +435,11 @@ func (runtime *runtime) drawText(text gfx.Text) { } clipRect(context, text.Bounds) context.Set("fillStyle", cssColor(text.Style.Color)) - context.Set("font", cssFontStyle(text.Style.Size, text.Style.Weight, text.Style.Italic)) + if text.Style.Mono { + context.Set("font", cssMonoFont(text.Style.Size, text.Style.Weight, text.Style.Italic, text.Style.MonoFace)) + } else { + context.Set("font", cssFontStyle(text.Style.Size, text.Style.Weight, text.Style.Italic)) + } if rtl { context.Set("direction", "rtl") } @@ -237,7 +469,11 @@ func (state *textStyleState) apply(context js.Value, style gfx.TextStyle) { context.Set("fillStyle", cssColor(style.Color)) } if !state.set || state.size != style.Size || state.weight != style.Weight || state.italic != style.Italic { - context.Set("font", cssFontStyle(style.Size, style.Weight, style.Italic)) + if style.Mono { + context.Set("font", cssMonoFont(style.Size, style.Weight, style.Italic, style.MonoFace)) + } else { + context.Set("font", cssFontStyle(style.Size, style.Weight, style.Italic)) + } } *state = textStyleState{set: true, color: style.Color, size: style.Size, weight: style.Weight, italic: style.Italic} } diff --git a/internal/platform/web/render_gl_js.go b/internal/platform/web/render_gl_js.go new file mode 100644 index 00000000..2c70569f --- /dev/null +++ b/internal/platform/web/render_gl_js.go @@ -0,0 +1,608 @@ +//go:build js && wasm + +package web + +import ( + "errors" + "math" + "syscall/js" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +var errContextLost = errors.New("webgl2: context lost") + +type textKey struct { + bitmap bool + id uint64 + version uint32 + hash uint64 + value string + size float32 + weight float32 + italic bool + color platform.Color + fontGen uint32 + mono bool + monoFace gfx.MonoFace + cellWidth float32 + baseline float32 + runs uint64 + width int + height int + stride int + deviceW int + deviceH int + tileLeft int + tileRight int + scale float32 + identity gfx.TextIdentity +} + +type labelTile struct { + texture js.Value + left int + right int + width int + height int + corners [4][2]float32 + tints [4][4]float32 +} + +type glTexture struct { + texture js.Value + width int + height int + bytes int64 + used uint64 +} + +type glRenderer struct { + ctx js.Value + program js.Value + text js.Value + attribs [5]int + uView js.Value + uPixel js.Value + uTarget js.Value + uOrigin js.Value + uCorners [4]js.Value + uTints [4]js.Value + uTexture js.Value + vbo js.Value + floats []float32 + batches []render.Batch + orders []render.LabelOrder + plan []render.PlanOp + planOrder []int + tiles []labelTile + width int + height int + scale float32 + maxTex int + frame uint64 + textures map[textKey]*glTexture + bytes int64 + runtime *runtime +} + +func newGLRenderer(runtime *runtime, canvas js.Value) (*glRenderer, error) { + ctx := canvas.Call("getContext", "webgl2", map[string]any{ + "alpha": true, "depth": false, "stencil": false, "antialias": false, + "premultipliedAlpha": true, "preserveDrawingBuffer": false, + "powerPreference": "default", + }) + if !ctx.Truthy() || ctx.IsNull() { + return nil, errors.New("webgl2: no context") + } + vertexSource, err := shaderSource("scene.vert.glsl") + if err != nil { + return nil, err + } + fragmentSource, err := shaderSource("scene.frag.glsl") + if err != nil { + return nil, err + } + vertex, err := compileShader(ctx, "VERTEX_SHADER", vertexSource) + if err != nil { + return nil, err + } + fragment, err := compileShader(ctx, "FRAGMENT_SHADER", fragmentSource) + if err != nil { + return nil, err + } + program, err := linkProgram(ctx, vertex, fragment) + if err != nil { + return nil, err + } + textVertexSource, err := shaderSource("text.vert.glsl") + if err != nil { + return nil, err + } + textFragmentSource, err := shaderSource("text.frag.glsl") + if err != nil { + return nil, err + } + textVertex, err := compileShader(ctx, "VERTEX_SHADER", textVertexSource) + if err != nil { + return nil, err + } + textFragment, err := compileShader(ctx, "FRAGMENT_SHADER", textFragmentSource) + if err != nil { + return nil, err + } + textProgram, err := linkProgram(ctx, textVertex, textFragment) + if err != nil { + return nil, err + } + renderer := &glRenderer{ + ctx: ctx, program: program, text: textProgram, + attribs: [5]int{0, 1, 2, 3, 4}, + uView: ctx.Call("getUniformLocation", program, "uViewport"), + uPixel: ctx.Call("getUniformLocation", program, "uPixelSize"), + uTarget: ctx.Call("getUniformLocation", program, "uTargetPixels"), + uOrigin: ctx.Call("getUniformLocation", program, "uOrigin"), + uTexture: ctx.Call("getUniformLocation", textProgram, "uTexture"), + runtime: runtime, + textures: make(map[textKey]*glTexture), + } + for index := range renderer.uCorners { + renderer.uCorners[index] = ctx.Call("getUniformLocation", textProgram, "uCorners["+itoa(index)+"]") + renderer.uTints[index] = ctx.Call("getUniformLocation", textProgram, "uTint["+itoa(index)+"]") + } + renderer.vbo = ctx.Call("createBuffer") + ctx.Call("bindBuffer", ctx.Get("ARRAY_BUFFER"), renderer.vbo) + ctx.Call("enable", ctx.Get("BLEND")) + ctx.Call("blendFunc", ctx.Get("ONE"), ctx.Get("ONE_MINUS_SRC_ALPHA")) + ctx.Call("disable", ctx.Get("DEPTH_TEST")) + ctx.Call("disable", ctx.Get("CULL_FACE")) + ctx.Call("enable", ctx.Get("SCISSOR_TEST")) + ctx.Call("pixelStorei", ctx.Get("UNPACK_ALIGNMENT"), 1) + renderer.maxTex = ctx.Call("getParameter", ctx.Get("MAX_TEXTURE_SIZE")).Int() + if renderer.maxTex <= 0 { + renderer.maxTex = 2048 + } + // A test can lower the limit to exercise tiling on a small viewport. + if override := js.Global().Get("vivaMaxTexture"); override.Type() == js.TypeNumber { + if limit := override.Int(); limit > 0 && limit < renderer.maxTex { + renderer.maxTex = limit + } + } + return renderer, nil +} + +func itoa(value int) string { + if value == 0 { + return "0" + } + var digits [3]byte + position := len(digits) + for value > 0 { + position-- + digits[position] = byte('0' + value%10) + value /= 10 + } + return string(digits[position:]) +} + +func (renderer *glRenderer) Resize(deviceWidth, deviceHeight int, scale float32) { + renderer.width, renderer.height, renderer.scale = deviceWidth, deviceHeight, scale + renderer.ctx.Call("viewport", 0, 0, deviceWidth, deviceHeight) + renderer.ctx.Call("useProgram", renderer.program) + renderer.ctx.Call("uniform2f", renderer.uView, float32(deviceWidth)/scale, float32(deviceHeight)/scale) + renderer.ctx.Call("uniform1f", renderer.uPixel, 1/scale) + renderer.ctx.Call("uniform2f", renderer.uTarget, float32(deviceWidth), float32(deviceHeight)) + renderer.ctx.Call("uniform2f", renderer.uOrigin, 0, 0) + renderer.ctx.Call("useProgram", renderer.text) + renderer.ctx.Call("uniform2f", renderer.ctx.Call("getUniformLocation", renderer.text, "uViewport"), float32(deviceWidth)/scale, float32(deviceHeight)/scale) +} + +func (renderer *glRenderer) Draw(frame platform.Frame, labels []platform.TextLabel, clear gfx.Color) error { + if renderer.ctx.Call("isContextLost").Bool() { + return errContextLost + } + renderer.frame++ + ctx := renderer.ctx + ctx.Call("clearColor", float64(clear.Red*clear.Alpha), float64(clear.Green*clear.Alpha), float64(clear.Blue*clear.Alpha), float64(clear.Alpha)) + ctx.Call("clear", ctx.Get("COLOR_BUFFER_BIT")) + if err := renderer.upload(frame); err != nil { + return err + } + batches := render.GroupBatches(renderer.batches[:0], frame.Rectangles) + renderer.batches = batches + orders := renderer.orders[:0] + for _, label := range labels { + orders = append(orders, render.LabelOrder{Layer: label.Layer, ShapesBefore: label.ShapesBefore}) + } + renderer.orders = orders + plan, order := render.PlanWithOrder(renderer.plan[:0], renderer.planOrder, batches, orders) + renderer.plan, renderer.planOrder = plan, order + for _, op := range plan { + switch op.Kind { + case render.PlanShapes: + renderer.drawShapes(op.First, op.Count, op.Clipped, op.Clip) + case render.PlanLabels: + if op.Label >= 0 && op.Label < len(labels) { + renderer.drawLabel(labels[op.Label]) + } + } + } + return nil +} + +func (renderer *glRenderer) upload(frame platform.Frame) error { + ctx := renderer.ctx + count := len(frame.Rectangles) + needed := count * 20 + if cap(renderer.floats) < needed { + grown := make([]float32, needed, needed*2) + copy(grown, renderer.floats) + renderer.floats = grown + } + rebuild := frame.Update.Rebuild || len(renderer.floats) < needed || renderer.frame == 1 + if rebuild { + renderer.floats = renderer.floats[:needed] + for index, instance := range frame.Rectangles { + packInstance(renderer.floats[index*20:], instance) + } + ctx.Call("bindBuffer", ctx.Get("ARRAY_BUFFER"), renderer.vbo) + ctx.Call("bufferData", ctx.Get("ARRAY_BUFFER"), jsFloat32(renderer.floats), ctx.Get("DYNAMIC_DRAW")) + return nil + } + if frame.Update.Count <= 0 { + return nil + } + first, last := frame.Update.First, frame.Update.First+frame.Update.Count + if first < 0 { + first = 0 + } + if last > count { + last = count + } + if first >= last { + return nil + } + renderer.floats = renderer.floats[:needed] + for index := first; index < last; index++ { + packInstance(renderer.floats[index*20:], frame.Rectangles[index]) + } + ctx.Call("bindBuffer", ctx.Get("ARRAY_BUFFER"), renderer.vbo) + ctx.Call("bufferSubData", ctx.Get("ARRAY_BUFFER"), first*80, jsFloat32(renderer.floats[first*20:last*20])) + return nil +} + +func (renderer *glRenderer) drawShapes(first, count int, clipped bool, clip scene.Rect) { + if count <= 0 { + return + } + ctx := renderer.ctx + renderer.scissor(clipped, clip) + ctx.Call("useProgram", renderer.program) + ctx.Call("bindBuffer", ctx.Get("ARRAY_BUFFER"), renderer.vbo) + for location := 0; location < 5; location++ { + ctx.Call("vertexAttribPointer", location, 4, ctx.Get("FLOAT"), false, 80, first*80+location*16) + ctx.Call("enableVertexAttribArray", location) + ctx.Call("vertexAttribDivisor", location, 1) + } + ctx.Call("drawArraysInstanced", ctx.Get("TRIANGLES"), 0, 6, count) +} + +// labelScissor is the device-pixel rectangle a clipped label may paint into. +// Labels use floor/ceil, like the native label backends, so partial coverage at +// the clip edge is kept. +func labelScissor(clip scene.Rect, scale float32, width, height int) (left, top, right, bottom int) { + clamp := func(value float64, limit int) int { + return int(min(max(value, 0), float64(limit))) + } + left = clamp(math.Floor(float64(clip.X*scale)), width) + top = clamp(math.Floor(float64(clip.Y*scale)), height) + right = clamp(math.Ceil(float64((clip.X+clip.Width)*scale)), width) + bottom = clamp(math.Ceil(float64((clip.Y+clip.Height)*scale)), height) + return left, top, right, bottom +} + +func (renderer *glRenderer) scissor(clipped bool, clip scene.Rect) { + ctx := renderer.ctx + if !clipped { + ctx.Call("scissor", 0, 0, renderer.width, renderer.height) + return + } + box, visible := render.ScissorOf(clip, renderer.scale, renderer.width, renderer.height) + if !visible { + ctx.Call("scissor", 0, 0, 0, 0) + return + } + ctx.Call("scissor", box.Left, renderer.height-box.Bottom, box.Right-box.Left, box.Bottom-box.Top) +} + +func (renderer *glRenderer) drawLabel(label platform.TextLabel) { + deviceWidth := int(math.Ceil(float64(label.Width) * float64(renderer.scale))) + deviceHeight := int(math.Ceil(float64(label.Height) * float64(renderer.scale))) + if deviceWidth <= 0 || deviceHeight <= 0 { + return + } + ctx := renderer.ctx + if label.Clipped { + left, top, right, bottom := labelScissor(scene.Rect{X: label.Clip.X, Y: label.Clip.Y, Width: label.Clip.Width, Height: label.Clip.Height}, renderer.scale, renderer.width, renderer.height) + if right <= left || bottom <= top { + return + } + ctx.Call("scissor", left, renderer.height-bottom, right-left, bottom-top) + } else { + ctx.Call("scissor", 0, 0, renderer.width, renderer.height) + } + for _, tile := range renderer.labelTiles(label, deviceWidth, deviceHeight) { + if tile.texture.IsUndefined() || tile.texture.IsNull() { + continue + } + ctx.Call("useProgram", renderer.text) + ctx.Call("activeTexture", ctx.Get("TEXTURE0")) + ctx.Call("bindTexture", ctx.Get("TEXTURE_2D"), tile.texture) + ctx.Call("uniform1i", renderer.uTexture, 0) + for index := 0; index < 4; index++ { + ctx.Call("uniform4f", renderer.uCorners[index], tile.corners[index][0], tile.corners[index][1], 0, 0) + ctx.Call("uniform4f", renderer.uTints[index], tile.tints[index][0], tile.tints[index][1], tile.tints[index][2], tile.tints[index][3]) + } + ctx.Call("drawArrays", ctx.Get("TRIANGLES"), 0, 6) + } +} + +// labelTiles splits a label wider than the GPU's largest texture into +// horizontal tiles. Each tile carries its own texture, destination quad and +// corner tints. A label one texture wide gets one tile. +func (renderer *glRenderer) labelTiles(label platform.TextLabel, deviceWidth, deviceHeight int) []labelTile { + renderer.tiles = renderer.tiles[:0] + for _, bounds := range tileRanges(deviceWidth, renderer.maxTex) { + tile := renderer.labelTile(label, deviceWidth, deviceHeight, bounds[0], bounds[1]) + if tile.width <= 0 || tile.height <= 0 { + continue + } + renderer.tiles = append(renderer.tiles, tile) + } + return renderer.tiles +} + +func (renderer *glRenderer) labelTile(label platform.TextLabel, deviceWidth, deviceHeight, left, right int) labelTile { + tile := labelTile{left: left, right: right} + x0 := label.X + label.OriginX + float32(left)/renderer.scale + x1 := label.X + label.OriginX + float32(right)/renderer.scale + y0 := label.Y + label.OriginY + y1 := y0 + label.Height + tile.corners = [4][2]float32{{x0, y0}, {x1, y0}, {x0, y1}, {x1, y1}} + for index := range tile.tints { + tile.tints[index] = [4]float32{1, 1, 1, 1} + } + if label.HasQuad { + u0 := float32(left) / float32(deviceWidth) + u1 := float32(right) / float32(deviceWidth) + tile.corners[0] = quadPoint(label.Quad, u0, 0) + tile.corners[1] = quadPoint(label.Quad, u1, 0) + tile.corners[2] = quadPoint(label.Quad, u0, 1) + tile.corners[3] = quadPoint(label.Quad, u1, 1) + tile.tints[0] = lerpTint(label.Tint[0], label.Tint[1], u0) + tile.tints[1] = lerpTint(label.Tint[0], label.Tint[1], u1) + tile.tints[2] = lerpTint(label.Tint[2], label.Tint[3], u0) + tile.tints[3] = lerpTint(label.Tint[2], label.Tint[3], u1) + } + tile.texture, tile.width, tile.height = renderer.tileTexture(label, deviceWidth, deviceHeight, left, right) + return tile +} + +func quadPoint(quad [4]gfx.Point, u, v float32) [2]float32 { + top := gfx.Point{X: quad[0].X + (quad[1].X-quad[0].X)*u, Y: quad[0].Y + (quad[1].Y-quad[0].Y)*u} + bottom := gfx.Point{X: quad[2].X + (quad[3].X-quad[2].X)*u, Y: quad[2].Y + (quad[3].Y-quad[2].Y)*u} + return [2]float32{top.X + (bottom.X-top.X)*v, top.Y + (bottom.Y-top.Y)*v} +} + +func lerpTint(left, right platform.Color, u float32) [4]float32 { + return [4]float32{ + float32(left.Red) + (float32(right.Red)-float32(left.Red))*u, + float32(left.Green) + (float32(right.Green)-float32(left.Green))*u, + float32(left.Blue) + (float32(right.Blue)-float32(left.Blue))*u, + float32(left.Alpha) + (float32(right.Alpha)-float32(left.Alpha))*u, + } +} + +// tileTexture rasterizes one horizontal tile of a label and retains it. +func (renderer *glRenderer) tileTexture(label platform.TextLabel, deviceWidth, deviceHeight, left, right int) (js.Value, int, int) { + key := renderer.key(label) + key.tileLeft, key.tileRight = left, right + key.deviceW, key.deviceH = deviceWidth, deviceHeight + if texture, ok := renderer.textures[key]; ok { + texture.used = renderer.frame + return texture.texture, texture.width, texture.height + } + if len(label.Bitmap) == 0 && label.BitmapID != 0 { + return js.Undefined(), 0, 0 + } + width, height, pixels, ok := renderer.rasterizeTile(label, deviceWidth, deviceHeight, left, right) + if !ok { + return js.Undefined(), 0, 0 + } + ctx := renderer.ctx + texture := ctx.Call("createTexture") + ctx.Call("bindTexture", ctx.Get("TEXTURE_2D"), texture) + ctx.Call("texParameteri", ctx.Get("TEXTURE_2D"), ctx.Get("TEXTURE_MIN_FILTER"), ctx.Get("LINEAR")) + ctx.Call("texParameteri", ctx.Get("TEXTURE_2D"), ctx.Get("TEXTURE_MAG_FILTER"), ctx.Get("LINEAR")) + ctx.Call("texParameteri", ctx.Get("TEXTURE_2D"), ctx.Get("TEXTURE_WRAP_S"), ctx.Get("CLAMP_TO_EDGE")) + ctx.Call("texParameteri", ctx.Get("TEXTURE_2D"), ctx.Get("TEXTURE_WRAP_T"), ctx.Get("CLAMP_TO_EDGE")) + ctx.Call("pixelStorei", ctx.Get("UNPACK_FLIP_Y_WEBGL"), false) + ctx.Call("texImage2D", ctx.Get("TEXTURE_2D"), 0, ctx.Get("RGBA"), width, height, 0, ctx.Get("RGBA"), ctx.Get("UNSIGNED_BYTE"), jsUint8(pixels)) + entry := &glTexture{texture: texture, width: width, height: height, bytes: int64(width) * int64(height) * 4, used: renderer.frame} + renderer.textures[key] = entry + renderer.bytes += entry.bytes + if len(renderer.textures) > 512 || renderer.bytes > 64<<20 { + for oldKey, old := range renderer.textures { + if len(renderer.textures) <= 384 && renderer.bytes <= 48<<20 { + break + } + if old.used+120 < renderer.frame || renderer.bytes > 64<<20 { + ctx.Call("deleteTexture", old.texture) + renderer.bytes -= old.bytes + delete(renderer.textures, oldKey) + } + } + } + return texture, width, height +} + +func (renderer *glRenderer) rasterizeTile(label platform.TextLabel, deviceWidth, deviceHeight, left, right int) (int, int, []byte, bool) { + width, height := right-left, deviceHeight + if width <= 0 || height <= 0 || width > renderer.maxTex || height > renderer.maxTex { + return 0, 0, nil, false + } + if len(label.Bitmap) > 0 { + source := renderer.runtime.bitmapCanvas(label) + if source.IsUndefined() || source.IsNull() { + return 0, 0, nil, false + } + canvas := renderer.runtime.document.Call("createElement", "canvas") + canvas.Set("width", width) + canvas.Set("height", height) + context := canvas.Call("getContext", "2d") + sx := float64(left) * float64(label.BitmapWidth) / float64(deviceWidth) + sw := float64(width) * float64(label.BitmapWidth) / float64(deviceWidth) + context.Call("drawImage", source, sx, 0, sw, float64(label.BitmapHeight), 0, 0, width, height) + data := context.Call("getImageData", 0, 0, width, height).Get("data") + rgba := make([]byte, width*height*4) + if copied := js.CopyBytesToGo(rgba, data); copied != len(rgba) { + return 0, 0, nil, false + } + return width, height, premultipliedBGRA(rgba), true + } + canvas := renderer.runtime.document.Call("createElement", "canvas") + canvas.Set("width", width) + canvas.Set("height", height) + context := canvas.Call("getContext", "2d") + context.Call("scale", renderer.scale, renderer.scale) + // Move the tile's device-pixel left edge to the texture's left edge. + context.Call("translate", -label.X-(label.OriginX+float32(left)/renderer.scale), -label.Y) + local := label + local.Clipped = false + local.Clip = gfx.Rect{} + if len(label.Runs) > 0 { + renderer.runtime.drawLabelRunsContext(context, local) + } else { + renderer.runtime.drawTextContext(context, gfx.Text{ + Value: label.Value, + Bounds: gfx.Rect{X: label.X + label.OriginX, Y: label.Y + label.OriginY, Width: label.Width, Height: label.Height}, + Style: gfx.TextStyle{ + Size: label.FontSize, Weight: label.Weight, Italic: label.Italic, + Color: platformColor(label.Color), Mono: label.Mono, MonoFace: label.MonoFace, + }, + Baseline: label.Baseline, + }) + } + data := context.Call("getImageData", 0, 0, width, height).Get("data") + rgba := make([]byte, width*height*4) + if copied := js.CopyBytesToGo(rgba, data); copied != len(rgba) { + return 0, 0, nil, false + } + return width, height, premultipliedBGRA(rgba), true +} + +func premultipliedBGRA(rgba []byte) []byte { + pixels := make([]byte, len(rgba)) + for index := 0; index < len(rgba); index += 4 { + alpha := rgba[index+3] + pixels[index] = byte(int(rgba[index+2]) * int(alpha) / 255) + pixels[index+1] = byte(int(rgba[index+1]) * int(alpha) / 255) + pixels[index+2] = byte(int(rgba[index]) * int(alpha) / 255) + pixels[index+3] = alpha + } + return pixels +} + +func (renderer *glRenderer) key(label platform.TextLabel) textKey { + key := textKey{ + id: label.BitmapID, version: label.BitmapVersion, + value: label.Value, size: label.FontSize, weight: label.Weight, italic: label.Italic, + color: label.Color, fontGen: label.FontGeneration, mono: label.Mono, monoFace: label.MonoFace, + cellWidth: label.CellWidth, baseline: label.Baseline, identity: label.Identity, + width: label.BitmapWidth, height: label.BitmapHeight, stride: label.BitmapStride, + scale: renderer.scale, + } + if len(label.Bitmap) > 0 { + key.bitmap = true + if key.id == 0 { + key.hash = fnvBytes(label.Bitmap) + } + return key + } + key.deviceW = int(math.Ceil(float64(label.Width) * float64(renderer.scale))) + key.deviceH = int(math.Ceil(float64(label.Height) * float64(renderer.scale))) + key.runs = hashRuns(label.Runs) + return key +} + +func hashRuns(runs []gfx.TextRun) uint64 { + hash := uint64(14695981039346656037) + for _, run := range runs { + hash ^= uint64(run.Column) + hash *= 1099511628211 + hash ^= uint64(run.Cells) + hash *= 1099511628211 + hash ^= uint64(run.Bytes) + hash *= 1099511628211 + hash ^= uint64(run.Color.Red * 255) + hash *= 1099511628211 + hash ^= uint64(run.Color.Green * 255) + hash *= 1099511628211 + hash ^= uint64(run.Color.Blue * 255) + hash *= 1099511628211 + hash ^= uint64(run.Color.Alpha * 255) + hash *= 1099511628211 + hash ^= uint64(run.Weight * 255) + hash *= 1099511628211 + if run.Italic { + hash ^= 3 + } + hash *= 1099511628211 + if run.Ligatures { + hash ^= 5 + } + hash *= 1099511628211 + if run.Underline { + hash ^= 1 + } + hash *= 1099511628211 + if run.Strike { + hash ^= 2 + } + hash *= 1099511628211 + } + return hash +} + +func (renderer *glRenderer) Destroy() { + ctx := renderer.ctx + for _, texture := range renderer.textures { + ctx.Call("deleteTexture", texture.texture) + } + renderer.textures = nil + ctx.Call("deleteBuffer", renderer.vbo) + ctx.Call("deleteProgram", renderer.program) + ctx.Call("deleteProgram", renderer.text) +} + +func jsFloat32(values []float32) js.Value { + array := js.Global().Get("Float32Array").New(len(values)) + if len(values) == 0 { + return array + } + bytes := js.Global().Get("Uint8Array").New(array.Get("buffer")) + js.CopyBytesToJS(bytes, unsafe.Slice((*byte)(unsafe.Pointer(&values[0])), len(values)*4)) + return array +} + +func jsUint8(values []byte) js.Value { + array := js.Global().Get("Uint8Array").New(len(values)) + if len(values) > 0 { + js.CopyBytesToJS(array, values) + } + return array +} diff --git a/internal/platform/web/render_warp_js.go b/internal/platform/web/render_warp_js.go new file mode 100644 index 00000000..b5e6c51c --- /dev/null +++ b/internal/platform/web/render_warp_js.go @@ -0,0 +1,187 @@ +//go:build js && wasm + +package web + +import ( + "math" + "syscall/js" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// warpKey identifies a rasterized label reused for a warped draw. +type warpKey struct { + value string + size, weight float32 + italic, mono bool + face gfx.MonoFace + cell, baseline float32 + color platform.Color + fontGen uint32 + runs uint64 + width, height int + scale float32 + bitmapID uint64 + bitmapVersion uint32 + bitmapW int + bitmapH int + bitmapStride int + bitmapHash uint64 +} + +// drawWarpedLabel paints a label whose picture lands on four arbitrary corners. +// Canvas2D has no projective transform, so the picture is divided into +// horizontal strips and each strip is drawn with the affine transform of its +// top and left edges. The result is an approximation of the quad, with the +// label's per-corner tint applied as a gradient. +func (runtime *runtime) drawWarpedLabel(label platform.TextLabel) { + source, sourceWidth, sourceHeight := runtime.warpLabelCanvas(label) + if source.IsUndefined() || source.IsNull() { + return + } + image := runtime.tintedWarp(label, source, sourceWidth, sourceHeight) + corners := label.Quad + context := runtime.context + context.Call("save") + defer context.Call("restore") + if label.Clipped { + clipRect(context, gfx.Rect(label.Clip)) + } + strips := int(math.Ceil(float64(float32(sourceHeight) / max(4, 2*runtime.dpr)))) + strips = min(max(strips, 1), 32) + for index := 0; index < strips; index++ { + v0 := float32(index) / float32(strips) + v1 := float32(index+1) / float32(strips) + topLeft := bilinear(corners[0], corners[1], corners[2], corners[3], 0, v0) + topRight := bilinear(corners[0], corners[1], corners[2], corners[3], 1, v0) + bottomLeft := bilinear(corners[0], corners[1], corners[2], corners[3], 0, v1) + sourceTop := v0 * float32(sourceHeight) + sourceBottom := v1 * float32(sourceHeight) + sourceStrip := sourceBottom - sourceTop + if sourceStrip <= 0 { + continue + } + a := (topRight.X - topLeft.X) / float32(sourceWidth) + b := (topRight.Y - topLeft.Y) / float32(sourceWidth) + c := (bottomLeft.X - topLeft.X) / sourceStrip + d := (bottomLeft.Y - topLeft.Y) / sourceStrip + context.Call("save") + context.Call("transform", a, b, c, d, topLeft.X, topLeft.Y) + context.Call("drawImage", image, 0, sourceTop, float32(sourceWidth), sourceStrip, 0, 0, float32(sourceWidth), sourceStrip) + context.Call("restore") + } +} + +func bilinear(topLeft, topRight, bottomLeft, bottomRight gfx.Point, u, v float32) gfx.Point { + top := gfx.Point{X: topLeft.X + (topRight.X-topLeft.X)*u, Y: topLeft.Y + (topRight.Y-topLeft.Y)*u} + bottom := gfx.Point{X: bottomLeft.X + (bottomRight.X-bottomLeft.X)*u, Y: bottomLeft.Y + (bottomRight.Y-bottomLeft.Y)*u} + return gfx.Point{X: top.X + (bottom.X-top.X)*v, Y: top.Y + (bottom.Y-top.Y)*v} +} + +// warpLabelCanvas rasterizes the label once, in its own device-pixel canvas, +// and retains it for later warped frames. +func (runtime *runtime) warpLabelCanvas(label platform.TextLabel) (js.Value, int, int) { + width := int(math.Ceil(float64(label.Width) * float64(runtime.dpr))) + height := int(math.Ceil(float64(label.Height) * float64(runtime.dpr))) + if width <= 0 || height <= 0 || width > 16384 || height > 16384 || width*height > 16*1024*1024 { + return js.Undefined(), 0, 0 + } + key := warpKey{ + value: label.Value, size: label.FontSize, weight: label.Weight, italic: label.Italic, + mono: label.Mono, face: label.MonoFace, cell: label.CellWidth, baseline: label.Baseline, + color: label.Color, fontGen: label.FontGeneration, runs: hashRuns(label.Runs), + width: width, height: height, scale: runtime.dpr, + bitmapID: label.BitmapID, bitmapVersion: label.BitmapVersion, + bitmapW: label.BitmapWidth, bitmapH: label.BitmapHeight, bitmapStride: label.BitmapStride, + } + if len(label.Bitmap) > 0 { + key.bitmapHash = fnvBytes(label.Bitmap) + } + if canvas, ok := runtime.warps[key]; ok { + return canvas, width, height + } + var canvas js.Value + if len(label.Bitmap) > 0 { + canvas = runtime.bitmapCanvas(label) + if canvas.IsUndefined() || canvas.IsNull() { + return js.Undefined(), 0, 0 + } + width, height = label.BitmapWidth, label.BitmapHeight + } else { + canvas = runtime.document.Call("createElement", "canvas") + canvas.Set("width", width) + canvas.Set("height", height) + context := canvas.Call("getContext", "2d") + context.Call("scale", runtime.dpr, runtime.dpr) + context.Call("translate", -label.X, -label.Y) + local := label + local.Clipped = false + local.Clip = gfx.Rect{} + if len(label.Runs) > 0 { + runtime.drawLabelRunsContext(context, local) + } else { + runtime.drawTextContext(context, gfx.Text{ + Value: label.Value, + Bounds: gfx.Rect{ + X: label.X + label.OriginX, Y: label.Y + label.OriginY, + Width: label.Width, Height: label.Height, + }, + Style: gfx.TextStyle{ + Size: label.FontSize, Weight: label.Weight, Italic: label.Italic, + Color: platformColor(label.Color), Mono: label.Mono, MonoFace: label.MonoFace, + }, + Baseline: label.Baseline, + }) + } + } + if runtime.warps == nil { + runtime.warps = make(map[warpKey]js.Value) + } + if len(runtime.warps) > 64 { + runtime.warps = make(map[warpKey]js.Value) + } + runtime.warps[key] = canvas + return canvas, width, height +} + +// tintedWarp applies a label's per-corner tint to its picture. Canvas2D has no +// per-vertex tint, so a gradient from the top-left to the bottom-right corner +// approximates the four tints. +func (runtime *runtime) tintedWarp(label platform.TextLabel, source js.Value, width, height int) js.Value { + white := true + for _, tint := range label.Tint { + if tint.Red < 1 || tint.Green < 1 || tint.Blue < 1 || tint.Alpha < 1 { + white = false + break + } + } + if white { + return source + } + if runtime.warpTint.IsUndefined() || runtime.warpTint.IsNull() { + runtime.warpTint = runtime.document.Call("createElement", "canvas") + } + runtime.warpTint.Set("width", width) + runtime.warpTint.Set("height", height) + context := runtime.warpCtx + if !context.Truthy() { + context = runtime.warpTint.Call("getContext", "2d") + runtime.warpCtx = context + } + context.Set("globalCompositeOperation", "source-over") + context.Call("clearRect", 0, 0, width, height) + context.Call("drawImage", source, 0, 0) + gradient := context.Call("createLinearGradient", 0, 0, width, height) + topLeft := platformColor(label.Tint[0]) + bottomRight := platformColor(label.Tint[3]) + gradient.Call("addColorStop", 0, cssColor(topLeft)) + gradient.Call("addColorStop", 1, cssColor(bottomRight)) + context.Set("globalCompositeOperation", "multiply") + context.Set("fillStyle", gradient) + context.Call("fillRect", 0, 0, width, height) + context.Set("globalCompositeOperation", "destination-in") + context.Call("drawImage", source, 0, 0) + context.Set("globalCompositeOperation", "source-over") + return runtime.warpTint +} diff --git a/internal/platform/web/shaders/scene.frag.glsl b/internal/platform/web/shaders/scene.frag.glsl new file mode 100644 index 00000000..3d1ae728 --- /dev/null +++ b/internal/platform/web/shaders/scene.frag.glsl @@ -0,0 +1,154 @@ +#version 300 es +precision highp float; +precision highp int; + +in vec4 vColor; +in vec2 vLocal; +in vec2 vSize; +in float vRadius; +in vec2 vFragment; +in vec2 vTriangleA; +in vec2 vTriangleB; +in vec2 vTriangleC; +flat in uint vTriangleMask; + +uniform vec2 uTargetPixels; +uniform vec2 uOrigin; +uniform float uPixelSize; + +out vec4 outColor; + +#define boundedTriangleFlag (1u << 8) + +float edgeDistance(vec2 point, vec2 from, vec2 to) { + vec2 edge = to - from; + float edgeLength = max(length(edge), 1e-6); + return (edge.x * (point.y - from.y) - edge.y * (point.x - from.x)) / edgeLength; +} +float cross2(vec2 a, vec2 b) { return a.x * b.y - a.y * b.x; } + +float segmentDistance(vec2 p, vec2 a, vec2 b) { + vec2 edge = b - a; + float along = clamp(dot(p - a, edge) / max(dot(edge, edge), 1e-12), 0.0, 1.0); + return length(p - a - along * edge); +} + +// Logical pixels per device pixel at this fragment. Edges feathered over a +// fixed logical band smear across several device pixels on a scaled display; +// one device pixel keeps thin strokes and corners crisp at any scale. +float devicePixel(vec2 position) { + return max(fwidth(position).x, 1e-4); +} + +// Signed distance from p to a rounded box centred on the origin. +float roundedBoxDistance(vec2 p, vec2 halfSize, float radius) { + vec2 q = abs(p) - halfSize + radius; + return length(max(q, vec2(0.0))) + min(max(q.x, q.y), 0.0) - radius; +} + +// A soft shadow. The shadow's shape is the casting rectangle moved by the offset +// and grown by the spread (the corner radius grows with it, a sharp corner +// staying sharp). Its edge is spread over a band of blur on either side: a +// smoothstep of the signed distance, which follows a Gaussian of deviation +// blur / 2 (the CSS box-shadow blur) to within a few percent. The casting +// rectangle itself is cut out, so a translucent surface drawn over the shadow is +// not darkened by it. +vec4 shadowColor(float pixel) { + vec2 offset = vTriangleA; + float spread = vTriangleB.x; + float blur = vTriangleB.y; + vec2 halfSize = max(vSize * 0.5 + spread, vec2(0.0)); + float radius = vRadius > 0.0 ? clamp(vRadius + spread, 0.0, min(halfSize.x, halfSize.y)) : 0.0; + float distance = roundedBoxDistance(vLocal - vSize * 0.5 - offset, halfSize, radius); + float t = clamp(0.5 - distance / (2.0 * blur), 0.0, 1.0); + float alpha = t * t * (3.0 - 2.0 * t); + float hole = min(vRadius, min(vSize.x, vSize.y) * 0.5); + float inside = roundedBoxDistance(vLocal - vSize * 0.5, vSize * 0.5, hole); + alpha *= 1.0 - clamp(0.5 - inside / pixel, 0.0, 1.0); + alpha *= vColor.a; + return vec4(vColor.rgb * alpha, alpha); +} + +void main() { + // WebGL's gl_FragCoord starts at the bottom-left; Viva's device space at + // the top-left of the target. + vec2 device = vec2(gl_FragCoord.x, uTargetPixels.y - gl_FragCoord.y) - uOrigin; + vec2 p = device * uPixelSize; + float pixel = uPixelSize; + if (vTriangleMask > 0u) { + // Winding-independent coverage: the signed distance to the nearest + // outer mesh edge is feathered over one device pixel, the same band the + // rounded-rect corners use. Shared tessellation edges stay opaque. + float area = (vTriangleB.x - vTriangleA.x) * (vTriangleC.y - vTriangleA.y) - + (vTriangleB.y - vTriangleA.y) * (vTriangleC.x - vTriangleA.x); + float orientation = area > 0.0 ? 1.0 : -1.0; + uint edgeMask = (vTriangleMask & ~boundedTriangleFlag) - 1u; + // Marked edges are supporting lines: only their half-pixel neighborhood + // of the triangle itself is coverage. Without this cut a sliver paints + // its lines across the window. + vec2 low = min(vTriangleA, min(vTriangleB, vTriangleC)) - 0.5 * pixel; + vec2 high = max(vTriangleA, max(vTriangleB, vTriangleC)) + 0.5 * pixel; + if (any(lessThan(p, low)) || any(greaterThan(p, high))) { + outColor = vec4(0.0); + return; + } + if ((vTriangleMask & boundedTriangleFlag) != 0u) { + vec2 points[3] = vec2[](vTriangleA, vTriangleB, vTriangleC); + for (uint i = 0u; i < 3u; i++) { + if ((edgeMask & (1u << i)) != 0u) { + continue; + } + // Evaluate in device coordinates: dividing a sample by 3 first + // can turn an exactly shared sample into a gap at 3x scale. + vec2 a = points[i] / pixel, b = points[(i + 1u) % 3u] / pixel; + float direction = orientation; + // Both faces evaluate the same ordered endpoints, so rounding + // cannot put a sample on the outside (or inside) of both. + if (a.x > b.x || (a.x == b.x && a.y > b.y)) { + vec2 swap = a; + a = b; + b = swap; + direction = -direction; + } + vec2 edge = b - a; + float side = direction * cross2(edge, device - a); + edge *= direction; + // Screen-space top-left rule: a shared edge belongs to one face. + bool topLeft = edge.y < 0.0 || (edge.y == 0.0 && edge.x > 0.0); + if (side < 0.0 || (side == 0.0 && !topLeft)) { + outColor = vec4(0.0); + return; + } + } + } + float distance0 = (edgeMask & 1u) != 0u ? orientation * edgeDistance(p, vTriangleA, vTriangleB) : 1e6; + float distance1 = (edgeMask & 2u) != 0u ? orientation * edgeDistance(p, vTriangleB, vTriangleC) : 1e6; + float distance2 = (edgeMask & 4u) != 0u ? orientation * edgeDistance(p, vTriangleC, vTriangleA) : 1e6; + float inside = min(distance0, min(distance1, distance2)); + if (inside < 0.0) { + // Acute offset-line miters must not paint beyond the actual ends. + float s0 = (edgeMask & 1u) != 0u ? segmentDistance(p, vTriangleA, vTriangleB) : 1e6; + float s1 = (edgeMask & 2u) != 0u ? segmentDistance(p, vTriangleB, vTriangleC) : 1e6; + float s2 = (edgeMask & 4u) != 0u ? segmentDistance(p, vTriangleC, vTriangleA) : 1e6; + inside = -min(s0, min(s1, s2)); + } + float coverage = edgeMask == 0u ? 1.0 : clamp(0.5 + inside / pixel, 0.0, 1.0); + vec4 shade = clamp(vColor, 0.0, 1.0); + float alpha = shade.a * coverage; + outColor = vec4(shade.rgb * alpha, alpha); + return; + } + if (vTriangleB.y > 0.0) { + outColor = shadowColor(devicePixel(vLocal)); + return; + } + float radius = min(vRadius, min(vSize.x, vSize.y) * 0.5); + float coverage = 1.0; + if (radius > 0.0) { + vec2 distanceVector = abs(vLocal - vSize * 0.5) - vSize * 0.5 + radius; + float distance = length(max(distanceVector, vec2(0.0))) + min(max(distanceVector.x, distanceVector.y), 0.0) - radius; + coverage = clamp(0.5 - distance / devicePixel(vLocal), 0.0, 1.0); + } + float alpha = vColor.a * coverage; + outColor = vec4(vColor.rgb * alpha, alpha); +} diff --git a/internal/platform/web/shaders/scene.vert.glsl b/internal/platform/web/shaders/scene.vert.glsl new file mode 100644 index 00000000..0f919b76 --- /dev/null +++ b/internal/platform/web/shaders/scene.vert.glsl @@ -0,0 +1,126 @@ +#version 300 es +precision highp float; +precision highp int; + +layout(location = 0) in vec4 inBounds; +layout(location = 1) in vec4 inColor; +layout(location = 2) in vec4 inStyle; +layout(location = 3) in vec4 inShade1; +layout(location = 4) in vec4 inShade2; + +uniform vec2 uViewport; +uniform float uPixelSize; + +// Low bits keep edgeMask+1; this bit is local to the rasterizer. +#define boundedTriangleFlag (1u << 8) + +out vec4 vColor; +out vec2 vLocal; +out vec2 vSize; +out float vRadius; +out vec2 vFragment; +out vec2 vTriangleA; +out vec2 vTriangleB; +out vec2 vTriangleC; +flat out uint vTriangleMask; + +const vec2 corners[6] = vec2[]( + vec2(0.0, 0.0), + vec2(1.0, 0.0), + vec2(0.0, 1.0), + vec2(0.0, 1.0), + vec2(1.0, 0.0), + vec2(1.0, 1.0) +); + +float cross2(vec2 a, vec2 b) { return a.x * b.y - a.y * b.x; } +bool finite1(float v) { return !isnan(v) && !isinf(v); } +bool finite2(vec2 v) { return finite1(v.x) && finite1(v.y); } + +// Expand silhouette edges only; shared edges keep their supporting line. +vec2 fringeVertex(vec2 previous, vec2 position, vec2 next, uint previousEdge, uint nextEdge, uint mask) { + vec2 before = position - previous, after = next - position; + float area = cross2(before, after); + if (abs(area) < 1e-8 || mask == 0u) return position; + float orientation = area > 0.0 ? 1.0 : -1.0; + float h = 0.5 * uPixelSize * orientation; + float first = (mask & previousEdge) != 0u ? -h * length(before) : 0.0; + float second = (mask & nextEdge) != 0u ? -h * length(after) : 0.0; + return position + (first * after - second * before) / area; +} + +void main() { + vec2 pixel; + vec2 localPixel; + vec2 size = inBounds.zw; + float radius = inStyle.x; + vec2 triangleA = vec2(0.0); + vec2 triangleB = vec2(0.0); + vec2 triangleC = vec2(0.0); + uint triangleMask = 0u; + vec4 color = inColor; + if (inStyle.w > 0.5) { + vec2 points[3] = vec2[](inBounds.xy, inBounds.zw, inStyle.xz); + uint index = gl_VertexID < 3 ? uint(gl_VertexID) : 0u; + uint edgeMask = uint(inStyle.w + 0.5) - 1u; + uint previous = (index + 2u) % 3u; + vec2 ab = points[1] - points[0], ac = points[2] - points[0]; + vec2 bc = points[2] - points[1]; + float area = cross2(ab, ac); + float longest2 = max(dot(ab, ab), max(dot(ac, ac), dot(bc, bc))); + bool valid = finite2(points[0]) && finite2(points[1]) && finite2(points[2]) && + finite1(area) && finite1(longest2) && abs(area) >= 1e-8; + // A sliver's offset lines can meet thousands of pixels away. Rasterize + // its finite support instead. Every face with a shared edge uses this + // path: mixing hardware and analytic edge ownership cracks at fractional + // scales because hardware snaps geometry to its own subpixel grid. + bool bounded = valid && (edgeMask != 7u || abs(area) < longest2 * 0.125); + if (!valid) { + pixel = vec2(0.0); + } else if (bounded) { + vec2 low = min(points[0], min(points[1], points[2])) - 0.5 * uPixelSize; + vec2 high = max(points[0], max(points[1], points[2])) + 0.5 * uPixelSize; + pixel = mix(low, high, corners[gl_VertexID]); + } else { + pixel = fringeVertex(points[previous], points[index], points[(index + 1u) % 3u], 1u << previous, 1u << index, edgeMask); + } + // Extrapolate corner colors so interpolation stays on the original mesh. + if (valid) { + vec2 delta = pixel - points[0]; + color = inColor + cross2(delta, ac) / area * (inShade1 - inColor) + + cross2(ab, delta) / area * (inShade2 - inColor); + } + localPixel = vec2(0.0); + size = vec2(0.0); + radius = 0.0; + triangleA = points[0]; + triangleB = points[1]; + triangleC = points[2]; + triangleMask = edgeMask + 1u + (bounded ? boundedTriangleFlag : 0u); + } else if (inStyle.z > 0.0) { + // A soft shadow: inBounds and inStyle.x are the rounded rectangle that + // casts it, inStyle.z its blur, inShade1 = (offset.x, offset.y, spread). + float extent = inStyle.z + max(inShade1.z, 0.0) + max(max(inShade1.x, -inShade1.x), max(inShade1.y, -inShade1.y)); + pixel = inBounds.xy - extent + corners[gl_VertexID] * (inBounds.zw + 2.0 * extent); + localPixel = pixel - inBounds.xy; + triangleA = inShade1.xy; + triangleB = vec2(inShade1.z, inStyle.z); + } else { + pixel = inBounds.xy + corners[gl_VertexID] * inBounds.zw; + localPixel = corners[gl_VertexID] * inBounds.zw; + } + // WebGL's NDC +1 is the top of the viewport; Viva's logical origin is top-left. + gl_Position = vec4( + pixel.x / uViewport.x * 2.0 - 1.0, + 1.0 - pixel.y / uViewport.y * 2.0, + 0.0, 1.0); + vColor = color; + vLocal = localPixel; + vSize = size; + vRadius = radius; + vFragment = pixel; + vTriangleA = triangleA; + vTriangleB = triangleB; + vTriangleC = triangleC; + vTriangleMask = triangleMask; +} diff --git a/internal/platform/web/shaders/text.frag.glsl b/internal/platform/web/shaders/text.frag.glsl new file mode 100644 index 00000000..389a7dbc --- /dev/null +++ b/internal/platform/web/shaders/text.frag.glsl @@ -0,0 +1,16 @@ +#version 300 es +precision highp float; + +uniform sampler2D uTexture; + +in vec2 vUV; +in vec4 vTint; +out vec4 outColor; + +void main() { + // Label textures carry premultiplied BGRA bytes in RGBA channels. + vec4 texel = texture(uTexture, vUV).bgra; + // vTint is straight RGBA; premultiply it before multiplying the texel. + vec4 tint = vec4(vTint.rgb * vTint.a, vTint.a); + outColor = texel * tint; +} diff --git a/internal/platform/web/shaders/text.vert.glsl b/internal/platform/web/shaders/text.vert.glsl new file mode 100644 index 00000000..6b6f48a7 --- /dev/null +++ b/internal/platform/web/shaders/text.vert.glsl @@ -0,0 +1,31 @@ +#version 300 es +precision highp float; + +uniform vec2 uViewport; +// Top-left, top-right, bottom-left, bottom-right, in logical pixels. +uniform vec4 uCorners[4]; +uniform vec4 uTint[4]; + +out vec2 vUV; +out vec4 vTint; + +const vec2 uv[6] = vec2[]( + vec2(0.0, 0.0), + vec2(1.0, 0.0), + vec2(0.0, 1.0), + vec2(0.0, 1.0), + vec2(1.0, 0.0), + vec2(1.0, 1.0) +); +const int corner[6] = int[](0, 1, 2, 2, 1, 3); + +void main() { + int index = corner[gl_VertexID]; + vec2 pixel = uCorners[index].xy; + gl_Position = vec4( + pixel.x / uViewport.x * 2.0 - 1.0, + 1.0 - pixel.y / uViewport.y * 2.0, + 0.0, 1.0); + vUV = uv[gl_VertexID]; + vTint = uTint[index]; +} diff --git a/internal/platform/web/shaders_js.go b/internal/platform/web/shaders_js.go new file mode 100644 index 00000000..166941c4 --- /dev/null +++ b/internal/platform/web/shaders_js.go @@ -0,0 +1,45 @@ +//go:build js && wasm + +package web + +import ( + "embed" + "fmt" + "syscall/js" +) + +//go:embed shaders/scene.vert.glsl shaders/scene.frag.glsl shaders/text.vert.glsl shaders/text.frag.glsl +var shaderFiles embed.FS + +func shaderSource(name string) (string, error) { + source, err := shaderFiles.ReadFile("shaders/" + name) + if err != nil { + return "", err + } + return string(source), nil +} + +func compileShader(gl js.Value, kind string, source string) (js.Value, error) { + shader := gl.Call("createShader", gl.Get(kind)) + gl.Call("shaderSource", shader, source) + gl.Call("compileShader", shader) + if !gl.Call("getShaderParameter", shader, gl.Get("COMPILE_STATUS")).Bool() { + log := gl.Call("getShaderInfoLog", shader).String() + gl.Call("deleteShader", shader) + return js.Undefined(), fmt.Errorf("webgl2: %s shader: %s", kind, log) + } + return shader, nil +} + +func linkProgram(gl js.Value, vertex, fragment js.Value) (js.Value, error) { + program := gl.Call("createProgram") + gl.Call("attachShader", program, vertex) + gl.Call("attachShader", program, fragment) + gl.Call("linkProgram", program) + if !gl.Call("getProgramParameter", program, gl.Get("LINK_STATUS")).Bool() { + log := gl.Call("getProgramInfoLog", program).String() + gl.Call("deleteProgram", program) + return js.Undefined(), fmt.Errorf("webgl2: program: %s", log) + } + return program, nil +} diff --git a/internal/platform/web/trace.go b/internal/platform/web/trace.go index 50cc06bb..10c00348 100644 --- a/internal/platform/web/trace.go +++ b/internal/platform/web/trace.go @@ -56,7 +56,7 @@ func (clock *frameClock) lap(phase *float64) { clock.last = now } -func (clock *frameClock) end(painter *painter, pathsBuilt, pathsReused int) { +func (clock *frameClock) end(rectangles, triangles, texts, hits, pathsBuilt, pathsReused int) { if !clock.on { return } @@ -67,10 +67,10 @@ func (clock *frameClock) end(painter *painter, pathsBuilt, pathsReused int) { for index, key := range [...]string{"frames", "totalMs", "a11yMs", "rectanglesMs", "trianglesMs", "textsMs"} { clock.stats.Set(key, clock.sum[index]) } - clock.stats.Set("rectangles", len(painter.rectangles)) - clock.stats.Set("triangles", len(painter.triangles)) - clock.stats.Set("texts", len(painter.texts)) - clock.stats.Set("hits", len(painter.accessibility)) + clock.stats.Set("rectangles", rectangles) + clock.stats.Set("triangles", triangles) + clock.stats.Set("texts", texts) + clock.stats.Set("hits", hits) clock.stats.Set("pathsBuilt", pathsBuilt) clock.stats.Set("pathsReused", pathsReused) } diff --git a/internal/platform/web/web.go b/internal/platform/web/web.go index 38dcd995..dfb061cf 100644 --- a/internal/platform/web/web.go +++ b/internal/platform/web/web.go @@ -17,6 +17,7 @@ import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" ) // Config describes the browser deployment. @@ -79,6 +80,8 @@ type runtime struct { focusRoot js.Value surface js.Value context js.Value + gl *glRenderer + renderer string a11y *accessibilityMirror dpr float32 pending bool @@ -89,6 +92,15 @@ type runtime struct { measurer *domMeasurer clock frameClock paths pathCache + batches []render.Batch + labelOrder []render.LabelOrder + plan []render.PlanOp + planOrder []int + triangles []gfx.Triangle + bitmaps map[bitmapKey]js.Value + warps map[warpKey]js.Value + warpTint js.Value + warpCtx js.Value sized bool hidden bool missed bool @@ -170,7 +182,30 @@ func (runtime *runtime) mount() { body.Call("appendChild", focusRoot) runtime.focusRoot = focusRoot runtime.surface = surface - runtime.context = surface.Call("getContext", "2d") + runtime.renderer = "canvas2d" + if choice := rendererChoice(runtime.window); choice != "canvas2d" { + if renderer, err := newGLRenderer(runtime, surface); err == nil { + runtime.gl = renderer + runtime.renderer = "webgl2" + } else { + runtime.window.Get("console").Call("warn", "viva: WebGL2 unavailable, using Canvas2D: "+err.Error()) + } + } + if runtime.gl == nil { + runtime.context = surface.Call("getContext", "2d") + } else { + surface.Call("addEventListener", "webglcontextlost", js.FuncOf(func(_ js.Value, args []js.Value) any { + if len(args) > 0 { + args[0].Call("preventDefault") + } + runtime.fallbackToCanvas2D("context lost") + return nil + })) + } + runtime.document.Get("documentElement").Get("dataset").Set("vivaRenderer", runtime.renderer) + if stats := runtime.window.Get("vivaWebStats"); stats.Type() == js.TypeObject { + stats.Set("renderer", runtime.renderer) + } runtime.a11y = newAccessibilityMirror(runtime.document, focusRoot, accessibilityLayer, runtime.config.Title) runtime.canvas = runtime.config.Canvas @@ -214,6 +249,45 @@ func (runtime *runtime) mount() { runtime.resize() } +func rendererChoice(window js.Value) string { + query := window.Get("location").Get("search").String() + switch { + case strings.Contains(query, "viva-renderer=canvas2d"): + return "canvas2d" + case strings.Contains(query, "viva-renderer=webgl2"): + return "webgl2" + } + return "auto" +} + +// fallbackToCanvas2D replaces a lost or failed WebGL2 canvas with a Canvas2D +// one. Input listeners live on the focus root, so the swap does not lose them; +// the next frame rebuilds the frame from the retained canvas. +func (runtime *runtime) fallbackToCanvas2D(reason string) { + if runtime.gl == nil { + return + } + runtime.gl.Destroy() + runtime.gl = nil + runtime.window.Get("console").Call("warn", "viva: WebGL2 stopped, using Canvas2D: "+reason) + old := runtime.surface + surface := runtime.document.Call("createElement", "canvas") + surface.Get("style").Set("cssText", old.Get("style").Get("cssText").String()) + surface.Set("width", old.Get("width").Int()) + surface.Set("height", old.Get("height").Int()) + runtime.focusRoot.Call("insertBefore", surface, old) + runtime.focusRoot.Call("removeChild", old) + runtime.surface = surface + runtime.context = surface.Call("getContext", "2d") + runtime.renderer = "canvas2d" + runtime.document.Get("documentElement").Get("dataset").Set("vivaRenderer", runtime.renderer) + if stats := runtime.window.Get("vivaWebStats"); stats.Type() == js.TypeObject { + stats.Set("renderer", runtime.renderer) + } + runtime.nextPaint = true + runtime.requestFrame() +} + // resizeSync reads the viewport size and reflows backing store and layout. func (runtime *runtime) resize() { previous := runtime.dpr @@ -241,6 +315,9 @@ func (runtime *runtime) resize() { changed := runtime.painter != nil && (runtime.painter.width != float32(width) || runtime.painter.height != float32(height)) runtime.surface.Set("width", int(float32(width)*runtime.dpr)) runtime.surface.Set("height", int(float32(height)*runtime.dpr)) + if runtime.gl != nil { + runtime.gl.Resize(int(float32(width)*runtime.dpr), int(float32(height)*runtime.dpr), runtime.dpr) + } if changed && runtime.sized && runtime.config.OnResize != nil { runtime.config.OnResize(gfx.Size{Width: float32(width), Height: float32(height)}) } @@ -394,7 +471,7 @@ func fullscreenActive(document js.Value) bool { // bindEvents wires pointer and keyboard input to the interaction router. func (runtime *runtime) bindEvents() { - surface := runtime.surface + events := runtime.focusRoot runtime.document.Call("addEventListener", "visibilitychange", js.FuncOf(func(js.Value, []js.Value) any { hidden := runtime.document.Get("hidden").Bool() if hidden == runtime.hidden { @@ -451,6 +528,10 @@ func (runtime *runtime) bindEvents() { } runtime.closed = true runtime.config.OnClosed() + if runtime.gl != nil { + runtime.gl.Destroy() + runtime.gl = nil + } return nil } runtime.window.Call("addEventListener", "pagehide", js.FuncOf(func(_ js.Value, args []js.Value) any { @@ -472,51 +553,53 @@ func (runtime *runtime) bindEvents() { return nil })) - surface.Call("addEventListener", "pointermove", js.FuncOf(func(_ js.Value, args []js.Value) any { + events.Call("addEventListener", "pointermove", js.FuncOf(func(_ js.Value, args []js.Value) any { event := args[0] if runtime.painter.pointerEvent(pointerEvent(gfx.PointerMove, event)) { runtime.requestFrame() } return nil })) - surface.Call("addEventListener", "pointerdown", js.FuncOf(func(_ js.Value, args []js.Value) any { + events.Call("addEventListener", "pointerdown", js.FuncOf(func(_ js.Value, args []js.Value) any { event := args[0] pointerID := event.Get("pointerId").Int() - surface.Call("setPointerCapture", pointerID) + event.Get("target").Call("setPointerCapture", pointerID) if runtime.painter.pointerEvent(pointerEvent(gfx.PointerDown, event)) { runtime.requestFrame() } runtime.focusRoot.Call("focus", map[string]any{"preventScroll": true}) return nil })) - surface.Call("addEventListener", "pointerup", js.FuncOf(func(_ js.Value, args []js.Value) any { + events.Call("addEventListener", "pointerup", js.FuncOf(func(_ js.Value, args []js.Value) any { event := args[0] if runtime.painter.pointerEvent(pointerEvent(gfx.PointerUp, event)) { runtime.requestFrame() } pointerID := event.Get("pointerId").Int() - if surface.Call("hasPointerCapture", pointerID).Bool() { - surface.Call("releasePointerCapture", pointerID) + target := event.Get("target") + if target.Call("hasPointerCapture", pointerID).Bool() { + target.Call("releasePointerCapture", pointerID) } return nil })) - surface.Call("addEventListener", "pointerleave", js.FuncOf(func(_ js.Value, args []js.Value) any { + events.Call("addEventListener", "pointerleave", js.FuncOf(func(_ js.Value, args []js.Value) any { if runtime.painter.pointerEvent(pointerEvent(gfx.PointerExit, args[0])) { runtime.requestFrame() } return nil })) - surface.Call("addEventListener", "pointercancel", js.FuncOf(func(_ js.Value, args []js.Value) any { + events.Call("addEventListener", "pointercancel", js.FuncOf(func(_ js.Value, args []js.Value) any { if runtime.painter.pointerCancel(pointerEvent(gfx.PointerExit, args[0])) { runtime.requestFrame() } pointerID := args[0].Get("pointerId").Int() - if surface.Call("hasPointerCapture", pointerID).Bool() { - surface.Call("releasePointerCapture", pointerID) + target := args[0].Get("target") + if target.Call("hasPointerCapture", pointerID).Bool() { + target.Call("releasePointerCapture", pointerID) } return nil })) - surface.Call("addEventListener", "contextmenu", js.FuncOf(func(_ js.Value, args []js.Value) any { + events.Call("addEventListener", "contextmenu", js.FuncOf(func(_ js.Value, args []js.Value) any { args[0].Call("preventDefault") return nil })) @@ -525,7 +608,7 @@ func (runtime *runtime) bindEvents() { runtime.requestFrame() return nil })) - surface.Call("addEventListener", "wheel", js.FuncOf(func(_ js.Value, args []js.Value) any { + events.Call("addEventListener", "wheel", js.FuncOf(func(_ js.Value, args []js.Value) any { event := args[0] event.Call("preventDefault") deltaX, deltaY, precise := wheelDeltas( diff --git a/internal/render/plan.go b/internal/render/plan.go new file mode 100644 index 00000000..16be2f93 --- /dev/null +++ b/internal/render/plan.go @@ -0,0 +1,112 @@ +package render + +import ( + "slices" + + "github.com/vivaui/viva/internal/scene" +) + +// PlanKind is what one planned operation draws. +type PlanKind uint8 + +const ( + // PlanShapes draws Count instances starting at First in the frame's + // rectangle list. + PlanShapes PlanKind = iota + 1 + // PlanLabels draws the label at Label. + PlanLabels +) + +// LabelOrder is what a renderer needs to place a label among shape batches: +// the layer it composes in and how many shape instances the frame painted +// before it. +type LabelOrder struct { + Layer uint16 + ShapesBefore uint32 +} + +// PlanOp is one draw in paint order: a run of shape instances, or one label. +type PlanOp struct { + Kind PlanKind + Layer uint16 + Clipped bool + Clip scene.Rect + First int + Count int + Label int +} + +// Plan interleaves shape batches and labels in paint order, splitting a batch +// when a label was painted inside it. Shape batches must already be ordered by +// layer, as GroupBatches returns them. Plan allocates the label order; callers +// that plan every frame use PlanWithOrder. +func Plan(dst []PlanOp, batches []Batch, labels []LabelOrder) []PlanOp { + order := make([]int, len(labels)) + planned, _ := PlanWithOrder(dst, order, batches, labels) + return planned +} + +// PlanWithOrder is Plan with a reusable order scratch. It returns the grown +// order slice so a caller can keep it for the next frame. +func PlanWithOrder(dst []PlanOp, order []int, batches []Batch, labels []LabelOrder) ([]PlanOp, []int) { + order = order[:0] + for index := range labels { + order = append(order, index) + } + slices.SortStableFunc(order, func(left, right int) int { + if layers := int(labels[left].Layer) - int(labels[right].Layer); layers != 0 { + return layers + } + return int(labels[left].ShapesBefore) - int(labels[right].ShapesBefore) + }) + dst = dst[:0] + for batchIndex, labelIndex := 0, 0; batchIndex < len(batches) || labelIndex < len(order); { + layer := ^uint16(0) + if batchIndex < len(batches) { + layer = batches[batchIndex].Layer + } + if labelIndex < len(order) && labels[order[labelIndex]].Layer < layer { + layer = labels[order[labelIndex]].Layer + } + batchEnd := batchIndex + for batchEnd < len(batches) && batches[batchEnd].Layer == layer { + batchEnd++ + } + labelEnd := labelIndex + for labelEnd < len(order) && labels[order[labelEnd]].Layer == layer { + labelEnd++ + } + cursor := 0 + if batchIndex < batchEnd { + cursor = batches[batchIndex].First + } + for batchIndex < batchEnd || labelIndex < labelEnd { + if labelIndex < labelEnd && + (batchIndex >= batchEnd || int(labels[order[labelIndex]].ShapesBefore) <= cursor) { + dst = append(dst, PlanOp{Kind: PlanLabels, Layer: layer, Label: order[labelIndex]}) + labelIndex++ + continue + } + batch := batches[batchIndex] + end := batch.First + batch.Count + first := cursor + for cursor < end && (labelIndex >= labelEnd || cursor < int(labels[order[labelIndex]].ShapesBefore)) { + cursor++ + } + if cursor > first { + dst = append(dst, PlanOp{ + Kind: PlanShapes, Layer: layer, + Clipped: batch.Clipped, Clip: batch.Clip, + First: first, Count: cursor - first, + }) + } + if cursor == end { + batchIndex++ + if batchIndex < batchEnd { + cursor = batches[batchIndex].First + } + } + } + } + return dst, order +} diff --git a/internal/render/plan_test.go b/internal/render/plan_test.go new file mode 100644 index 00000000..9a65d886 --- /dev/null +++ b/internal/render/plan_test.go @@ -0,0 +1,97 @@ +package render + +import ( + "reflect" + "testing" + + "github.com/vivaui/viva/internal/scene" +) + +func TestPlanWithoutLabelsIsTheBatches(t *testing.T) { + batches := []Batch{ + {Layer: 0, First: 0, Count: 3}, + {Layer: 1, Clipped: true, Clip: scene.Rect{X: 1, Y: 2, Width: 3, Height: 4}, First: 3, Count: 2}, + } + got := Plan(nil, batches, nil) + want := []PlanOp{ + {Kind: PlanShapes, Layer: 0, First: 0, Count: 3}, + {Kind: PlanShapes, Layer: 1, Clipped: true, Clip: scene.Rect{X: 1, Y: 2, Width: 3, Height: 4}, First: 3, Count: 2}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("plan = %#v, want %#v", got, want) + } +} + +func TestPlanInterleavesLabelsByShapesBefore(t *testing.T) { + batches := []Batch{{Layer: 0, First: 0, Count: 5}} + labels := []LabelOrder{ + {Layer: 0, ShapesBefore: 2}, + {Layer: 0, ShapesBefore: 0}, + {Layer: 0, ShapesBefore: 5}, + } + got := Plan(nil, batches, labels) + want := []PlanOp{ + {Kind: PlanLabels, Layer: 0, Label: 1}, + {Kind: PlanShapes, Layer: 0, First: 0, Count: 2}, + {Kind: PlanLabels, Layer: 0, Label: 0}, + {Kind: PlanShapes, Layer: 0, First: 2, Count: 3}, + {Kind: PlanLabels, Layer: 0, Label: 2}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("plan = %#v, want %#v", got, want) + } +} + +func TestPlanOrdersLayersAndKeepsLabelIndices(t *testing.T) { + batches := []Batch{ + {Layer: 0, First: 0, Count: 2}, + {Layer: 1, First: 2, Count: 2}, + } + labels := []LabelOrder{ + {Layer: 1, ShapesBefore: 0}, + {Layer: 0, ShapesBefore: 1}, + } + got := Plan(nil, batches, labels) + want := []PlanOp{ + {Kind: PlanShapes, Layer: 0, First: 0, Count: 1}, + {Kind: PlanLabels, Layer: 0, Label: 1}, + {Kind: PlanShapes, Layer: 0, First: 1, Count: 1}, + {Kind: PlanLabels, Layer: 1, Label: 0}, + {Kind: PlanShapes, Layer: 1, First: 2, Count: 2}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("plan = %#v, want %#v", got, want) + } +} + +func TestPlanHandlesShapesBeforePastTheEnd(t *testing.T) { + batches := []Batch{{Layer: 0, First: 0, Count: 2}} + labels := []LabelOrder{{Layer: 0, ShapesBefore: 10}} + got := Plan(nil, batches, labels) + want := []PlanOp{ + {Kind: PlanShapes, Layer: 0, First: 0, Count: 2}, + {Kind: PlanLabels, Layer: 0, Label: 0}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("plan = %#v, want %#v", got, want) + } +} + +func TestPlanWithOrderReusesTheScratch(t *testing.T) { + order := make([]int, 0, 2) + batches := []Batch{{Layer: 0, First: 0, Count: 1}} + labels := []LabelOrder{{Layer: 0, ShapesBefore: 0}, {Layer: 2, ShapesBefore: 0}} + got, order := PlanWithOrder(nil, order, batches, labels) + if len(order) != 2 || cap(order) < 2 { + t.Fatalf("order = %v, want two entries retained", order) + } + if len(got) != 3 { + t.Fatalf("plan = %#v, want three ops", got) + } +} + +func TestPlanOfNothingIsEmpty(t *testing.T) { + if got := Plan(nil, nil, nil); len(got) != 0 { + t.Fatalf("plan = %#v, want empty", got) + } +} diff --git a/internal/webbuild/webbuild.go b/internal/webbuild/webbuild.go new file mode 100644 index 00000000..975d5380 --- /dev/null +++ b/internal/webbuild/webbuild.go @@ -0,0 +1,191 @@ +// Package webbuild compiles a Go program for the browser and writes the +// static files a web host serves: the WebAssembly program, the Go runtime's +// loader, and optionally a page that starts it. It is host-side build tooling; +// nothing here is linked into an application. +package webbuild + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/json" + "errors" + "fmt" + "html" + "io" + "os" + "os/exec" + "path/filepath" + "strings" +) + +// Options describe one browser build. +type Options struct { + Context context.Context + // Dir is the module directory the go tool runs in. + Dir string + // OutputDir receives the program, wasm_exec.js and, with Page, index.html. + OutputDir string + // Executable names the .wasm file, without its extension. + Executable string + // Package is the main package to build. + Package string + // Flags are the go build flags before -o, such as -trimpath and -ldflags. + Flags []string + // Tags are added with -tags. + Tags []string + // Environment is the base process environment. WebEnvironment makes it the + // browser target's; nil uses os.Environ. + Environment []string + // Title names the generated page. + Title string + // Page writes index.html beside the program. + Page bool + // Stdout and Stderr receive the go tool's output; nil discards it. + Stdout io.Writer + Stderr io.Writer +} + +// Result reports what the build wrote. +type Result struct { + WasmPath string + WasmSize int64 + GzipSize int64 +} + +// Build compiles the package and writes the browser files into OutputDir. +func Build(options Options) (Result, error) { + if options.OutputDir == "" || options.Executable == "" || options.Package == "" { + return Result{}, errors.New("web build needs an output directory, executable name and package") + } + ctx := options.Context + if ctx == nil { + ctx = context.Background() + } + stdout, stderr := options.Stdout, options.Stderr + if stdout == nil { + stdout = io.Discard + } + if stderr == nil { + stderr = io.Discard + } + if err := os.MkdirAll(options.OutputDir, 0o755); err != nil { + return Result{}, err + } + base := options.Environment + if base == nil { + base = os.Environ() + } + environment := WebEnvironment(base) + wasm := filepath.Join(options.OutputDir, options.Executable+".wasm") + arguments := []string{"build"} + arguments = append(arguments, options.Flags...) + if len(options.Tags) > 0 { + arguments = append(arguments, "-tags", strings.Join(options.Tags, ",")) + } + arguments = append(arguments, "-o", wasm, options.Package) + command := exec.CommandContext(ctx, "go", arguments...) + command.Dir = options.Dir + command.Env = environment + command.Stdout, command.Stderr = stdout, stderr + if err := command.Run(); err != nil { + if errors.Is(err, exec.ErrNotFound) { + return Result{}, errors.New("the go tool was not found in PATH") + } + return Result{}, fmt.Errorf("go build failed: %w", err) + } + root, err := exec.CommandContext(ctx, "go", "env", "GOROOT").Output() + if err != nil { + return Result{}, fmt.Errorf("go env GOROOT: %w", err) + } + loader, err := os.ReadFile(filepath.Join(strings.TrimSpace(string(root)), "lib", "wasm", "wasm_exec.js")) + if err != nil { + return Result{}, fmt.Errorf("reading wasm_exec.js from the Go installation: %w", err) + } + if err := os.WriteFile(filepath.Join(options.OutputDir, "wasm_exec.js"), loader, 0o644); err != nil { + return Result{}, err + } + if options.Page { + title := options.Title + if title == "" { + title = options.Executable + } + page, err := pageHTML(title, options.Executable+".wasm") + if err != nil { + return Result{}, err + } + if err := os.WriteFile(filepath.Join(options.OutputDir, "index.html"), page, 0o644); err != nil { + return Result{}, err + } + } + program, err := os.ReadFile(wasm) + if err != nil { + return Result{}, err + } + var compressed bytes.Buffer + writer, _ := gzip.NewWriterLevel(&compressed, gzip.BestCompression) + _, _ = writer.Write(program) + _ = writer.Close() + return Result{WasmPath: wasm, WasmSize: int64(len(program)), GzipSize: int64(compressed.Len())}, nil +} + +// WebEnvironment returns base as the browser target's environment, with any +// existing GOOS, GOARCH and CGO_ENABLED replaced. +func WebEnvironment(base []string) []string { + environment := make([]string, 0, len(base)+3) + for _, entry := range base { + if strings.HasPrefix(entry, "GOOS=") || strings.HasPrefix(entry, "GOARCH=") || strings.HasPrefix(entry, "CGO_ENABLED=") { + continue + } + environment = append(environment, entry) + } + return append(environment, "GOOS=js", "GOARCH=wasm", "CGO_ENABLED=0") +} + +// pageHTML is the page that starts the program. The title is HTML text and the +// program's file name is a JavaScript string, so each is escaped for where it +// lands. +func pageHTML(title, wasm string) ([]byte, error) { + quoted, err := json.Marshal(wasm) + if err != nil { + return nil, err + } + var page bytes.Buffer + fmt.Fprintf(&page, ` + + + + + %s + + + + + + + +`, html.EscapeString(title), quoted, quoted, quoted) + return page.Bytes(), nil +} diff --git a/tools/docs/content.go b/tools/docs/content.go index 5d714db2..a5adaecb 100644 --- a/tools/docs/content.go +++ b/tools/docs/content.go @@ -58,7 +58,7 @@ func documentation() map[string]Page { {Platform: "macOS", Status: "Native preview", Detail: "AppKit + Metal. Run locally to check system fonts, focus and accessibility."}, {Platform: "Windows", Status: "Experimental", Detail: "Native runner cross-builds; this documentation is not a Windows hardware-validation report."}, {Platform: "Linux", Status: "Not available", Detail: "The current Linux backend cannot run these Canvas component examples."}, - {Platform: "Web", Status: "Canvas2D preview", Detail: "The same Go example compiled to WASM, not HTML/CSS imitation. Native performance and system integration are not measured here."}, + {Platform: "Web", Status: "WebGL2 preview", Detail: "The same Go example compiled to WASM, drawn with WebGL2 and falling back to Canvas2D; not HTML/CSS imitation. Native performance and system integration are not measured here."}, } if id == "input" { page.Capabilities[3] = Capability{Platform: "Web", Status: "Interactive text input", Detail: "Browser typing, selection and IME connect to the same caller-owned Go editor used by the native preview."} diff --git a/tools/docs/main.go b/tools/docs/main.go index dde12fd2..604748ac 100644 --- a/tools/docs/main.go +++ b/tools/docs/main.go @@ -9,10 +9,11 @@ import ( "fmt" "io" "os" - "os/exec" "path/filepath" "strings" "time" + + "github.com/vivaui/viva/internal/webbuild" ) //go:embed preview/* @@ -68,24 +69,19 @@ func run(output string, check bool) error { } ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) defer cancel() - command := exec.CommandContext(ctx, "go", "build", "-trimpath", "-ldflags=-s -w -buildid=", "-o", filepath.Join(staging, "public", "preview", "preview-"+manifest.Revision+".wasm"), "./cmd/component-preview") - command.Dir = root - command.Env = targetEnvironment(os.Environ()) - command.Stdout, command.Stderr = os.Stdout, os.Stderr - if err := command.Run(); err != nil { + if _, err := webbuild.Build(webbuild.Options{ + Context: ctx, + Dir: root, + OutputDir: filepath.Join(staging, "public", "preview"), + Executable: "preview-" + manifest.Revision, + Package: "./cmd/component-preview", + Flags: []string{"-trimpath", "-ldflags=-s -w -buildid="}, + Environment: os.Environ(), + Stdout: os.Stdout, + Stderr: os.Stderr, + }); err != nil { return fmt.Errorf("compile shared Web preview: %w", err) } - gorootBytes, err := exec.Command("go", "env", "GOROOT").Output() - if err != nil { - return err - } - wasmRuntime, err := os.ReadFile(filepath.Join(strings.TrimSpace(string(gorootBytes)), "lib", "wasm", "wasm_exec.js")) - if err != nil { - return err - } - if err := os.WriteFile(filepath.Join(staging, "public", "preview", "wasm_exec.js"), wasmRuntime, 0o644); err != nil { - return err - } current, err := sourceManifest(root) if err != nil { return err @@ -138,13 +134,7 @@ func retainPreviousPreview(output, staging, currentRevision string) error { } func targetEnvironment(environment []string) []string { - result := make([]string, 0, len(environment)+3) - for _, entry := range environment { - if !strings.HasPrefix(entry, "GOOS=") && !strings.HasPrefix(entry, "GOARCH=") && !strings.HasPrefix(entry, "CGO_ENABLED=") { - result = append(result, entry) - } - } - return append(result, "GOOS=js", "GOARCH=wasm", "CGO_ENABLED=0") + return webbuild.WebEnvironment(environment) } func findRoot() (string, error) { diff --git a/tools/webcheck/check.mjs b/tools/webcheck/check.mjs index d67d91b6..b8ecf19e 100644 --- a/tools/webcheck/check.mjs +++ b/tools/webcheck/check.mjs @@ -2,6 +2,12 @@ // // viva build --target web ./tools/webcheck/fixture -o build/webcheck // node tools/webcheck/check.mjs --dir build/webcheck --browser chromium +// node tools/webcheck/check.mjs --dir build/webcheck --renderer webgl2 +// +// --renderer is auto (the default), webgl2 or canvas2d. A forced renderer is +// passed in the page query string and asserted from the page's +// data-viva-renderer. A forced-WebGL2 run also loses the context and verifies +// the Canvas2D fallback keeps pointer input. // // The checks cover the complete browser interaction path, not just painting: // a pointer click, Enter on the focused button, Tab traversal, a captured @@ -19,9 +25,12 @@ import { existsSync } from 'node:fs'; import { readFileSync } from 'node:fs'; import { extname, join, normalize } from 'node:path'; import { chromium, firefox, webkit } from 'playwright'; +import { PNG } from 'pngjs'; const args = Object.fromEntries(process.argv.slice(2).map((a, i, all) => a.startsWith('--') ? [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]] : []).filter(e => e.length)); const width = +(args.width ?? 640), height = +(args.height ?? 480); +const renderer = args.renderer ?? 'auto'; +if (!['auto', 'webgl2', 'canvas2d'].includes(renderer)) throw new Error(`unknown renderer ${renderer}; use auto, webgl2 or canvas2d`); const engines = { chromium, firefox, webkit }; const requested = args.browser ?? 'chromium'; const names = requested === 'all' ? Object.keys(engines) : [requested]; @@ -73,7 +82,10 @@ async function run(name, url) { const page = await context.newPage(); const errors = []; page.on('pageerror', error => errors.push(error.message)); - page.on('console', message => { if (message.type() === 'error') errors.push(message.text()); }); + page.on('console', message => { + if (message.type() === 'error') errors.push(message.text()); + if (message.type() === 'warning') console.log(`warn ${message.text()}`); + }); const wait = async (fn, message, arg, timeout = 10000) => { try { @@ -94,16 +106,22 @@ async function run(name, url) { try { console.log(`# ${name} ${browser.version()}`); - await page.goto(url); + const target = new URL(url); + target.searchParams.set('viva-renderer', renderer); + await page.goto(target.href); await wait(() => !!document.querySelector('canvas'), 'the page mounted a canvas'); await page.waitForSelector('[role=button][aria-label^="Count:"]'); - check(await page.evaluate(() => { - const canvas = document.querySelector('canvas'); - const data = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data; - let painted = 0; - for (let i = 0; i < data.length; i += 64) if (data[i] || data[i + 1] || data[i + 2] || data[i + 3]) painted++; - return painted > (data.length / 64) / 10; - }), 'the canvas is not blank'); + const chosen = await page.evaluate(() => document.documentElement.dataset.vivaRenderer); + check(renderer === 'auto' ? chosen === 'webgl2' || chosen === 'canvas2d' : chosen === renderer, `the page chose the ${renderer} renderer`); + const shot = PNG.sync.read(await page.locator('canvas').screenshot()); + const background = [shot.data[0], shot.data[1], shot.data[2]]; + let painted = 0; + for (let i = 0; i < shot.data.length; i += 4) { + if (Math.abs(shot.data[i] - background[0]) + Math.abs(shot.data[i + 1] - background[1]) + Math.abs(shot.data[i + 2] - background[2]) > 30) painted++; + } + check(painted > (shot.width * shot.height) / 50, 'the canvas is not blank'); + const imagePixel = (420 * 4) + (320 * shot.width * 4); + check(shot.data[imagePixel] > 200 && shot.data[imagePixel + 1] < 80 && shot.data[imagePixel + 2] > 200, 'the bitmap image is painted'); await waitLabel('[role=button][aria-label^="Count:"]', 'Count: 0', 'the counter starts at zero'); await page.mouse.click(110, 40); @@ -212,6 +230,22 @@ async function run(name, url) { await page.waitForSelector('[role=group][aria-label="Dismiss"]', { state: 'detached' }); check(true, 'the pass-through backdrop closed'); + if (renderer === 'webgl2') { + const lost = await page.evaluate(() => { + const canvas = document.querySelector('canvas'); + const gl = canvas.getContext('webgl2'); + const extension = gl?.getExtension('WEBGL_lose_context'); + if (!extension) return false; + extension.loseContext(); + return true; + }); + if (lost) { + await wait(() => document.documentElement.dataset.vivaRenderer === 'canvas2d', 'a lost WebGL2 context falls back to Canvas2D'); + await page.mouse.click(110, 40); + await waitLabel('[role=button][aria-label^="Count:"]', 'Count: 4', 'input survives the renderer fallback'); + } + } + check(errors.length === 0, `the page reported no errors${errors.length ? ': ' + errors.join('; ') : ''}`); console.log(`web check passed (${name} ${browser.version()})`); } finally { diff --git a/tools/webcheck/fixture/main.go b/tools/webcheck/fixture/main.go index a09fc9c2..bdcd476b 100644 --- a/tools/webcheck/fixture/main.go +++ b/tools/webcheck/fixture/main.go @@ -38,10 +38,19 @@ type fixture struct { level float32 menuOpen bool editor *text.Editor + image gfx.Bitmap +} + +func solidBitmap(width, height int, b, g, r, a byte) gfx.Bitmap { + pixels := make([]byte, width*height*4) + for index := 0; index < len(pixels); index += 4 { + pixels[index], pixels[index+1], pixels[index+2], pixels[index+3] = b, g, r, a + } + return gfx.Bitmap{Pix: pixels, Width: width, Height: height, Stride: width * 4, ID: 1, Version: 1} } func main() { - page := &fixture{level: 20, editor: text.NewEditor("")} + page := &fixture{level: 20, editor: text.NewEditor(""), image: solidBitmap(40, 40, 255, 0, 255, 255)} var input app.TextInput _ = app.RunCanvas(app.Config{ Title: "Viva web check", @@ -108,6 +117,18 @@ func (f *fixture) paint(canvas *gfx.Canvas, size gfx.Size) { Role: gfx.RoleStatus, SkipFocus: true, Live: gfx.LivePolite, Value: "Text: " + value, }) + // A solid bitmap checks both renderers' image path from a screenshot. + canvas.DrawBitmap(f.image, gfx.Rect{X: 400, Y: 300, Width: 40, Height: 40}) + canvas.LabelQuad("Warped", gfx.Rect{X: 400, Y: 360, Width: 100, Height: 24}, gfx.Quad{ + Points: [4]gfx.Point{ + {X: 400, Y: 360}, {X: 500, Y: 350}, + {X: 400, Y: 384}, {X: 500, Y: 394}, + }, + Tint: [4]gfx.Color{ + {Red: 1, Green: 1, Blue: 1, Alpha: 1}, {Red: 1, Green: 1, Blue: 1, Alpha: 1}, + {Red: 1, Green: 1, Blue: 1, Alpha: 1}, {Red: 1, Green: 1, Blue: 1, Alpha: 1}, + }, + }, gfx.TextStyle{Size: 14, Color: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}}) if f.menuOpen { if canvas.Clicked(backdropID) { diff --git a/tools/webcheck/package-lock.json b/tools/webcheck/package-lock.json index 5e4fcfc0..054f1637 100644 --- a/tools/webcheck/package-lock.json +++ b/tools/webcheck/package-lock.json @@ -6,7 +6,8 @@ "": { "name": "viva-webcheck", "dependencies": { - "playwright": "1.65.0" + "playwright": "1.65.0", + "pngjs": "^7.0.0" } }, "node_modules/playwright": { @@ -35,6 +36,15 @@ "engines": { "node": ">=20" } + }, + "node_modules/pngjs": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz", + "integrity": "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==", + "license": "MIT", + "engines": { + "node": ">=14.19.0" + } } } } diff --git a/tools/webcheck/package.json b/tools/webcheck/package.json index 67623905..ffcc1a34 100644 --- a/tools/webcheck/package.json +++ b/tools/webcheck/package.json @@ -4,6 +4,7 @@ "description": "Cross-browser gate for the Viva WebAssembly backend", "type": "module", "dependencies": { - "playwright": "1.65.0" + "playwright": "1.65.0", + "pngjs": "^7.0.0" } } diff --git a/tools/webcheck/safari.mjs b/tools/webcheck/safari.mjs new file mode 100644 index 00000000..e55a7211 --- /dev/null +++ b/tools/webcheck/safari.mjs @@ -0,0 +1,142 @@ +// Drives the browser verification fixture in the system Safari through +// safaridriver, which is the only way to exercise Apple's own browser rather +// than Playwright's WebKit build. +// +// One-time setup (requires an administrator): +// +// sudo safaridriver --enable +// +// Then: +// +// viva build --target web ./tools/webcheck/fixture -o build/webcheck +// node tools/webcheck/safari.mjs --dir build/webcheck +// +// This is a smoke gate: it checks the renderer the page chose, a non-blank +// canvas, the bitmap pixel, and that a trusted pointer click reaches the +// application. The full interaction and IME suite remains in check.mjs; a real +// operating-system IME candidate window still needs a human on the target +// machine. +import { createServer } from 'node:http'; +import { readFileSync } from 'node:fs'; +import { extname, join, normalize } from 'node:path'; +import { spawn } from 'node:child_process'; +import { PNG } from 'pngjs'; + +const args = Object.fromEntries(process.argv.slice(2).map((a, i, all) => a.startsWith('--') ? [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]] : []).filter(e => e.length)); +if (!args.dir) throw new Error('--dir is required'); +const renderer = args.renderer ?? 'auto'; +const port = +(args.port ?? 4444); +const root = normalize(args.dir); +const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.wasm': 'application/wasm', '.json': 'application/json', '.png': 'image/png' }; + +const server = createServer((request, response) => { + const pathname = decodeURIComponent(new URL(request.url, 'http://x').pathname); + const path = normalize(join(root, pathname)); + if (!path.startsWith(root)) { response.writeHead(403).end(); return; } + const file = path.endsWith('/') ? join(path, 'index.html') : path; + try { + const body = readFileSync(file); + response.writeHead(200, { 'content-type': types[extname(file)] ?? 'application/octet-stream', 'cache-control': 'no-store' }); + response.end(body); + } catch { + response.writeHead(404).end('not found'); + } +}); +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +const pageURL = `http://127.0.0.1:${server.address().port}/?viva-renderer=${renderer}`; + +const driver = spawn('safaridriver', ['-p', String(port)], { stdio: ['ignore', 'pipe', 'pipe'] }); +let driverLog = ''; +driver.stdout.on('data', chunk => { driverLog += chunk; }); +driver.stderr.on('data', chunk => { driverLog += chunk; }); +const cleanup = () => { server.close(); driver.kill('SIGTERM'); }; +process.on('exit', cleanup); + +async function waitForDriver() { + for (let attempt = 0; attempt < 60; attempt++) { + try { + const response = await fetch(`http://127.0.0.1:${port}/status`); + if (response.ok) return; + } catch {} + await new Promise(resolve => setTimeout(resolve, 250)); + } + throw new Error('safaridriver did not start: ' + driverLog.trim()); +} + +async function webdriver(method, path, body) { + const response = await fetch(`http://127.0.0.1:${port}${path}`, { + method, + headers: { 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const data = await response.json(); + if (!response.ok || data.value?.error) { + throw new Error(`${method} ${path}: ${data.value?.error ?? response.status} ${data.value?.message ?? ''}`.trim()); + } + return data.value; +} + +function check(ok, message) { + if (!ok) throw new Error(message); + console.log(`ok ${message}`); +} + +async function execute(session, script) { + return webdriver('POST', `/session/${session}/execute/sync`, { script, args: [] }); +} + +async function waitFor(session, script, message) { + for (let attempt = 0; attempt < 120; attempt++) { + if (await execute(session, script)) { check(true, message); return; } + await new Promise(resolve => setTimeout(resolve, 100)); + } + throw new Error('timed out: ' + message); +} + +try { + await waitForDriver(); + let session; + try { + const created = await webdriver('POST', '/session', { capabilities: { alwaysMatch: { browserName: 'safari' } } }); + session = created.sessionId; + } catch (error) { + console.error('Safari remote automation is not enabled. Run "sudo safaridriver --enable" once, then retry.'); + console.error(String(error.message || error)); + process.exit(1); + } + try { + await webdriver('POST', `/session/${session}/url`, { url: pageURL }); + await waitFor(session, `return !!document.querySelector('[role=button][aria-label^="Count:"]')`, 'the page mounted the application'); + const chosen = await execute(session, `return document.documentElement.dataset.vivaRenderer`); + check(renderer === 'auto' ? chosen === 'webgl2' || chosen === 'canvas2d' : chosen === renderer, `the page chose the ${renderer} renderer`); + + // A trusted click through WebDriver actions, not a DOM-dispatched event. + await webdriver('POST', `/session/${session}/actions`, { + actions: [{ + type: 'pointer', id: 'mouse', parameters: { pointerType: 'mouse' }, + actions: [ + { type: 'pointerMove', duration: 0, x: 110, y: 40 }, + { type: 'pointerDown', button: 0 }, + { type: 'pointerUp', button: 0 }, + ], + }], + }); + await waitFor(session, `return document.querySelector('[role=button][aria-label^="Count:"]')?.getAttribute('aria-label') === 'Count: 1'`, 'a trusted pointer click reaches the application'); + + const base64 = await webdriver('GET', `/session/${session}/screenshot`); + const shot = PNG.sync.read(Buffer.from(base64, 'base64')); + const background = [shot.data[0], shot.data[1], shot.data[2]]; + let painted = 0; + for (let index = 0; index < shot.data.length; index += 4) { + if (Math.abs(shot.data[index] - background[0]) + Math.abs(shot.data[index + 1] - background[1]) + Math.abs(shot.data[index + 2] - background[2]) > 30) painted++; + } + check(painted > (shot.width * shot.height) / 50, 'the canvas is not blank'); + const imagePixel = (420 * 4) + (320 * shot.width * 4); + check(shot.data[imagePixel] > 200 && shot.data[imagePixel + 1] < 80 && shot.data[imagePixel + 2] > 200, 'the bitmap image is painted'); + console.log(`Safari smoke check passed (${chosen})`); + } finally { + await webdriver('DELETE', `/session/${session}`).catch(() => {}); + } +} finally { + cleanup(); +} diff --git a/website/content/guides/en/platforms.md b/website/content/guides/en/platforms.md index 637efc30..870f75e7 100644 --- a/website/content/guides/en/platforms.md +++ b/website/content/guides/en/platforms.md @@ -35,12 +35,16 @@ X11 through dynamically loaded system XCB, Vulkan, Pango and Cairo, with a block ## Browser (optional) -A secondary target: the same Go components compiled to WebAssembly and drawn with Canvas2D. The component catalog's previews use it. +A secondary target: the same Go components compiled to WebAssembly and drawn +with WebGL2, falling back to Canvas2D when WebGL2 is unavailable or a context +is lost. The component catalog's previews use it. - The browser build uses the same application, layout and component code as the native backends. - Clipboard and file pickers use the browser's asynchronous APIs. - Text editing is available in the Input example, and the same Go editor backs it as the native preview. -- WebGPU is a planned backend. +- WebGL2 is the primary browser renderer, with Canvas2D as the compatibility + fallback. WebGPU is not required; it may be added later as an optional backend + only if measurements show a need. The browser backend is built separately and never makes a native artifact larger, slower or more complicated. diff --git a/website/content/guides/zh/platforms.md b/website/content/guides/zh/platforms.md index ddce64c5..2089ed61 100644 --- a/website/content/guides/zh/platforms.md +++ b/website/content/guides/zh/platforms.md @@ -35,12 +35,12 @@ Win32 事件、带预编译着色器的 Direct3D 11、用于测量的 DirectWrit ## 浏览器(可选) -次要目标:把同样的 Go 组件编译为 WebAssembly,用 Canvas2D 绘制。组件目录里的预览就用它。 +次要目标:把同样的 Go 组件编译为 WebAssembly,优先用 WebGL2 绘制;WebGL2 不可用或上下文丢失时回退 Canvas2D。组件目录里的预览就用它。 - 浏览器构建复用与原生后端相同的应用、布局和组件代码。 - 剪贴板和文件选择器使用浏览器的异步 API。 - 文本编辑已在 Input 示例中接通,使用与原生预览相同的 Go 编辑器。 -- WebGPU 是计划中的后端。 +- WebGL2 是主要的浏览器渲染器,Canvas2D 是兼容回退。WebGPU 不是必需的;只有测量证明有需要时,才可能作为可选后端加入。 浏览器后端单独构建,绝不会让原生产物变大、变慢或变复杂。 diff --git a/website/src/lib/home.ts b/website/src/lib/home.ts index 92bab1d9..3dc5f0ef 100644 --- a/website/src/lib/home.ts +++ b/website/src/lib/home.ts @@ -50,7 +50,7 @@ const english = { { name: 'Linux', stack: 'X11 · Vulkan · Pango/Cairo', detail: 'X11 through system XCB and Vulkan libraries, with Pango/Cairo text and packaged builds.' }, ] satisfies Platform[], platformsLink: 'Platform details', - platformsWebNote: 'There is also an optional web target: the same Go components compiled to WebAssembly and drawn with Canvas2D in the browser. It is a secondary deployment and preview target, not part of the desktop runtime, and it does not replace native verification.', + platformsWebNote: 'There is also an optional web target: the same Go components compiled to WebAssembly and drawn with WebGL2, falling back to Canvas2D when WebGL2 is unavailable or a context is lost. It is a secondary deployment and preview target, not part of the desktop runtime, and it does not replace native verification.', }; const chinese: typeof english = { @@ -95,7 +95,7 @@ const chinese: typeof english = { { name: 'Linux', stack: 'X11 · Vulkan · Pango/Cairo', detail: '通过系统 XCB 与 Vulkan 库使用 X11,Pango/Cairo 文字,并提供打包构建。' }, ], platformsLink: '平台详情', - platformsWebNote: '另有可选的 Web 目标:同一份 Go 组件编译为 WASM,在浏览器里用 Canvas2D 绘制。它是次要的部署与预览目标,不进入桌面运行时,也不替代原生验证。', + platformsWebNote: '另有可选的 Web 目标:同一份 Go 组件编译为 WASM,优先用 WebGL2 绘制,WebGL2 不可用或上下文丢失时回退 Canvas2D。它是次要的部署与预览目标,不进入桌面运行时,也不替代原生验证。', }; export const home = { zh: chinese, en: english } as const; diff --git a/website/src/lib/i18n.ts b/website/src/lib/i18n.ts index ea3dd55c..07a57264 100644 --- a/website/src/lib/i18n.ts +++ b/website/src/lib/i18n.ts @@ -310,7 +310,7 @@ export function localizePage(page: Page, locale: Locale): Page { macOS: ['原生预览', 'AppKit + Metal。请在本机验证系统字体、焦点与可访问性。'], Windows: ['实验性', '原生运行器通过交叉编译;本文档不是 Windows 真机验证报告。'], Linux: ['暂不可用', '当前 Linux 后端尚不能运行这些 Canvas 组件示例。'], - Web: page.ID === 'input' ? ['交互式文本输入', '浏览器输入、选区与 IME 连接到原生预览使用的同一个应用持有 Go Editor。'] : ['Canvas2D 预览', '同一份 Go 示例编译为 WASM,不是 HTML/CSS 仿制,不能据此推断原生性能。'], + Web: page.ID === 'input' ? ['交互式文本输入', '浏览器输入、选区与 IME 连接到原生预览使用的同一个应用持有 Go Editor。'] : ['WebGL2 预览(Canvas2D 回退)', '同一份 Go 示例编译为 WASM,优先用 WebGL2 绘制,不可用时回退 Canvas2D;不是 HTML/CSS 仿制,不能据此推断原生性能。'], }; if (!translated[capability.Platform]) throw new Error(`Missing platform translation: ${capability.Platform}`); return { Platform: capability.Platform, Status: translated[capability.Platform][0], Detail: translated[capability.Platform][1] }; From 2b9314dbf608fc3ea5f9bf70d9be43246cc260c7 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 18:37:34 +0800 Subject: [PATCH 41/66] fix(website): type demo page snippets Add the optional page snippet fields to Demo and keep the usage string defined. --- website/src/lib/types.ts | 2 ++ website/src/pages/[lang]/ui/[component].astro | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/website/src/lib/types.ts b/website/src/lib/types.ts index 07128a6e..9de8c636 100644 --- a/website/src/lib/types.ts +++ b/website/src/lib/types.ts @@ -9,6 +9,8 @@ export interface Demo { Title: string; Description: string; Snippet?: string; + PageSnippet?: string; + PageSnippetZh?: string; Height?: number; } diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index 2a683e7f..ce044ede 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -73,7 +73,7 @@ const optionalImports = { {(() => { const own = example.Snippet && !/components\.|Begin/.test(example.Snippet); const localized = locale === 'zh' ? example.PageSnippetZh : example.PageSnippet; - const usage = localized || example.PageSnippet || (own ? example.Snippet : ''); + const usage = localized || example.PageSnippet || (own ? example.Snippet : '') || ''; if (!usage.trim()) throw new Error(`No page usage for ${page.ID}/${example.ID} (${locale})`); const imports = Object.entries(optionalImports) .filter(([name]) => new RegExp(`\\b${name}\\.`).test(usage)) From bf28ee7e419f5bbc001662b7507b9613562f6262 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 18:37:35 +0800 Subject: [PATCH 42/66] fix(linux): report visibility when Hide races the window manager --- internal/platform/linux/gtk_window_linux.go | 7 +++++++ internal/platform/linux/status_item_linux.go | 7 +++++++ internal/platform/linux/window_linux.go | 7 +++++++ 3 files changed, 21 insertions(+) diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index 698c83ac..40196d33 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -53,6 +53,9 @@ type gtkWindow struct { minimized bool focused bool focusSerial uint64 // coalesces GDK focus transfers between a Wayland parent and its child + // visible is the last visibility reported to OnVisibility; known says it was reported at + // least once. GTK's map and unmap are the visibility the compositor can express here. + visibleKnown, visible bool regionsDirty bool // dragging and dropping follow a drag of files over the window. @@ -486,6 +489,10 @@ func (w *gtkWindow) mapChanged(on bool) { // attach to. w.wl.mapped(w, on) } + if w.config.OnVisibility != nil && (!w.visibleKnown || w.visible != on) { + w.visibleKnown, w.visible = true, on + w.config.OnVisibility(on) + } } // installActions fills in what the controls Viva draws in a custom title bar call. diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go index 391ad459..1753b064 100644 --- a/internal/platform/linux/status_item_linux.go +++ b/internal/platform/linux/status_item_linux.go @@ -180,6 +180,13 @@ func (state *linuxWindowState) command(command uint32, data []byte) error { state.hidden = true win.api.unmapWindow(win.connection, win.id) win.api.flush(win.connection) + // Hide may arrive before the window manager has mapped a new window: the + // unmap is then a no-op and no UnmapNotify follows. Report the window as + // hidden now, so no wake paints what the user just hid. + if state.config.OnVisibility != nil && state.visible { + state.visible = false + state.config.OnVisibility(false) + } case commandShow: win.api.mapWindow(win.connection, win.id) if win.topmostConfigured.Load() { diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 161f6543..8e83b364 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -871,6 +871,13 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { case xcbDestroyNotify: return true, nil case xcbMapNotify, xcbUnmapNotify: + if kind == xcbMapNotify && (*xcbMapEvent)(event).Window == win.id && state.hidden { + // The window manager mapped the window after Hide raced its first + // map: ask it to go away again, rather than show a hidden window. + win.api.unmapWindow(win.connection, win.id) + win.api.flush(win.connection) + return false, nil + } // Mapped is what the user can see here: the window manager unmaps a minimized window // and one that is on a desktop that is not showing. A compositor can hide a window // that is mapped and covered without telling it; that is not reported. From b1356ff4b378020482d4212b68f93dd6cd92f52b Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 18:37:35 +0800 Subject: [PATCH 43/66] test(conformance): hide the window before opening the panel --- cmd/viva-conformance/main.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/cmd/viva-conformance/main.go b/cmd/viva-conformance/main.go index 711bfdf7..a3b370b8 100644 --- a/cmd/viva-conformance/main.go +++ b/cmd/viva-conformance/main.go @@ -448,6 +448,11 @@ func (r *runner) scenarios(results *report) { if err != nil { return err } + // Hide it before the panel opens: a panel is dismissed when it loses the + // focus, and hiding another window takes it on platforms that hand the + // focus to the next window, which would close this one early. + hidden.window.Hide() + time.Sleep(300 * time.Millisecond) refuser, err := r.open("refuses", app.WindowTitled, true) if err != nil { return err @@ -456,8 +461,6 @@ func (r *runner) scenarios(results *report) { if err != nil { return err } - hidden.window.Hide() - time.Sleep(300 * time.Millisecond) // The panel is the window that handled an event last, as when a user has // just clicked in it, and it is closing as Quit is asked for: a Quit posted // to just that window would be lost with it. This is what the tray's Quit From d812524c40f10c6a84de629c06234e4d0a16235a Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 19 Nov 2026 18:47:32 +0800 Subject: [PATCH 44/66] feat(ui): close page control state gaps --- base/color.go | 29 ++- base/combobox.go | 77 +++++- base/controls.go | 7 +- base/elements.go | 11 +- base/field.go | 55 ++++- base/flags.go | 1 + base/form_field.go | 45 +++- base/page_bases.go | 3 +- base/range_slider.go | 63 ++++- base/range_slider_labels_test.go | 45 ++++ base/select.go | 31 ++- base/table.go | 59 ++++- base/table_fitheadings_test.go | 81 +++++++ base/toast.go | 43 +++- base/validation_options_test.go | 105 ++++++++ cmd/viva/initfiles/AGENTS.md.txt | 2 + cmd/viva/templates/drawer.go.txt | 14 +- components/drawer.go | 14 +- internal/componentdemo/checkbox.go | 45 ++-- internal/componentdemo/color_picker.go | 139 ++--------- internal/componentdemo/color_swatch.go | 33 ++- internal/componentdemo/combobox.go | 209 +++++++--------- internal/componentdemo/drawer.go | 6 +- internal/componentdemo/field.go | 33 +-- internal/componentdemo/form.go | 41 ++-- internal/componentdemo/input.go | 202 ++++------------ internal/componentdemo/label.go | 34 ++- internal/componentdemo/native_select.go | 80 ++++--- internal/componentdemo/segmented_control.go | 70 +++--- internal/componentdemo/select.go | 111 +++------ internal/componentdemo/slider.go | 10 +- internal/componentdemo/sonner.go | 88 ++----- internal/componentdemo/table.go | 76 ++---- internal/componentdemo/textarea.go | 174 +++++++------- internal/componentdemo/toast.go | 59 ++--- internal/componentdemo/toggle.go | 57 ++--- ui/color_page_gaps_test.go | 116 +++++++++ ui/color_paint.go | 16 +- ui/combobox_page_gaps_test.go | 83 +++++++ ui/combobox_paint.go | 1 + ui/controls_paint.go | 15 +- ui/engine.go | 1 + ui/field_paint.go | 18 ++ ui/field_readonly_test.go | 251 ++++++++++++++++++++ ui/range_slider_labels_test.go | 48 ++++ ui/range_slider_paint.go | 32 ++- ui/select_paint.go | 4 +- ui/toast_paint.go | 9 +- ui/validation_options_test.go | 121 ++++++++++ 49 files changed, 1829 insertions(+), 1038 deletions(-) create mode 100644 base/range_slider_labels_test.go create mode 100644 base/table_fitheadings_test.go create mode 100644 base/validation_options_test.go create mode 100644 ui/color_page_gaps_test.go create mode 100644 ui/combobox_page_gaps_test.go create mode 100644 ui/field_readonly_test.go create mode 100644 ui/range_slider_labels_test.go create mode 100644 ui/validation_options_test.go diff --git a/base/color.go b/base/color.go index 82188e11..b77f9399 100644 --- a/base/color.go +++ b/base/color.go @@ -16,7 +16,8 @@ func (s *ColorPickerState) SetHexText(value string) { // ColorSwatch adds a circular color choice, a radio button in a group of them: color is // what it shows (a transparent color is "no color", drawn as a slash), selected rings // it, and label names it for assistive technology. A click is Clicked; the application -// owns the choice. It is as wide and tall as its Size, 28 when it has none. +// owns the choice. It is as wide and tall as its Size, 28 when it has none. Disabled +// makes it dimmed and inert, as it does for the other controls. // // if ui.ColorSwatch(c.Key(name), color, m.color == color, name).Clicked() { m.color = color } func ColorSwatch(c C, Color Color, selected bool, Label string) Box { @@ -58,6 +59,7 @@ func (b Box) TabStop(on bool) Box { // closed. type ColorPickerState struct { open, restoreFocus, applied bool + showAlpha bool draft ColorPickerValue hexEditor text.Editor hex Field @@ -72,6 +74,10 @@ type ColorPickerState struct { // Open reports whether the picker's panel is open. func (s *ColorPickerState) Open() bool { return s.open } +// ShowsAlpha reports whether the picker offers an opacity bar and reads and writes +// #RRGGBBAA, as ShowAlpha set it. +func (s *ColorPickerState) ShowsAlpha() bool { return s.showAlpha } + // Draft is the color being staged while the panel is open, which follows the plane, the // hue bar and the hex field as they change and is not yet the application's: a preview // that tracks the drag reads it. It reports false when the panel is closed. @@ -104,7 +110,8 @@ type ColorPickerLook struct { // color is staged while the panel is open and written to *color on Apply (Enter in the // hex field); Cancel, Escape and a press outside leave it as it was. A transparent // *color is no color, which Clear sets. The box is the 32 pixel trigger; Applied -// reports a change. RoundTrigger, TriggerIcon, NoColor and PanelLabels change how it looks. +// reports a change. RoundTrigger, TriggerIcon, NoColor and PanelLabels change how it +// looks, and ShowAlpha adds an opacity bar and #RRGGBBAA input. // // ui.ColorPicker(c, &m.picker, &m.accent, "Accent") // if m.picker.Applied() { m.save() } @@ -178,8 +185,8 @@ func (b Box) NoColor(empty bool) Box { } // PanelLabels overrides the words of a ColorPicker's panel: its title, the plane, the hue -// bar, the hex field and the buttons. A label left empty keeps its default. Other -// elements ignore it. +// bar, the alpha bar, the hex field and the buttons. A label left empty keeps its +// default. Other elements ignore it. func (b Box) PanelLabels(labels ColorPickerLabels) Box { if extra := b.pickerExtra(); extra != nil { extra.pickerLook.labels = labels @@ -187,6 +194,16 @@ func (b Box) PanelLabels(labels ColorPickerLabels) Box { return b } +// ShowAlpha makes a ColorPicker offer an opacity bar and read and write #RRGGBBAA, +// so the chosen color keeps its alpha; without it a picked color is opaque. Other +// elements ignore it. +func (b Box) ShowAlpha(show bool) Box { + if extra := b.pickerExtra(); extra != nil { + extra.picker.showAlpha = show + } + return b +} + func (b Box) pickerExtra() *Extra { n := b.N() if n.Ext == 0 || b.f.Exts[n.Ext].picker == nil { @@ -221,7 +238,7 @@ func (s *ColorPickerState) ApplyDraft() { func (s *ColorPickerState) SetDraftValue(v ColorPickerValue) { s.draft = v var buf [9]byte - value := string(v.AppendHex(buf[:0], false)) + value := string(v.AppendHex(buf[:0], s.showAlpha)) if s.hexEditor.String() != value { s.hexEditor = text.Editor{} s.hexEditor.Insert(value) @@ -280,7 +297,7 @@ func (s *ColorPickerState) syncHex() { return } s.seen = value - color, valid := ParseColorHex(value, false) + color, valid := ParseColorHex(value, s.showAlpha) s.invalid = !valid if valid { s.draft = s.draft.WithColor(color) diff --git a/base/combobox.go b/base/combobox.go index 7e9622ad..5b10335f 100644 --- a/base/combobox.go +++ b/base/combobox.go @@ -5,6 +5,7 @@ import ( "unsafe" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" "github.com/vivaui/viva/window" ) @@ -21,7 +22,8 @@ import ( // Clearable adds a button that clears the choice, Empty says what the list shows // when nothing matches, and Creatable offers what was typed as a new choice, which // Created reports for the application to add. Describe gives choices a detail, text to -// search by and a disabled state. +// search by and a disabled state. InitiallyOpen and InitialQuery start the list open +// with a search, once; Invalid marks the field as one whose value is wrong. // // Not inside a Memo. func Combobox[T comparable](c C, Value *T, choices []T, nameOf func(T) string, Label string) Box { @@ -120,6 +122,7 @@ func combobox[T comparable](c C, Value *T, choices []T, nameOf func(T) string, L // Clearable, Empty and Creatable say these again for this paint, after the clicks // were taken with what the last paint showed. state.clearable, state.empty, state.list.AllowCreate, state.createPrefix = false, "", false, "" + state.Invalid = false state.layer = f.WidgetLayer() + 1 // The field declares its own hits as it paints; the element only places it, as // wide as its container, a control tall. @@ -155,10 +158,15 @@ type ComboState struct { Node int32 gen uint32 Label, placeholder, empty string - clearLabel, clearLabelOf string // "Clear