From a5b102b0c92eb0e304fb94970f3306847b22325d Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 20 Nov 2026 00:47:43 +0800 Subject: [PATCH 1/4] feat(ui): split the page's wheel routing from the window fallback Page.Wheel gave an event its own areas could not use to the OnScroll the Config was given. A window whose OnScroll forwards the wheel to the page therefore received the same event back from the fallback and forwarded it again, which overflowed the stack when no area under the pointer could scroll. RouteWheel is that routing on its own, and Wheel is RouteWheel plus the fallback. A host that hands the wheel to the page from its own OnScroll calls RouteWheel, so the page cannot fall back into the handler already routing the event. It mirrors RouteKey, which is a page's key routing without its window fallback. The companion Motty commit switches the dialogs that forward the wheel to the page and drops its own one-shot guard for this exact loop. --- base/page.go | 26 +++++++++++++---- ui/page_wheel_fallback_test.go | 52 ++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 6 deletions(-) create mode 100644 ui/page_wheel_fallback_test.go diff --git a/base/page.go b/base/page.go index 1a5add13..864d2bc5 100644 --- a/base/page.go +++ b/base/page.go @@ -1104,10 +1104,27 @@ func (p *Page) PointerOver(r Rect) bool { return p != nil && p.pointerIn && pointInRect(p.pointer.X, p.pointer.Y, r) } -// Wheel scrolls an open Select, else the scroll area under the pointer, and gives -// an event neither takes to the OnScroll Config was given. It is the Config's -// OnScroll; a host that draws a page into a region calls it itself. +// Wheel routes the wheel through the page and gives an event no route takes to +// the OnScroll Config was given. It is the Config's OnScroll; a host that draws a +// page into a region calls it itself, and a host whose own OnScroll hands the +// wheel to the page gives RouteWheel instead, so the page does not fall back into +// the handler already routing it. func (p *Page) Wheel(event gfx.ScrollEvent) gfx.EventResult { + if result := p.RouteWheel(event); result.Handled || result.Repaint { + return result + } + if p.baseScroll != nil { + return p.baseScroll(event) + } + return gfx.EventResult{} +} + +// RouteWheel scrolls an open Select, a TextArea under the pointer, or the scroll +// area or sideways list under it, and reports an event none of them takes as not +// handled. It is the page's own routing without the OnScroll fallback: a host +// that forwards a wheel to the page from its own OnScroll calls this, so the page +// cannot hand the same event back to the handler that is already routing it. +func (p *Page) RouteWheel(event gfx.ScrollEvent) gfx.EventResult { if h := p.controlOf(event.Target); h != nil && h.Scroll != nil { if result := h.Scroll(event); result.Handled { return result @@ -1158,9 +1175,6 @@ func (p *Page) Wheel(event gfx.ScrollEvent) gfx.EventResult { if moved { return gfx.EventResult{Handled: true, Repaint: true} } - if p.baseScroll != nil { - return p.baseScroll(event) - } return gfx.EventResult{} } diff --git a/ui/page_wheel_fallback_test.go b/ui/page_wheel_fallback_test.go new file mode 100644 index 00000000..ce56d664 --- /dev/null +++ b/ui/page_wheel_fallback_test.go @@ -0,0 +1,52 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// RouteWheel is the page's own routing: it scrolls what it owns and leaves the +// OnScroll fallback to Wheel. A host whose own OnScroll forwards the wheel to the +// page calls it, so the page cannot hand the same event back to that handler. +func TestRouteWheelLeavesTheOnScrollFallbackToWheel(t *testing.T) { + var area ui.Box + view := func(c ui.C) { + ui.Column(c).Fill().Children(func() { + area = ui.Scroll(c).Height(100).Shrink(0).Children(func() { + ui.Slot(c).Height(1000).Shrink(0) + }) + ui.Slot(c).Grow(1) + }) + } + page := ui.NewPage(ui.PageConfig{Root: "route-wheel", View: view}) + calls := 0 + ui.Configure(page, app.Config{OnScroll: func(gfx.ScrollEvent) gfx.EventResult { + calls++ + return gfx.EventResult{Handled: true, Repaint: true} + }}) + canvas := benchCanvas() + drawPage(page, canvas, view) + r := area.Rect() + over := gfx.ScrollEvent{X: r.X + 10, Y: r.Y + 10, DeltaY: 80, Precise: true} + if result := page.RouteWheel(over); !result.Handled || !result.Repaint { + t.Fatalf("RouteWheel over the area gave %+v, want it handled and repainted", result) + } + if calls != 0 { + t.Fatalf("RouteWheel called the OnScroll fallback %d times", calls) + } + drawPage(page, canvas, view) + if area.ScrollState().Offset == 0 { + t.Fatal("RouteWheel did not move the page's own area") + } + outside := gfx.ScrollEvent{X: r.X + 10, Y: r.Y + r.Height + 40, DeltaY: 10, Precise: true} + if result := page.Wheel(outside); !result.Handled || calls != 1 { + t.Fatalf("Wheel outside every area gave %+v after %d fallback calls, want the fallback once", result, calls) + } + steady := gfx.ScrollEvent{X: r.X + 10, Y: r.Y + 10, DeltaX: 1, Precise: true} + if allocs := testing.AllocsPerRun(20, func() { drawPage(page, canvas, view); page.RouteWheel(steady) }); allocs != 0 { + t.Fatalf("a steady paint and RouteWheel allocates %v times", allocs) + } +} From e2e6a07523a334b21b25175098e6413f18006f9e Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 20 Nov 2026 01:32:09 +0800 Subject: [PATCH 2/4] docs(release): v0.6.6 notes --- docs/releases/0.6.6.md | 85 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 docs/releases/0.6.6.md diff --git a/docs/releases/0.6.6.md b/docs/releases/0.6.6.md new file mode 100644 index 00000000..bb37dc20 --- /dev/null +++ b/docs/releases/0.6.6.md @@ -0,0 +1,85 @@ +v0.6.6 是 v0.6.5 之后的版本:页面控件补齐单选、标签、分页、拆分按钮、颜色选择与组合框选项,表单、布局和画布组件有了页面版 API;应用侧新增窗口标题、菜单动作结果、拖拽预览与 PCM 音频输出。macOS 是参考平台。有一处签名变化需要迁移,见“注意 · Caveats”。 + +v0.6.6 comes after v0.6.5: the page controls gain radio groups, badges, pagination, split buttons, color choices and described combobox options, the form, layout and canvas components get page-first APIs, and applications gain window titles, menu action results, drag previews and PCM audio output. macOS is the reference platform. One signature change needs a migration; see "注意 · Caveats". + +## 拿到它 · Getting it + +`go get github.com/vivaui/viva@v0.6.6`,需要 Go 1.26 或更新;系统依赖与 v0.6.5 相同,Vulkan 加载器现在只是推荐安装,没有时用 CPU 渲染。每个 Release 附带 `viva` 命令的预编译压缩包、`SHA256SUMS`,以及 Homebrew 与 Scoop 清单(`brew install vivaui/tap/viva`,或 `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` 后 `scoop install viva`);压缩包没有代码签名或公证,浏览器下载的 macOS 版会被 Gatekeeper 拦下,brew、curl 与 `go install` 不受影响。 + +`go get github.com/vivaui/viva@v0.6.6` needs Go 1.26 or newer; the system requirements are those of v0.6.5, with the Vulkan loader now a recommendation whose absence falls back to CPU rendering. Every Release carries prebuilt archives of the `viva` command, `SHA256SUMS`, and Homebrew and Scoop manifests (`brew install vivaui/tap/viva`, or `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` then `scoop install viva`); the archives are not code-signed or notarized, so a browser download on macOS is stopped by Gatekeeper while brew, curl and `go install` are not affected. + +## 有什么 · What is in it + +- `ui.Radio` 与 `ui.RadioGroup` 在页面里做单选,`ui.RadioID` 给应用命名的选项一个身份。 +- `ui.Badge`、`ui.Pagination`、`ui.SplitButton` 与 `ui.Kbd` 覆盖标签、分页、拆分操作和快捷键按键提示。 +- `ui.AlertDialog` 提供确认对话框;`ui.Dialog` 不设高度时按应用绘制的主体决定高度。 +- `ui.ColorSwatch` 与 `ui.ColorPicker` 让页面选择颜色,`ColorPickerState.Draft` 让预览跟随拖动。 +- `ui.ComboboxItems` 为每个选项给出说明、搜索文本与禁用状态,`ui.Select` 可以用 `DisabledOptions` 禁用单个选项,并用 `XSmall` 画更短的触发器。 +- `ui.Checkbox.Mixed` 表达部分选中,`ui.Toggle` 是带样式的开关,`ui.RangeSlider` 是两个拇指的范围滑块。 +- `ui.List` 的拖动可以从行的手柄开始,Alt 加方向键移动行,焦点留在移动后的手柄上。 +- `ui.FormField` 与 `ui.Field` 支持说明、错误、无效、禁用与提示,`FormField` 可以标出它命名的控件。 +- `ui.Box.ButtonRecipe` 与 `SwitchRecipe` 让单个按钮或开关使用自己的外观,而不是页面统一的 `Styles`。 +- `AlwaysScrollbars` 保留滚动条的槽位,滚动条在指针离开后停留并淡出,菜单行与滚动条值可以被辅助技术读出。 +- 弹出层与抽屉在窗口边缘内夹住,弹出层可以带自己的圆角与锚点偏移。 +- `ui.OpenWindow` 从页面打开自己的窗口,`Page.RouteWheel` 把滚轮交给页面而不落回窗口的 `OnScroll`。 +- 表单、布局与画布组件有了 `ui/<组件>` 的页面版 API,例如 `ui/chart`、`ui/buttongroup`、`ui/calendar`,只在被导入时链接。 +- 新增可选的 `ui/multiselect` 与 `ui/hierarchypicker` 控件包。 +- `components` 新增可组合的头像裁剪编辑器。 +- `Window.SetTitle` 在 macOS、Windows、X11 与无头后端设置窗口标题。 +- `MenuBarItem.OnSelect` 返回 `gfx.EventResult`,菜单命令的焦点、剪贴板与重绘应用到当前窗口,菜单快捷键先交给焦点控件处理。 +- `Application.OpenDragPreview` 显示跟随拖动的透明预览窗口。 +- `audio` 包把 PCM 播放到系统默认输出设备:macOS 用 AudioUnit,Windows 用 WASAPI 共享模式,Linux 用 ALSA 默认插件。 +- `window`、`base` 与 `style` 包公开窗口契约、页面引擎与样式层,`ui` 仍是写页面的入口。 +- Web 部署用 WebGL2 渲染,不支持时回退 Canvas2D。 +- 安装包把 Vulkan 加载器当作可选项,`viva doctor` 会把缺少加载器报告为 CPU 渲染说明。 +- Linux 上合成桌面没有同步缩放时仍绘制窗口框,隐藏与窗口管理器的竞争会报告正确的可见性。 +- Linux 上 GTK 组合被取消时保留选区,只含图片的 X11 剪贴板可以粘贴,CPU 渲染器会缩放位图。 +- Linux 上在 XDG 配置目录查找 Vulkan ICD,只读编辑器在第一次按键前恢复输入,Wayland 内容点击后保留键盘与输入法。 +- Windows 上隐藏窗口的唤醒不再等 `WM_PAINT`,实时缩放保持响应且不拉伸内容。 +- Windows 上安装时替换被程序加载的原生文件,更新在退出前暂存补丁载荷。 +- macOS 上双击选中单词、三击选中整行,建议的保存扩展名保持完整。 +- 文本编辑与代码行保留 CRLF 行尾。 +- memo 重放保留完整的命中语义、命中文本与无效状态,禁用控件仍能接收次要按键。 +- `ui.Tabs` 按给定的高度绘制,上下文菜单从焦点控件取方向键,`ui.Radio` 的标签放不下时以省略号结尾。 +- 场景与渲染只在删除节点时收缩保留实例,无障碍镜像只重建变化的语义,页面没有用到的控件画笔不链接。 + +- `ui.Radio` and `ui.RadioGroup` offer a single choice in a page, and `ui.RadioID` names an option the application identifies. +- `ui.Badge`, `ui.Pagination`, `ui.SplitButton` and `ui.Kbd` cover labels, page items, a joined action and a menu, and shortcut keycaps. +- `ui.AlertDialog` gives a page a confirmation dialog; a `ui.Dialog` with no height is as tall as the body the application paints. +- `ui.ColorSwatch` and `ui.ColorPicker` let a page choose colors, and `ColorPickerState.Draft` makes the preview follow the drag. +- `ui.ComboboxItems` gives every option a detail, search text and disabled state, and `ui.Select` disables single options with `DisabledOptions` and draws a shorter trigger with `XSmall`. +- `ui.Checkbox.Mixed` shows a partial choice, `ui.Toggle` is a styled switch, and `ui.RangeSlider` is a two-thumb range. +- A `ui.List` drag can start on a row's handle, and Alt with the arrow keys moves a row while the focus stays on the handle it moved. +- `ui.FormField` and `ui.Field` take a description, an error, the invalid look, disabled and a hint, and `FormField` labels the control it names. +- `ui.Box.ButtonRecipe` and `SwitchRecipe` give one button or switch its own look instead of the page's `Styles`. +- `AlwaysScrollbars` keeps a scroll area's gutter, a bar lingers and fades after the pointer leaves, and menu rows and scrollbar values reach assistive technology. +- Popovers and drawers stay clear of the page edges, and a popover can carry its own radius and anchor offset. +- `ui.OpenWindow` opens a page's own window, and `Page.RouteWheel` gives the wheel to the page without falling back into the window's `OnScroll`. +- The form, layout and canvas components have page-first APIs in `ui/`, such as `ui/chart`, `ui/buttongroup` and `ui/calendar`, linked only when imported. +- `ui/multiselect` and `ui/hierarchypicker` are new opt-in page controls. +- `components` gains a composable avatar crop editor. +- `Window.SetTitle` sets the window title on macOS, Windows, X11 and the headless backends. +- `MenuBarItem.OnSelect` returns a `gfx.EventResult`; the runtime applies the focus, clipboard and repaint a menu command returns to the active window, and a menu shortcut is offered to the focused control first. +- `Application.OpenDragPreview` shows a transparent preview window that follows a drag. +- Package `audio` plays PCM on the default output device: an AudioUnit on macOS, WASAPI shared mode on Windows and ALSA's default plugin on Linux. +- Packages `window`, `base` and `style` publish the window contracts, the page engine and the styled layer, and `ui` stays how a page is written. +- Web deployments render with WebGL2 and fall back to Canvas2D. +- The packages treat the Vulkan loader as optional, and `viva doctor` reports a missing loader as a CPU-rendering note. +- On Linux a compositing desktop without synced resize still draws the frame, and Hide racing the window manager reports the correct visibility. +- On Linux a cancelled GTK preedit keeps its selection, an image-only X11 clipboard can be pasted, and the CPU renderer scales bitmaps. +- On Linux the Vulkan ICD search covers XDG config directories, a read-only editor restores input before the first key, and Wayland keeps the keyboard and IME after a content click. +- On Windows a hidden window's wake no longer waits for `WM_PAINT`, and a live resize stays responsive without stretching the content. +- On Windows an install replaces the native files a running program loaded, and an update stages its patch payload before quitting. +- On macOS a double-click selects a word and a triple-click the line, and a suggested save extension is kept intact. +- Line editing and code rows keep CRLF line endings. +- A memo replay keeps the complete hit semantics, the hit texts and the invalid state, and a disabled control still takes a secondary press. +- `ui.Tabs` paints at the height it is given, a context menu takes the arrow keys from the focused control, and a `ui.Radio` label ends with an ellipsis when it does not fit. +- The scene and render paths shrink retained instances only on deletion, the accessibility mirror rebuilds only the semantics a repaint changed, and a page links only the control painters it uses. + +## 注意 · Caveats + +- `MenuBarItem.OnSelect` 的签名从 `func()` 变为 `func() gfx.EventResult`:每个菜单项返回命令的结果,没有变化时返回 `gfx.EventResult{}`。编译器会指出需要改的入口。 +- 通过窗口自己的 `OnScroll` 把滚轮转给页面的宿主,改用 `Page.RouteWheel`;否则页面会把同一个事件交回正在路由它的处理器。 + +- `MenuBarItem.OnSelect` changed from `func()` to `func() gfx.EventResult`: every entry returns what its command did, and `gfx.EventResult{}` when it changes nothing. The compiler points at each entry to update. +- A host whose own `OnScroll` forwards the wheel to the page calls the new `Page.RouteWheel`; otherwise the page hands the same event back to the handler already routing it. From 0a00a30ee99aac0a96668b255122b9a1b1bc3179 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 20 Nov 2026 01:41:30 +0800 Subject: [PATCH 3/4] docs: point at v0.6.6 --- README.md | 2 +- README.zh-CN.md | 2 +- website/content/guides/en/getting-started.md | 2 +- website/content/guides/zh/getting-started.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3ba06b78..5d3be502 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Pango and Cairo libraries, and a Vulkan loader and driver for GPU acceleration and DirectWrite. Viva loads the system libraries at runtime and bundles none of them. -The current release is `v0.6.5`; name it explicitly (`@v0.6.5`) to pin it. Guides, +The current release is `v0.6.6`; name it explicitly (`@v0.6.6`) to pin it. Guides, the API reference, and a component catalog with live previews live in [`website/`](website/); run it with `npm run dev` there, or read them on [vivaui.dev](https://vivaui.dev/en/), which is also available in diff --git a/README.zh-CN.md b/README.zh-CN.md index be713423..12e0b871 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -34,7 +34,7 @@ viva dev . # hot reload: save a file, the window updates and keeps its st 环境要求:Go 1.26 或更新版本(缺失时 viva 会自己下载)。macOS 上需要 Xcode 命令行工具,因为 Viva 通过 cgo 访问 Cocoa 和 Metal;Linux 上需要带系统 XCB、Pango 和 Cairo 库的 X11,Vulkan 加载库和驱动用于 GPU 加速,缺失时窗口用 CPU 渲染;Windows 上需要 Win32、Direct3D 11 和 DirectWrite。Viva 在运行时加载系统库,自身不捆绑任何一个。 -当前版本是 `v0.6.5`;要固定版本就写明(`@v0.6.5`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 +当前版本是 `v0.6.6`;要固定版本就写明(`@v0.6.6`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 下面的一切描述的都是这个仓库:它的测量、它自己的程序,以及如何开发框架本身,而不是如何用框架。 diff --git a/website/content/guides/en/getting-started.md b/website/content/guides/en/getting-started.md index 92254de8..7e1b6d1a 100644 --- a/website/content/guides/en/getting-started.md +++ b/website/content/guides/en/getting-started.md @@ -22,7 +22,7 @@ go mod init example.com/hello go get github.com/vivaui/viva ``` -`go get` without a version resolves to the latest tagged release, which is `v0.6.5`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.5`. Viva is not yet at 1.0, so the API in `go.mod` can still change between minor releases; read the release notes before upgrading. +`go get` without a version resolves to the latest tagged release, which is `v0.6.6`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.6`. Viva is not yet at 1.0, so the API in `go.mod` can still change between minor releases; read the release notes before upgrading. If you are working on Viva itself rather than using it, `replace` it with your checkout instead: diff --git a/website/content/guides/zh/getting-started.md b/website/content/guides/zh/getting-started.md index ca1d7b77..47155f28 100644 --- a/website/content/guides/zh/getting-started.md +++ b/website/content/guides/zh/getting-started.md @@ -22,7 +22,7 @@ go mod init example.com/hello go get github.com/vivaui/viva ``` -`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.5`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.5`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 +`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.6`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.6`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 如果你是在 Viva 仓库里改框架本身、而不是使用它,改用 `replace` 指向检出目录: From f5b634bbcebfc6c0fd23eb9b12643128541954a8 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Fri, 20 Nov 2026 09:41:17 +0800 Subject: [PATCH 4/4] feat(ui): paint icon-only tabs on the page tabs strip TabIconOnly() exposes the components layer's TabOption.IconOnly to a declarative Tabs strip: the strip paints the icons TabIcons gives it, and each label stays the tab's accessible name and its hover hint. A tab whose icon is zero keeps its label, since there would be nothing to see. Motty's per-host view strip is 40px wide and uses it; that application change is paired with this one. --- base/accessors.go | 3 ++ base/tabs.go | 31 +++++++++++++++-- base/tabs_test.go | 58 ++++++++++++++++++++++++++++++++ cmd/viva/initfiles/AGENTS.md.txt | 3 +- ui/tabs_paint.go | 7 +++- 5 files changed, 98 insertions(+), 4 deletions(-) diff --git a/base/accessors.go b/base/accessors.go index b2b83cd5..48eb4d9f 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -1209,6 +1209,9 @@ 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 } +// GetIconOnly reads the iconOnly of TabsDecl for the styled painting layer. +func (x *TabsDecl) GetIconOnly() bool { return x.iconOnly } + // GetLine reads the line of TabsDecl for the styled painting layer. func (x *TabsDecl) GetLine() bool { return x.line } diff --git a/base/tabs.go b/base/tabs.go index eccd1359..73ac94d7 100644 --- a/base/tabs.go +++ b/base/tabs.go @@ -11,6 +11,7 @@ type TabsDecl struct { selected int line bool vertical bool + iconOnly bool } // tabHeight is the height of one trigger of a components.Tabs; the line variant @@ -51,6 +52,20 @@ func (b Box) TabIcons(icon func(index int) gfx.Icon) Box { return b } +// TabIconOnly hides the labels of a Tabs strip and paints only the icons that +// TabIcons gives it, for a strip too narrow to hold its labels. The labels stay +// the tabs' accessible names and their hover hints, as components.TabOption.IconOnly +// keeps them. A tab whose icon function returns a zero icon keeps its label, since +// there would be nothing to see otherwise. +// +// ui.Tabs(c, &m.tab, tabs, nil).TabIcons(icons).TabIconOnly().Vertical() +func (b Box) TabIconOnly() Box { + if n := b.N(); n.Kind == kindTabs { + WidgetsOf(b.f).tabs[n.Aux].iconOnly = true + } + 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 { @@ -84,8 +99,20 @@ func (b Box) TabClicked() (int, bool) { func (f *Frame) measureTabs(n *Node) { t := &WidgetsOf(f).tabs[n.Aux] var widest float32 - for _, label := range t.labels { - widest = max(widest, f.Surface.TextWidthWeight(label, f.Palette.Metrics.FontSizeM, gfx.WeightMedium)) + for index, label := range t.labels { + width := f.Surface.TextWidthWeight(label, f.Palette.Metrics.FontSizeM, gfx.WeightMedium) + if t.icon != nil { + icon := t.icon(index) + if len(icon.Commands) > 0 || len(icon.Layers) > 0 { + if t.iconOnly { + // The label is the tab's accessible name, not its face. + width = f.Palette.Metrics.FontSizeM + } else { + width += f.Palette.Metrics.FontSizeM + 6 + } + } + } + widest = max(widest, width) } count := float32(len(t.labels)) var gap float32 diff --git a/base/tabs_test.go b/base/tabs_test.go index 652dc015..e76b8903 100644 --- a/base/tabs_test.go +++ b/base/tabs_test.go @@ -119,6 +119,64 @@ func TestTabsReportTheClickedTabAndTheContentFollowsTheIndex(t *testing.T) { } } +// A strip too narrow for its labels paints only the icons TabIcons gives it, +// while the labels remain the names a tab is reached and read by. +func TestIconOnlyTabsPaintTheirIconsAndKeepTheirNames(t *testing.T) { + theme := gfx.LightTheme() + icons := []gfx.Icon{ + {ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{gfx.MoveTo(4, 4), gfx.LineTo(20, 20)}}, + {ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{gfx.MoveTo(4, 12), gfx.LineTo(20, 12)}}, + {ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{gfx.MoveTo(12, 4), gfx.LineTo(12, 20)}}, + } + flexed, direct := testCanvas(), testCanvas() + var view View + view.Draw(flexed, theme, gfx.Rect{Width: 40, Height: 108}, func(f *Frame) { + f.Column().Children(func() { + f.Tabs(tabsScope, tabLabels, 1). + TabIcons(func(index int) gfx.Icon { return icons[index] }). + TabIconOnly().Vertical().Height(108) + }) + }) + options := make([]TabOption, len(tabLabels)) + for index, label := range tabLabels { + options[index] = TabOption{ID: tabsScope.At(index), Label: label, Icon: icons[index], IconOnly: true} + } + components.BeginTabs(direct, theme, gfx.Rect{Width: 40, Height: 108}, options, options[1].ID).Vertical().Paint() + sameCanvas(t, "icon-only", flexed, direct) + if texts := flexed.Texts(); len(texts) != 0 { + t.Fatalf("an icon-only strip painted %d labels, want none", len(texts)) + } + for index, label := range tabLabels { + if hit := hitByID(flexed, tabsScope.At(index)); hit.Label != label || hit.Hint != label { + t.Errorf("tab %d is named %q and hinted %q, want %q", index, hit.Label, hit.Hint, label) + } + } +} + +// A tab of an icon-only strip whose icon is zero keeps its label: the strip +// would otherwise show an empty trigger. +func TestAnIconOnlyTabWithoutAnIconKeepsItsLabel(t *testing.T) { + theme := gfx.LightTheme() + icon := gfx.Icon{ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{gfx.MoveTo(4, 4), gfx.LineTo(20, 20)}} + canvas := testCanvas() + var view View + view.Draw(canvas, theme, gfx.Rect{Width: 40, Height: 108}, func(f *Frame) { + f.Column().Children(func() { + f.Tabs(tabsScope, tabLabels, 1). + TabIcons(func(index int) gfx.Icon { + if index == 0 { + return gfx.Icon{} + } + return icon + }).TabIconOnly().Vertical().Height(108) + }) + }) + texts := canvas.Texts() + if len(texts) != 1 || texts[0].Value != tabLabels[0] { + t.Fatalf("texts = %v, want only %q", texts, tabLabels[0]) + } +} + func TestTabsAllocateNothingOnceWarm(t *testing.T) { var view View canvas := testCanvas() diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 8ad2600d..6cc220da 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -516,7 +516,8 @@ func (m *model) page(c ui.C) { - 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, - and `TabIcons(func(i int) gfx.Icon)` puts an icon before each label without a second constructor. + and `TabIcons(func(i int) gfx.Icon)` puts an icon before each label without a second constructor. A strip too narrow for + its labels adds `TabIconOnly()`: it paints the icons alone and keeps each label as the tab's accessible name and hint. `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/ui/tabs_paint.go b/ui/tabs_paint.go index d5e37082..d29a9aac 100644 --- a/ui/tabs_paint.go +++ b/ui/tabs_paint.go @@ -26,9 +26,14 @@ func paintTabs(f *Frame, n *Node) { widgets := base.WidgetsOf(f) labels := t.GetLabels() widgets.TabOptions = widgets.TabOptions[:0] + iconOnly := t.GetIconOnly() for index, label := range labels { + glyph := icon(index) widgets.TabOptions = append(widgets.TabOptions, base.TabOption{ - ID: t.GetScope().At(index), Label: label, Icon: icon(index), + ID: t.GetScope().At(index), Label: label, Icon: glyph, + // An icon-only strip still needs a glyph to paint; a zero one + // leaves the tab text-only, as TabIconOnly documents. + IconOnly: iconOnly && (len(glyph.Commands) > 0 || len(glyph.Layers) > 0), }) } selected := gfx.ID{}