From 0a90e7ad9b9276b06863a82cb02b3731c0c59e84 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 11 Nov 2026 18:11:06 +0800 Subject: [PATCH] ui: MenuItems.Beside opens a menu to the right of its anchor A Menu opened from a row of a list or popup covered the rows under it, since it could only open under or over its anchor. Beside places it to the right of the anchor, its top at the anchor's, flipping to the left when there is no room, and slides it in from that edge. The side a Menu opens on is now asked again in every paint, so a menu that stops calling Above or Beside opens under its anchor again. --- ui/menu.go | 46 +++++++++++++++---- ui/menu_test.go | 24 +++++++++- .../content/guides/en/declarative-layout.md | 2 +- .../content/guides/zh/declarative-layout.md | 2 +- 4 files changed, 62 insertions(+), 12 deletions(-) diff --git a/ui/menu.go b/ui/menu.go index b151542fc..23f9bf0a0 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -37,7 +37,9 @@ import ( // }) // // An item may carry a second line with Description; WidthRange bounds the menu's -// width; Above opens it over the anchor, for a trigger along the bottom of a panel. +// width; Above opens it over the anchor, for a trigger along the bottom of a panel, +// and Beside to its right, for a row of a list whose actions should not cover the +// rows under it. // // Not inside a Memo. func Menu(c C, anchor Box, open *bool, body func(*MenuItems)) { @@ -110,6 +112,7 @@ func (p *Page) declareMenu(c C, menu *MenuItems, scope gfx.Scope, open *bool, an menu.page, menu.f, menu.open, menu.anchor = p, f, open, anchor menu.scope, menu.root, menu.parent = scope, menu, nil menu.layer = f.widgetLayer() + 2 // over the page, and over a dialog it is declared in + menu.side = menuBelow // unless body says otherwise again in this paint menu.fresh() menu.declare(body) if f.canvas != nil && f.canvas.Clicked(scope.At(menuDismiss)) { @@ -120,9 +123,12 @@ func (p *Page) declareMenu(c C, menu *MenuItems, scope gfx.Scope, open *bool, an popup := f.Popup() if anchor >= 0 { anchorBox := Box{f: f, i: anchor, gen: f.gen} - if menu.above { + switch menu.side { + case menuAbove: popup.AboveBox(anchorBox, 4, Start) - } else { + case menuBeside: + popup.BesideBox(anchorBox, 4, Start) + default: popup.BelowBox(anchorBox, 4, Start) } } else { @@ -263,8 +269,8 @@ type MenuItems struct { shown bool // a ContextMenu is open at Rect // where a ContextMenu opened - above bool // open over the anchor instead of under it (Menu only) - widthMin, widthMax float32 // the least and greatest surface width; zero keeps the default + side menuSide // the edge of the anchor a Menu opens on + widthMin, widthMax float32 // the least and greatest surface width; zero keeps the default // A submenu's menu, and the menu of the one open in it: root is the Menu or // ContextMenu the chain hangs off, itself for that one, and parent the menu its @@ -365,11 +371,26 @@ func (m *MenuItems) Sub(label string, body func(*MenuItems)) MenuItem { return item } +// menuSide is the edge of its anchor a Menu opens on. +type menuSide uint8 + +const ( + menuBelow menuSide = iota // under the anchor, flipping over it when there is no room + menuAbove // over the anchor, flipping under it when there is no room + menuBeside // right of the anchor, flipping to its left when there is no room +) + // Above opens the menu over its anchor instead of under it, flipping under when // there is no room over: the menu of a trigger along the bottom of a panel, which // should cover what is above it. A submenu opens beside its row and a ContextMenu // opens at the pointer, so neither is affected. -func (m *MenuItems) Above() { m.above = true } +func (m *MenuItems) Above() { m.side = menuAbove } + +// Beside opens the menu to the right of its anchor, its top at the anchor's, +// flipping to the left when there is no room on the right: the menu of a row in a +// list or a popup, which should leave the rows under it in sight, as a submenu +// leaves its menu. A submenu and a ContextMenu are not affected. +func (m *MenuItems) Beside() { m.side = menuBeside } // WidthRange sets the least and greatest width of the menu's surface. Zero keeps // the menu's own minimum (128 for a Menu, 144 for a ContextMenu) or leaves that end @@ -497,11 +518,18 @@ func (m *MenuItems) paintAt(canvas *gfx.Canvas, theme *Theme, bounds Rect, layer } menu.End() } else { - side := components.OverlayRight + side := components.OverlayRight // the edge the menu slides in from, its anchor's if m.parent == nil { - side = components.OverlayBottom - if anchor := f.nodes[m.anchor].rect; bounds.Y+bounds.Height <= anchor.Y+anchor.Height/2 { + anchor := f.nodes[m.anchor].rect + switch { + case m.side == menuBeside: + if bounds.X+bounds.Width <= anchor.X+anchor.Width/2 { + side = components.OverlayLeft // flipped for want of room + } + case bounds.Y+bounds.Height <= anchor.Y+anchor.Height/2: side = components.OverlayTop + default: + side = components.OverlayBottom } } menu := components.BeginDropdownMenu(canvas, *theme, bounds, components.DropdownMenuOptions{ diff --git a/ui/menu_test.go b/ui/menu_test.go index a4af9c28c..85cc91bec 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -397,10 +397,11 @@ func TestSubmenuRepaintAllocates(t *testing.T) { } // menuOptionsModel exercises the menu calls that shape its surface: a second line -// under an item, its width range, and opening over the anchor. +// under an item, its width range, and opening over or beside the anchor. type menuOptionsModel struct { open bool above bool + beside bool least, greatest float32 description string label string @@ -421,6 +422,9 @@ func (m *menuOptionsModel) page(c ui.C) { if m.above { menu.Above() } + if m.beside { + menu.Beside() + } label := m.label if label == "" { label = "Model" @@ -476,6 +480,24 @@ func TestMenuWidthRange(t *testing.T) { }) } +// Beside opens the menu right of its anchor, its first row level with the anchor +// rather than under it, and a menu that stops asking for it opens under it again. +func TestMenuBeside(t *testing.T) { + m := &menuOptionsModel{beside: true} + d := openPage(t, m.page) + d.click("More") + anchor, item := d.hit("More").Bounds, d.hit("Model").Bounds + if item.X < anchor.X+anchor.Width || item.Y > anchor.Y+anchor.Height { + t.Fatalf("the menu at %v is not beside its anchor at %v", item, anchor) + } + d.key(gfx.KeyEscape) + m.beside = false + d.click("More") + if item := d.hit("Model").Bounds; item.Y < anchor.Y+anchor.Height { + t.Fatalf("the menu at %v is not under its anchor at %v once Beside is gone", item, anchor) + } +} + // Above puts the menu over the anchor even where it would fit under it. func TestMenuAbove(t *testing.T) { m := &menuOptionsModel{above: true} diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md index 34e8bc76e..80f5332ee 100644 --- a/website/content/guides/en/declarative-layout.md +++ b/website/content/guides/en/declarative-layout.md @@ -67,7 +67,7 @@ An element is named by where it is: its kind and its number among the elements o - Inside `c.Key(item.ID)` or `c.KeyInt(id)`, elements are numbered within that row, so a row's buttons follow it when rows come, go or move. Keys are reused two paints after their row is gone. A loop whose rows hold a `Button` keys its rows; `viva vet` reports one that does not. - While the user holds a button (presses it, or it has the focus), a paint in which another button took its place does not deliver the press, and the focus is given up. -`ui.TextArea(c, &m.notes, label, placeholder)` is a field of several rows. A control of your own (a terminal, an editor, a canvas the user draws on) is `ui.Control(c, label, &m.handlers)`: an empty, focusable element you paint with `Draw`, whose `Handlers` receive its keys, presses, wheel and, for `RoleTextField` or `RoleTerminal`, the platform's typing and input methods through `Text`; no identity is declared and the window dispatches nothing. A control with several interactive parts (the stars of a rating, the nodes of a graph) declares them as it draws, with `Handlers.Parts().At(i)` as their identities: a key, a press or the wheel on a part reaches the same `Handlers` with the part as the event's `Target`, and a printable key typed while the control has the focus reaches `Key` with its `Text`. `.FocusGroup(ui.FocusHorizontal)` on a row or column makes the controls inside one Tab stop with the arrow keys between them, as a toolbar's are; `.FocusOrder` gives a custom grid the row and column order it needs. The controls without their look are `ui.ButtonBase`, `CheckboxBase`, `SwitchBase`, `ToggleBase`, `RadioBase`, `TabBase`, `SliderBase`, `SelectBase` and `TextFieldBase`: bound and keyed like their dressed forms, for a design of your own. `ui.TextField(...).AutoFocus()` takes the focus as the field appears (once: the user's choice stays), and `.Submitted()` is true in the paint that delivers Enter in it; `.Secure()` makes it a password field. `.Tooltip("Delete")` gives a control the tip shown while the pointer rests on it, which is also its description. `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, and `menu.Above()` opens it over the anchor, for a trigger along the bottom of a panel. `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.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerLeft, Size: 320}, body, footer)` slides a panel in from an edge, as shadcn's Sheet: with an empty title the body has the whole panel, and `NonModal` leaves the keyboard on the page behind it; `Swipe` adds a handle at its inner edge, and a drag on it moves the panel toward its edge, closing it when dragged past half its size or thrown, sliding it back otherwise. `ui.Tree(c, &m.tree, n, label, content)` is a List of the visible rows of the application's tree, with `TreeState.Node` describing each (its depth, whether it is a branch and open); the arrows move, open and close, and the tree reports `Toggled()` and `Chosen()` for the application to act on. Typing the start of a row's name moves to it. With `TreeState.CanDrop` set, rows can be dragged onto one another (before, into or after a row, as `CanDrop` allows), and `Dropped()` reports the drop; move the rows in `c.After`, since the paint reporting it is still declaring them. `state.RowID(i)` is the identity of visible row i (`DisclosureID(i)` its chevron's, and `ListState` has `RowID` too), for giving a row the focus or finding its hit. Any other box can drag and drop with a `ui.DragState` kept in the model: `ui.Row(c).Hit(ui.ID(c), "Group").DragSource(&m.drag)` makes a box a source, and `.DropTarget(&m.drag, m.accepts, m.drops)` makes one a target. The page follows the press, the short distance that makes it a drag, and the target under the pointer; `m.drag.Dragging()`, `Source()`, `Target()` and `At()` paint the gesture, `accept(source, target)` decides, `drop(source, target)` runs on release, and Escape lets go. A press that does not move is still a click. Inside a `ui.Control`'s `Draw`, a card of a custom grid is declared as a part with `d.Canvas.Hit(part, r)` and becomes a source and target of the same state with `d.DragSource(&m.drag, part, r)` and `d.DropTarget(&m.drag, part, r, accept, drop)`, so one control carries many draggable parts with stable identities; a target part needs no Hit. Keep the callbacks in the model and declare the boxes every paint, not in a `Memo`. Toasts are a `ui.Toaster` kept in the model: `m.toaster.Show("Saved", "", ui.ToastSuccess)` puts one up, and `ui.Toasts(c, &m.toaster)`, declared once and last, paints them and takes each down after five seconds, asking for one frame when the next is due and none while nothing is up. `ShowAction(title, description, kind, "Undo")` gives one a button, whose press `m.toaster.Acted()` reports after `Toasts` and which takes the toast down; a `ui.ToastLoading` toast spins and stays until `m.toaster.Done(id, "Uploaded", "", ui.ToastSuccess)` replaces it; `Toaster.Position` puts the stack in another corner or centered (`ui.ToastTopCenter`). A keyboard shortcut is declared where it acts, as a click is read: `if ui.Shortcut(c, ui.Primary, "s") { m.save() }` is the page's (Primary is Command on macOS, Control elsewhere), and `list.Shortcut(0, "delete")` on a container or control acts only while the focus is in it, the innermost of nested ones winning. A chord without Primary, Ctrl or Alt is left to a field or terminal being typed in, and while a Popover, Modal, Menu, or Select or Combobox list is open the page's own shortcuts wait. `ui.List(c, &state, n, row)` declares only the rows on screen of a list of `n`, each as tall as its content, and scrolls it; `row` gets a `ui.ListRow` whose `Element` is the row's container to style and whose `C` declares what is in it, and `ListState.Key` names rows by an item's ID. A click chooses a row and the arrows, Home, End and Page Up and Down move between them, with the choice in `state.Selected()` and `state.Changed()` reporting that the user made one; Enter or a double click is `state.Submitted()`; `ListState.Label` makes typing the start of a row's text move to it. Set `ListState.Selection` to a `ui.Selection` to let the user choose several (Primary-click adds or removes a row, Shift extends, Primary+A chooses all). `ScrollTo`, `ScrollIntoView`, `ScrollToEnd`, `Visible` and `AtEnd` move and read the scroll position, and `box.ClickModifiers()` and `box.DoubleClicked()` say how a click on any element came. A row's `Element` is a Row, so an icon, a name and a size lie side by side. `ListState.Header` marks rows that head a section: the heading of the section at the top stays there while its rows scroll under it, until the next one pushes it away (give it a background; headings are not chosen, focused or typed to, and the keys pass over them). `ListState.Reorder` lets the user drag rows to another place, the chosen ones when the row dragged is one of them, and calls it with the rows and the row they go before; the list shows where they would go and scrolls near its edges, and Escape lets go. `ListState.RowWidth` makes the rows at least that wide: where they are wider than the list it scrolls sideways too (the horizontal wheel, or the wheel with Shift), and where they are not they grow to its width, as the columns of a table do; a header above the list follows the rows with `box.ScrollWith(&state)` on its content: give it the rows' width, and put it in a container of the header's height that clips. `ui.State[T](c, "open")` is an element's own small state (whether its menu is open), found by its name in its container and kept while the container is declared. `ui.Memo(c, *row, fn)` copies the part `fn` declares from the last paint while that value compares equal, declaring it again when it is hovered, focused, animated or resized; see Cost below. +`ui.TextArea(c, &m.notes, label, placeholder)` is a field of several rows. A control of your own (a terminal, an editor, a canvas the user draws on) is `ui.Control(c, label, &m.handlers)`: an empty, focusable element you paint with `Draw`, whose `Handlers` receive its keys, presses, wheel and, for `RoleTextField` or `RoleTerminal`, the platform's typing and input methods through `Text`; no identity is declared and the window dispatches nothing. A control with several interactive parts (the stars of a rating, the nodes of a graph) declares them as it draws, with `Handlers.Parts().At(i)` as their identities: a key, a press or the wheel on a part reaches the same `Handlers` with the part as the event's `Target`, and a printable key typed while the control has the focus reaches `Key` with its `Text`. `.FocusGroup(ui.FocusHorizontal)` on a row or column makes the controls inside one Tab stop with the arrow keys between them, as a toolbar's are; `.FocusOrder` gives a custom grid the row and column order it needs. The controls without their look are `ui.ButtonBase`, `CheckboxBase`, `SwitchBase`, `ToggleBase`, `RadioBase`, `TabBase`, `SliderBase`, `SelectBase` and `TextFieldBase`: bound and keyed like their dressed forms, for a design of your own. `ui.TextField(...).AutoFocus()` takes the focus as the field appears (once: the user's choice stays), and `.Submitted()` is true in the paint that delivers Enter in it; `.Secure()` makes it a password field. `.Tooltip("Delete")` gives a control the tip shown while the pointer rests on it, which is also its description. `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.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerLeft, Size: 320}, body, footer)` slides a panel in from an edge, as shadcn's Sheet: with an empty title the body has the whole panel, and `NonModal` leaves the keyboard on the page behind it; `Swipe` adds a handle at its inner edge, and a drag on it moves the panel toward its edge, closing it when dragged past half its size or thrown, sliding it back otherwise. `ui.Tree(c, &m.tree, n, label, content)` is a List of the visible rows of the application's tree, with `TreeState.Node` describing each (its depth, whether it is a branch and open); the arrows move, open and close, and the tree reports `Toggled()` and `Chosen()` for the application to act on. Typing the start of a row's name moves to it. With `TreeState.CanDrop` set, rows can be dragged onto one another (before, into or after a row, as `CanDrop` allows), and `Dropped()` reports the drop; move the rows in `c.After`, since the paint reporting it is still declaring them. `state.RowID(i)` is the identity of visible row i (`DisclosureID(i)` its chevron's, and `ListState` has `RowID` too), for giving a row the focus or finding its hit. Any other box can drag and drop with a `ui.DragState` kept in the model: `ui.Row(c).Hit(ui.ID(c), "Group").DragSource(&m.drag)` makes a box a source, and `.DropTarget(&m.drag, m.accepts, m.drops)` makes one a target. The page follows the press, the short distance that makes it a drag, and the target under the pointer; `m.drag.Dragging()`, `Source()`, `Target()` and `At()` paint the gesture, `accept(source, target)` decides, `drop(source, target)` runs on release, and Escape lets go. A press that does not move is still a click. Inside a `ui.Control`'s `Draw`, a card of a custom grid is declared as a part with `d.Canvas.Hit(part, r)` and becomes a source and target of the same state with `d.DragSource(&m.drag, part, r)` and `d.DropTarget(&m.drag, part, r, accept, drop)`, so one control carries many draggable parts with stable identities; a target part needs no Hit. Keep the callbacks in the model and declare the boxes every paint, not in a `Memo`. Toasts are a `ui.Toaster` kept in the model: `m.toaster.Show("Saved", "", ui.ToastSuccess)` puts one up, and `ui.Toasts(c, &m.toaster)`, declared once and last, paints them and takes each down after five seconds, asking for one frame when the next is due and none while nothing is up. `ShowAction(title, description, kind, "Undo")` gives one a button, whose press `m.toaster.Acted()` reports after `Toasts` and which takes the toast down; a `ui.ToastLoading` toast spins and stays until `m.toaster.Done(id, "Uploaded", "", ui.ToastSuccess)` replaces it; `Toaster.Position` puts the stack in another corner or centered (`ui.ToastTopCenter`). A keyboard shortcut is declared where it acts, as a click is read: `if ui.Shortcut(c, ui.Primary, "s") { m.save() }` is the page's (Primary is Command on macOS, Control elsewhere), and `list.Shortcut(0, "delete")` on a container or control acts only while the focus is in it, the innermost of nested ones winning. A chord without Primary, Ctrl or Alt is left to a field or terminal being typed in, and while a Popover, Modal, Menu, or Select or Combobox list is open the page's own shortcuts wait. `ui.List(c, &state, n, row)` declares only the rows on screen of a list of `n`, each as tall as its content, and scrolls it; `row` gets a `ui.ListRow` whose `Element` is the row's container to style and whose `C` declares what is in it, and `ListState.Key` names rows by an item's ID. A click chooses a row and the arrows, Home, End and Page Up and Down move between them, with the choice in `state.Selected()` and `state.Changed()` reporting that the user made one; Enter or a double click is `state.Submitted()`; `ListState.Label` makes typing the start of a row's text move to it. Set `ListState.Selection` to a `ui.Selection` to let the user choose several (Primary-click adds or removes a row, Shift extends, Primary+A chooses all). `ScrollTo`, `ScrollIntoView`, `ScrollToEnd`, `Visible` and `AtEnd` move and read the scroll position, and `box.ClickModifiers()` and `box.DoubleClicked()` say how a click on any element came. A row's `Element` is a Row, so an icon, a name and a size lie side by side. `ListState.Header` marks rows that head a section: the heading of the section at the top stays there while its rows scroll under it, until the next one pushes it away (give it a background; headings are not chosen, focused or typed to, and the keys pass over them). `ListState.Reorder` lets the user drag rows to another place, the chosen ones when the row dragged is one of them, and calls it with the rows and the row they go before; the list shows where they would go and scrolls near its edges, and Escape lets go. `ListState.RowWidth` makes the rows at least that wide: where they are wider than the list it scrolls sideways too (the horizontal wheel, or the wheel with Shift), and where they are not they grow to its width, as the columns of a table do; a header above the list follows the rows with `box.ScrollWith(&state)` on its content: give it the rows' width, and put it in a container of the header's height that clips. `ui.State[T](c, "open")` is an element's own small state (whether its menu is open), found by its name in its container and kept while the container is declared. `ui.Memo(c, *row, fn)` copies the part `fn` declares from the last paint while that value compares equal, declaring it again when it is hovered, focused, animated or resized; see Cost below. A settings struct can have its form written for it. Tag the fields and run `viva form` (from `//go:generate go tool viva form`): it writes `viva_form.go` with `func (v *Settings) Form(c ui.C) ui.Box`, plain page code with no reflection: diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md index 37d125e93..cfa4ce715 100644 --- a/website/content/guides/zh/declarative-layout.md +++ b/website/content/guides/zh/declarative-layout.md @@ -67,7 +67,7 @@ ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, m.page) - 在 `c.Key(item.ID)` 或 `c.KeyInt(id)` 里,元素只在这一行内部编号,所以行出现、消失或移动时,行里的按钮跟着这一行走。行消失两遍绘制之后,它的 Key 才会被复用。行里有 `Button` 的循环要给行加 Key;没加时 `viva vet` 会报告。 - 用户按住一个按钮(按下它,或它有焦点)时,如果某一遍绘制里另一个按钮占了它的位置,这次按下不会递送,焦点也会被放弃。 -`ui.TextArea(c, &m.notes, label, placeholder)` 是多行输入框。自己写的控件(终端、编辑器、可以画画的画布)用 `ui.Control(c, label, &m.handlers)`:它是一个可获得焦点的空元素,用 `Draw` 绘制,`Handlers` 接收它的按键、指针和滚轮;角色为 `RoleTextField` 或 `RoleTerminal` 时,还通过 `Text` 接收平台的打字和输入法。不用声明任何标识,窗口也不用分派任何事件。有多个可交互部分的控件(评分的几颗星、图的节点)在绘制时声明它们,用 `Handlers.Parts().At(i)` 作标识:落在某个部分上的按键、点击和滚轮,会连同该部分作为事件的 `Target` 交给同一个 `Handlers`;控件有焦点时打出的可打印字符,以 `Text` 交给 `Key`。在行或列上写 `.FocusGroup(ui.FocusHorizontal)`,里面的控件就成为一个 Tab 停靠点,方向键在它们之间移动,像工具栏一样;`.FocusOrder` 可以给自定义网格按行列移动。没有外观的控件有 `ui.ButtonBase`、`CheckboxBase`、`SwitchBase`、`ToggleBase`、`RadioBase`、`TabBase`、`SliderBase`、`SelectBase` 和 `TextFieldBase`:绑定和命名方式与带外观的版本相同,用来做你自己的设计。`ui.TextField(...).AutoFocus()` 在输入框出现时把焦点给它(只给一次,用户移开后不抢回),`.Submitted()` 在递送回车的那一遍绘制里为真;`.Secure()` 让它成为密码字段。`.Tooltip("Delete")` 给控件一个指针停留时显示的提示,它同时也是控件的描述。`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()` 让菜单在锚点上方展开(锚点在面板底部时)。`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.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerLeft, Size: 320}, body, footer)` 从窗口一边滑入一个面板,即 shadcn 的 Sheet:标题为空时整个面板都给 body,`NonModal` 让键盘留在背后的页面;`Swipe` 在面板内侧边缘加一个把手,拖动它面板随之移向边缘,拖过一半或快速甩出时关闭,否则滑回原位。`ui.Tree(c, &m.tree, n, label, content)` 是应用自己的树里可见行组成的 List,由 `TreeState.Node` 描述每一行(深度、是否为分支、是否展开);方向键移动、展开和折叠,树报告 `Toggled()` 和 `Chosen()` 由应用处理。输入行名的开头会跳到那一行。设置 `TreeState.CanDrop` 后,行可以拖到另一行的前面、里面或后面(由 `CanDrop` 决定接受哪些),`Dropped()` 报告放下的那一次;移动行要放在 `c.After` 里做,因为报告它的那次绘制还在声明这些行。`state.RowID(i)` 是第 i 个可见行的身份(`DisclosureID(i)` 是它箭头的身份,`ListState` 也有 `RowID`),用来给某一行焦点或找到它的 hit。其他元素可以用模型里的 `ui.DragState` 拖放:`ui.Row(c).Hit(ui.ID(c), "Group").DragSource(&m.drag)` 把元素声明为源,`.DropTarget(&m.drag, m.accepts, m.drops)` 把它声明为目标。页面负责按下、把按下变成拖拽的短距离,以及指针下的目标;`m.drag.Dragging()`、`Source()`、`Target()` 和 `At()` 用来绘制拖拽,`accept(source, target)` 决定接不接受,`drop(source, target)` 在松开时执行,Escape 放弃。没有移动的按下仍然是点击。在 `ui.Control` 的 `Draw` 里,自定义网格的卡片用 `d.Canvas.Hit(part, r)` 声明为 part,再用 `d.DragSource(&m.drag, part, r)` 和 `d.DropTarget(&m.drag, part, r, accept, drop)` 声明为同一个状态的源和目标,一个控件就能承载多个身份稳定、可拖拽的 part;目标 part 不需要 Hit。回调保存在模型里,元素每遍绘制都重新声明,不要放在 `Memo` 里。Toast 是模型里的一个 `ui.Toaster`:`m.toaster.Show("Saved", "", ui.ToastSuccess)` 显示一条,`ui.Toasts(c, &m.toaster)` 在页面里声明一次、放在最后,负责绘制并在五秒后收起;它只在下一条到期时请求一帧,没有 toast 时不做任何调度。`ShowAction(title, description, kind, "Undo")` 给 toast 加一个按钮,按下后 toast 收起,在 `Toasts` 之后用 `m.toaster.Acted()` 读取;`ui.ToastLoading` 的 toast 显示转圈且不会自动收起,直到 `m.toaster.Done(id, "Uploaded", "", ui.ToastSuccess)` 替换它;`Toaster.Position` 把整组 toast 放到别的角落或居中(`ui.ToastTopCenter`)。键盘快捷键在它起作用的地方声明,和读取点击一样:`if ui.Shortcut(c, ui.Primary, "s") { m.save() }` 是整个页面的快捷键(Primary 在 macOS 上是 Command,其他平台是 Control);在容器或控件上用 `list.Shortcut(0, "delete")`,只在焦点位于它之内时生效,嵌套时最内层的生效。不带 Primary、Ctrl 或 Alt 的按键留给正在输入的输入框或终端;Popover、Modal、Menu 或 Select、Combobox 列表打开时,页面级快捷键不生效。`ui.List(c, &state, n, row)` 只声明 `n` 行列表里显示在屏幕上的行,每行高度由内容决定,并负责滚动;`row` 得到一个 `ui.ListRow`,其中 `Element` 是这一行的容器(用来设置样式),`C` 用来声明行里的内容,`ListState.Key` 按条目 ID 为行命名。点击会选中一行,方向键、Home、End、Page Up 和 Page Down 在行之间移动,选中的行在 `state.Selected()` 里,`state.Changed()` 报告用户做了选择;回车或双击是 `state.Submitted()`;设置 `ListState.Label` 后,输入行文字的开头会跳到那一行。把 `ListState.Selection` 设为一个 `ui.Selection` 就能让用户选多行(Primary 加点击增减一行,Shift 扩展,Primary+A 全选)。`ScrollTo`、`ScrollIntoView`、`ScrollToEnd`、`Visible` 和 `AtEnd` 移动并读取滚动位置,`box.ClickModifiers()` 和 `box.DoubleClicked()` 说明任何元素上的点击是怎么发生的。行的 `Element` 是一个 Row,所以图标、名称和大小并排放。`ListState.Header` 标出作为分组标题的行:处在顶部的那一组的标题会留在顶部,它的行从下面滚过,直到下一个标题把它顶走(给它设个背景;标题不会被选中、聚焦,也不参与输入跳转,按键会跳过它)。`ListState.Reorder` 让用户把行拖到别的位置,拖动的行被选中时拖走所有选中的行,并用这些行和它们要放到哪一行之前来调用它;列表会显示它们要去的位置,靠近边缘时自动滚动,按 Escape 放弃拖动。`ListState.RowWidth` 让行至少这么宽:行比列表宽时列表也能横向滚动(水平滚轮,或按住 Shift 用滚轮),不比列表宽时行会撑满列表,像表格的列那样;列表上方的表头用 `box.ScrollWith(&state)` 加在它的内容上,随行一起移动:给它和行一样的宽度,放在定高、会裁剪的容器里。`ui.State[T](c, "open")` 是元素自己的小状态(比如菜单是否打开),在它的容器里按名字查找,容器被声明期间一直保留。`ui.Memo(c, *row, fn)` 在那个值比较相等时从上一遍绘制复制 `fn` 声明的部分,在它被悬停、获得焦点、处于动画中或改变大小时重新声明;见下面的开销。 +`ui.TextArea(c, &m.notes, label, placeholder)` 是多行输入框。自己写的控件(终端、编辑器、可以画画的画布)用 `ui.Control(c, label, &m.handlers)`:它是一个可获得焦点的空元素,用 `Draw` 绘制,`Handlers` 接收它的按键、指针和滚轮;角色为 `RoleTextField` 或 `RoleTerminal` 时,还通过 `Text` 接收平台的打字和输入法。不用声明任何标识,窗口也不用分派任何事件。有多个可交互部分的控件(评分的几颗星、图的节点)在绘制时声明它们,用 `Handlers.Parts().At(i)` 作标识:落在某个部分上的按键、点击和滚轮,会连同该部分作为事件的 `Target` 交给同一个 `Handlers`;控件有焦点时打出的可打印字符,以 `Text` 交给 `Key`。在行或列上写 `.FocusGroup(ui.FocusHorizontal)`,里面的控件就成为一个 Tab 停靠点,方向键在它们之间移动,像工具栏一样;`.FocusOrder` 可以给自定义网格按行列移动。没有外观的控件有 `ui.ButtonBase`、`CheckboxBase`、`SwitchBase`、`ToggleBase`、`RadioBase`、`TabBase`、`SliderBase`、`SelectBase` 和 `TextFieldBase`:绑定和命名方式与带外观的版本相同,用来做你自己的设计。`ui.TextField(...).AutoFocus()` 在输入框出现时把焦点给它(只给一次,用户移开后不抢回),`.Submitted()` 在递送回车的那一遍绘制里为真;`.Secure()` 让它成为密码字段。`.Tooltip("Delete")` 给控件一个指针停留时显示的提示,它同时也是控件的描述。`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.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerLeft, Size: 320}, body, footer)` 从窗口一边滑入一个面板,即 shadcn 的 Sheet:标题为空时整个面板都给 body,`NonModal` 让键盘留在背后的页面;`Swipe` 在面板内侧边缘加一个把手,拖动它面板随之移向边缘,拖过一半或快速甩出时关闭,否则滑回原位。`ui.Tree(c, &m.tree, n, label, content)` 是应用自己的树里可见行组成的 List,由 `TreeState.Node` 描述每一行(深度、是否为分支、是否展开);方向键移动、展开和折叠,树报告 `Toggled()` 和 `Chosen()` 由应用处理。输入行名的开头会跳到那一行。设置 `TreeState.CanDrop` 后,行可以拖到另一行的前面、里面或后面(由 `CanDrop` 决定接受哪些),`Dropped()` 报告放下的那一次;移动行要放在 `c.After` 里做,因为报告它的那次绘制还在声明这些行。`state.RowID(i)` 是第 i 个可见行的身份(`DisclosureID(i)` 是它箭头的身份,`ListState` 也有 `RowID`),用来给某一行焦点或找到它的 hit。其他元素可以用模型里的 `ui.DragState` 拖放:`ui.Row(c).Hit(ui.ID(c), "Group").DragSource(&m.drag)` 把元素声明为源,`.DropTarget(&m.drag, m.accepts, m.drops)` 把它声明为目标。页面负责按下、把按下变成拖拽的短距离,以及指针下的目标;`m.drag.Dragging()`、`Source()`、`Target()` 和 `At()` 用来绘制拖拽,`accept(source, target)` 决定接不接受,`drop(source, target)` 在松开时执行,Escape 放弃。没有移动的按下仍然是点击。在 `ui.Control` 的 `Draw` 里,自定义网格的卡片用 `d.Canvas.Hit(part, r)` 声明为 part,再用 `d.DragSource(&m.drag, part, r)` 和 `d.DropTarget(&m.drag, part, r, accept, drop)` 声明为同一个状态的源和目标,一个控件就能承载多个身份稳定、可拖拽的 part;目标 part 不需要 Hit。回调保存在模型里,元素每遍绘制都重新声明,不要放在 `Memo` 里。Toast 是模型里的一个 `ui.Toaster`:`m.toaster.Show("Saved", "", ui.ToastSuccess)` 显示一条,`ui.Toasts(c, &m.toaster)` 在页面里声明一次、放在最后,负责绘制并在五秒后收起;它只在下一条到期时请求一帧,没有 toast 时不做任何调度。`ShowAction(title, description, kind, "Undo")` 给 toast 加一个按钮,按下后 toast 收起,在 `Toasts` 之后用 `m.toaster.Acted()` 读取;`ui.ToastLoading` 的 toast 显示转圈且不会自动收起,直到 `m.toaster.Done(id, "Uploaded", "", ui.ToastSuccess)` 替换它;`Toaster.Position` 把整组 toast 放到别的角落或居中(`ui.ToastTopCenter`)。键盘快捷键在它起作用的地方声明,和读取点击一样:`if ui.Shortcut(c, ui.Primary, "s") { m.save() }` 是整个页面的快捷键(Primary 在 macOS 上是 Command,其他平台是 Control);在容器或控件上用 `list.Shortcut(0, "delete")`,只在焦点位于它之内时生效,嵌套时最内层的生效。不带 Primary、Ctrl 或 Alt 的按键留给正在输入的输入框或终端;Popover、Modal、Menu 或 Select、Combobox 列表打开时,页面级快捷键不生效。`ui.List(c, &state, n, row)` 只声明 `n` 行列表里显示在屏幕上的行,每行高度由内容决定,并负责滚动;`row` 得到一个 `ui.ListRow`,其中 `Element` 是这一行的容器(用来设置样式),`C` 用来声明行里的内容,`ListState.Key` 按条目 ID 为行命名。点击会选中一行,方向键、Home、End、Page Up 和 Page Down 在行之间移动,选中的行在 `state.Selected()` 里,`state.Changed()` 报告用户做了选择;回车或双击是 `state.Submitted()`;设置 `ListState.Label` 后,输入行文字的开头会跳到那一行。把 `ListState.Selection` 设为一个 `ui.Selection` 就能让用户选多行(Primary 加点击增减一行,Shift 扩展,Primary+A 全选)。`ScrollTo`、`ScrollIntoView`、`ScrollToEnd`、`Visible` 和 `AtEnd` 移动并读取滚动位置,`box.ClickModifiers()` 和 `box.DoubleClicked()` 说明任何元素上的点击是怎么发生的。行的 `Element` 是一个 Row,所以图标、名称和大小并排放。`ListState.Header` 标出作为分组标题的行:处在顶部的那一组的标题会留在顶部,它的行从下面滚过,直到下一个标题把它顶走(给它设个背景;标题不会被选中、聚焦,也不参与输入跳转,按键会跳过它)。`ListState.Reorder` 让用户把行拖到别的位置,拖动的行被选中时拖走所有选中的行,并用这些行和它们要放到哪一行之前来调用它;列表会显示它们要去的位置,靠近边缘时自动滚动,按 Escape 放弃拖动。`ListState.RowWidth` 让行至少这么宽:行比列表宽时列表也能横向滚动(水平滚轮,或按住 Shift 用滚轮),不比列表宽时行会撑满列表,像表格的列那样;列表上方的表头用 `box.ScrollWith(&state)` 加在它的内容上,随行一起移动:给它和行一样的宽度,放在定高、会裁剪的容器里。`ui.State[T](c, "open")` 是元素自己的小状态(比如菜单是否打开),在它的容器里按名字查找,容器被声明期间一直保留。`ui.Memo(c, *row, fn)` 在那个值比较相等时从上一遍绘制复制 `fn` 声明的部分,在它被悬停、获得焦点、处于动画中或改变大小时重新声明;见下面的开销。 设置类结构体的表单可以自动生成。给字段加 tag,然后运行 `viva form`(写成 `//go:generate go tool viva form`):它生成 `viva_form.go`,里面是 `func (v *Settings) Form(c ui.C) ui.Box`,就是普通的页面代码,不用反射: