From 62fc9dc9fefa1e3e069c209fb34b0f3e169718fb Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Wed, 11 Nov 2026 00:47:50 -0800 Subject: [PATCH] ui: MenuAt opens a menu at a point of the window For a menu the application opens itself where no control stands for it, such as a mark painted inside a custom-drawn view. It looks and behaves as a ContextMenu. Co-Authored-By: Claude Opus 5.5 --- ui/menu.go | 23 +++++++++++++++++++++++ ui/menu_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/ui/menu.go b/ui/menu.go index b151542fc..3c09c0876 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -52,6 +52,29 @@ func Menu(c C, anchor Box, open *bool, body func(*MenuItems)) { p.declareMenu(c, menu, scope, open, anchor.i, body) } +// MenuAt shows the items body declares at the point x, y of the window while *open, +// as a ContextMenu looks and behaves: for a menu the application opens itself at a +// place no control stands for, such as a mark painted inside a custom-drawn view. +// Choosing an item, Escape or a press outside closes it. +// +// if pressed := m.markAt(event); pressed { +// m.lanes, m.lanesAt = true, ui.Rect{X: event.X, Y: event.Y} +// } +// ui.MenuAt(c, m.lanesAt.X, m.lanesAt.Y, &m.lanes, func(menu *ui.MenuItems) { ... }) +// +// Not inside a Memo. +func MenuAt(c C, x, y float32, open *bool, body func(*MenuItems)) { + p := c.page + p.forbidInMemo("MenuAt") + if !*open { + return + } + scope := p.boundScope(pkMenu, unsafe.Pointer(open)) + menu := stateIn[MenuItems](p, scope, "menu") + menu.context, menu.at = true, Rect{X: x, Y: y} + p.declareMenu(c, menu, scope, open, -1, body) +} + // ContextMenu shows the items body declares at the pointer when target is pressed // with the secondary button, or at the target when it has the focus and Shift+F10 // is pressed, as shadcn's ContextMenu. It behaves as a Menu then, but Tab does not diff --git a/ui/menu_test.go b/ui/menu_test.go index a4af9c28c..ce33be7b9 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -486,3 +486,27 @@ func TestMenuAbove(t *testing.T) { t.Fatalf("the menu at %v is not over its anchor at %v", item, anchor) } } + +// MenuAt opens where the application says, closes when an item is chosen, and +// leaves *open false. +func TestMenuAtOpensAtThePointGiven(t *testing.T) { + open, chosen := true, 0 + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.Button(c, "Below") + ui.MenuAt(c, 120, 90, &open, func(menu *ui.MenuItems) { + if menu.Item("Lane").Clicked() { + chosen++ + } + }) + }) + }) + lane := d.hit("Lane").Bounds + if !d.page.Overlay() || lane.X < 119 || lane.Y < 89 { + t.Fatalf("overlay %v, the menu at %v is not at (120, 90)", d.page.Overlay(), lane) + } + d.click("Lane") + if chosen != 1 || open || d.has("Lane") { + t.Fatalf("chosen %d, open %v, shown %v", chosen, open, d.has("Lane")) + } +}