From cc1c87dd28045acdf5fc1d0e4fa0836c6fbdb250 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 11 Nov 2026 12:02:09 +0800 Subject: [PATCH 1/8] fix(ui): show a List's requested scroll in the paint that applies it listArea declared its ScrollArea, which takes the offset the state had, and applied ScrollTo, ScrollIntoView or ScrollToEnd only afterwards. The rows were placed for the new offset while the layout still scrolled the area by the old one, so the paint that applied a far request showed the rows out of view: a blank list until something else repainted it. ScrollAt already writes the offset to the node for this reason; the List now does the same. A request past the end is brought only as far as the rows go, and ScrollToEnd places the last rows, so neither needs a second paint either. --- ui/list.go | 30 +++++++++++++++++++++--------- ui/list_selection_test.go | 14 +++++++++----- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/ui/list.go b/ui/list.go index fee19d6d2..acceb2542 100644 --- a/ui/list.go +++ b/ui/list.go @@ -435,11 +435,13 @@ func (s *ListState) indexOf(id gfx.ID) int { } // applyScrollRequest applies the scroll the application asked for, before the list -// places its rows. -func (s *ListState) applyScrollRequest(f *Frame) { +// places its rows, and reports whether it moved the offset. A row near the end is +// brought only as far as the rows go: the layout would clamp the offset to the +// content too, but only for the next paint, and the rows are placed for this one. +func (s *ListState) applyScrollRequest(f *Frame) bool { in := &s.list if in.pending == listScrollNone || in.scroll == nil { - return + return false } kind, row := in.pending, int(in.pendingRow)-1 in.pending, in.pendingRow = listScrollNone, 0 @@ -448,32 +450,38 @@ func (s *ListState) applyScrollRequest(f *Frame) { if viewport <= 0 { viewport = f.bounds.Height } + before, end := scroll.Offset, max(s.top(in.n)-viewport, 0) + to := func(y float32) { scroll.ScrollTo(min(y, end)) } switch kind { case listScrollToEnd: + // The layout puts the area at the end of what is there; the offset says which + // rows to place for it. scroll.ScrollToEnd() + scroll.Offset = end case listScrollStart: if row >= 0 && row < in.n { - scroll.ScrollTo(s.top(row)) + to(s.top(row)) } case listScrollCenter: if row >= 0 && row < in.n { - scroll.ScrollTo((s.top(row)+s.top(row+1))/2 - viewport/2) + to((s.top(row)+s.top(row+1))/2 - viewport/2) } case listScrollEnd: if row >= 0 && row < in.n { - scroll.ScrollTo(s.top(row+1) - viewport) + to(s.top(row+1) - viewport) } case listScrollNear: if row >= 0 && row < in.n { top, bottom := s.top(row), s.top(row+1) switch { case top < scroll.Offset: - scroll.ScrollTo(top) + to(top) case bottom > scroll.Offset+viewport: - scroll.ScrollTo(bottom - viewport) + to(bottom - viewport) } } } + return scroll.Offset != before } // estimate is the height a row not yet measured is taken to have: the average of @@ -716,7 +724,11 @@ func (p *Page) listArea(c C, state *ListState, n int, horizontal bool, row func( state.resize(n) scroll := c.f.exts[c.f.nodes[area.i].ext].scrollState in.scroll = scroll - state.applyScrollRequest(c.f) + if state.applyScrollRequest(c.f) { + // The area was declared at the offset it had; the layout reads the node, so it + // takes the requested one too, which the rows are placed for below (as ScrollAt). + c.f.nodes[area.i].scroll = scroll.Offset + } viewport := scroll.Viewport if viewport <= 0 { viewport = c.f.bounds.Height diff --git a/ui/list_selection_test.go b/ui/list_selection_test.go index 41a134bfb..2c5136838 100644 --- a/ui/list_selection_test.go +++ b/ui/list_selection_test.go @@ -292,8 +292,8 @@ func TestListSelectAll(t *testing.T) { } } -// ScrollTo, ScrollIntoView and ScrollToEnd move the list, and Visible reports what -// it showed. +// ScrollTo, ScrollIntoView and ScrollToEnd move the list in the one paint that applies +// them, without waiting for another, and Visible reports what it showed. func TestListScrollToARow(t *testing.T) { var names []string for i := range 1000 { @@ -307,22 +307,26 @@ func TestListScrollToARow(t *testing.T) { } m.list.ScrollTo(900, ui.ListStart) d.repaint() - d.repaint() if !d.has("row 900") { t.Fatalf("ScrollTo(900) did not show it: Visible %v", visibleOf(&m.list)) } m.list.ScrollToEnd() d.repaint() - d.repaint() if !m.list.AtEnd() || !d.has("row 999") { t.Fatalf("ScrollToEnd: at end %v, Visible %v", m.list.AtEnd(), visibleOf(&m.list)) } m.list.ScrollIntoView(10) d.repaint() - d.repaint() if !d.has("row 10") { t.Fatalf("ScrollIntoView(10) did not show it: Visible %v", visibleOf(&m.list)) } + // The middle of the last row is past where the list can scroll to: the list stops at + // its end, in the same paint. + m.list.ScrollTo(999, ui.ListCenter) + d.repaint() + if !d.has("row 999") || !d.has("row 990") { + t.Fatalf("ScrollTo(999, ListCenter) did not show the end: Visible %v", visibleOf(&m.list)) + } } func visibleOf(s *ui.ListState) [2]int { From fc9a5953d4c8afdbbbf725fdbedaf5919cdb8d3b Mon Sep 17 00:00:00 2001 From: Lichenkang <2188718831@qq.com> Date: Tue, 10 Nov 2026 23:29:05 -0800 Subject: [PATCH 2/8] feat(app): Window.SetTitle changes a window's title after it opens (#1) macOS sets the NSWindow title on the main thread; Windows posts the change to the window thread and applies it with SetWindowTextW (a direct call from another thread would block on WM_SETTEXT); Linux sets the GTK toplevel title on the GTK thread; the headless host records it in its windows listing. Co-authored-by: Claude Opus 5.5 --- README.md | 2 + app/title.go | 24 +++++++++ app/title_test.go | 41 ++++++++++++++++ docs/conformance.md | 8 +++ headless/application.go | 12 +++++ internal/platform/darwin/native.h | 1 + internal/platform/darwin/native.m | 31 ++++++++++++ internal/platform/darwin/platform.go | 13 +++++ internal/platform/linux/gtk_window_linux.go | 11 +++++ internal/platform/windows/title_windows.go | 54 +++++++++++++++++++++ internal/platform/windows/window_windows.go | 5 ++ 11 files changed, 202 insertions(+) create mode 100644 app/title.go create mode 100644 app/title_test.go create mode 100644 internal/platform/windows/title_windows.go diff --git a/README.md b/README.md index dce853abb..181e5ece1 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,8 @@ WebView and no bundled rendering runtime. by the application. - Native fullscreen through `Window.SetFullscreen`, with `Config.OnFullscreen` reporting system transitions and restoring normal window placement on exit. +- `Window.SetTitle` changes a window's title after it opens: the system title + bar, the task switcher and the taskbar or Dock window list. - Explicit multi-window applications through `app.RunApplication`: every window owns independent retained paint, focus, input, text, invalidation, and close state, and the native loop exits after the final window closes. diff --git a/app/title.go b/app/title.go new file mode 100644 index 000000000..3ad9c3a3e --- /dev/null +++ b/app/title.go @@ -0,0 +1,24 @@ +package app + +import "fmt" + +type titleControl interface { + SetTitle(string) error +} + +// SetTitle changes the window's title: the text of its system title bar, the +// task switcher and the taskbar or Dock window list. A window with +// WindowCustomTitlebar keeps no visible system title bar, but the title is still +// what the system lists and what assistive technology reads. Calls are safe from +// any goroutine; the change is applied on the window's thread. Unsupported hosts +// return an error wrapping ErrUnsupported. +func (window *Window) SetTitle(title string) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("app: window is closed") + } + control, ok := window.control.(titleControl) + if !ok { + return fmt.Errorf("%w: window titles", ErrUnsupported) + } + return control.SetTitle(title) +} diff --git a/app/title_test.go b/app/title_test.go new file mode 100644 index 000000000..a2828d29d --- /dev/null +++ b/app/title_test.go @@ -0,0 +1,41 @@ +//go:build darwin || windows || linux + +package app + +import ( + "errors" + "testing" +) + +type titleTestControl struct { + fakeWindow + titles []string +} + +func (control *titleTestControl) SetTitle(title string) error { + control.titles = append(control.titles, title) + return nil +} + +func TestSetTitleDelegatesToTheHost(t *testing.T) { + control := &titleTestControl{} + window := &Window{control: control} + if err := window.SetTitle("project – main.go"); err != nil { + t.Fatal(err) + } + if len(control.titles) != 1 || control.titles[0] != "project – main.go" { + t.Fatalf("titles = %q", control.titles) + } + window.closed.Store(true) + if err := window.SetTitle("closed"); err == nil || len(control.titles) != 1 { + t.Fatal("closed window accepted a title") + } + var missing *Window + if err := missing.SetTitle("nil"); err == nil { + t.Fatal("nil window accepted a title") + } + unsupported := &Window{control: &fakeWindow{}} + if err := unsupported.SetTitle("x"); !errors.Is(err, ErrUnsupported) { + t.Fatalf("unsupported host: %v", err) + } +} diff --git a/docs/conformance.md b/docs/conformance.md index 928444774..7586a44af 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -231,6 +231,14 @@ moves). `VIVA_SCALE` overrides it for Viva alone, snapped to quarters and kept b Linux: it draws a window at 125% or 150% on a display at 100%, which is how fractional scaling was measured. The renderer puts every label texture and image on a whole device pixel. +## Window titles + +`Window.SetTitle` changes the native title after creation from any goroutine. macOS +sets the NSWindow title on the main thread, Windows posts the change to the window +thread and applies it with `SetWindowTextW` (also updating the accessibility tree's +window name), and Linux sets the GTK toplevel's title on the GTK thread. The +headless host records it in the `windows` listing. + ## Fullscreen windows `Window.SetFullscreen` requests native fullscreen; `Config.OnFullscreen` publishes diff --git a/headless/application.go b/headless/application.go index e109d4bf4..e6db9731e 100644 --- a/headless/application.go +++ b/headless/application.go @@ -146,6 +146,18 @@ func (window *headlessWindow) SetFullscreen(fullscreen bool) error { return nil } +// SetTitle records the title the windows command lists. +func (window *headlessWindow) SetTitle(title string) error { + window.application.mu.Lock() + defer window.application.mu.Unlock() + entry := window.application.windows[window.id] + if entry == nil { + return fmt.Errorf("headless: window is closed") + } + entry.title = title + return nil +} + func (window *headlessWindow) Fullscreen() bool { window.application.mu.Lock() entry := window.application.windows[window.id] diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 2560cb6da..a08ff0bd9 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -375,6 +375,7 @@ int viva_application_window_frame(void *window, double *out); /* Puts the window's content area at x, y in top-left screen coordinates. */ void viva_application_move_window(void *window, double x, double y); int viva_application_set_fullscreen(void *window, int fullscreen); +int viva_application_set_title(void *window, const char *title); int viva_application_fullscreen(void *window); int viva_application_set_always_on_top(void *window, int enabled); int viva_application_run(void); diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 0de95ae4a..5eb7c1678 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -5702,6 +5702,7 @@ - (void)confirmClose; - (void)hideWindow; - (void)showWindow; - (void)setFullscreen:(BOOL)fullscreen; +- (void)setWindowTitle:(NSString *)title; - (void)setAlwaysOnTop:(BOOL)enabled; - (BOOL)isFullscreen; - (void)reopenWindow; @@ -6244,6 +6245,14 @@ - (BOOL)isFullscreen { return (_window.styleMask & NSWindowStyleMaskFullScreen) != 0; } +- (void)setWindowTitle:(NSString *)title { + [_title release]; + _title = [title copy]; + if (_window != nil) { + _window.title = _title; + } +} + - (void)setFullscreen:(BOOL)fullscreen { _fullscreenTarget = fullscreen; if (!_fullscreenTransition && [self isFullscreen] != fullscreen) { @@ -6960,6 +6969,28 @@ int viva_application_set_fullscreen(void *window, int fullscreen) { return found; } +int viva_application_set_title(void *window, const char *title) { + __block int found = 0; + NSString *value = [[NSString alloc] initWithUTF8String:title != NULL ? title : ""]; + if (value == nil) { + value = [@"" retain]; + } + void (^work)(void) = ^{ + VivaAppDelegate *delegate = viva_find_window(window); + if (delegate != nil) { + found = 1; + [delegate setWindowTitle:value]; + } + }; + if ([NSThread isMainThread]) { + work(); + } else { + dispatch_sync(dispatch_get_main_queue(), work); + } + [value release]; + return found; +} + int viva_application_fullscreen(void *window) { __block int fullscreen = 0; void (^work)(void) = ^{ diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index 1ffa55d7e..226d30ff9 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -109,6 +109,19 @@ func (window *nativeWindow) SetFullscreen(fullscreen bool) error { return nil } +// SetTitle changes the NSWindow's title on the main thread. +func (window *nativeWindow) SetTitle(title string) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("darwin: window is closed") + } + value := C.CString(title) + defer C.free(unsafe.Pointer(value)) + if C.viva_application_set_title(window.token, value) == 0 { + return fmt.Errorf("darwin: window is unavailable") + } + return nil +} + func (window *nativeWindow) Fullscreen() bool { return window != nil && !window.closed.Load() && C.viva_application_fullscreen(window.token) != 0 } diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index 62fdd2e26..c185e08f1 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -284,6 +284,17 @@ func (w *gtkWindow) SetFullscreen(fullscreen bool) error { func (w *gtkWindow) Fullscreen() bool { return w.fullscreen.Load() } +// SetTitle changes the toplevel's title on the GTK thread. +func (w *gtkWindow) SetTitle(title string) error { + w.app.enqueue(func() { + if !w.closed { + value := cString(title) + w.g.windowSetTitle(w.toplevel, &value[0]) + } + }) + return nil +} + func (w *gtkWindow) SetAlwaysOnTop(enabled bool) error { if w == nil || w.app == nil { return fmt.Errorf("linux: window is closed") diff --git a/internal/platform/windows/title_windows.go b/internal/platform/windows/title_windows.go new file mode 100644 index 000000000..e8959a93f --- /dev/null +++ b/internal/platform/windows/title_windows.go @@ -0,0 +1,54 @@ +package windows + +import ( + "fmt" + "sync" + "syscall" + "unsafe" +) + +// wmSetTitle asks the window thread to apply the title SetTitle stored. +// SetWindowTextW from another thread would send WM_SETTEXT and wait for the +// window thread, so the change is posted instead. +const wmSetTitle = 0x8052 + +var setWindowText = user.NewProc("SetWindowTextW") + +// titleRequest holds the latest title asked for until the window thread applies it. +type titleRequest struct { + mu sync.Mutex + title string + pending bool +} + +func (window *nativeWindow) SetTitle(title string) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("windows: window is closed") + } + request := &window.state.pendingTitle + request.mu.Lock() + request.title, request.pending = title, true + request.mu.Unlock() + if ok, _, err := postMessage.Call(window.state.window, wmSetTitle, 0, 0); ok == 0 { + return fmt.Errorf("windows: request title: %w", err) + } + return nil +} + +// applyTitle sets the stored title on the window and in the accessibility tree. +func (state *windowState) applyTitle() { + request := &state.pendingTitle + request.mu.Lock() + title, pending := request.title, request.pending + request.pending = false + request.mu.Unlock() + if !pending || state.window == 0 { + return + } + value, err := syscall.UTF16PtrFromString(title) + if err != nil { + return + } + state.config.Title = title + setWindowText.Call(state.window, uintptr(unsafe.Pointer(value))) +} diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 17d495bb5..d2268b024 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -67,6 +67,8 @@ const ( ) type windowState struct { + // pendingTitle is the title SetTitle asked for, applied on the window thread. + pendingTitle titleRequest fullscreen atomic.Bool fullscreenChanging bool fullscreenStyle uint32 @@ -433,6 +435,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { case wmFullscreen: state.setFullscreen(first != 0) return 0 + case wmSetTitle: + state.applyTitle() + return 0 case wmSysCommand: if state.fullscreen.Load() { switch first & 0xfff0 { From 61446ac1eb2887904078dd084342b460581a1623 Mon Sep 17 00:00:00 2001 From: Lichenkang <2188718831@qq.com> Date: Wed, 11 Nov 2026 00:45:24 -0800 Subject: [PATCH 3/8] app: report the window losing the keyboard (Config.OnFocusLost) (#2) Native windows already hear the loss of focus to release held keys; the application now hears it too, after the release, so it can save or hide what only makes sense while the window has the user's attention. Co-authored-by: Claude Opus 5.5 --- app/app.go | 5 +++++ app/focus_lost_test.go | 38 ++++++++++++++++++++++++++++++++++++++ app/painter.go | 20 ++++++++++++++------ 3 files changed, 57 insertions(+), 6 deletions(-) create mode 100644 app/focus_lost_test.go diff --git a/app/app.go b/app/app.go index b99a44099..ef3b32b3f 100644 --- a/app/app.go +++ b/app/app.go @@ -144,6 +144,11 @@ type Config struct { // text input and input methods behave as before. Handled and Repaint apply // as for OnKey. OnModifierTap func(event gfx.ModifierTapEvent) gfx.EventResult + // OnFocusLost is called when the window loses the keyboard to another window + // or application, after the keys that were down are released. It is how an + // application saves or hides what only makes sense while it has the user's + // attention. Its Repaint asks for a new frame. Native windows only. + OnFocusLost func() gfx.EventResult // 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 diff --git a/app/focus_lost_test.go b/app/focus_lost_test.go new file mode 100644 index 000000000..3d8198025 --- /dev/null +++ b/app/focus_lost_test.go @@ -0,0 +1,38 @@ +//go:build darwin || windows || linux + +package app + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +func TestFocusLostIsReportedAfterKeysAreReleased(t *testing.T) { + var keys []gfx.KeyEvent + lost := 0 + heldWhenLost := -1 + driver, err := NewDriver(Config{ + Width: 320, Height: 180, + Paint: func(canvas *gfx.Canvas, _ gfx.Size) {}, + OnKey: func(event gfx.KeyEvent) gfx.EventResult { keys = append(keys, event); return gfx.EventResult{} }, + OnFocusLost: func() gfx.EventResult { + lost++ + heldWhenLost = len(keys) + return gfx.EventResult{Repaint: true} + }, + }, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + if err := driver.LoseFocus(); err != nil { + t.Fatal(err) + } + if lost != 1 { + t.Fatalf("OnFocusLost called %d times, want 1", lost) + } + if heldWhenLost != len(keys) { + t.Fatalf("OnFocusLost ran before the held keys were released: %d of %d key events", heldWhenLost, len(keys)) + } +} diff --git a/app/painter.go b/app/painter.go index 79a24c6ef..21b40f422 100644 --- a/app/painter.go +++ b/app/painter.go @@ -31,9 +31,11 @@ type painter struct { onScroll func(gfx.ScrollEvent) gfx.EventResult // onModifierTap and tap recognize a modifier pressed and released on its own. onModifierTap func(gfx.ModifierTapEvent) gfx.EventResult - tap input.ModifierTap - onFileDrop func(gfx.FileDropEvent) gfx.EventResult - onResize func(gfx.Size) + // onFocusLost hears that the window lost the keyboard (Config.OnFocusLost). + onFocusLost func() gfx.EventResult + tap input.ModifierTap + onFileDrop func(gfx.FileDropEvent) gfx.EventResult + onResize func(gfx.Size) // scale is the display's device pixels per logical pixel, zero when the platform // does not report it (see platform.Size): the canvas then keeps the scale it was given. scale float32 @@ -150,6 +152,7 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D onShortcut: config.OnShortcut, onScroll: config.OnScroll, onModifierTap: config.OnModifierTap, + onFocusLost: config.OnFocusLost, onFileDrop: config.OnFileDrop, onResize: config.OnResize, textInput: config.TextInput, @@ -604,9 +607,9 @@ func (painter *painter) releaseKeys() bool { // focusLostHandler is what a window hands the platform for the loss of the // keyboard: it releases the keys that were down, since their releases will go -// to whatever window has the keyboard now. +// to whatever window has the keyboard now, and tells the application. func (painter *painter) focusLostHandler() platform.FocusLostHandler { - if painter.onKey == nil && painter.onModifierTap == nil { + if painter.onKey == nil && painter.onModifierTap == nil && painter.onFocusLost == nil { return nil } return painter.focusLost @@ -614,7 +617,12 @@ func (painter *painter) focusLostHandler() platform.FocusLostHandler { func (painter *painter) focusLost() (platform.Frame, error) { painter.tap.Cancel() - if !painter.releaseKeys() { + repaint := painter.releaseKeys() + if painter.onFocusLost != nil { + response := painter.onFocusLost() + repaint = painter.applyEventResult(response) || response.Repaint || repaint + } + if !repaint { return platform.Frame{}, nil } return painter.repaint() From 2220f345f538ceba2883ae920622cf5bdb607e13 Mon Sep 17 00:00:00 2001 From: Lichenkang <2188718831@qq.com> Date: Wed, 11 Nov 2026 00:47:58 -0800 Subject: [PATCH 4/8] ui: MenuAt opens a menu at a point of the window (#3) 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")) + } +} From cdf0039d4ac631c95eedb26a3ae044b3e1fd08b5 Mon Sep 17 00:00:00 2001 From: Lichenkang <2188718831@qq.com> Date: Wed, 11 Nov 2026 01:02:11 -0800 Subject: [PATCH 5/8] markdown, components: images in MarkdownView from host bitmaps (#4) The parser makes ![alt](destination) a Span whose Image is the destination as written. MarkdownStyle.Image asks the application for each image's bitmap; the view lays it out inline, scaled down to the column and never up, makes a line as tall as its tallest image, keeps a linked image a link, and paints it. Without a bitmap the alt text shows, as before. The framework never reads files or the network. Closes the need of vivaui/viva#220 in this fork. Co-authored-by: Claude Opus 5.5 --- components/markdown.go | 80 ++++++++++++++++++++++++++++++++++--- components/markdown_test.go | 38 ++++++++++++++++++ markdown/inline.go | 10 +++++ markdown/markdown.go | 7 +++- markdown/markdown_test.go | 20 ++++++++++ 5 files changed, 148 insertions(+), 7 deletions(-) diff --git a/components/markdown.go b/components/markdown.go index 5bd2dd8db..7366781db 100644 --- a/components/markdown.go +++ b/components/markdown.go @@ -31,6 +31,13 @@ type MarkdownStyle struct { // string that runs over several lines is only colored where the lexer can // tell from the line itself. The colors come from MarkdownLook.Code. Highlight func(language, line string, dst []MarkdownCodeRun) []MarkdownCodeRun + // Image, when set, is asked for the bitmap of every image (![alt](destination)), + // with the destination as written. The view never reads files or the network: + // an application resolves relative paths and fetches what it allows. A bitmap's + // pixels are its size in the layout, scaled down to the column and never up. + // false lays the image out as its alt text, so an application can answer once + // the image has loaded and lay the document out again. + Image func(destination string) (gfx.Bitmap, bool) } // MarkdownCodeClass says what a stretch of code is, which MarkdownLook.Code turns @@ -167,6 +174,7 @@ type MarkdownView struct { boxes []mdBox links []mdLink codes []MarkdownCode + images []mdImage anchors []MarkdownAnchor atoms []mdAtom numbers []byte @@ -489,11 +497,21 @@ type mdLink struct { text, dest string } +// mdImage is an image laid out at x, y, w by h. +type mdImage struct { + bitmap gfx.Bitmap + x, y, w, h float32 +} + type mdAtom struct { span, lo, hi int32 - w, space float32 // width, and the width of the blank that follows it - brk bool // a line break - glue bool // punctuation that may not start a line + // image marks an image's atom: w by h of bitmap. + image bool + h float32 + bitmap gfx.Bitmap + w, space float32 // width, and the width of the blank that follows it + brk bool // a line break + glue bool // punctuation that may not start a line } type mdFont struct { @@ -503,6 +521,8 @@ type mdFont struct { // mdLayout is the state of one Layout call. type mdLayout struct { + // column is the widest an image may be laid out, set by inline. + column float32 v *MarkdownView canvas *gfx.Canvas style MarkdownStyle @@ -519,6 +539,7 @@ func (v *MarkdownView) Layout(canvas *gfx.Canvas, style MarkdownStyle, doc *mark if style.LineHeight <= 0 { style.LineHeight = float32(int(style.Size*1.55 + 0.5)) } + v.images = v.images[:0] v.pieces, v.boxes, v.links, v.codes, v.anchors, v.numbers, v.runs, v.tabs, v.tabBound, v.plain, v.spanBase = v.pieces[:0], v.boxes[:0], v.links[:0], v.codes[:0], v.anchors[:0], v.numbers[:0], v.runs[:0], v.tabs[:0], v.tabBound[:0], v.plain[:0], v.spanBase[:0] v.bars = [markdownMaxQuote + 1]int32{} v.face = style.MonoFace @@ -1070,6 +1091,20 @@ func (l *mdLayout) atomize(spans []markdown.Span, t mdFont) { pending = 0 continue } + if sp.Image != "" && l.style.Image != nil { + if bitmap, ok := l.style.Image(sp.Image); ok && bitmap.Width > 0 && bitmap.Height > 0 { + w, h := float32(bitmap.Width), float32(bitmap.Height) + if column := l.column; column > 0 && w > column { + w, h = column, h*column/w + } + if pending > 0 && len(atoms) > 0 && !atoms[len(atoms)-1].brk { + atoms[len(atoms)-1].space = pending + } + pending = 0 + atoms = append(atoms, mdAtom{span: int32(si), image: true, w: w, h: h, bitmap: bitmap}) + continue + } + } mono := sp.Style&markdown.Mono != 0 italic := sp.Style&markdown.Italic != 0 size, weight := t.size, spanWeight(t.weight, sp.Style) @@ -1148,9 +1183,12 @@ type mdLine struct { piece int // the open piece, or -1 lo int32 span int32 - pieceP int // first piece, box and link of the line, for alignment + pieceP int // first piece, box, link and image of the line, for alignment pieceB int pieceL int + pieceI int + // tall is the height of the tallest image on the line. + tall float32 // grew reports that the open piece took a second atom, so its width is a // running sum that closePiece must settle. grew bool @@ -1167,7 +1205,9 @@ func (l *mdLayout) inline(spans []markdown.Span, x, width, y float32, t mdFont, if len(spans) == 0 { return y } + l.column = width l.atomize(spans, t) + l.column = 0 m := mdLine{l: l, spans: spans, t: t, align: align, x0: x, width: width, y: y, piece: -1} m.reset() for _, a := range l.v.atoms { @@ -1232,7 +1272,8 @@ func (m *mdLine) fit(a mdAtom) (mdAtom, bool) { func (m *mdLine) reset() { v := m.l.v m.x, m.w, m.has, m.piece = 0, 0, false, -1 - m.pieceP, m.pieceB, m.pieceL = len(v.pieces), len(v.boxes), len(v.links) + m.pieceP, m.pieceB, m.pieceL, m.pieceI = len(v.pieces), len(v.boxes), len(v.links), len(v.images) + m.tall = 0 m.measuredSpan, m.measuredLo, m.measuredHi, m.measuredEnd = -1, 0, 0, 0 m.grew = false } @@ -1261,6 +1302,9 @@ func (m *mdLine) spanPad(sp markdown.Span) float32 { } func (m *mdLine) exactWidth(a mdAtom) float32 { + if a.image { + return a.w + } if a.hi <= a.lo { return 0 } @@ -1431,6 +1475,20 @@ func (m *mdLine) place(a mdAtom) { v := l.v sp := m.spans[a.span] mono := sp.Style&markdown.Mono != 0 + if a.image { + m.closePiece() + x := m.x0 + m.x + v.images = append(v.images, mdImage{bitmap: a.bitmap, x: x, y: m.y, w: a.w, h: a.h}) + if sp.Link != "" { + v.links = append(v.links, mdLink{x: x, y: m.y, w: a.w, h: a.h, size: m.t.size, text: sp.Text, dest: sp.Link}) + } + m.x += a.w + m.w = m.x + m.x += a.space + m.has = true + m.tall = max(m.tall, a.h) + return + } if a.hi <= a.lo { return } @@ -1553,9 +1611,13 @@ func (m *mdLine) endLine() { for i := m.pieceL; i < len(v.links); i++ { v.links[i].x += shift } + for i := m.pieceI; i < len(v.images); i++ { + v.images[i].x += shift + } } } - m.y += m.t.line + // A line with an image is as tall as the image, with the text along its top. + m.y += max(m.t.line, m.tall+4) m.l.lines++ m.reset() } @@ -1592,6 +1654,12 @@ func (v *MarkdownView) Paint(canvas *gfx.Canvas, p MarkdownPaint) { canvas.Rounded(rect, 4, look.InlineCodeFill) } } + for _, image := range v.images { + rect := gfx.Rect{X: p.X + image.x, Y: p.Y + image.y, Width: image.w, Height: image.h} + if visible(rect.Y, rect.Height) { + canvas.DrawBitmap(image.bitmap, rect) + } + } start, end := p.Selection.Range(v.plain) if start < end && look.Selection.Alpha > 0 { for index := range v.pieces { diff --git a/components/markdown_test.go b/components/markdown_test.go index d076036a1..656b417a4 100644 --- a/components/markdown_test.go +++ b/components/markdown_test.go @@ -1740,3 +1740,41 @@ func TestHeadingInlineCodeSelectionUsesItsOwnCellWidth(t *testing.T) { t.Errorf("heading inline code selection is %v wide, want %v", rects[0].Bounds.Width, want) } } + +func TestMarkdownImagesAreScaledToTheColumnAndPainted(t *testing.T) { + wide := gfx.Bitmap{Pix: make([]byte, 400*100*4), Width: 400, Height: 100, Stride: 400 * 4, ID: 1} + small := gfx.Bitmap{Pix: make([]byte, 20*10*4), Width: 20, Height: 10, Stride: 20 * 4, ID: 2} + style := MarkdownStyle{Size: 12, Image: func(dest string) (gfx.Bitmap, bool) { + switch dest { + case "wide.png": + return wide, true + case "small.png": + return small, true + } + return gfx.Bitmap{}, false + }} + view, _ := layoutMarkdown(t, "![a](wide.png)\n\n[![b](small.png)](https://example.com/) ![missing](gone.png)", 200, style) + if len(view.images) != 2 { + t.Fatalf("images = %+v", view.images) + } + if got := view.images[0]; got.w != 200 || got.h != 50 { + t.Errorf("a wide image is %vx%v, want 200x50", got.w, got.h) + } + if got := view.images[1]; got.w != 20 || got.h != 10 { + t.Errorf("a small image is %vx%v, want its own 20x10", got.w, got.h) + } + if view.Height() < 50 { + t.Errorf("height %v leaves no room for the image", view.Height()) + } + if view.LinkCount() != 1 || view.Link(0) != "https://example.com/" { + t.Errorf("the linked badge is not a link: %d", view.LinkCount()) + } + if !strings.Contains(string(view.plain), "missing") { + t.Errorf("an unresolved image shows no alt text: %q", view.plain) + } + var canvas gfx.Canvas + view.Paint(&canvas, MarkdownPaint{X: 0, Y: 0}) + if len(canvas.Images()) != 2 { + t.Errorf("painted %d images", len(canvas.Images())) + } +} diff --git a/markdown/inline.go b/markdown/inline.go index fa80c0d08..3da7a8fc0 100644 --- a/markdown/inline.go +++ b/markdown/inline.go @@ -63,6 +63,16 @@ func (d *Document) inline(s string, style Style, link string, depth int) { } i += n continue + case '!': + if i+1 < len(s) && s[i+1] == '[' { + if labelEnd, dest, end := d.findLink(s, i+1); end >= 0 { + d.emit(s[text:i], style, link) + d.spans = append(d.spans, Span{Text: s[i+2 : labelEnd], Style: style, Link: link, Image: dest}) + i = end + text = i + continue + } + } case '[': if link == "" && depth < maxNesting { if labelEnd, dest, end := d.findLink(s, i); end >= 0 { diff --git a/markdown/markdown.go b/markdown/markdown.go index b435d8d64..4412a0b64 100644 --- a/markdown/markdown.go +++ b/markdown/markdown.go @@ -14,7 +14,8 @@ // not closed (a "**" with no partner, a fence nobody ended yet) stays as typed, // so half a message that is still arriving reads sensibly. Links are kept only // when they point to http, https or mailto; any other destination is shown as -// plain text. HTML, images, footnotes and indented code are not interpreted. +// plain text. HTML, footnotes and indented code are not interpreted; an image is a +// Span whose Image is its destination. package markdown import "strings" @@ -55,6 +56,10 @@ type Span struct { // Link is the destination when the text is a link, and empty otherwise. // Only http, https and mailto destinations are ever set. Link string + // Image is the destination of an image (![alt](destination)) as written, + // whatever its scheme, and empty for text; Text is then the alt text. The + // package never reads it: a view asks the application for the bitmap. + Image string } // Newline is the Text of the Span that separates two lines of a block. diff --git a/markdown/markdown_test.go b/markdown/markdown_test.go index a6f599dce..554f2e58e 100644 --- a/markdown/markdown_test.go +++ b/markdown/markdown_test.go @@ -297,3 +297,23 @@ func TestBlockRangesNameTheLinesOfTheirBlocks(t *testing.T) { } } } + +func TestAnImageIsASpanWithItsDestination(t *testing.T) { + var d Document + d.Parse("see ![the diagram](docs/arch.png) and [![build](https://x/badge.svg)](https://x/ci)") + var images []Span + for _, span := range d.Spans(&d.Blocks[0]) { + if span.Image != "" { + images = append(images, span) + } + } + if len(images) != 2 { + t.Fatalf("images = %+v", images) + } + if images[0].Image != "docs/arch.png" || images[0].Text != "the diagram" || images[0].Link != "" { + t.Errorf("first image %+v", images[0]) + } + if images[1].Image != "https://x/badge.svg" || images[1].Link != "https://x/ci" { + t.Errorf("a linked badge %+v", images[1]) + } +} From 4dd479b64b28784e09b98f17955619e7997b4bbd Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <3075514079@qq.com> Date: Wed, 11 Nov 2026 17:56:24 +0800 Subject: [PATCH 6/8] darwin: keep the traffic lights centered when the title changes (#5) Setting the window title lays the titlebar out again, and AppKit puts the zoom button back at the system's height without posting the frame change keepTrafficLightsCentered listens for. In a custom titlebar taller than the system's, the green button then sits above the other two until the next resize. setWindowTitle: now places the buttons again itself. --- internal/platform/darwin/native.m | 6 ++++++ internal/platform/darwin/testdata/traffic_lights.m | 7 +++++++ 2 files changed, 13 insertions(+) diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 5eb7c1678..4e62135b3 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -6250,6 +6250,12 @@ - (void)setWindowTitle:(NSString *)title { _title = [title copy]; if (_window != nil) { _window.title = _title; + /* A new title lays the titlebar out again, and AppKit sets the zoom + * button back at the system's height without reporting the move as a + * frame change, so keepTrafficLightsCentered never hears of it. */ + if (_windowMode == VIVA_WINDOW_CUSTOM_TITLEBAR) { + viva_place_traffic_lights(_window, _titlebarHeight); + } } } diff --git a/internal/platform/darwin/testdata/traffic_lights.m b/internal/platform/darwin/testdata/traffic_lights.m index bdcae84fd..e6c7e15c5 100644 --- a/internal/platform/darwin/testdata/traffic_lights.m +++ b/internal/platform/darwin/testdata/traffic_lights.m @@ -121,6 +121,13 @@ int main(void) { window.titlebarAppearsTransparent = NO; window.titlebarAppearsTransparent = YES; assertCenter(window, 18, "after the titlebar was restyled"); + // A new title lays the titlebar out too, and AppKit moves the zoom + // button back without reporting it as a frame change. + [delegate setWindowTitle:@"project"]; + assertCenter(window, 18, "after the title changed"); + assertAligned(window, "after the title changed"); + [delegate setWindowTitle:@"project - file"]; + assertAligned(window, "after the title changed again"); [delegate setAlwaysOnTop:YES]; assert(window.level == NSFloatingWindowLevel); [delegate setAlwaysOnTop:NO]; From 7850516be532c5732fa7c6ac75a462c9d8390435 Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <3075514079@qq.com> Date: Wed, 11 Nov 2026 18:29:51 +0800 Subject: [PATCH 7/8] ui: MenuItems.Beside opens a menu to the right of its anchor (#6) 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 3c09c0876..46c145f02 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)) { @@ -133,6 +135,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)) { @@ -143,9 +146,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 { @@ -286,8 +292,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 @@ -388,11 +394,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 @@ -520,11 +541,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 ce33be7b9..acec13c5c 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`,就是普通的页面代码,不用反射: From f7b30913ed39b26334099d59daf6e26e058b4e2e Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 11 Nov 2026 19:29:49 +0800 Subject: [PATCH 8/8] ui: a following List places its rows at the end it is pinned to A List with Follow(true) chose the rows it declares from the offset the area had in the paint before, and the layout then pinned the area to the new end. When more rows arrived at once than the viewport holds, the declared rows sat far above the viewport and the paint that added them was blank; a long list that started following stayed blank until something else repainted it. The list now reads whether the area keeps to its end before ScrollArea resets Follow for the paint, places its rows for the end the layout will pin to, and asks for a bounded number of paints when a following list still did not reach its last row (its first paint, or estimated heights that fell short). --- ui/list.go | 29 +++++++++++++++++++-- ui/list_follow_test.go | 59 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 ui/list_follow_test.go diff --git a/ui/list.go b/ui/list.go index d024904dd..9abcaccb1 100644 --- a/ui/list.go +++ b/ui/list.go @@ -90,6 +90,7 @@ type listInternals struct { pendingRow int32 // 1 + the row it asked to show pendingAt float32 // where the last paint of it left the offset pendingFrame uint8 // the paints it has been applied in, counted to a bound + followFrame uint8 // the paints a following list asked for to reach its end, counted to a bound declared []listDeclRow f *frame typeahead components.MenuTypeahead @@ -554,12 +555,23 @@ func (s *ListState) applyScrollRequest(f *frame) bool { } // afterLayout records where a pending request left the list, so the next paint can -// tell an offset the request moved from one something else moved. +// tell an offset the request moved from one something else moved, and asks for the +// paint a following list needs when this one did not place its last row: the first +// paint of a list that starts following, whose rows were placed before Follow said +// so, or one whose estimated heights fell short of the end. func (s *ListState) afterLayout() { in := &s.list if in.pending != listScrollNone && in.scroll != nil { in.pendingAt = in.scroll.Offset } + if in.scroll == nil || !in.scroll.pinned() || in.last >= in.n-1 { + in.followFrame = 0 + return + } + if in.followFrame < listScrollFrames && in.f != nil && in.f.canvas != nil { + in.followFrame++ + in.f.canvas.RequestFrame() + } } // scrollTarget is where the request kind puts row as the list knows the heights now: @@ -837,7 +849,11 @@ func blockBehind(d *DrawContext) { d.Canvas.Block(d.Rect) } // i's element. func (p *Page) listArea(c C, state *ListState, n int, horizontal bool, row func(i int, box Box)) Box { at, _ := p.name(pkContainer) - area := c.f.ScrollArea(p.id(at)) + id := p.id(at) + // Follow is declared on the area the List returns, after its rows: whether the area + // keeps to its end is what the paint before left it, as ScrollState.Pinned says. + pinned := c.f.scrolls.get(id).pinned() + area := c.f.ScrollArea(id) p.setNode(area.i, at) in := &state.list in.n, in.area, in.pinned = n, area.i, -1 @@ -853,6 +869,15 @@ func (p *Page) listArea(c C, state *ListState, n int, horizontal bool, row func( if viewport <= 0 { viewport = c.f.bounds.Height } + if pinned || scroll.pinned() { + // The layout puts the area at its end, which the rows that arrived since the + // last paint moved: the rows are placed for that end, not for the offset the + // area had, which would leave the paint that adds them blank. + if end := max(state.top(n)-viewport, 0); end != scroll.Offset { + scroll.Offset = end + c.f.nodes[area.i].scroll = end + } + } first := max(state.rowAt(scroll.Offset)-listOverscan, 0) if in.n == 0 { first = 0 diff --git a/ui/list_follow_test.go b/ui/list_follow_test.go new file mode 100644 index 000000000..b17596b64 --- /dev/null +++ b/ui/list_follow_test.go @@ -0,0 +1,59 @@ +package ui_test + +import ( + "strconv" + "testing" + "time" + + "github.com/vivaui/viva/ui" +) + +// followingRows is a log of rows of varying height in a List that follows its end. +func followingRows(m *logRows) func(ui.C) { + return func(c ui.C) { + ui.Column(c).Fill().Children(func() { + ui.List(c, &m.list, m.n, func(row ui.ListRow) { + row.Element.Height(m.height(row.Index)).Children(func() { + ui.Text(row.C, "row "+strconv.Itoa(row.Index)) + }) + }).Label("Rows").Follow(true).Grow(1) + }) + } +} + +// A List that follows its end shows its last rows in the paint that adds rows, even +// when more rows arrive at once than the viewport holds: the rows are placed for the +// end the layout pins the area to, not for the offset the area had before. +func TestListFollowShowsTheEndAsRowsArrive(t *testing.T) { + m := newLogRows(10) + d := openPage(t, followingRows(m)) + d.repaint() + for step := range 8 { + m.n += 3000 + d.repaint() + last := "row " + strconv.Itoa(m.n-1) + if !d.has(last) || !m.list.AtEnd() { + t.Fatalf("step %d: %s painted %v after %d rows arrived (Visible %v, at the end %v)", step, last, d.has(last), m.n, visibleOf(&m.list), m.list.AtEnd()) + } + } +} + +// A long List that starts following places its first rows before Follow is +// declared; it asks for the paint that shows its end instead of staying blank. +func TestListFollowReachesTheEndOfALongListItStartsWith(t *testing.T) { + m := newLogRows(5000) + d := openPage(t, followingRows(m)) + d.repaint() + for frames := 0; d.driver.Transitioning(); frames++ { + if frames == 10 { + t.Fatal("the list asked for ten paints to reach its end") + } + if err := d.driver.Advance(16 * time.Millisecond); err != nil { + t.Fatal(err) + } + } + d.repaint() + if !d.has("row 4999") || !m.list.AtEnd() { + t.Fatalf("the last row painted %v (Visible %v, at the end %v)", d.has("row 4999"), visibleOf(&m.list), m.list.AtEnd()) + } +}