From 176b43497e74dee25aa42312e4c05971d93e5cea Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 25 Nov 2026 20:54:15 +0800 Subject: [PATCH 1/7] feat(ui): show the full text of an ellipsized label on hover A label that Ellipsis cuts short hides the rest of its text with no way to read it. Layout now marks a text node it actually truncated, and painting registers a non-interactive hover hint for it (gfx.HoverHint: owner, bounds, full text, the control it belongs to, layer and clip scope). After the tooltip delay a Page shows the hint through the shared tooltip, the same one Tooltip uses. The hint adds no hit target, focus stop or accessibility node, so clicks, selection and keyboard behaviour are unchanged. It only appears when the layout really cut the text: a value that merely ends in an ellipsis does not trigger it. A clip, a hit painted later, a higher layer or a focus trap hides it; pressing the pointer hides it until the pointer leaves. Box.OverflowTooltip(text) lets a caller that shortened a value itself (a middle-elided path, say) hand over the original. Select, combobox, dropdown menu and hierarchy menu items, multi-select chips, table cells and area chart axis labels use the same path. Canvas Reset, Trim, Rewind, embedding and replay carry or clear the hints with the rest of the frame. The components that share the ellipsis helper now require label, so the installer templates and componentRequires are regenerated with componentgen. --- base/box.go | 1 + base/flags.go | 5 +- base/frame.go | 9 +- base/layout.go | 1 + base/page.go | 19 ++- base/paint.go | 8 + base/text_wrap.go | 28 ++-- base/tooltip.go | 21 +++ cmd/viva/components_gen.go | 14 +- cmd/viva/templates/chart_area.go.txt | 3 +- cmd/viva/templates/combobox.go.txt | 18 +-- cmd/viva/templates/dropdown_menu.go.txt | 8 +- cmd/viva/templates/hierarchy_menu.go.txt | 6 +- cmd/viva/templates/label.go.txt | 10 ++ cmd/viva/templates/multi_select.go.txt | 9 +- cmd/viva/templates/select.go.txt | 8 +- cmd/viva/templates/single_select.go.txt | 12 +- cmd/viva/templates/table.go.txt | 9 ++ components/chart_area.go | 3 +- components/combobox.go | 18 +-- components/dropdown_menu.go | 8 +- components/hierarchy_menu.go | 6 +- components/label.go | 10 ++ components/multi_select.go | 9 +- components/select.go | 8 +- components/single_select.go | 12 +- components/table.go | 9 ++ gfx/canvas.go | 7 + gfx/embed.go | 27 +++- gfx/hover_hint.go | 87 ++++++++++ gfx/hover_hint_test.go | 56 +++++++ gfx/pose.go | 2 +- gfx/presence.go | 8 +- gfx/replay.go | 26 ++- gfx/wrap.go | 11 ++ ui/multiselect/multiselect_test.go | 37 +++++ ui/tooltip_paint.go | 42 ++++- ui/tooltip_test.go | 194 +++++++++++++++++++++++ 38 files changed, 674 insertions(+), 95 deletions(-) create mode 100644 gfx/hover_hint.go create mode 100644 gfx/hover_hint_test.go diff --git a/base/box.go b/base/box.go index 5e9c7cb29..01df5effe 100644 --- a/base/box.go +++ b/base/box.go @@ -430,6 +430,7 @@ func (b Box) MonoFace(Face gfx.MonoFace) Box { // Ellipsis keeps a Text to one line and ends it with an ellipsis when it does not // fit the width it gets, instead of clipping it. It is Paragraph(value, 1). +// In a Page, hovering truncated text shows its complete value in a tooltip. func (b Box) Ellipsis() Box { n := b.N() n.Flags |= flagWrap diff --git a/base/flags.go b/base/flags.go index 7476d5c48..361330abb 100644 --- a/base/flags.go +++ b/base/flags.go @@ -41,8 +41,9 @@ const ( // face describes the text rather than the element, so they have a byte of their own // (Node.TextDecor). const ( - textItalic uint8 = 1 << iota // Italic: the face gfx.StyledTextEngine shapes - textStrike // Strike: one line through the middle of each line + textItalic uint8 = 1 << iota // Italic: the face gfx.StyledTextEngine shapes + textStrike // Strike: one line through the middle of each line + textTruncated // layout omitted text at MaxLines; no new Node storage ) // flagRequired marks a page Label that appends the field title's required diff --git a/base/frame.go b/base/frame.go index 194d563dc..008831468 100644 --- a/base/frame.go +++ b/base/frame.go @@ -219,6 +219,7 @@ type Extra struct { memo int32 // 1 + the index the element's cache has with whoever declared it (memoFn), or 0 Draws int32 // 1 + the index of the element's Draw and DrawOver callbacks in frame.draws, or 0 for none tooltip string // what Tooltip says over the element; empty for none + overflowTip string // full text already shortened by the application tooltipSide uint8 // 1 + the TooltipSide TooltipOn opens the element's tip on; 0 is below addons int32 // 1 + the index of the field's icon and button in frame.addons, or 0 focusGroup FocusAxis // FocusGroup: the arrow keys that move the focus between the controls inside; zero is none @@ -426,6 +427,10 @@ func (f *Frame) End() { f.reportScrolls() f.Scrolls.sweep() f.reportSplitters() + if f.page != nil { + previous := f.Surface.SetHoverHintOwner(f.page.root) + defer f.Surface.SetHoverHintOwner(previous) + } f.PaintChild(0) f.raiseOverNativeViews() if f.popupLayer != 0 { @@ -437,8 +442,8 @@ func (f *Frame) End() { if f.popupLayer != 0 { f.Surface.PopLayer() } - if f.tooltips { - f.paintTooltipFn(f) + if f.tooltips || f.page != nil { + f.paintTooltip() } else if f.paintTooltipFn != nil { f.tooltip = nil } diff --git a/base/layout.go b/base/layout.go index c72dabee5..61132b17f 100644 --- a/base/layout.go +++ b/base/layout.go @@ -84,6 +84,7 @@ func (f *Frame) measure(axis int) { f.measureLeaf(n) } if n.Kind == kindText && n.Flags&flagWrap != 0 && axis == AxisY { + n.TextDecor &^= textTruncated first := int32(len(f.Lines)) // An empty text has no line at all, as WrapLines gives it none; anything // else that fits is one line and needs no breaking. diff --git a/base/page.go b/base/page.go index 587d79d0e..f0f585d80 100644 --- a/base/page.go +++ b/base/page.go @@ -298,8 +298,10 @@ type Page struct { pointer gfx.Point // where the pointer was at the last pointer event pointerIn bool // a pointer event put it there, and no exit has taken it away hoverArea gfx.ID // the scroll area or self-scrolling table the pointer is on - selects []*SelectState // the Selects of the last paint, which Wheel scrolls - labels []string // scratch for Choice's labels + hoverText gfx.HoverHint // changes wake a page even when text has no pointer target + pointerDown bool + selects []*SelectState // the Selects of the last paint, which Wheel scrolls + labels []string // scratch for Choice's labels memos map[gfx.ID]*memoEntry memoBoxes []memoBox memoChecks []memoCheckOf @@ -566,6 +568,12 @@ func (p *Page) onKey(event gfx.KeyEvent) gfx.EventResult { } func (p *Page) onPointer(event gfx.PointerEvent) gfx.EventResult { + switch event.Kind { + case gfx.PointerDown: + p.pointerDown = true + case gfx.PointerUp, gfx.PointerExit: + p.pointerDown = false + } switch event.Kind { case gfx.PointerMove, gfx.PointerDown, gfx.PointerUp: p.pointer, p.pointerIn = gfx.Point{X: event.X, Y: event.Y}, true @@ -586,6 +594,9 @@ func (p *Page) onPointer(event gfx.PointerEvent) gfx.EventResult { p.hoverArea = p.hoverPlaceAt(p.pointer.X, p.pointer.Y) } entered := wasArea != p.hoverArea + text := p.HoveredText() + textChanged := !text.SameText(p.hoverText) + p.hoverText = text var result gfx.EventResult if done, ok := p.dropPointer(event); ok { result = done @@ -598,7 +609,8 @@ func (p *Page) onPointer(event gfx.PointerEvent) gfx.EventResult { } else if p.basePointer != nil { result = p.basePointer(event) } - result.Repaint = result.Repaint || entered + result.Repaint = result.Repaint || entered || textChanged || + text.Text != "" && (event.Kind == gfx.PointerDown || event.Kind == gfx.PointerUp) return result } @@ -843,6 +855,7 @@ func (p *Page) paintOnce(Surface *gfx.Canvas, bounds Rect, View func(C)) { p.Nodes = append(p.Nodes[:0], protoNode{scope: p.root, named: true, parentNode: -1}) // node 0, the root column View(&p.ctx) f.End() + p.hoverText = p.HoveredText() if p.settleContainers() { p.retry = true } diff --git a/base/paint.go b/base/paint.go index d6da041ce..20ea4ff09 100644 --- a/base/paint.go +++ b/base/paint.go @@ -179,6 +179,10 @@ func (f *Frame) PaintChild(i int32) { } } + if extra.overflowTip != "" && f.page != nil { + canvas.HoverHint(f.page.root, r, extra.overflowTip, n.ID) + } + // A Text and an Icon draw with their color, which is the one the looks give. color := n.Color n.Color = fade(style.Color, f.Opacity) @@ -379,6 +383,10 @@ func (f *Frame) paintText(n *Node) { f.paintStrike(line, bounds, style, alignment) } } + if n.TextDecor&textTruncated != 0 && f.page != nil && f.Exts[n.Ext].overflowTip == "" { + r.Height = min(r.Height, float32(n.LineCount)*lh) + f.Surface.HoverHint(f.page.root, r, n.Text) + } return } height := max(n.Pref[AxisY]-top-bottom, 0) diff --git a/base/text_wrap.go b/base/text_wrap.go index 2637dd3a6..0f6c5d16f 100644 --- a/base/text_wrap.go +++ b/base/text_wrap.go @@ -11,16 +11,17 @@ import ( // that did not change can append the saved lines instead of measuring every // prefix again. type wrapCache struct { - Text string - Size float32 - Weight float32 - mono bool - italic bool - Face gfx.MonoFace - width float32 - MaxLines int - Lines []string - filled bool + Text string + Size float32 + Weight float32 + mono bool + italic bool + Face gfx.MonoFace + width float32 + MaxLines int + Lines []string + filled bool + truncated bool } // wrapText appends the lines of a wrapped Text, breaking them as gfx.Canvas.WrapLines @@ -51,10 +52,17 @@ func (f *Frame) wrapText(dst []string, n *Node) []string { if wrapped.filled && wrapped.Text == n.Text && wrapped.Size == n.FontSize && wrapped.Weight == n.Weight && wrapped.mono == mono && wrapped.italic == italic && wrapped.Face == face && wrapped.width == width && wrapped.MaxLines == maxLines { + if wrapped.truncated { + n.TextDecor |= textTruncated + } return append(dst, wrapped.Lines...) } start := len(dst) dst = f.Surface.WrapLinesStyle(dst, n.Text, n.textStyle(), width, maxLines, cache) + wrapped.truncated = cache.Truncated() + if wrapped.truncated { + n.TextDecor |= textTruncated + } wrapped.Text, wrapped.Size, wrapped.Weight, wrapped.mono, wrapped.italic, wrapped.Face = n.Text, n.FontSize, n.Weight, mono, italic, face wrapped.width, wrapped.MaxLines = width, maxLines wrapped.Lines = append(wrapped.Lines[:0], dst[start:]...) diff --git a/base/tooltip.go b/base/tooltip.go index b9200b882..3f5e99792 100644 --- a/base/tooltip.go +++ b/base/tooltip.go @@ -9,6 +9,27 @@ import ( // popovers, menus and dialogs. const TooltipLayer = 1000 +// OverflowTooltip supplies the complete value when an application shortened +// the displayed text itself, possibly across several highlighted labels. Call +// it only when content was omitted. Unlike Tooltip it declares no control and +// leaves the enclosing row's pointer, focus and accessibility unchanged. Text +// truncated by Ellipsis or MaxLines supplies its complete value automatically. +func (b Box) OverflowTooltip(text string) Box { + b.f.Extra(b.i).overflowTip = text + return b +} + +// HoveredText returns this page's visible truncation hint under the pointer. +func (p *Page) HoveredText() gfx.HoverHint { + if p == nil || !p.pointerIn || p.View.Frame == nil || p.View.Frame.Surface == nil { + return gfx.HoverHint{} + } + return p.View.Frame.Surface.HoverHintAt(p.root, p.pointer.X, p.pointer.Y) +} + +// PointerDown reports a held pointer button, including a press on plain text. +func (p *Page) PointerDown() bool { return p != nil && p.pointerDown } + // Tooltip names what the element does in a tip that appears beside it while the // pointer rests on it, and is its description for assistive technology: what an // icon-only button needs. The tip hides on a press and stays hidden until the diff --git a/cmd/viva/components_gen.go b/cmd/viva/components_gen.go index 44939e382..6b4d70be5 100644 --- a/cmd/viva/components_gen.go +++ b/cmd/viva/components_gen.go @@ -119,7 +119,7 @@ var componentRequires = map[string][]string{ "button-group": {"button"}, "calendar": {"direction", "tree"}, "carousel": {"direction", "tree"}, - "chart-area": {"chart"}, + "chart-area": {"chart", "label"}, "chart-bar": {"chart", "chart-area"}, "checkbox": {"button"}, "code-diff": {"code-diff-model", "code-editor", "code-editor-layout", "scroll-area", "textarea"}, @@ -131,16 +131,16 @@ var componentRequires = map[string][]string{ "code-merge": {"code-diff", "code-diff-model", "code-editor", "code-editor-layout", "scroll-area"}, "color-picker": {"button", "input", "popover"}, "column-resize": {"button"}, - "combobox": {"checkbox", "dialog", "dropdown-menu", "input", "popover", "tree"}, + "combobox": {"checkbox", "dialog", "dropdown-menu", "input", "label", "popover", "tree"}, "command": {"checkbox", "dialog", "dropdown-menu"}, "context-menu": {"dialog", "dropdown-menu", "popover"}, "dialog": {"button"}, "drawer": {"button", "dialog"}, - "dropdown-menu": {"checkbox", "dialog", "hover-card", "kbd", "popover", "tree"}, + "dropdown-menu": {"checkbox", "dialog", "hover-card", "kbd", "label", "popover", "tree"}, "find-bar": {"button", "dialog", "input", "toggle", "tree"}, "go-to-line": {"button", "find-bar", "input"}, "graph": {"graph-sim"}, - "hierarchy-menu": {"checkbox", "dialog", "dropdown-menu", "popover", "tree"}, + "hierarchy-menu": {"checkbox", "dialog", "dropdown-menu", "label", "popover", "tree"}, "hover-card": {"dialog", "popover"}, "input": {"textarea"}, "input-group": {"button", "input", "spinner", "textarea"}, @@ -151,7 +151,7 @@ var componentRequires = map[string][]string{ "marker": {"spinner"}, "menubar": {"dialog", "direction", "dropdown-menu", "hover-card", "popover"}, "metric-card": {"card"}, - "multi-select": {"checkbox", "combobox", "dialog", "dropdown-menu", "input", "popover", "tree"}, + "multi-select": {"checkbox", "combobox", "dialog", "dropdown-menu", "input", "label", "popover", "tree"}, "native-select": {"input", "tree"}, "navigation-menu": {"dialog", "direction", "hover-card", "tree"}, "pagination": {"breadcrumb", "tree"}, @@ -160,10 +160,10 @@ var componentRequires = map[string][]string{ "radio-group": {"button", "direction"}, "resizable": {"button"}, "segmented-control": {"button", "direction"}, - "select": {"checkbox", "dialog", "dropdown-menu", "input", "popover", "tree"}, + "select": {"checkbox", "dialog", "dropdown-menu", "input", "label", "popover", "tree"}, "sheet": {"button", "dialog"}, "sidebar": {"button"}, - "single-select": {"checkbox", "dialog", "dropdown-menu", "hierarchy-menu", "input", "popover", "tree"}, + "single-select": {"checkbox", "dialog", "dropdown-menu", "hierarchy-menu", "input", "label", "popover", "tree"}, "slider": {"button", "direction"}, "sonner": {"dialog", "toast"}, "split-button": {"button", "button-group", "tree"}, diff --git a/cmd/viva/templates/chart_area.go.txt b/cmd/viva/templates/chart_area.go.txt index 9f201794c..b1d0ab86b 100644 --- a/cmd/viva/templates/chart_area.go.txt +++ b/cmd/viva/templates/chart_area.go.txt @@ -502,8 +502,7 @@ func chartBeginFrame(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, spec // Edge ticks remain anchored to their data, but their labels must // fit inside the chart container rather than spill into a neighbor. x := min(max(plot.X+frac*plot.Width-width/2, area.X), area.X+area.Width-width) - text = canvas.FitLine(text, fontSize, gfx.WeightRegular, width) - canvas.Label(text, gfx.Rect{X: x, Y: plot.Y + plot.Height + chartAxisGap*scale, Width: width, Height: rowHeight}, labelStyle) + labelEllipsis(canvas, text, gfx.Rect{X: x, Y: plot.Y + plot.Height + chartAxisGap*scale, Width: width, Height: rowHeight}, labelStyle, gfx.ID{}) } } return chartFrame{layout: layout, plot: ChartPlot{ChartLayout: layout, Plot: plot, geo: geo}, scale: scale} diff --git a/cmd/viva/templates/combobox.go.txt b/cmd/viva/templates/combobox.go.txt index 2dfda91b9..c2bc5f072 100644 --- a/cmd/viva/templates/combobox.go.txt +++ b/cmd/viva/templates/combobox.go.txt @@ -218,9 +218,9 @@ func (combobox *Combobox) AddItem(item ComboboxItem) gfx.Rect { labelWidth = maxLabelWidth } - combobox.canvas.Label(combobox.canvas.FitLine(item.Label, sizeM, gfx.WeightRegular, labelWidth), gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(combobox.canvas, item.Label, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeM, Weight: gfx.WeightRegular, Color: foreground, - }) + }, item.ID) detailX := bounds.X + 8 + labelWidth + 8 detailWidth := comboboxMax(0, bounds.X+8+contentWidth-detailX) @@ -229,9 +229,9 @@ func (combobox *Combobox) AddItem(item ComboboxItem) gfx.Rect { if item.Disabled { detailColor.Alpha *= .5 } - combobox.canvas.Label(combobox.canvas.FitLine(item.Detail, sizeS, gfx.WeightRegular, detailWidth), gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(combobox.canvas, item.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeS, Weight: gfx.WeightRegular, Color: detailColor, - }) + }, item.ID) } } if item.Selected { @@ -454,9 +454,9 @@ func (combobox Combobox) paintInput() { if labelWidth > maxLabelWidth { labelWidth = maxLabelWidth } - canvas.Label(canvas.FitLine(options.Value, sizeM, gfx.WeightRegular, labelWidth), gfx.Rect{X: bounds.X + inset, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(canvas, options.Value, gfx.Rect{X: bounds.X + inset, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeM, Weight: gfx.WeightRegular, Color: foreground, - }) + }, options.InputID) detailX := bounds.X + inset + labelWidth + 8 detailWidth := comboboxMax(0, bounds.X+inset+availableWidth-detailX) if detailWidth > 0 { @@ -464,12 +464,12 @@ func (combobox Combobox) paintInput() { if options.Disabled { detailColor.Alpha *= 0.50 } - canvas.Label(canvas.FitLine(options.Detail, sizeS, gfx.WeightRegular, detailWidth), gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(canvas, options.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeS, Weight: gfx.WeightRegular, Color: detailColor, - }) + }, options.InputID) } } else if options.Query == "" || options.InputID.IsZero() || canvas.Focused() != options.InputID || options.Disabled { - canvas.Label(canvas.FitLine(value, combobox.theme.Metrics.FontSizeM, gfx.WeightRegular, availableWidth), textRect, gfx.TextStyle{Size: combobox.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground}) + labelEllipsis(canvas, value, textRect, gfx.TextStyle{Size: combobox.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground}, options.InputID) } if !options.InputID.IsZero() { canvas.HitWithOptions(options.InputID, bounds, options.Label, gfx.HitOptions{ diff --git a/cmd/viva/templates/dropdown_menu.go.txt b/cmd/viva/templates/dropdown_menu.go.txt index e0ec01fd9..1ab6b34c1 100644 --- a/cmd/viva/templates/dropdown_menu.go.txt +++ b/cmd/viva/templates/dropdown_menu.go.txt @@ -907,6 +907,9 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { canvas.Label(label, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelWidth, Height: labelHeight}, gfx.TextStyle{ Size: theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, }) + if label != "" && label != item.Label { + canvas.HoverHint(0, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelWidth, Height: labelHeight}, item.Label, item.ID) + } if item.Description != "" { color := theme.MutedForeground if active { @@ -914,10 +917,9 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { } color = dropdownMenuOpacity(color, item.Disabled) width := max(0, bounds.Width-left-right-menu.hitInset) - value := canvas.FitLine(item.Description, theme.Metrics.FontSizeS, gfx.WeightRegular, width) - canvas.Label(value, gfx.Rect{X: bounds.X + left, Y: descriptionY, Width: width, Height: descriptionHeight}, gfx.TextStyle{ + labelEllipsis(canvas, item.Description, gfx.Rect{X: bounds.X + left, Y: descriptionY, Width: width, Height: descriptionHeight}, gfx.TextStyle{ Size: theme.Metrics.FontSizeS, Weight: gfx.WeightRegular, Color: color, - }) + }, item.ID) } menu.declareItemHit(bounds, item) } diff --git a/cmd/viva/templates/hierarchy_menu.go.txt b/cmd/viva/templates/hierarchy_menu.go.txt index e7815fbd5..f64b26668 100644 --- a/cmd/viva/templates/hierarchy_menu.go.txt +++ b/cmd/viva/templates/hierarchy_menu.go.txt @@ -226,7 +226,7 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m } paintChevron(canvas, &hierarchyLeftIcon, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: 16, Height: bounds.Height}, look.Foreground) text := gfx.Rect{X: bounds.X + 32, Y: bounds.Y, Width: max(bounds.Width-40, 0), Height: bounds.Height} - canvas.Label(canvas.FitLine(label, theme.Metrics.FontSizeM, gfx.WeightRegular, text.Width), text, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: look.Foreground}) + labelEllipsis(canvas, label, text, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: look.Foreground}, o.OptionIDs.At(hierarchyBackIndex)) canvas.HitWithOptions(o.OptionIDs.At(hierarchyBackIndex), bounds, label, gfx.HitOptions{Role: gfx.RoleButton, Description: m.Nodes[parent].Path, SkipFocus: true}) menu.top += bounds.Height menu.viewHeight = max(menu.viewHeight-bounds.Height, 0) @@ -261,7 +261,7 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m reserve += 16 } labelWidth := max(rowBounds.Width-reserve, 0) - canvas.Label(canvas.FitLine(info.Name, theme.Metrics.FontSizeM, gfx.WeightRegular, labelWidth), gfx.Rect{X: rowBounds.X + 8, Y: rowBounds.Y, Width: labelWidth, Height: rowBounds.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}) + labelEllipsis(canvas, info.Name, gfx.Rect{X: rowBounds.X + 8, Y: rowBounds.Y, Width: labelWidth, Height: rowBounds.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) switch { case info.Count > 0 && rowBounds.Width >= reserve: chevron := &chevronRightIcon @@ -323,7 +323,7 @@ func paintAction(m *HierarchyMenuState, menu *menuSurface, action HierarchyMenuA } color := look.Foreground label := gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-16, 0), Height: row.Height} - canvas.Label(canvas.FitLine(action.Label, theme.Metrics.FontSizeM, gfx.WeightRegular, label.Width), label, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}) + labelEllipsis(canvas, action.Label, label, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, action.ID) row.Width = max(row.Width-menu.hitInset, 0) canvas.HitWithOptions(action.ID, row, action.Label, gfx.HitOptions{Role: gfx.RoleMenuItem, Disabled: action.Disabled, SkipFocus: true}) }) diff --git a/cmd/viva/templates/label.go.txt b/cmd/viva/templates/label.go.txt index 7d965f56a..25ec39a11 100644 --- a/cmd/viva/templates/label.go.txt +++ b/cmd/viva/templates/label.go.txt @@ -75,3 +75,13 @@ func (label LabelPainter) Paint(text string) { }) } } + +// labelEllipsis keeps the complete value alongside the fitted label. Its +// control may declare its hit after painting; that hit still owns the pointer. +func labelEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx.TextStyle, target gfx.ID) { + shown := canvas.FitLine(value, style.Size, style.Weight, bounds.Width) + canvas.Label(shown, bounds, style) + if shown != "" && shown != value { + canvas.HoverHint(0, bounds, value, target) + } +} diff --git a/cmd/viva/templates/multi_select.go.txt b/cmd/viva/templates/multi_select.go.txt index dbb1311b0..7aa2fad40 100644 --- a/cmd/viva/templates/multi_select.go.txt +++ b/cmd/viva/templates/multi_select.go.txt @@ -93,7 +93,11 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M break } chip := gfx.Rect{X: x, Y: bounds.Y + (bounds.Height-22)/2, Width: width, Height: 22} - paintComboboxChip(canvas, theme, chip, ComboboxChip{RemoveID: o.RemoveIDs.At(i), Label: canvas.FitLine(label, theme.Metrics.FontSizeS, gfx.WeightMedium, width-30), Value: value, Disabled: o.Disabled}) + shown := canvas.FitLine(label, theme.Metrics.FontSizeS, gfx.WeightMedium, width-30) + paintComboboxChip(canvas, theme, chip, ComboboxChip{RemoveID: o.RemoveIDs.At(i), Label: shown, Value: value, Disabled: o.Disabled}) + if shown != "" && shown != label { + canvas.HoverHint(0, gfx.Rect{X: chip.X + comboboxChipPad, Y: chip.Y, Width: chip.Width - comboboxChipPad - comboboxChipRemove, Height: chip.Height}, label) + } x += width + 5 } if layout.Hidden > 0 { @@ -180,8 +184,7 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M } label = text } - label = canvas.FitLine(label, theme.Metrics.FontSizeM, gfx.WeightRegular, max(row.Width-38, 0)) - canvas.Label(label, gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-38, 0), Height: row.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}) + labelEllipsis(canvas, label, gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-38, 0), Height: row.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) if choice.Selected { paintCheck(canvas, gfx.Rect{X: row.X + row.Width - 25, Y: row.Y, Width: 16, Height: row.Height}, 14, color) } diff --git a/cmd/viva/templates/select.go.txt b/cmd/viva/templates/select.go.txt index 87ece9c33..058ba044c 100644 --- a/cmd/viva/templates/select.go.txt +++ b/cmd/viva/templates/select.go.txt @@ -355,9 +355,9 @@ func (selectControl Select) paintTrigger() { if options.Weight > 0 { weight = options.Weight } - canvas.Label(value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(canvas, value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: textSize, Weight: weight, Color: foreground, - }) + }, options.TriggerID) } paintChevron(canvas, &chevronDownIcon, gfx.Rect{X: bounds.X + bounds.Width - chevronSpan, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, chevron) } @@ -386,9 +386,9 @@ func (selectControl *Select) paintItem(bounds gfx.Rect, item SelectItem) { textX += SelectIconSpan textWidth -= SelectIconSpan } - selectControl.canvas.Label(item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(selectControl.canvas, item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: selectControl.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, - }) + }, item.ID) if item.Selected { paintCheck(selectControl.canvas, gfx.Rect{X: bounds.X + bounds.Width - 24, Y: bounds.Y, Width: 14, Height: bounds.Height}, 14, foreground) } diff --git a/cmd/viva/templates/single_select.go.txt b/cmd/viva/templates/single_select.go.txt index 0c58a5df0..6d2b5d2ac 100644 --- a/cmd/viva/templates/single_select.go.txt +++ b/cmd/viva/templates/single_select.go.txt @@ -134,7 +134,7 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * if query == "" && !open { detail = s.Detail(s.ValueText) } - paintLabelAndDetail(canvas, theme, layout.Input.X, layout.Input.Y, layout.Input.Width, layout.Input.Height, display, detail, color, o.Disabled) + paintLabelAndDetail(canvas, theme, layout.Input.X, layout.Input.Y, layout.Input.Width, layout.Input.Height, display, detail, color, o.Disabled, o.InputID) } accessibleValue := query if accessibleValue == "" { @@ -240,7 +240,7 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * if content := choice.Content; content.Paint != nil { content.Paint(canvas, gfx.Rect{X: left, Y: row.Y, Width: labelWidth, Height: row.Height}, theme) } else { - paintLabelAndDetail(canvas, theme, left, row.Y, labelWidth, row.Height, label, choice.Detail, color, choice.Disabled) + paintLabelAndDetail(canvas, theme, left, row.Y, labelWidth, row.Height, label, choice.Detail, color, choice.Disabled, id) } if choice.Selected { paintCheck(canvas, gfx.Rect{X: row.X + row.Width - 25, Y: row.Y, Width: 16, Height: row.Height}, 14, color) @@ -261,21 +261,21 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * // paintLabelAndDetail paints a label in the width it has and, after it, the muted detail in // what is left, as Combobox rows did: the label keeps what it needs up to all but 40 pixels. -func paintLabelAndDetail(canvas *gfx.Canvas, theme gfx.Theme, x, y, width, height float32, label, detail string, color gfx.Color, disabled bool) { +func paintLabelAndDetail(canvas *gfx.Canvas, theme gfx.Theme, x, y, width, height float32, label, detail string, color gfx.Color, disabled bool, target gfx.ID) { sizeM, sizeS := theme.Metrics.FontSizeM, theme.Metrics.FontSizeS if detail == "" { - canvas.Label(canvas.FitLine(label, sizeM, gfx.WeightRegular, width), gfx.Rect{X: x, Y: y, Width: width, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}) + labelEllipsis(canvas, label, gfx.Rect{X: x, Y: y, Width: width, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) return } labelWidth := min(canvas.TextWidthWeight(label, sizeM, gfx.WeightRegular), max(width-40, 0)) - canvas.Label(canvas.FitLine(label, sizeM, gfx.WeightRegular, labelWidth), gfx.Rect{X: x, Y: y, Width: labelWidth, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}) + labelEllipsis(canvas, label, gfx.Rect{X: x, Y: y, Width: labelWidth, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) detailX := x + labelWidth + singleSelectDetailGap if detailWidth := max(x+width-detailX, 0); detailWidth > 0 { muted := theme.MutedForeground if disabled { muted.Alpha *= .5 } - canvas.Label(canvas.FitLine(detail, sizeS, gfx.WeightRegular, detailWidth), gfx.Rect{X: detailX, Y: y, Width: detailWidth, Height: height}, gfx.TextStyle{Size: sizeS, Color: muted}) + labelEllipsis(canvas, detail, gfx.Rect{X: detailX, Y: y, Width: detailWidth, Height: height}, gfx.TextStyle{Size: sizeS, Color: muted}, target) } } diff --git a/cmd/viva/templates/table.go.txt b/cmd/viva/templates/table.go.txt index 40e93143f..02c66cec7 100644 --- a/cmd/viva/templates/table.go.txt +++ b/cmd/viva/templates/table.go.txt @@ -424,6 +424,9 @@ func (table *Table) paintRow(id gfx.ID, cells []string, state TableRowState, kin }) } if text != "" { + if text != value { + table.canvas.HoverHint(0, textBounds, value, id) + } table.canvas.Clip(textBounds) tableLabel(table.canvas, text, textBounds, column.Alignment, style) table.canvas.Unclip() @@ -954,6 +957,9 @@ func (table *Table) paintSortableHeaderCell( style := gfx.TextStyle{Size: size, Weight: gfx.WeightMedium, Color: color} if !interactive { label := canvas.FitLine(cell.Label, size, gfx.WeightMedium, textBounds.Width) + if label != "" && label != cell.Label { + canvas.HoverHint(0, textBounds, cell.Label, cell.ID) + } painted := tableTextCell{ bounds: textBounds, textLo: field.lo, textHi: field.hi, contentLo: field.contentLo, contentHi: field.contentHi, @@ -976,6 +982,9 @@ func (table *Table) paintSortableHeaderCell( } const iconSize, gap = tableSortIconSize, tableSortIconGap label := canvas.FitLine(cell.Label, size, gfx.WeightMedium, max(textBounds.Width-iconSize-gap, 0)) + if label != "" && label != cell.Label { + canvas.HoverHint(0, textBounds, cell.Label, cell.ID) + } labelWidth := min(canvas.TextWidthWeight(label, size, gfx.WeightMedium), max(textBounds.Width-iconSize-gap, 0)) groupWidth := min(labelWidth+gap+iconSize, max(textBounds.Width, 0)) switch column.Alignment { diff --git a/components/chart_area.go b/components/chart_area.go index fddd7a983..d0d8d2aba 100644 --- a/components/chart_area.go +++ b/components/chart_area.go @@ -502,8 +502,7 @@ func chartBeginFrame(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, spec // Edge ticks remain anchored to their data, but their labels must // fit inside the chart container rather than spill into a neighbor. x := min(max(plot.X+frac*plot.Width-width/2, area.X), area.X+area.Width-width) - text = canvas.FitLine(text, fontSize, gfx.WeightRegular, width) - canvas.Label(text, gfx.Rect{X: x, Y: plot.Y + plot.Height + chartAxisGap*scale, Width: width, Height: rowHeight}, labelStyle) + labelEllipsis(canvas, text, gfx.Rect{X: x, Y: plot.Y + plot.Height + chartAxisGap*scale, Width: width, Height: rowHeight}, labelStyle, gfx.ID{}) } } return chartFrame{layout: layout, plot: ChartPlot{ChartLayout: layout, Plot: plot, geo: geo}, scale: scale} diff --git a/components/combobox.go b/components/combobox.go index 4f0a2e149..a56d27c42 100644 --- a/components/combobox.go +++ b/components/combobox.go @@ -218,9 +218,9 @@ func (combobox *Combobox) AddItem(item ComboboxItem) gfx.Rect { labelWidth = maxLabelWidth } - combobox.canvas.Label(combobox.canvas.FitLine(item.Label, sizeM, gfx.WeightRegular, labelWidth), gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(combobox.canvas, item.Label, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeM, Weight: gfx.WeightRegular, Color: foreground, - }) + }, item.ID) detailX := bounds.X + 8 + labelWidth + 8 detailWidth := comboboxMax(0, bounds.X+8+contentWidth-detailX) @@ -229,9 +229,9 @@ func (combobox *Combobox) AddItem(item ComboboxItem) gfx.Rect { if item.Disabled { detailColor.Alpha *= .5 } - combobox.canvas.Label(combobox.canvas.FitLine(item.Detail, sizeS, gfx.WeightRegular, detailWidth), gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(combobox.canvas, item.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeS, Weight: gfx.WeightRegular, Color: detailColor, - }) + }, item.ID) } } if item.Selected { @@ -454,9 +454,9 @@ func (combobox Combobox) paintInput() { if labelWidth > maxLabelWidth { labelWidth = maxLabelWidth } - canvas.Label(canvas.FitLine(options.Value, sizeM, gfx.WeightRegular, labelWidth), gfx.Rect{X: bounds.X + inset, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(canvas, options.Value, gfx.Rect{X: bounds.X + inset, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeM, Weight: gfx.WeightRegular, Color: foreground, - }) + }, options.InputID) detailX := bounds.X + inset + labelWidth + 8 detailWidth := comboboxMax(0, bounds.X+inset+availableWidth-detailX) if detailWidth > 0 { @@ -464,12 +464,12 @@ func (combobox Combobox) paintInput() { if options.Disabled { detailColor.Alpha *= 0.50 } - canvas.Label(canvas.FitLine(options.Detail, sizeS, gfx.WeightRegular, detailWidth), gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(canvas, options.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeS, Weight: gfx.WeightRegular, Color: detailColor, - }) + }, options.InputID) } } else if options.Query == "" || options.InputID.IsZero() || canvas.Focused() != options.InputID || options.Disabled { - canvas.Label(canvas.FitLine(value, combobox.theme.Metrics.FontSizeM, gfx.WeightRegular, availableWidth), textRect, gfx.TextStyle{Size: combobox.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground}) + labelEllipsis(canvas, value, textRect, gfx.TextStyle{Size: combobox.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground}, options.InputID) } if !options.InputID.IsZero() { canvas.HitWithOptions(options.InputID, bounds, options.Label, gfx.HitOptions{ diff --git a/components/dropdown_menu.go b/components/dropdown_menu.go index 28d413eff..d20a35ae4 100644 --- a/components/dropdown_menu.go +++ b/components/dropdown_menu.go @@ -907,6 +907,9 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { canvas.Label(label, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelWidth, Height: labelHeight}, gfx.TextStyle{ Size: theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, }) + if label != "" && label != item.Label { + canvas.HoverHint(0, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelWidth, Height: labelHeight}, item.Label, item.ID) + } if item.Description != "" { color := theme.MutedForeground if active { @@ -914,10 +917,9 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { } color = dropdownMenuOpacity(color, item.Disabled) width := max(0, bounds.Width-left-right-menu.hitInset) - value := canvas.FitLine(item.Description, theme.Metrics.FontSizeS, gfx.WeightRegular, width) - canvas.Label(value, gfx.Rect{X: bounds.X + left, Y: descriptionY, Width: width, Height: descriptionHeight}, gfx.TextStyle{ + labelEllipsis(canvas, item.Description, gfx.Rect{X: bounds.X + left, Y: descriptionY, Width: width, Height: descriptionHeight}, gfx.TextStyle{ Size: theme.Metrics.FontSizeS, Weight: gfx.WeightRegular, Color: color, - }) + }, item.ID) } menu.declareItemHit(bounds, item) } diff --git a/components/hierarchy_menu.go b/components/hierarchy_menu.go index afafc51ec..42e616c89 100644 --- a/components/hierarchy_menu.go +++ b/components/hierarchy_menu.go @@ -226,7 +226,7 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m } paintChevron(canvas, &hierarchyLeftIcon, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: 16, Height: bounds.Height}, look.Foreground) text := gfx.Rect{X: bounds.X + 32, Y: bounds.Y, Width: max(bounds.Width-40, 0), Height: bounds.Height} - canvas.Label(canvas.FitLine(label, theme.Metrics.FontSizeM, gfx.WeightRegular, text.Width), text, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: look.Foreground}) + labelEllipsis(canvas, label, text, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: look.Foreground}, o.OptionIDs.At(hierarchyBackIndex)) canvas.HitWithOptions(o.OptionIDs.At(hierarchyBackIndex), bounds, label, gfx.HitOptions{Role: gfx.RoleButton, Description: m.Nodes[parent].Path, SkipFocus: true}) menu.top += bounds.Height menu.viewHeight = max(menu.viewHeight-bounds.Height, 0) @@ -261,7 +261,7 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m reserve += 16 } labelWidth := max(rowBounds.Width-reserve, 0) - canvas.Label(canvas.FitLine(info.Name, theme.Metrics.FontSizeM, gfx.WeightRegular, labelWidth), gfx.Rect{X: rowBounds.X + 8, Y: rowBounds.Y, Width: labelWidth, Height: rowBounds.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}) + labelEllipsis(canvas, info.Name, gfx.Rect{X: rowBounds.X + 8, Y: rowBounds.Y, Width: labelWidth, Height: rowBounds.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) switch { case info.Count > 0 && rowBounds.Width >= reserve: chevron := &chevronRightIcon @@ -323,7 +323,7 @@ func paintAction(m *HierarchyMenuState, menu *menuSurface, action HierarchyMenuA } color := look.Foreground label := gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-16, 0), Height: row.Height} - canvas.Label(canvas.FitLine(action.Label, theme.Metrics.FontSizeM, gfx.WeightRegular, label.Width), label, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}) + labelEllipsis(canvas, action.Label, label, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, action.ID) row.Width = max(row.Width-menu.hitInset, 0) canvas.HitWithOptions(action.ID, row, action.Label, gfx.HitOptions{Role: gfx.RoleMenuItem, Disabled: action.Disabled, SkipFocus: true}) }) diff --git a/components/label.go b/components/label.go index 560ca6ffb..cb6632f2d 100644 --- a/components/label.go +++ b/components/label.go @@ -75,3 +75,13 @@ func (label LabelPainter) Paint(text string) { }) } } + +// labelEllipsis keeps the complete value alongside the fitted label. Its +// control may declare its hit after painting; that hit still owns the pointer. +func labelEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx.TextStyle, target gfx.ID) { + shown := canvas.FitLine(value, style.Size, style.Weight, bounds.Width) + canvas.Label(shown, bounds, style) + if shown != "" && shown != value { + canvas.HoverHint(0, bounds, value, target) + } +} diff --git a/components/multi_select.go b/components/multi_select.go index d26f5e694..bd03e243f 100644 --- a/components/multi_select.go +++ b/components/multi_select.go @@ -93,7 +93,11 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M break } chip := gfx.Rect{X: x, Y: bounds.Y + (bounds.Height-22)/2, Width: width, Height: 22} - paintComboboxChip(canvas, theme, chip, ComboboxChip{RemoveID: o.RemoveIDs.At(i), Label: canvas.FitLine(label, theme.Metrics.FontSizeS, gfx.WeightMedium, width-30), Value: value, Disabled: o.Disabled}) + shown := canvas.FitLine(label, theme.Metrics.FontSizeS, gfx.WeightMedium, width-30) + paintComboboxChip(canvas, theme, chip, ComboboxChip{RemoveID: o.RemoveIDs.At(i), Label: shown, Value: value, Disabled: o.Disabled}) + if shown != "" && shown != label { + canvas.HoverHint(0, gfx.Rect{X: chip.X + comboboxChipPad, Y: chip.Y, Width: chip.Width - comboboxChipPad - comboboxChipRemove, Height: chip.Height}, label) + } x += width + 5 } if layout.Hidden > 0 { @@ -180,8 +184,7 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M } label = text } - label = canvas.FitLine(label, theme.Metrics.FontSizeM, gfx.WeightRegular, max(row.Width-38, 0)) - canvas.Label(label, gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-38, 0), Height: row.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}) + labelEllipsis(canvas, label, gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-38, 0), Height: row.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) if choice.Selected { paintCheck(canvas, gfx.Rect{X: row.X + row.Width - 25, Y: row.Y, Width: 16, Height: row.Height}, 14, color) } diff --git a/components/select.go b/components/select.go index f64c5b583..4087e4086 100644 --- a/components/select.go +++ b/components/select.go @@ -355,9 +355,9 @@ func (selectControl Select) paintTrigger() { if options.Weight > 0 { weight = options.Weight } - canvas.Label(value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(canvas, value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: textSize, Weight: weight, Color: foreground, - }) + }, options.TriggerID) } paintChevron(canvas, &chevronDownIcon, gfx.Rect{X: bounds.X + bounds.Width - chevronSpan, Y: bounds.Y, Width: selectIconSize, Height: bounds.Height}, chevron) } @@ -386,9 +386,9 @@ func (selectControl *Select) paintItem(bounds gfx.Rect, item SelectItem) { textX += SelectIconSpan textWidth -= SelectIconSpan } - selectControl.canvas.Label(item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + labelEllipsis(selectControl.canvas, item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: selectControl.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, - }) + }, item.ID) if item.Selected { paintCheck(selectControl.canvas, gfx.Rect{X: bounds.X + bounds.Width - 24, Y: bounds.Y, Width: 14, Height: bounds.Height}, 14, foreground) } diff --git a/components/single_select.go b/components/single_select.go index b2ef692b4..f71519751 100644 --- a/components/single_select.go +++ b/components/single_select.go @@ -134,7 +134,7 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * if query == "" && !open { detail = s.Detail(s.ValueText) } - paintLabelAndDetail(canvas, theme, layout.Input.X, layout.Input.Y, layout.Input.Width, layout.Input.Height, display, detail, color, o.Disabled) + paintLabelAndDetail(canvas, theme, layout.Input.X, layout.Input.Y, layout.Input.Width, layout.Input.Height, display, detail, color, o.Disabled, o.InputID) } accessibleValue := query if accessibleValue == "" { @@ -240,7 +240,7 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * if content := choice.Content; content.Paint != nil { content.Paint(canvas, gfx.Rect{X: left, Y: row.Y, Width: labelWidth, Height: row.Height}, theme) } else { - paintLabelAndDetail(canvas, theme, left, row.Y, labelWidth, row.Height, label, choice.Detail, color, choice.Disabled) + paintLabelAndDetail(canvas, theme, left, row.Y, labelWidth, row.Height, label, choice.Detail, color, choice.Disabled, id) } if choice.Selected { paintCheck(canvas, gfx.Rect{X: row.X + row.Width - 25, Y: row.Y, Width: 16, Height: row.Height}, 14, color) @@ -261,21 +261,21 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * // paintLabelAndDetail paints a label in the width it has and, after it, the muted detail in // what is left, as Combobox rows did: the label keeps what it needs up to all but 40 pixels. -func paintLabelAndDetail(canvas *gfx.Canvas, theme gfx.Theme, x, y, width, height float32, label, detail string, color gfx.Color, disabled bool) { +func paintLabelAndDetail(canvas *gfx.Canvas, theme gfx.Theme, x, y, width, height float32, label, detail string, color gfx.Color, disabled bool, target gfx.ID) { sizeM, sizeS := theme.Metrics.FontSizeM, theme.Metrics.FontSizeS if detail == "" { - canvas.Label(canvas.FitLine(label, sizeM, gfx.WeightRegular, width), gfx.Rect{X: x, Y: y, Width: width, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}) + labelEllipsis(canvas, label, gfx.Rect{X: x, Y: y, Width: width, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) return } labelWidth := min(canvas.TextWidthWeight(label, sizeM, gfx.WeightRegular), max(width-40, 0)) - canvas.Label(canvas.FitLine(label, sizeM, gfx.WeightRegular, labelWidth), gfx.Rect{X: x, Y: y, Width: labelWidth, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}) + labelEllipsis(canvas, label, gfx.Rect{X: x, Y: y, Width: labelWidth, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) detailX := x + labelWidth + singleSelectDetailGap if detailWidth := max(x+width-detailX, 0); detailWidth > 0 { muted := theme.MutedForeground if disabled { muted.Alpha *= .5 } - canvas.Label(canvas.FitLine(detail, sizeS, gfx.WeightRegular, detailWidth), gfx.Rect{X: detailX, Y: y, Width: detailWidth, Height: height}, gfx.TextStyle{Size: sizeS, Color: muted}) + labelEllipsis(canvas, detail, gfx.Rect{X: detailX, Y: y, Width: detailWidth, Height: height}, gfx.TextStyle{Size: sizeS, Color: muted}, target) } } diff --git a/components/table.go b/components/table.go index 1e7a06d40..307f9bd75 100644 --- a/components/table.go +++ b/components/table.go @@ -424,6 +424,9 @@ func (table *Table) paintRow(id gfx.ID, cells []string, state TableRowState, kin }) } if text != "" { + if text != value { + table.canvas.HoverHint(0, textBounds, value, id) + } table.canvas.Clip(textBounds) tableLabel(table.canvas, text, textBounds, column.Alignment, style) table.canvas.Unclip() @@ -954,6 +957,9 @@ func (table *Table) paintSortableHeaderCell( style := gfx.TextStyle{Size: size, Weight: gfx.WeightMedium, Color: color} if !interactive { label := canvas.FitLine(cell.Label, size, gfx.WeightMedium, textBounds.Width) + if label != "" && label != cell.Label { + canvas.HoverHint(0, textBounds, cell.Label, cell.ID) + } painted := tableTextCell{ bounds: textBounds, textLo: field.lo, textHi: field.hi, contentLo: field.contentLo, contentHi: field.contentHi, @@ -976,6 +982,9 @@ func (table *Table) paintSortableHeaderCell( } const iconSize, gap = tableSortIconSize, tableSortIconGap label := canvas.FitLine(cell.Label, size, gfx.WeightMedium, max(textBounds.Width-iconSize-gap, 0)) + if label != "" && label != cell.Label { + canvas.HoverHint(0, textBounds, cell.Label, cell.ID) + } labelWidth := min(canvas.TextWidthWeight(label, size, gfx.WeightMedium), max(textBounds.Width-iconSize-gap, 0)) groupWidth := min(labelWidth+gap+iconSize, max(textBounds.Width, 0)) switch column.Alignment { diff --git a/gfx/canvas.go b/gfx/canvas.go index cf1bc4139..8da521315 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -696,6 +696,9 @@ type Canvas struct { texts []Text runs []TextRun hits []Hit + hoverHints []HoverHint + + hoverHintOwner Scope // hitTexts holds the text geometry of the hits that declared any, in // declaration order; Hit.Text is one more than the entry's index. hitTexts []HitText @@ -1030,6 +1033,8 @@ func (canvas *Canvas) Reset() { canvas.texts = canvas.texts[:0] canvas.runs = canvas.runs[:0] canvas.hits = canvas.hits[:0] + canvas.hoverHints = canvas.hoverHints[:0] + canvas.hoverHintOwner = 0 canvas.hitTexts = canvas.hitTexts[:0] canvas.clips = canvas.clips[:0] canvas.overlayClips = canvas.overlayClips[:0] @@ -1078,6 +1083,7 @@ func (canvas *Canvas) Trim() { releaseTail(canvas.images, &canvas.tails.images) releaseTail(canvas.texts, &canvas.tails.texts) releaseTail(canvas.hits, &canvas.tails.hits) + releaseTail(canvas.hoverHints, &canvas.tails.hoverHints) releaseTail(canvas.hitTexts, &canvas.tails.hitTexts) releaseTail(canvas.nativeViews, &canvas.tails.nativeViews) canvas.rectangles = trimCapacity(canvas.rectangles) @@ -1088,6 +1094,7 @@ func (canvas *Canvas) Trim() { canvas.texts = trimCapacity(canvas.texts) canvas.runs = trimCapacity(canvas.runs) canvas.hits = trimCapacity(canvas.hits) + canvas.hoverHints = trimCapacity(canvas.hoverHints) canvas.hitTexts = trimCapacity(canvas.hitTexts) canvas.clips = trimCapacity(canvas.clips) canvas.overlayClips = trimCapacity(canvas.overlayClips) diff --git a/gfx/embed.go b/gfx/embed.go index 347bee4c8..a3483198c 100644 --- a/gfx/embed.go +++ b/gfx/embed.go @@ -142,7 +142,31 @@ func (canvas *Canvas) Embed(child *Canvas, origin Point, mount Scope) { scope := canvas.currentFocusScope() tree := canvas.Tree() - for _, hit := range child.hits { + hintIndex := 0 + appendHints := func(before int) { + for hintIndex < len(child.hoverHints) && int(child.hoverHints[hintIndex].hitAt) <= before { + hint := child.hoverHints[hintIndex] + hintIndex++ + hint.Owner = tree.Mount(mount, hint.Owner) + hint.target = tree.MountID(mount, hint.target) + hint.Bounds = translateRect(hint.Bounds, origin) + if hasOuter { + hint.Bounds = intersectCanvasRect(hint.Bounds, outer) + } + if hint.scope.IsZero() { + hint.scope = scope + } else { + hint.scope = tree.MountID(mount, hint.scope) + } + hint.layer += layer + hint.hitAt = uint32(len(canvas.hits)) + if hint.Bounds.Width > 0 && hint.Bounds.Height > 0 { + canvas.hoverHints = append(canvas.hoverHints, hint) + } + } + } + for index, hit := range child.hits { + appendHints(index) hit.Bounds = translateRect(hit.Bounds, origin) hit.Layer += layer if hasOuter { @@ -169,6 +193,7 @@ func (canvas *Canvas) Embed(child *Canvas, origin Point, mount Scope) { } canvas.hits = append(canvas.hits, hit) } + appendHints(len(child.hits)) if child.motion.animating { canvas.motion.animating = true diff --git a/gfx/hover_hint.go b/gfx/hover_hint.go new file mode 100644 index 000000000..4cde5d88c --- /dev/null +++ b/gfx/hover_hint.go @@ -0,0 +1,87 @@ +package gfx + +// HoverHint is a noninteractive description of text hidden by truncation. It +// has no pointer target, tab stop or accessibility control. Owner is the page +// that paints its tooltip; bounds are clipped and move with the painted text. +type HoverHint struct { + Owner Scope + Bounds Rect + Text string + target ID + layer uint16 + scope ID + hitAt uint32 +} + +// HoverHint declares full text for an ellipsized label or group of labels. It +// does not change pointer routing. A Page paints hints belonging to its owner. +func (canvas *Canvas) HoverHint(owner Scope, bounds Rect, text string, target ...ID) { + if owner.IsZero() { + owner = canvas.hoverHintOwner + } + if owner.IsZero() || text == "" { + return + } + if clip, clipped := canvas.clipSnapshot(); clipped { + bounds = intersectCanvasRect(bounds, clip) + } + if bounds.Width <= 0 || bounds.Height <= 0 { + return + } + hint := HoverHint{ + Owner: owner, Bounds: bounds, Text: text, layer: canvas.currentLayer(), + scope: canvas.currentFocusScope(), hitAt: uint32(len(canvas.hits)), + } + if len(target) > 0 { + hint.target = target[0] + } + canvas.hoverHints = append(canvas.hoverHints, hint) +} + +// SetHoverHintOwner sets the page whose text components are painting and returns +// the previous owner, to restore after a nested page. A zero owner disables +// automatic hints for components painted outside a Page. +func (canvas *Canvas) SetHoverHintOwner(owner Scope) Scope { + previous := canvas.hoverHintOwner + canvas.hoverHintOwner = owner + return previous +} + +// SameText reports whether two hints describe the same visible text. Changes +// to unrelated pointer targets do not restart the tooltip's delay. +func (hint HoverHint) SameText(other HoverHint) bool { + return hint.Owner == other.Owner && hint.Bounds == other.Bounds && hint.Text == other.Text && + hint.layer == other.layer && hint.scope == other.scope && hint.target == other.target +} + +// HoverHintAt returns the frontmost hint owned by owner under the pointer. +// Later controls and opaque overlays cover it just as they cover its text. +func (canvas *Canvas) HoverHintAt(owner Scope, x, y float32) HoverHint { + var best HoverHint + for i := len(canvas.hoverHints) - 1; i >= 0; i-- { + hint := canvas.hoverHints[i] + if hint.Owner != owner || !hintContains(hint.Bounds, x, y) || + !canvas.trappedScope.IsZero() && hint.scope != canvas.trappedScope || + best.Text != "" && hint.layer <= best.layer { + continue + } + covered := false + for k := len(canvas.hits) - 1; k >= 0; k-- { + hit := &canvas.hits[k] + if hit.Container || hit.IsLabel || !hint.target.IsZero() && hit.ID == hint.target || hit.Layer < hint.layer || + hit.Layer == hint.layer && uint32(k) < hint.hitAt || !hintContains(hit.Bounds, x, y) { + continue + } + covered = true + break + } + if !covered { + best = hint + } + } + return best +} + +func hintContains(r Rect, x, y float32) bool { + return x >= r.X && y >= r.Y && x < r.X+r.Width && y < r.Y+r.Height +} diff --git a/gfx/hover_hint_test.go b/gfx/hover_hint_test.go new file mode 100644 index 000000000..b7e5e514a --- /dev/null +++ b/gfx/hover_hint_test.go @@ -0,0 +1,56 @@ +package gfx + +import "testing" + +func TestHoverHintFollowsReplayAndRewind(t *testing.T) { + var canvas Canvas + owner := canvas.Tree().Feature("page") + canvas.KeepPrevious(true) + canvas.Reset() + canvas.BeginFrame() + start := canvas.Mark() + canvas.HitWithLabel(Item(1), Rect{Width: 100, Height: 40}, "row") + canvas.HoverHint(owner, Rect{X: 10, Y: 10, Width: 60, Height: 20}, "Complete filename.txt") + span := canvas.SpanSince(start) + canvas.EndFrame() + + canvas.Reset() + canvas.BeginFrame() + canvas.HitWithLabel(Item(2), Rect{X: 200, Width: 30, Height: 30}, "other") + mark := canvas.Mark() + if _, ok := canvas.ReplayAt(span, 0, 50); !ok { + t.Fatal("the unchanged row could not be replayed") + } + if hint := canvas.HoverHintAt(owner, 20, 65); hint.Text != "Complete filename.txt" || hint.Bounds.Y != 60 { + t.Fatalf("replayed row lost its tooltip: %+v", hint) + } + if hint := canvas.HoverHintAt(owner, 20, 15); hint.Text != "" { + t.Fatal("the tooltip stayed at the row's old position") + } + if !canvas.Rewind(mark) || canvas.HoverHintAt(owner, 20, 65).Text != "" { + t.Fatal("rewinding the row left its tooltip behind") + } + canvas.EndFrame() +} + +func TestHoverHintIsMountedAndClippedWithEmbeddedText(t *testing.T) { + var child, page Canvas + owner := child.Tree().Feature("page") + child.HoverHint(owner, Rect{Width: 80, Height: 20}, "Complete filename.txt", Item(1)) + child.HitWithLabel(Item(1), Rect{Width: 80, Height: 20}, "row") + mount := testMount(&page, 1) + page.Clip(Rect{X: 100, Y: 100, Width: 40, Height: 50}) + page.Embed(&child, Point{X: 100, Y: 100}, mount) + page.Unclip() + mounted := page.Tree().Mount(mount, owner) + if hint := page.HoverHintAt(mounted, 110, 110); hint.Text != "Complete filename.txt" || hint.Bounds != (Rect{X: 100, Y: 100, Width: 40, Height: 20}) { + t.Fatalf("embedded text lost its full value or clip: %+v", hint) + } + if page.HoverHintAt(mounted, 150, 110).Text != "" || page.HoverHintAt(owner, 110, 110).Text != "" { + t.Fatal("the embedded tooltip escaped its clip or page owner") + } + page.Block(Rect{X: 100, Y: 100, Width: 40, Height: 20}) + if page.HoverHintAt(mounted, 110, 110).Text != "" { + t.Fatal("covered text still showed its tooltip") + } +} diff --git a/gfx/pose.go b/gfx/pose.go index 40661c89d..23e23ea3d 100644 --- a/gfx/pose.go +++ b/gfx/pose.go @@ -62,7 +62,7 @@ func (canvas *Canvas) BeginPose(id ID, slot uint8, pose Pose, motion Motion, piv entry: -1, rectangles: len(canvas.rectangles), triangles: len(canvas.triangles), images: len(canvas.images), texts: len(canvas.texts), runs: len(canvas.runs), shadows: len(canvas.shadows), - hits: len(canvas.hits), order: canvas.order, + hits: len(canvas.hits), hoverHints: len(canvas.hoverHints), order: canvas.order, pose: poseTarget{pose: pose, pivot: pivot}, } if state.active && !id.IsZero() { diff --git a/gfx/presence.go b/gfx/presence.go index 3efe73274..47114972e 100644 --- a/gfx/presence.go +++ b/gfx/presence.go @@ -38,6 +38,7 @@ type presenceOpen struct { runs int shadows int hits int + hoverHints int // order is the canvas's last paint order when the group opened. The // snapshot stores its primitives relative to it. order uint32 @@ -152,7 +153,7 @@ func (canvas *Canvas) BeginPresence(id ID, slot uint8, presence Presence, pivot entry: -1, rectangles: len(canvas.rectangles), triangles: len(canvas.triangles), images: len(canvas.images), texts: len(canvas.texts), runs: len(canvas.runs), shadows: len(canvas.shadows), - hits: len(canvas.hits), order: canvas.order, + hits: len(canvas.hits), hoverHints: len(canvas.hoverHints), order: canvas.order, } if state.active && !state.reduce && !id.IsZero() && presence.Motion.Duration > 0 && presence.moves() { now := state.frameTime() @@ -352,7 +353,7 @@ func (snapshot *presenceSnapshot) replay(canvas *Canvas, presence Presence, pivo open := presenceOpen{ rectangles: len(canvas.rectangles), triangles: len(canvas.triangles), images: len(canvas.images), texts: len(canvas.texts), runs: len(canvas.runs), shadows: len(canvas.shadows), - order: canvas.order, + hoverHints: len(canvas.hoverHints), order: canvas.order, } base := canvas.order order := base @@ -602,6 +603,9 @@ func (presence Presence) apply(canvas *Canvas, open presenceOpen, pivot Point, p // border backings into rings first, which a fade that is not complete needs so // the backing does not show through the fill. func (transform presenceTransform) apply(canvas *Canvas, open presenceOpen, fade, vectorize bool) { + for index := open.hoverHints; index < len(canvas.hoverHints); index++ { + canvas.hoverHints[index].Bounds = transform.rect(canvas.hoverHints[index].Bounds) + } moving := transform.scale != 1 || transform.offset != (Point{}) if vectorize { vectorizeBorderBackings(canvas, open.rectangles) diff --git a/gfx/replay.go b/gfx/replay.go index 081745b26..2bb4904fb 100644 --- a/gfx/replay.go +++ b/gfx/replay.go @@ -22,6 +22,7 @@ import "slices" // or ends. type Mark struct { rectangles, triangles, shadows, images, texts, runs, hits, hitTexts, nativeViews uint32 + hoverHints uint32 // epoch is the paint the mark was taken in. epoch uint32 // The clip, layer and focus scope in effect at the mark: what everything the @@ -56,6 +57,7 @@ func (canvas *Canvas) Mark() Mark { shadows: uint32(len(canvas.shadows)), images: uint32(len(canvas.images)), texts: uint32(len(canvas.texts)), runs: uint32(len(canvas.runs)), hits: uint32(len(canvas.hits)), hitTexts: uint32(len(canvas.hitTexts)), + hoverHints: uint32(len(canvas.hoverHints)), nativeViews: uint32(len(canvas.nativeViews)), epoch: canvas.previous.epoch, layer: canvas.currentLayer(), scope: canvas.currentFocusScope(), } @@ -135,6 +137,10 @@ func (canvas *Canvas) ReplayAt(span Span, dx, dy float32) (Span, bool) { } } canvas.nativeViews = append(canvas.nativeViews, old.nativeViews[f.nativeViews:t.nativeViews]...) + for _, hint := range old.hoverHints[f.hoverHints:t.hoverHints] { + hint.hitAt = uint32(int64(hint.hitAt) + int64(from.hits) - int64(f.hits)) + canvas.hoverHints = append(canvas.hoverHints, hint) + } if dx != 0 || dy != 0 { canvas.moveSince(from, dx, dy) } @@ -230,6 +236,9 @@ func (canvas *Canvas) moveSince(from Mark, dx, dy float32) { for i := from.nativeViews; i < uint32(len(canvas.nativeViews)); i++ { canvas.nativeViews[i].Bounds = canvas.nativeViews[i].Bounds.Offset(dx, dy) } + for i := from.hoverHints; i < uint32(len(canvas.hoverHints)); i++ { + canvas.hoverHints[i].Bounds = canvas.hoverHints[i].Bounds.Offset(dx, dy) + } } // Rewind takes back everything painted since to, in this paint: a part that is @@ -240,13 +249,14 @@ func (canvas *Canvas) Rewind(to Mark) bool { if to.epoch != canvas.previous.epoch || int(to.rectangles) > len(canvas.rectangles) || int(to.triangles) > len(canvas.triangles) || int(to.shadows) > len(canvas.shadows) || int(to.images) > len(canvas.images) || int(to.texts) > len(canvas.texts) || int(to.runs) > len(canvas.runs) || int(to.hits) > len(canvas.hits) || int(to.hitTexts) > len(canvas.hitTexts) || - int(to.nativeViews) > len(canvas.nativeViews) { + int(to.nativeViews) > len(canvas.nativeViews) || int(to.hoverHints) > len(canvas.hoverHints) { return false } clear(canvas.texts[to.texts:]) // their strings are not kept past the rewind clear(canvas.hits[to.hits:]) clear(canvas.hitTexts[to.hitTexts:]) clear(canvas.images[to.images:]) + clear(canvas.hoverHints[to.hoverHints:]) canvas.rectangles = canvas.rectangles[:to.rectangles] canvas.triangles = canvas.triangles[:to.triangles] canvas.shadows = canvas.shadows[:to.shadows] @@ -256,6 +266,7 @@ func (canvas *Canvas) Rewind(to Mark) bool { canvas.hits = canvas.hits[:to.hits] canvas.hitTexts = canvas.hitTexts[:to.hitTexts] canvas.nativeViews = canvas.nativeViews[:to.nativeViews] + canvas.hoverHints = canvas.hoverHints[:to.hoverHints] kept := canvas.motion.hitMotions[:0] for _, entry := range canvas.motion.hitMotions { if entry.index < int(to.hits) { @@ -328,6 +339,7 @@ func (canvas *Canvas) SameAsPrevious(span, prev Span, dx, dy float32) bool { scratch.hits = append(scratch.hits, canvas.hits[:span.from.hits]...) scratch.hitTexts = append(scratch.hitTexts, canvas.hitTexts[:span.from.hitTexts]...) scratch.nativeViews = append(scratch.nativeViews, canvas.nativeViews[:span.from.nativeViews]...) + scratch.hoverHints = append(scratch.hoverHints, canvas.hoverHints[:span.from.hoverHints]...) prev.from.clip, prev.from.clipped, prev.from.layer, prev.from.scope = span.from.clip, span.from.clipped, span.from.layer, span.from.scope copied, ok := scratch.ReplayAt(prev, dx, dy) if !ok { @@ -341,6 +353,7 @@ func (canvas *Canvas) SameAsPrevious(span, prev Span, dx, dy float32) bool { slices.Equal(canvas.runs[span.from.runs:span.to.runs], scratch.runs[copied.from.runs:]) && slices.EqualFunc(canvas.hits[span.from.hits:span.to.hits], scratch.hits[copied.from.hits:copied.to.hits], sameHit) && slices.Equal(canvas.hitTexts[span.from.hitTexts:span.to.hitTexts], scratch.hitTexts[copied.from.hitTexts:copied.to.hitTexts]) && + slices.Equal(canvas.hoverHints[span.from.hoverHints:span.to.hoverHints], scratch.hoverHints[copied.from.hoverHints:copied.to.hoverHints]) && slices.Equal(canvas.nativeViews[span.from.nativeViews:span.to.nativeViews], scratch.nativeViews[copied.from.nativeViews:]) } @@ -372,6 +385,7 @@ type primitiveLists struct { texts []Text runs []TextRun hits []Hit + hoverHints []HoverHint hitTexts []HitText nativeViews []NativeView } @@ -413,6 +427,9 @@ func (lists *primitiveLists) extent(span Span) (Rect, bool) { for _, v := range lists.nativeViews[f.nativeViews:t.nativeViews] { grow(v.Bounds) } + for _, hint := range lists.hoverHints[f.hoverHints:t.hoverHints] { + grow(hint.Bounds) + } return out, have } @@ -421,7 +438,8 @@ func (lists *primitiveLists) holds(span Span) bool { return int(t.rectangles) <= len(lists.rectangles) && int(t.triangles) <= len(lists.triangles) && int(t.shadows) <= len(lists.shadows) && int(t.images) <= len(lists.images) && int(t.texts) <= len(lists.texts) && int(t.runs) <= len(lists.runs) && - int(t.hits) <= len(lists.hits) && int(t.hitTexts) <= len(lists.hitTexts) && int(t.nativeViews) <= len(lists.nativeViews) + int(t.hits) <= len(lists.hits) && int(t.hitTexts) <= len(lists.hitTexts) && int(t.nativeViews) <= len(lists.nativeViews) && + int(t.hoverHints) <= len(lists.hoverHints) } // previousPaint is the previous paint's lists, kept for Replay, and the number of @@ -435,7 +453,7 @@ type previousPaint struct { // canvasTails is how long each pointer-holding list of a paint was when the // canvas last trimmed it: what lies past its length up to there is stale. -type canvasTails struct{ images, texts, hits, hitTexts, nativeViews int } +type canvasTails struct{ images, texts, hits, hitTexts, nativeViews, hoverHints int } // releaseTail clears items[len(items):*end], what an earlier paint held past this // one's length, and records this length. Everything past it was cleared before, @@ -464,6 +482,7 @@ func (canvas *Canvas) rotate() { canvas.hits, old.hits = old.hits[:0], canvas.hits canvas.hitTexts, old.hitTexts = old.hitTexts[:0], canvas.hitTexts canvas.nativeViews, old.nativeViews = old.nativeViews[:0], canvas.nativeViews + canvas.hoverHints, old.hoverHints = old.hoverHints[:0], canvas.hoverHints canvas.tails, canvas.previous.tails = canvas.previous.tails, canvas.tails } @@ -480,4 +499,5 @@ func (canvas *Canvas) trimPrevious() { old.hits = trimCapacity(old.hits) old.hitTexts = trimCapacity(old.hitTexts) old.nativeViews = trimCapacity(old.nativeViews) + old.hoverHints = trimCapacity(old.hoverHints) } diff --git a/gfx/wrap.go b/gfx/wrap.go index 2e9897a71..07535766e 100644 --- a/gfx/wrap.go +++ b/gfx/wrap.go @@ -52,9 +52,14 @@ type EllipsisCache struct { width float32 result string filled bool + truncated bool // the most recent wrapping stopped at its line limit generation uint32 // the canvas's FontGeneration when result was cut } +// Truncated reports whether the last WrapLinesCached or WrapLinesStyle call +// using cache omitted text. A literal ellipsis in the input is not truncation. +func (cache *EllipsisCache) Truncated() bool { return cache != nil && cache.truncated } + // WrapLinesCached is WrapLines that takes the ellipsized last line from cache when // it is the one wanted, and stores it there when it is not. A nil cache builds the // string every time. @@ -106,6 +111,9 @@ func (canvas *Canvas) widthIn(value string, font lineFont) float32 { // wrapLines is WrapLinesStyle in font. func (canvas *Canvas) wrapLines(dst []string, value string, font lineFont, width float32, maxLines int, cache *EllipsisCache) []string { + if cache != nil { + cache.truncated = false + } if maxLines <= 0 || width <= 0 { return dst } @@ -122,6 +130,9 @@ func (canvas *Canvas) wrapLines(dst []string, value string, font lineFont, width break } if last { + if cache != nil { + cache.truncated = true + } return append(dst, canvas.ellipsizeCached(line, font, width, cache)) } cut := breakPoint(line, fit) diff --git a/ui/multiselect/multiselect_test.go b/ui/multiselect/multiselect_test.go index 57db2a4c9..020f6be1d 100644 --- a/ui/multiselect/multiselect_test.go +++ b/ui/multiselect/multiselect_test.go @@ -1,6 +1,7 @@ package multiselect_test import ( + "strings" "testing" "github.com/vivaui/viva/app" @@ -11,6 +12,42 @@ import ( "github.com/vivaui/viva/window" ) +func TestEllipsizedChipKeepsItsFullLabelAndRemoveButton(t *testing.T) { + h := open(t) + const full = "Development-with-a-complete-long-name" + h.state.SetOptions([]base.MultiSelectOption{{Value: "dev", Label: full}}) + h.state.SetValues([]string{"dev"}) + h.repaint() + var text gfx.Rect + for _, label := range h.drv.Snapshot().Labels { + if strings.HasSuffix(label.Value, "…") { + text = label.Bounds + break + } + } + if text.Width == 0 { + t.Fatal("the selected chip did not ellipsize") + } + if err := h.drv.Move(text.X+2, text.Y+text.Height/2); err != nil { + t.Fatal(err) + } + var tip string + for _, label := range h.drv.Snapshot().Labels { + if label.Layer == ui.TooltipLayer { + tip += label.Value + } + } + if tip != full { + t.Fatalf("chip tooltip %q, want %q", tip, full) + } + if err := h.drv.Click(center(h.hit(h.rem.At(0)).Bounds)); err != nil { + t.Fatal(err) + } + if len(h.state.Values()) != 0 { + t.Fatal("the text hint intercepted the remove button") + } +} + type harness struct { t *testing.T state *base.MultiSelectState diff --git a/ui/tooltip_paint.go b/ui/tooltip_paint.go index 41aea3137..829b3f027 100644 --- a/ui/tooltip_paint.go +++ b/ui/tooltip_paint.go @@ -1,23 +1,57 @@ package ui import ( + "time" + "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" ) +type tooltipState struct { + components.HoverTooltip + text gfx.HoverHint + since time.Duration + suppressed bool +} + // paintTooltip paints the Tooltip of the element the pointer rests on, over // everything the frame painted. func paintTooltip(f *Frame) { if f.Surface == nil { return } + if page := f.GetPage(); page != nil { + if text := page.HoveredText(); text.Text != "" { + state := frameTooltipState(f) + if !state.text.SameText(text) { + state.text, state.since, state.suppressed = text, f.Surface.Now(), false + state.HoverTooltip = components.HoverTooltip{} + } + if page.PointerDown() || !f.Surface.Pressed().IsZero() { + state.suppressed = true + } + if state.suppressed { + return + } + if remaining := f.Palette.TooltipDelay - (f.Surface.Now() - state.since); remaining > 0 { + f.Surface.RequestFrameIn(remaining) + return + } + components.BeginTooltip(f.Surface, f.Palette, f.GetBounds(), text.Bounds, + components.TooltipOptions{Layer: TooltipLayer, Side: components.TooltipBottom}).Paint(text.Text) + return + } + } + if state, _ := f.GetTooltip().(*tooltipState); state != nil { + state.text, state.suppressed = gfx.HoverHint{}, false + } // The element a tooltip belongs to: the one the pointer rests on, or the one a finger // held (the press that opens it, then the element it stays for). target := f.Surface.Hovered() if event, _, ok := f.Surface.PointerPass(); ok && event.Device == gfx.PointerTouch && event.Kind == gfx.PointerDown && event.Button == gfx.PointerButtonSecondary { target = event.Target - } else if state, _ := f.GetTooltip().(*components.HoverTooltip); state != nil && !state.Holding().IsZero() { + } else if state, _ := f.GetTooltip().(*tooltipState); state != nil && !state.Holding().IsZero() { target = state.Holding() } if !f.HasTooltip(target) { @@ -32,10 +66,10 @@ func paintTooltip(f *Frame) { // tooltipState is the tooltip state the layer above owns; the engine only keeps // it between paints. -func frameTooltipState(f *Frame) *components.HoverTooltip { - state, _ := f.GetTooltip().(*components.HoverTooltip) +func frameTooltipState(f *Frame) *tooltipState { + state, _ := f.GetTooltip().(*tooltipState) if state == nil { - state = new(components.HoverTooltip) + state = new(tooltipState) f.SetTooltipValue(state) } return state diff --git a/ui/tooltip_test.go b/ui/tooltip_test.go index 2fb9c1284..26fdab27e 100644 --- a/ui/tooltip_test.go +++ b/ui/tooltip_test.go @@ -1,6 +1,7 @@ package ui_test import ( + "strings" "testing" "time" @@ -9,6 +10,199 @@ import ( "github.com/vivaui/viva/ui" ) +func textTooltip(d *pageDriver) string { + var lines []string + for _, label := range d.driver.Snapshot().Labels { + if label.Layer == ui.TooltipLayer { + lines = append(lines, label.Value) + } + } + return strings.Join(lines, "") +} + +// An ellipsized label keeps its complete value available without taking the +// hit, focus or click of the row that contains it. A memo must keep that value. +func TestEllipsisTooltip(t *testing.T) { + for _, memo := range []bool{false, true} { + t.Run(map[bool]string{false: "plain", true: "memo"}[memo], func(t *testing.T) { + const full = "完整文件名称-with-a-long-extension.txt" + width := float32(100) + clicks := 0 + var label ui.Box + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(40).Gap(20).Children(func() { + row := func() { + if ui.Row(c).Width(width).HitWith(ui.ID(c), "Open file", gfx.HitOptions{Role: gfx.RoleButton}).Children(func() { + label = ui.Text(c, full).Ellipsis() + }).Clicked() { + clicks++ + } + } + if memo { + ui.Memo(c, width, row) + } else { + row() + } + ui.Text(c, "Already complete…").Ellipsis() + }) + }) + d.repaint() // allow the memo to replay while the pointer is elsewhere + if err := d.driver.Move(center(d.hit("Open file").Bounds)); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != full { + t.Fatalf("tooltip %q, want %q", got, full) + } + if got := d.driver.Snapshot().Hovered; got != d.hit("Open file").ID { + t.Fatalf("text took the row's pointer: %v", got) + } + d.click("Open file") + if clicks != 1 || textTooltip(d) != "" { + t.Fatalf("clicks %d, tooltip after click %q", clicks, textTooltip(d)) + } + if err := d.driver.Move(300, 300); err != nil { + t.Fatal(err) + } + if textTooltip(d) != "" { + t.Fatal("tooltip followed the pointer away") + } + width = 390 + d.repaint() + if err := d.driver.Move(center(label.Rect())); err != nil { + t.Fatal(err) + } + if textTooltip(d) != "" { + t.Fatal("complete text still has an overflow tooltip") + } + }) + } +} + +func TestEllipsisTooltipWithoutAHit(t *testing.T) { + theme := ui.LightTheme() + theme.TooltipDelay = 500 * time.Millisecond + var first, second ui.Box + d := openPageWith(t, ui.PageConfig{Theme: &theme, View: func(c ui.C) { + ui.Column(c).Pad(40).Gap(20).Children(func() { + first = ui.Text(c, "First complete filename.txt").Width(80).Ellipsis() + second = ui.Text(c, "Second complete filename.txt").Width(80).Ellipsis() + }) + }}, app.Config{}) + if err := d.driver.Move(center(first.Rect())); err != nil { + t.Fatal(err) + } + if textTooltip(d) != "" { + t.Fatal("tooltip appeared before its delay") + } + if err := d.driver.Advance(600 * time.Millisecond); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "First complete filename.txt" { + t.Fatalf("first tooltip %q", got) + } + if err := d.driver.Move(center(second.Rect())); err != nil { + t.Fatal(err) + } + if textTooltip(d) != "" { + t.Fatal("moving to a different label did not restart the delay") + } + if err := d.driver.Advance(600 * time.Millisecond); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "Second complete filename.txt" { + t.Fatalf("second tooltip %q", got) + } +} + +func TestEllipsisTooltipClippingAndExistingHint(t *testing.T) { + const full = "Complete filename before the suffix.txt" + var text ui.Box + covered := false + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(40).Children(func() { + ui.Row(c).Width(60).Height(30).Clip().HitWith(ui.ID(c), "Row", gfx.HitOptions{Role: gfx.RoleButton}).Tooltip("Open file").Children(func() { + text = ui.Text(c, full).Width(100).Shrink(0).Ellipsis() + }) + ui.Text(c, "Already complete…").Ellipsis() + if covered { + ui.Row(c).Absolute().Left(0).Top(0).Size(200, 200).HitWith(ui.ID(c), "Cover", gfx.HitOptions{Role: gfx.RoleButton}) + } + }) + }) + if err := d.driver.Move(45, text.Rect().Y+5); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != full { + t.Fatalf("visible text tooltip %q", got) + } + if err := d.driver.Move(45, text.Rect().Y+27); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "Open file" { + t.Fatalf("row's original hint %q", got) + } + if err := d.driver.Move(120, text.Rect().Y+5); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "" { + t.Fatalf("clipped text tooltip %q", got) + } + if err := d.driver.Move(45, text.Rect().Y+5); err != nil { + t.Fatal(err) + } + covered = true + d.repaint() + if err := d.driver.Move(46, text.Rect().Y+5); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "" { + t.Fatalf("covered text tooltip %q", got) + } +} + +func TestMaxLinesTooltipAndLiteralEllipsis(t *testing.T) { + const full = "First line\nSecond line\nThird line" + var paragraph, complete ui.Box + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(40).Gap(30).Children(func() { + paragraph = ui.Text(c, full).Width(220).MaxLines(2) + complete = ui.Text(c, "Already complete…").Ellipsis() + }) + }) + if err := d.driver.Move(center(paragraph.Rect())); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "First lineSecond lineThird line" { + t.Fatalf("paragraph tooltip %q", got) + } + if err := d.driver.Move(center(complete.Rect())); err != nil { + t.Fatal(err) + } + if textTooltip(d) != "" { + t.Fatal("a literal ellipsis was mistaken for truncation") + } +} + +func TestOverflowTooltipKeepsCheckboxCaptionClickable(t *testing.T) { + const full = "Trust all projects in /workspace/long-directory/projects" + checked := false + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(40).Children(func() { + ui.Checkbox(c, &checked, "Trust /workspace/…/projects").OverflowTooltip(full) + }) + }) + if err := d.driver.Move(center(d.hit("Trust /workspace/…/projects").Bounds)); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != full { + t.Fatalf("checkbox tooltip %q, want %q", got, full) + } + d.click("Trust /workspace/…/projects") + if !checked || textTooltip(d) != "" { + t.Fatalf("checked %v, tooltip after click %q", checked, textTooltip(d)) + } +} + // tooltipShown reports whether the frame shows text in a tooltip: a label with // that text and no control of that name. func tooltipShown(d *pageDriver, Text string) bool { From 8ac9b9060d4e50c292f71d5a38efb35c2a4c991c Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 26 Nov 2026 16:02:30 +0800 Subject: [PATCH 2/7] feat(ui): make the ellipsis tooltip opt-in Showing the complete value of shortened text changed every existing app, since every Ellipsis and MaxLines text grew a hover tip. It is now off by default, as Arco's ellipsis.showTooltip is: PageConfig.EllipsisTooltips turns it on for a page and Box.EllipsisTooltip(on) turns it on or off for an element and what it holds, the nearest one winning. A Popup follows the element it hangs off, or the element it was declared in when it is placed by a rectangle or a point. Components see the setting as the canvas's hover hint owner, which stays zero where the tooltips are off, so Table cells, menu items and chips register no hint there. Select keeps clipping its value at the bounds, as before, unless the tooltip can show the rest. A Memo redeclares when the setting it was painted under changes. OverflowTooltip is the caller's own opt-in and keeps working on any page. The documentation says what keyboard and screen reader users get: only the pointer shows the tip, and a control keeps its complete name and value in the accessibility tree whatever its drawing shortens. Over the text, the tip takes the place of the Tooltip of the element the text is in. --- base/box.go | 3 +- base/ellipsis_tooltip.go | 86 +++++++++++++ base/frame.go | 19 ++- base/memo.go | 5 +- base/page.go | 10 ++ base/paint.go | 16 ++- base/text_wrap.go | 2 +- base/tooltip.go | 8 +- cmd/viva/templates/label.go.txt | 12 ++ cmd/viva/templates/select.go.txt | 4 +- components/label.go | 12 ++ components/select.go | 4 +- gfx/hover_hint.go | 8 +- ui/multiselect/multiselect_test.go | 28 +++- ui/tooltip_test.go | 200 ++++++++++++++++++++++++++++- 15 files changed, 394 insertions(+), 23 deletions(-) create mode 100644 base/ellipsis_tooltip.go diff --git a/base/box.go b/base/box.go index 7d67fd7cb..b6b85c8f8 100644 --- a/base/box.go +++ b/base/box.go @@ -430,7 +430,8 @@ func (b Box) MonoFace(Face gfx.MonoFace) Box { // Ellipsis keeps a Text to one line and ends it with an ellipsis when it does not // fit the width it gets, instead of clipping it. It is Paragraph(value, 1). -// In a Page, hovering truncated text shows its complete value in a tooltip. +// A page with EllipsisTooltips, or an EllipsisTooltip on the Text or around it, +// shows the complete value in a tooltip while the pointer rests on the text. func (b Box) Ellipsis() Box { n := b.N() n.Flags |= flagWrap diff --git a/base/ellipsis_tooltip.go b/base/ellipsis_tooltip.go new file mode 100644 index 000000000..3d36f4f8d --- /dev/null +++ b/base/ellipsis_tooltip.go @@ -0,0 +1,86 @@ +package base + +import ( + "slices" + + "github.com/vivaui/viva/gfx" +) + +// What EllipsisTooltip set on an element; zero is what the element is inside. +const ( + ellipsisTipOn uint8 = 1 + iota + ellipsisTipOff +) + +// popupFrom is the element a Popup was declared in, which it takes no room in +// but follows for EllipsisTooltip when it hangs off no element. +type popupFrom struct{ popup, from int32 } + +// EllipsisTooltip turns on, or with false off, the tooltip that shows the +// complete value of text shortened with an ellipsis, for the element and what +// it holds: a Text cut by Ellipsis or MaxLines, and the labels components +// shorten themselves, such as Table cells, Select values and menu items. It +// overrides PageConfig.EllipsisTooltips and an EllipsisTooltip further out. A +// Popup follows the element it hangs off (BelowBox and the like) or, placed by +// a rectangle or a point, the element it was declared in. +// +// ui.Text(c, path).Ellipsis().EllipsisTooltip(true) +// ui.Table(c, &table, spec).EllipsisTooltip(true) +func (b Box) EllipsisTooltip(on bool) Box { + b.N() + tip := ellipsisTipOff + if on { + tip = ellipsisTipOn + } + b.f.Extra(b.i).ellipsisTip = tip + b.f.ellipsisSet = true + return b +} + +// setEllipsisTips sets whether what is painted next shows the tooltips +// EllipsisTooltip describes, and returns what it was. Components see it as the +// canvas's hover hint owner, which is zero while it is off. +func (f *Frame) setEllipsisTips(on bool) bool { + was := f.ellipsisTips + if on != was && f.page != nil && f.Surface != nil { + f.ellipsisTips = on + var owner gfx.Scope + if on { + owner = f.page.root + } + f.Surface.SetHoverHintOwner(owner) + } + return was +} + +// ellipsisTipsAt reports whether element i shows the tooltips: the nearest +// EllipsisTooltip on it or on what it is inside, or else the page's setting. +func (f *Frame) ellipsisTipsAt(i int32) bool { + for steps := 0; i >= 0 && steps < len(f.Nodes); steps++ { + n := &f.Nodes[i] + if tip := f.Exts[n.Ext].ellipsisTip; tip != 0 { + return tip == ellipsisTipOn + } + switch { + case n.Parent >= 0: + i = n.Parent + case n.AnchorRef > 0: + i = n.AnchorRef - 1 + default: + i = f.popupParent(i) + } + } + return f.page != nil && f.page.config.EllipsisTooltips +} + +// popupParent is the element Popup i was declared in, or -1 for the root and +// for a popup declared outside every container. +func (f *Frame) popupParent(i int32) int32 { + at, found := slices.BinarySearchFunc(f.popupFrom, i, func(p popupFrom, i int32) int { + return int(p.popup - i) + }) + if !found { + return -1 + } + return f.popupFrom[at].from +} diff --git a/base/frame.go b/base/frame.go index 1f32e712c..5483bd941 100644 --- a/base/frame.go +++ b/base/frame.go @@ -224,6 +224,7 @@ type Extra struct { Draws int32 // 1 + the index of the element's Draw and DrawOver callbacks in frame.draws, or 0 for none tooltip string // what Tooltip says over the element; empty for none overflowTip string // full text already shortened by the application + ellipsisTip uint8 // EllipsisTooltip: ellipsisTipOn or ellipsisTipOff; zero follows what the element is inside tooltipSide uint8 // 1 + the TooltipSide TooltipOn opens the element's tip on; 0 is below addons int32 // 1 + the index of the field's icon and button in frame.addons, or 0 focusGroup FocusAxis // FocusGroup: the arrow keys that move the focus between the controls inside; zero is none @@ -266,6 +267,7 @@ type Frame struct { Images []gfx.Bitmap // what each Image element draws, indexed by its aux Exts []Extra // exts[0] is never written: an element without extras points at it Floats []int32 // the Popups, which belong to no container + popupFrom []popupFrom // where each Popup was declared, in declaration order hidden []int32 // the elements Hide was called on, taken out of the page at End States []stateLooks // what Hover, Pressed and Focus declared, by element Draws []drawHooks // what Draw and DrawOver declared, by element @@ -279,6 +281,8 @@ type Frame struct { Stops []gfx.GradientStop // their stops, in the order declared paintStops []gfx.GradientStop // the stops of the gradient being painted, faded Opacity float32 // the product of the opacities of the elements being painted + ellipsisTips bool // what is being painted shows the tooltips of EllipsisTooltip + ellipsisSet bool // an element was given EllipsisTooltip: End works out each Popup's popupLayer uint16 // the canvas layer the Popups are painted on nativeMark int // how many native views the canvas had when the page began Binds []bindDecl // the bound controls, see bind.go @@ -362,6 +366,8 @@ func (View *View) Begin(Surface *gfx.Canvas, Palette Theme, bounds Rect) *Frame clear(f.Binds) // a binding holds pointers into the model: not past the frame f.Binds = f.Binds[:0] f.Floats = f.Floats[:0] + f.popupFrom = f.popupFrom[:0] + f.ellipsisSet = false f.hidden = f.hidden[:0] f.States, f.Gradients, f.Stops = f.States[:0], f.Gradients[:0], f.Stops[:0] clear(f.Draws) // a callback holds what it captured: not past the frame it was declared in @@ -432,8 +438,13 @@ func (f *Frame) End() { f.Scrolls.sweep() f.reportSplitters() if f.page != nil { - previous := f.Surface.SetHoverHintOwner(f.page.root) + // Truncated text shows its complete value only where the page or an + // EllipsisTooltip turned the tooltips on; components read it from the + // canvas's hover hint owner. + previous := f.Surface.SetHoverHintOwner(0) defer f.Surface.SetHoverHintOwner(previous) + f.ellipsisTips = false + f.setEllipsisTips(f.page.config.EllipsisTooltips) } f.PaintChild(0) f.raiseOverNativeViews() @@ -441,8 +452,12 @@ func (f *Frame) End() { f.Surface.PushLayer(f.popupLayer) } for _, index := range f.Floats { + if f.ellipsisSet { + f.setEllipsisTips(f.ellipsisTipsAt(index)) + } f.PaintChild(index) } + f.ellipsisTips = false if f.popupLayer != 0 { f.Surface.PopLayer() } @@ -485,6 +500,7 @@ func (f *Frame) trim() { f.Draws = trimFlexCapacity(f.Draws) f.Binds = trimFlexCapacity(f.Binds) f.Floats = trimFlexCapacity(f.Floats) + f.popupFrom = trimFlexCapacity(f.popupFrom) f.hidden = trimFlexCapacity(f.hidden) f.Lines = trimFlexCapacity(f.Lines) f.Ellipses = trimFlexCapacity(f.Ellipses) @@ -563,6 +579,7 @@ func (f *Frame) Popup() Box { b := f.Box(kindContainer) f.Parent = saved f.Floats = append(f.Floats, b.i) + f.popupFrom = append(f.popupFrom, popupFrom{popup: b.i, from: saved}) return b } diff --git a/base/memo.go b/base/memo.go index da470c631..7b4ea33fa 100644 --- a/base/memo.go +++ b/base/memo.go @@ -127,6 +127,7 @@ type memoEntry struct { cell any // *memoCell[T] of the value the part was last declared with themeEpoch uint32 // the page's theme when the part was last painted Opacity float32 // the inherited opacity then + tips bool // whether EllipsisTooltip's tooltips were on then scale float32 // the canvas's pixel scale then fonts uint32 // the canvas's font generation then epoch uint32 // the paint the part was last declared or copied in @@ -205,7 +206,7 @@ func (p *Page) memoPaint(f *Frame, i int32, before bool) bool { canvas := f.Surface rect := f.Nodes[i].Rect if box.copy { - if entry.themeEpoch != p.themeEpoch || entry.Opacity != f.Opacity { + if entry.themeEpoch != p.themeEpoch || entry.Opacity != f.Opacity || entry.tips != f.ellipsisTips { entry.stale = true p.retry = true return true @@ -231,7 +232,7 @@ func (p *Page) memoPaint(f *Frame, i int32, before bool) bool { entry.Span = canvas.SpanSince(box.before) entry.listens = len(canvas.HitsSince(box.before)) > 0 entry.Rect, entry.bounds, entry.painted, entry.stale = rect, f.bounds, true, false - entry.themeEpoch, entry.Opacity = p.themeEpoch, f.Opacity + entry.themeEpoch, entry.Opacity, entry.tips = p.themeEpoch, f.Opacity, f.ellipsisTips hovered, pressed, focused := canvas.Hovered(), canvas.Pressed(), canvas.Focused() for _, hit := range canvas.HitsSince(box.before) { if !hit.ID.IsZero() && (hit.ID == hovered || hit.ID == pressed || hit.ID == focused) { diff --git a/base/page.go b/base/page.go index e7f56602e..085d6d463 100644 --- a/base/page.go +++ b/base/page.go @@ -222,6 +222,16 @@ type PageConfig struct { // keeps the thin hover default. It is the page's one place for the weight its // bars share. ScrollbarSize float32 + // EllipsisTooltips shows the complete value of text shortened with an + // ellipsis in a tooltip while the pointer rests on it: a Text cut by Ellipsis + // or MaxLines, and the labels components shorten themselves, such as Table + // cells, Select values and menu items. It is off by default, which paints + // such text as before; Box.EllipsisTooltip turns it on or off for part of the + // page. Over the text, this tooltip takes the place of the Tooltip of the + // element the text is in. Only the pointer shows it, not keyboard focus; it is + // not in the accessibility tree, where a control keeps its complete name and + // value whatever its drawing shortens. + EllipsisTooltips bool // Invalidator wakes the window the page is drawn in when an Effect of the page // finishes. Configure uses it instead of the app.Config's; a page the application // draws into a window of its own (Draw, not Paint) needs it, since only Config diff --git a/base/paint.go b/base/paint.go index 20ea4ff09..90296ee4c 100644 --- a/base/paint.go +++ b/base/paint.go @@ -5,7 +5,21 @@ import ( controlstyle "github.com/vivaui/viva/style" ) +// PaintChild paints element i and what it holds. func (f *Frame) PaintChild(i int32) { + // An EllipsisTooltip changes the setting for the element's subtree only. + // It is restored here, not by a deferred call in paintElement, whose other + // defers would stop being open-coded. + if tip := f.Exts[f.Nodes[i].Ext].ellipsisTip; tip != 0 { + was := f.setEllipsisTips(tip == ellipsisTipOn) + f.paintElement(i) + f.setEllipsisTips(was) + return + } + f.paintElement(i) +} + +func (f *Frame) paintElement(i int32) { n := &f.Nodes[i] if !n.FocusScope.IsZero() { // A menu's page controls paint in the menu's focus scope, so a press on @@ -383,7 +397,7 @@ func (f *Frame) paintText(n *Node) { f.paintStrike(line, bounds, style, alignment) } } - if n.TextDecor&textTruncated != 0 && f.page != nil && f.Exts[n.Ext].overflowTip == "" { + if n.TextDecor&textTruncated != 0 && f.ellipsisTips && f.Exts[n.Ext].overflowTip == "" { r.Height = min(r.Height, float32(n.LineCount)*lh) f.Surface.HoverHint(f.page.root, r, n.Text) } diff --git a/base/text_wrap.go b/base/text_wrap.go index 0f6c5d16f..7bb974fd6 100644 --- a/base/text_wrap.go +++ b/base/text_wrap.go @@ -82,7 +82,7 @@ func (f *Frame) Wrap(Value string) Box { return f.Paragraph(Value, math.MaxInt32 // MaxLines makes a Text a paragraph of at most n lines, the last ending with an // ellipsis when the text needs more (n of one is Ellipsis); n of zero or less -// takes as many lines as the width needs. +// takes as many lines as the width needs. EllipsisTooltip shows what it cut. func (b Box) MaxLines(n int) Box { node := b.N() node.Flags |= flagWrap diff --git a/base/tooltip.go b/base/tooltip.go index 3f5e99792..0fe61388c 100644 --- a/base/tooltip.go +++ b/base/tooltip.go @@ -12,8 +12,10 @@ const TooltipLayer = 1000 // OverflowTooltip supplies the complete value when an application shortened // the displayed text itself, possibly across several highlighted labels. Call // it only when content was omitted. Unlike Tooltip it declares no control and -// leaves the enclosing row's pointer, focus and accessibility unchanged. Text -// truncated by Ellipsis or MaxLines supplies its complete value automatically. +// leaves the enclosing row's pointer, focus and accessibility unchanged. Giving +// it is the caller's opt-in, so it shows whatever PageConfig.EllipsisTooltips +// says. Text truncated by Ellipsis or MaxLines supplies its complete value +// itself where the page or an EllipsisTooltip turned the tooltips on. func (b Box) OverflowTooltip(text string) Box { b.f.Extra(b.i).overflowTip = text return b @@ -34,6 +36,8 @@ func (p *Page) PointerDown() bool { return p != nil && p.pointerDown } // pointer rests on it, and is its description for assistive technology: what an // icon-only button needs. The tip hides on a press and stays hidden until the // pointer leaves. The element is a control, or a container given an identity. +// While the pointer is over shortened text inside the element whose complete +// value EllipsisTooltip or OverflowTooltip shows, that tip shows instead. // // ui.Button(c, "").Icon(trash).Tooltip("Delete") func (b Box) Tooltip(Text string) Box { diff --git a/cmd/viva/templates/label.go.txt b/cmd/viva/templates/label.go.txt index 25ec39a11..d08c7a090 100644 --- a/cmd/viva/templates/label.go.txt +++ b/cmd/viva/templates/label.go.txt @@ -78,6 +78,7 @@ func (label LabelPainter) Paint(text string) { // labelEllipsis keeps the complete value alongside the fitted label. Its // control may declare its hit after painting; that hit still owns the pointer. +// The hint is dropped where the page leaves its ellipsis tooltips off. func labelEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx.TextStyle, target gfx.ID) { shown := canvas.FitLine(value, style.Size, style.Weight, bounds.Width) canvas.Label(shown, bounds, style) @@ -85,3 +86,14 @@ func labelEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx. canvas.HoverHint(0, bounds, value, target) } } + +// labelOrEllipsis draws a value a control has always clipped at the edge of its +// bounds, as Label does. Where the page shows ellipsis tooltips it ends the value +// with an ellipsis instead, as labelEllipsis does, since the hint shows the rest. +func labelOrEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx.TextStyle, target gfx.ID) { + if canvas.HoverHintOwner().IsZero() { + canvas.Label(value, bounds, style) + return + } + labelEllipsis(canvas, value, bounds, style, target) +} diff --git a/cmd/viva/templates/select.go.txt b/cmd/viva/templates/select.go.txt index 3d8e8af78..da9a08b48 100644 --- a/cmd/viva/templates/select.go.txt +++ b/cmd/viva/templates/select.go.txt @@ -372,7 +372,7 @@ func (selectControl Select) paintTrigger() { if options.Weight > 0 { weight = options.Weight } - labelEllipsis(canvas, value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + labelOrEllipsis(canvas, value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: textSize, Weight: weight, Color: foreground, }, options.TriggerID) } @@ -403,7 +403,7 @@ func (selectControl *Select) paintItem(bounds gfx.Rect, item SelectItem) { textX += SelectIconSpan textWidth -= SelectIconSpan } - labelEllipsis(selectControl.canvas, item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + labelOrEllipsis(selectControl.canvas, item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: selectControl.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, }, item.ID) if item.Selected { diff --git a/components/label.go b/components/label.go index cb6632f2d..a7e4fc1f1 100644 --- a/components/label.go +++ b/components/label.go @@ -78,6 +78,7 @@ func (label LabelPainter) Paint(text string) { // labelEllipsis keeps the complete value alongside the fitted label. Its // control may declare its hit after painting; that hit still owns the pointer. +// The hint is dropped where the page leaves its ellipsis tooltips off. func labelEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx.TextStyle, target gfx.ID) { shown := canvas.FitLine(value, style.Size, style.Weight, bounds.Width) canvas.Label(shown, bounds, style) @@ -85,3 +86,14 @@ func labelEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx. canvas.HoverHint(0, bounds, value, target) } } + +// labelOrEllipsis draws a value a control has always clipped at the edge of its +// bounds, as Label does. Where the page shows ellipsis tooltips it ends the value +// with an ellipsis instead, as labelEllipsis does, since the hint shows the rest. +func labelOrEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx.TextStyle, target gfx.ID) { + if canvas.HoverHintOwner().IsZero() { + canvas.Label(value, bounds, style) + return + } + labelEllipsis(canvas, value, bounds, style, target) +} diff --git a/components/select.go b/components/select.go index 0a57c8c5b..995b4fd5d 100644 --- a/components/select.go +++ b/components/select.go @@ -372,7 +372,7 @@ func (selectControl Select) paintTrigger() { if options.Weight > 0 { weight = options.Weight } - labelEllipsis(canvas, value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + labelOrEllipsis(canvas, value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: textSize, Weight: weight, Color: foreground, }, options.TriggerID) } @@ -403,7 +403,7 @@ func (selectControl *Select) paintItem(bounds gfx.Rect, item SelectItem) { textX += SelectIconSpan textWidth -= SelectIconSpan } - labelEllipsis(selectControl.canvas, item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + labelOrEllipsis(selectControl.canvas, item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: selectControl.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, }, item.ID) if item.Selected { diff --git a/gfx/hover_hint.go b/gfx/hover_hint.go index 4cde5d88c..2b41a8cc8 100644 --- a/gfx/hover_hint.go +++ b/gfx/hover_hint.go @@ -40,13 +40,19 @@ func (canvas *Canvas) HoverHint(owner Scope, bounds Rect, text string, target .. // SetHoverHintOwner sets the page whose text components are painting and returns // the previous owner, to restore after a nested page. A zero owner disables -// automatic hints for components painted outside a Page. +// automatic hints: for components painted outside a Page, and where the page +// leaves its EllipsisTooltips off. func (canvas *Canvas) SetHoverHintOwner(owner Scope) Scope { previous := canvas.hoverHintOwner canvas.hoverHintOwner = owner return previous } +// HoverHintOwner is the page SetHoverHintOwner set, zero when automatic hints +// are off. A component that shortens text only when the hint can show the rest +// reads it. +func (canvas *Canvas) HoverHintOwner() Scope { return canvas.hoverHintOwner } + // SameText reports whether two hints describe the same visible text. Changes // to unrelated pointer targets do not restart the tooltip's delay. func (hint HoverHint) SameText(other HoverHint) bool { diff --git a/ui/multiselect/multiselect_test.go b/ui/multiselect/multiselect_test.go index 020f6be1d..ae9f24f18 100644 --- a/ui/multiselect/multiselect_test.go +++ b/ui/multiselect/multiselect_test.go @@ -31,13 +31,15 @@ func TestEllipsizedChipKeepsItsFullLabelAndRemoveButton(t *testing.T) { if err := h.drv.Move(text.X+2, text.Y+text.Height/2); err != nil { t.Fatal(err) } - var tip string - for _, label := range h.drv.Snapshot().Labels { - if label.Layer == ui.TooltipLayer { - tip += label.Value - } + if tip := h.tooltip(); tip != "" { + t.Fatalf("chip tooltip %q with the tooltips off", tip) } - if tip != full { + h.tips = true + h.repaint() + if err := h.drv.Move(text.X+3, text.Y+text.Height/2); err != nil { + t.Fatal(err) + } + if tip := h.tooltip(); tip != full { t.Fatalf("chip tooltip %q, want %q", tip, full) } if err := h.drv.Click(center(h.hit(h.rem.At(0)).Bounds)); err != nil { @@ -58,6 +60,17 @@ type harness struct { inv *app.Invalidator opts gfx.Scope rem gfx.Scope + tips bool // the picker is given EllipsisTooltip(true) +} + +func (h *harness) tooltip() string { + var tip string + for _, label := range h.drv.Snapshot().Labels { + if label.Layer == ui.TooltipLayer { + tip += label.Value + } + } + return tip } func open(t *testing.T) *harness { @@ -73,6 +86,9 @@ func open(t *testing.T) *harness { h.box = h.pick.View(c, multiselect.Spec{ Label: "Tags", Placeholder: "Add a tag", Options: h.opts, Removes: h.rem, }).Width(260) + if h.tips { + h.box.EllipsisTooltip(true) + } }}) h.inv = new(app.Invalidator) var err error diff --git a/ui/tooltip_test.go b/ui/tooltip_test.go index 26fdab27e..56e2f6cdb 100644 --- a/ui/tooltip_test.go +++ b/ui/tooltip_test.go @@ -20,6 +20,12 @@ func textTooltip(d *pageDriver) string { return strings.Join(lines, "") } +// openTipsPage opens a page with EllipsisTooltips on. +func openTipsPage(t *testing.T, View func(ui.C)) *pageDriver { + t.Helper() + return openPageWith(t, ui.PageConfig{View: View, EllipsisTooltips: true}, app.Config{}) +} + // An ellipsized label keeps its complete value available without taking the // hit, focus or click of the row that contains it. A memo must keep that value. func TestEllipsisTooltip(t *testing.T) { @@ -29,7 +35,7 @@ func TestEllipsisTooltip(t *testing.T) { width := float32(100) clicks := 0 var label ui.Box - d := openPage(t, func(c ui.C) { + d := openTipsPage(t, func(c ui.C) { ui.Column(c).Pad(40).Gap(20).Children(func() { row := func() { if ui.Row(c).Width(width).HitWith(ui.ID(c), "Open file", gfx.HitOptions{Role: gfx.RoleButton}).Children(func() { @@ -82,7 +88,7 @@ func TestEllipsisTooltipWithoutAHit(t *testing.T) { theme := ui.LightTheme() theme.TooltipDelay = 500 * time.Millisecond var first, second ui.Box - d := openPageWith(t, ui.PageConfig{Theme: &theme, View: func(c ui.C) { + d := openPageWith(t, ui.PageConfig{Theme: &theme, EllipsisTooltips: true, View: func(c ui.C) { ui.Column(c).Pad(40).Gap(20).Children(func() { first = ui.Text(c, "First complete filename.txt").Width(80).Ellipsis() second = ui.Text(c, "Second complete filename.txt").Width(80).Ellipsis() @@ -118,7 +124,7 @@ func TestEllipsisTooltipClippingAndExistingHint(t *testing.T) { const full = "Complete filename before the suffix.txt" var text ui.Box covered := false - d := openPage(t, func(c ui.C) { + d := openTipsPage(t, func(c ui.C) { ui.Column(c).Pad(40).Children(func() { ui.Row(c).Width(60).Height(30).Clip().HitWith(ui.ID(c), "Row", gfx.HitOptions{Role: gfx.RoleButton}).Tooltip("Open file").Children(func() { text = ui.Text(c, full).Width(100).Shrink(0).Ellipsis() @@ -164,7 +170,7 @@ func TestMaxLinesTooltipAndLiteralEllipsis(t *testing.T) { const full = "First line\nSecond line\nThird line" var paragraph, complete ui.Box d := openPage(t, func(c ui.C) { - ui.Column(c).Pad(40).Gap(30).Children(func() { + ui.Column(c).Pad(40).Gap(30).EllipsisTooltip(true).Children(func() { paragraph = ui.Text(c, full).Width(220).MaxLines(2) complete = ui.Text(c, "Already complete…").Ellipsis() }) @@ -183,6 +189,192 @@ func TestMaxLinesTooltipAndLiteralEllipsis(t *testing.T) { } } +// A page that does not turn EllipsisTooltips on paints shortened text as it +// did: no tooltip, and a Select clips its value at its edge rather than ending +// it with an ellipsis. OverflowTooltip, given explicitly, still shows. +func TestEllipsisTooltipIsOffByDefault(t *testing.T) { + const full = "Complete configuration name (3)" + value := full + var text ui.Box + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(40).Gap(20).Children(func() { + text = ui.Text(c, "Complete filename before the suffix.txt").Width(80).Ellipsis() + ui.Select(c, &value, []string{full}, nil).Width(112) + }) + }) + if err := d.driver.Move(center(text.Rect())); err != nil { + t.Fatal(err) + } + if err := d.driver.Advance(2 * time.Second); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "" { + t.Fatalf("text tooltip %q with the tooltips off", got) + } + if !tooltipShown(d, full) { + t.Fatal("the Select no longer draws its whole value, clipped") + } + for _, label := range d.driver.Snapshot().Labels { + if strings.HasPrefix(label.Value, "Complete configuration") && strings.HasSuffix(label.Value, "…") { + t.Fatalf("the Select ended its value with an ellipsis: %q", label.Value) + } + } + if err := d.driver.Move(center(selectTrigger(d).Bounds)); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "" { + t.Fatalf("Select tooltip %q with the tooltips off", got) + } +} + +func selectTrigger(d *pageDriver) gfx.Hit { + d.t.Helper() + for _, hit := range d.driver.Snapshot().Hits { + if hit.Role == gfx.RoleCombobox { + return hit + } + } + d.t.Fatal("no Select trigger") + return gfx.Hit{} +} + +// EllipsisTooltip on a Select turns the tooltips on for its trigger and for the +// list that hangs off it. Assistive technology reads the whole value from the +// trigger whatever the drawing shortened. +func TestEllipsisTooltipOnASelectAndItsList(t *testing.T) { + const full = "A complete configuration name far too long for the trigger, and for the list that opens below it" + value := full + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(40).Children(func() { + ui.Select(c, &value, []string{full, "Short"}, nil).Width(112).EllipsisTooltip(true) + }) + }) + trigger := selectTrigger(d) + if trigger.Value != full { + t.Fatalf("trigger's accessible value %q, want the whole value", trigger.Value) + } + if tooltipShown(d, full) { + t.Fatal("the trigger still draws its whole value") + } + if err := d.driver.Move(center(trigger.Bounds)); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); !sameWrapped(got, full) { + t.Fatalf("trigger tooltip %q", got) + } + if err := d.driver.Click(center(trigger.Bounds)); err != nil { + t.Fatal(err) + } + d.repaint() + var row gfx.Hit + for _, hit := range d.driver.Snapshot().Hits { + if hit.Label == full && hit.Role != gfx.RoleCombobox { + row = hit + } + } + if row.Bounds.Width == 0 { + t.Fatal("the list did not open") + } + if err := d.driver.Move(row.Bounds.X+30, row.Bounds.Y+row.Bounds.Height/2); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); !sameWrapped(got, full) { + t.Fatalf("list row tooltip %q", got) + } +} + +// sameWrapped compares a tooltip's lines, joined, with the text it wrapped. +func sameWrapped(lines, text string) bool { + return lines != "" && strings.ReplaceAll(lines, " ", "") == strings.ReplaceAll(text, " ", "") +} + +// EllipsisTooltip changes the setting for an element and what it holds, over +// the page's and over one further out. +func TestEllipsisTooltipFollowsTheSubtree(t *testing.T) { + var off, on ui.Box + d := openTipsPage(t, func(c ui.C) { + ui.Column(c).Pad(40).Gap(20).EllipsisTooltip(false).Children(func() { + off = ui.Text(c, "Off: complete filename before the suffix.txt").Width(80).Ellipsis() + ui.Row(c).EllipsisTooltip(true).Children(func() { + on = ui.Text(c, "On: complete filename before the suffix.txt").Width(80).Ellipsis() + }) + }) + }) + if err := d.driver.Move(center(off.Rect())); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "" { + t.Fatalf("tooltip %q inside EllipsisTooltip(false)", got) + } + if err := d.driver.Move(center(on.Rect())); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "On: complete filename before the suffix.txt" { + t.Fatalf("tooltip %q inside EllipsisTooltip(true)", got) + } +} + +// A Popup placed by a rectangle follows the element it was declared in, not +// the one its rectangle happens to be over. +func TestEllipsisTooltipInAPopupFollowsWhereItWasDeclared(t *testing.T) { + var inside, outside ui.Box + d := openPage(t, func(c ui.C) { + ui.Column(c).EllipsisTooltip(true).Children(func() { + ui.Overlay(c, ui.OverlaySpec{Bounds: gfx.Rect{X: 20, Y: 20, Width: 200, Height: 40}}).Children(func() { + inside = ui.Text(c, "Inside: complete filename before the suffix.txt").Width(80).Ellipsis() + }) + }) + ui.Overlay(c, ui.OverlaySpec{Bounds: gfx.Rect{X: 20, Y: 120, Width: 200, Height: 40}}).Children(func() { + outside = ui.Text(c, "Outside: complete filename before the suffix.txt").Width(80).Ellipsis() + }) + }) + if err := d.driver.Move(center(inside.Rect())); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "Inside: complete filename before the suffix.txt" { + t.Fatalf("tooltip %q in a popup declared inside EllipsisTooltip(true)", got) + } + if err := d.driver.Move(center(outside.Rect())); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "" { + t.Fatalf("tooltip %q in a popup declared outside it", got) + } +} + +// A Memo's copy is painted again when the setting around it changed, so it does +// not bring back the hints of the paint it copies. +func TestEllipsisTooltipSettingRedeclaresAMemo(t *testing.T) { + const full = "Complete filename before the suffix.txt" + on := true + var text ui.Box + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(40).EllipsisTooltip(on).Children(func() { + ui.Memo(c, 1, func() { text = ui.Text(c, full).Width(80).Ellipsis() }) + }) + }) + at := text.Rect() // a copied Memo declares no Box + d.repaint() // the Memo is copied from here on + if err := d.driver.Move(center(at)); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != full { + t.Fatalf("tooltip %q", got) + } + if err := d.driver.Move(300, 300); err != nil { + t.Fatal(err) + } + on = false + d.repaint() + d.repaint() + if err := d.driver.Move(center(at)); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "" { + t.Fatalf("a copied Memo kept tooltip %q after EllipsisTooltip(false)", got) + } +} + func TestOverflowTooltipKeepsCheckboxCaptionClickable(t *testing.T) { const full = "Trust all projects in /workspace/long-directory/projects" checked := false From 6de2dcb5d292a994b6f8c21ed776fc9c1b6023a8 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 26 Nov 2026 16:02:30 +0800 Subject: [PATCH 3/7] test(gfx): benchmark HoverHintAt over many hits A page asks for the hint under the pointer once a frame. The benchmark measures a table whose every row is a hit holding shortened text, with the pointer on the first row's text (every hint and every later hit is walked), beside the text (every hint), and with the tooltips off (no hints). --- gfx/hover_hint_test.go | 51 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/gfx/hover_hint_test.go b/gfx/hover_hint_test.go index b7e5e514a..9efe73a24 100644 --- a/gfx/hover_hint_test.go +++ b/gfx/hover_hint_test.go @@ -1,6 +1,9 @@ package gfx -import "testing" +import ( + "fmt" + "testing" +) func TestHoverHintFollowsReplayAndRewind(t *testing.T) { var canvas Canvas @@ -54,3 +57,49 @@ func TestHoverHintIsMountedAndClippedWithEmbeddedText(t *testing.T) { t.Fatal("covered text still showed its tooltip") } } + +// BenchmarkHoverHintAt is a page asking for the tooltip under the pointer once +// a frame: a table whose every row is a hit holding shortened text. On the first +// row's text the query passes every hint and every hit painted after the row; +// beside the text it passes every hint alone; with the tooltips off the page +// declares no hints at all. +func BenchmarkHoverHintAt(b *testing.B) { + for _, rows := range []int{100, 1000, 10000} { + var canvas Canvas + owner := canvas.Tree().Feature("page") + canvas.Reset() + canvas.BeginFrame() + for index := range rows { + y := float32(index) * 24 + canvas.HitWithLabel(Item(index+1), Rect{Y: y, Width: 400, Height: 24}, "row") + canvas.HoverHint(owner, Rect{X: 8, Y: y + 4, Width: 160, Height: 16}, "Complete filename.txt") + } + var off Canvas + offOwner := off.Tree().Feature("page") + off.Reset() + off.BeginFrame() + for index := range rows { + off.HitWithLabel(Item(index+1), Rect{Y: float32(index) * 24, Width: 400, Height: 24}, "row") + } + for _, run := range []struct { + name string + canvas *Canvas + owner Scope + x, y float32 + want string + }{ + {"on the first row's text", &canvas, owner, 20, 10, "Complete filename.txt"}, + {"beside the text", &canvas, owner, 300, 10, ""}, + {"tooltips off", &off, offOwner, 20, 10, ""}, + } { + b.Run(fmt.Sprintf("rows=%d/%s", rows, run.name), func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + if hint := run.canvas.HoverHintAt(run.owner, run.x, run.y); hint.Text != run.want { + b.Fatalf("hint %q, want %q", hint.Text, run.want) + } + } + }) + } + } +} From a7d30ae915771d71bf3169800aceba09d52ee99e Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 26 Nov 2026 16:12:25 +0800 Subject: [PATCH 4/7] perf(base): paint children without the EllipsisTooltip wrapper's call PaintChild checks for an EllipsisTooltip before painting an element, and the check does not inline, so every element paid one more call. The child loop, which paints nearly every element, now checks the setting itself and calls paintElement directly; only an element that sets it goes through paintWithEllipsisTip. PageFleet's median went from +5.5% to +1.6% over main. --- base/paint.go | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/base/paint.go b/base/paint.go index 90296ee4c..a3aa76d30 100644 --- a/base/paint.go +++ b/base/paint.go @@ -7,18 +7,22 @@ import ( // PaintChild paints element i and what it holds. func (f *Frame) PaintChild(i int32) { - // An EllipsisTooltip changes the setting for the element's subtree only. - // It is restored here, not by a deferred call in paintElement, whose other - // defers would stop being open-coded. - if tip := f.Exts[f.Nodes[i].Ext].ellipsisTip; tip != 0 { - was := f.setEllipsisTips(tip == ellipsisTipOn) - f.paintElement(i) - f.setEllipsisTips(was) + if f.Exts[f.Nodes[i].Ext].ellipsisTip != 0 { + f.paintWithEllipsisTip(i) return } f.paintElement(i) } +// paintWithEllipsisTip paints element i under the EllipsisTooltip it sets, +// for its subtree only. The setting is restored here, not by a deferred call +// in paintElement, whose other defers would stop being open-coded. +func (f *Frame) paintWithEllipsisTip(i int32) { + was := f.setEllipsisTips(f.Exts[f.Nodes[i].Ext].ellipsisTip == ellipsisTipOn) + f.paintElement(i) + f.setEllipsisTips(was) +} + func (f *Frame) paintElement(i int32) { n := &f.Nodes[i] if !n.FocusScope.IsZero() { @@ -227,7 +231,13 @@ func (f *Frame) paintElement(i int32) { f.runDraw(n, hooks.under) } for c := n.First; c >= 0; c = f.Nodes[c].Next { - f.PaintChild(c) + // PaintChild written out: it does not inline, and this loop paints + // nearly every element. + if f.Exts[f.Nodes[c].Ext].ellipsisTip != 0 { + f.paintWithEllipsisTip(c) + } else { + f.paintElement(c) + } } if n.OutOfFlow&absChildren != 0 { f.paintAbsolute(i) From 963c08d653238d325f252a9d2aba91331142d638 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 26 Nov 2026 16:43:10 +0800 Subject: [PATCH 5/7] perf(base): look up the hovered hint once per paint A page looked up the hint under the pointer twice per paint: the tooltip painter asked HoveredText during End, and paintOnce asked again after End to store it, with the same result both times since the tooltip declares no hits. End now stores the lookup before it paints the tooltip, a pointer event stores its own, and HoveredText returns the stored hint. --- base/frame.go | 3 +++ base/page.go | 8 +++++--- base/tooltip.go | 17 ++++++++++++++--- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/base/frame.go b/base/frame.go index 5483bd941..50cd8b2ec 100644 --- a/base/frame.go +++ b/base/frame.go @@ -461,6 +461,9 @@ func (f *Frame) End() { if f.popupLayer != 0 { f.Surface.PopLayer() } + if f.page != nil { + f.page.hoverText = f.page.hoverTextOn(f.Surface) + } if f.tooltips || f.page != nil { f.paintTooltip() } else if f.paintTooltipFn != nil { diff --git a/base/page.go b/base/page.go index 085d6d463..8d53651ed 100644 --- a/base/page.go +++ b/base/page.go @@ -318,7 +318,7 @@ type Page struct { pointer gfx.Point // where the pointer was at the last pointer event pointerIn bool // a pointer event put it there, and no exit has taken it away hoverArea gfx.ID // the scroll area or self-scrolling table the pointer is on - hoverText gfx.HoverHint // changes wake a page even when text has no pointer target + hoverText gfx.HoverHint // the hint under the pointer at the last paint or pointer event; changes wake a page even when text has no pointer target pointerDown bool selects []*SelectState // the Selects of the last paint, which Wheel scrolls labels []string // scratch for Choice's labels @@ -615,7 +615,10 @@ func (p *Page) onPointer(event gfx.PointerEvent) gfx.EventResult { p.hoverArea = p.hoverPlaceAt(p.pointer.X, p.pointer.Y) } entered := wasArea != p.hoverArea - text := p.HoveredText() + var text gfx.HoverHint + if p.View.Frame != nil { + text = p.hoverTextOn(p.View.Frame.Surface) + } textChanged := !text.SameText(p.hoverText) p.hoverText = text var result gfx.EventResult @@ -883,7 +886,6 @@ func (p *Page) paintOnce(Surface *gfx.Canvas, bounds Rect, View func(C)) { View(&p.ctx) p.declareEditMenus(&p.ctx) f.End() - p.hoverText = p.HoveredText() if p.settleContainers() { p.retry = true } diff --git a/base/tooltip.go b/base/tooltip.go index 0fe61388c..33c85e540 100644 --- a/base/tooltip.go +++ b/base/tooltip.go @@ -21,12 +21,23 @@ func (b Box) OverflowTooltip(text string) Box { return b } -// HoveredText returns this page's visible truncation hint under the pointer. +// HoveredText returns this page's visible truncation hint under the pointer, as +// the page's last paint or pointer event found it. func (p *Page) HoveredText() gfx.HoverHint { - if p == nil || !p.pointerIn || p.View.Frame == nil || p.View.Frame.Surface == nil { + if p == nil { return gfx.HoverHint{} } - return p.View.Frame.Surface.HoverHintAt(p.root, p.pointer.X, p.pointer.Y) + return p.hoverText +} + +// hoverTextOn looks up the page's hint under the pointer among those surface +// holds. A page looks once per paint, before the tooltip, and once per pointer +// event; HoveredText returns what it found. +func (p *Page) hoverTextOn(surface *gfx.Canvas) gfx.HoverHint { + if !p.pointerIn || surface == nil { + return gfx.HoverHint{} + } + return surface.HoverHintAt(p.root, p.pointer.X, p.pointer.Y) } // PointerDown reports a held pointer button, including a press on plain text. From 966a96c4de25c06e80cfac33c955df42ae613001 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 26 Nov 2026 16:43:33 +0800 Subject: [PATCH 6/7] feat(ui): open the ellipsis tooltip on the side EllipsisTooltipOn gives The tooltip of shortened text always opened below the text, which hides the rows under a list and does not fit a status bar along the window's bottom. Box.EllipsisTooltipOn(side) opens the tooltips of the shortened text in an element and what it holds beside side, as TooltipOn does for a Tooltip: those EllipsisTooltip shows and those OverflowTooltip gives. It does not turn them on. The nearest one decides, and a Popup follows it as it follows EllipsisTooltip. Without room on side, a tooltip opens on the opposite one. The element keeps the switch and the side in its one ellipsisTip byte, the frame tracks both while painting, and the canvas stamps the side on each hint, which the shared tooltip reads. --- base/ellipsis_tooltip.go | 102 +++++++++++++++---- base/frame.go | 22 ++-- base/memo.go | 24 ++--- base/page.go | 9 +- base/paint.go | 13 +-- base/tooltip.go | 15 ++- gfx/canvas.go | 3 +- gfx/hover_hint.go | 17 +++- gfx/hover_hint_test.go | 14 ++- ui/tooltip_paint.go | 3 +- ui/tooltip_test.go | 214 +++++++++++++++++++++++++++++++++++++++ 11 files changed, 373 insertions(+), 63 deletions(-) diff --git a/base/ellipsis_tooltip.go b/base/ellipsis_tooltip.go index 3d36f4f8d..014cc5421 100644 --- a/base/ellipsis_tooltip.go +++ b/base/ellipsis_tooltip.go @@ -6,12 +6,26 @@ import ( "github.com/vivaui/viva/gfx" ) -// What EllipsisTooltip set on an element; zero is what the element is inside. +// What EllipsisTooltip and EllipsisTooltipOn set on an element, in one byte so +// that painting checks a single field. The low bits are the switch, ellipsisTipOn +// or ellipsisTipOff; the bits above are 1 + the side EllipsisTooltipOn gave. +// Zero in either part follows what the element is inside. const ( ellipsisTipOn uint8 = 1 + iota ellipsisTipOff + + ellipsisTipSwitch uint8 = 3 + ellipsisTipSideShift = 2 ) +// ellipsisState is what the text being painted does with the tooltips of +// shortened text: whether EllipsisTooltip's show, and 1 + the side every one +// of them opens on, OverflowTooltip's too; a zero side opens them below. +type ellipsisState struct { + on bool + side uint8 +} + // popupFrom is the element a Popup was declared in, which it takes no room in // but follows for EllipsisTooltip when it hangs off no element. type popupFrom struct{ popup, from int32 } @@ -32,34 +46,81 @@ func (b Box) EllipsisTooltip(on bool) Box { if on { tip = ellipsisTipOn } - b.f.Extra(b.i).ellipsisTip = tip + x := b.f.Extra(b.i) + x.ellipsisTip = x.ellipsisTip&^ellipsisTipSwitch | tip + b.f.ellipsisSet = true + return b +} + +// EllipsisTooltipOn opens the tooltips of the shortened text in the element and +// what it holds beside side of the text rather than below it, as TooltipOn does +// for a Tooltip: those EllipsisTooltip shows and those OverflowTooltip gives. A +// list in a sidebar on the window's left opens them to its right, over the +// content beside it, and a status bar along the window's bottom opens them +// above it. It does not turn them on. The nearest EllipsisTooltipOn decides, and +// a Popup follows it as it follows EllipsisTooltip. Without room on side, a +// tooltip opens on the opposite one. +// +// ui.Column(c).EllipsisTooltipOn(ui.TooltipRight).Children(func() { … }) +func (b Box) EllipsisTooltipOn(side TooltipSide) Box { + b.N() + x := b.f.Extra(b.i) + x.ellipsisTip = x.ellipsisTip&ellipsisTipSwitch | (uint8(side)+1)<> ellipsisTipSideShift; side != 0 { + state.side = side + } + return state +} + +// setEllipsis sets what is painted next does with the tooltips of shortened +// text, and returns what it did. Components see it on the canvas: as the hover +// hint owner, which is zero while EllipsisTooltip's are off, and the hint side. +func (f *Frame) setEllipsis(state ellipsisState) ellipsisState { + was := f.ellipsis + if state != was && f.page != nil && f.Surface != nil { + f.ellipsis = state + if state.on != was.on { + var owner gfx.Scope + if state.on { + owner = f.page.root + } + f.Surface.SetHoverHintOwner(owner) + } + if state.side != was.side { + f.Surface.SetHoverHintSide(state.side) } - f.Surface.SetHoverHintOwner(owner) } return was } -// ellipsisTipsAt reports whether element i shows the tooltips: the nearest -// EllipsisTooltip on it or on what it is inside, or else the page's setting. -func (f *Frame) ellipsisTipsAt(i int32) bool { - for steps := 0; i >= 0 && steps < len(f.Nodes); steps++ { +// restoreHoverHints gives the canvas back the hover hint owner and side it had +// before the frame painted, those of the page whose pane holds this one. +func (f *Frame) restoreHoverHints(owner gfx.Scope, side uint8) { + f.Surface.SetHoverHintOwner(owner) + f.Surface.SetHoverHintSide(side) +} + +// ellipsisAt is the state element i paints in: the nearest EllipsisTooltip and +// EllipsisTooltipOn on it or on what it is inside, or else the page's setting. +func (f *Frame) ellipsisAt(i int32) ellipsisState { + var tip, side uint8 + for steps := 0; i >= 0 && steps < len(f.Nodes) && (tip == 0 || side == 0); steps++ { n := &f.Nodes[i] - if tip := f.Exts[n.Ext].ellipsisTip; tip != 0 { - return tip == ellipsisTipOn + set := f.Exts[n.Ext].ellipsisTip + if tip == 0 { + tip = set & ellipsisTipSwitch + } + if side == 0 { + side = set >> ellipsisTipSideShift } switch { case n.Parent >= 0: @@ -70,7 +131,8 @@ func (f *Frame) ellipsisTipsAt(i int32) bool { i = f.popupParent(i) } } - return f.page != nil && f.page.config.EllipsisTooltips + state := ellipsisState{on: f.page != nil && f.page.config.EllipsisTooltips} + return state.under(tip | side< 0 entry.Rect, entry.bounds, entry.painted, entry.stale = rect, f.bounds, true, false - entry.themeEpoch, entry.Opacity, entry.tips = p.themeEpoch, f.Opacity, f.ellipsisTips + entry.themeEpoch, entry.Opacity, entry.tips = p.themeEpoch, f.Opacity, f.ellipsis hovered, pressed, focused := canvas.Hovered(), canvas.Pressed(), canvas.Focused() for _, hit := range canvas.HitsSince(box.before) { if !hit.ID.IsZero() && (hit.ID == hovered || hit.ID == pressed || hit.ID == focused) { diff --git a/base/page.go b/base/page.go index 8d53651ed..288cd480e 100644 --- a/base/page.go +++ b/base/page.go @@ -227,10 +227,11 @@ type PageConfig struct { // or MaxLines, and the labels components shorten themselves, such as Table // cells, Select values and menu items. It is off by default, which paints // such text as before; Box.EllipsisTooltip turns it on or off for part of the - // page. Over the text, this tooltip takes the place of the Tooltip of the - // element the text is in. Only the pointer shows it, not keyboard focus; it is - // not in the accessibility tree, where a control keeps its complete name and - // value whatever its drawing shortens. + // page. The tooltip opens below the text, or beside the side + // Box.EllipsisTooltipOn gives. Over the text, this tooltip takes the place of + // the Tooltip of the element the text is in. Only the pointer shows it, not + // keyboard focus; it is not in the accessibility tree, where a control keeps + // its complete name and value whatever its drawing shortens. EllipsisTooltips bool // Invalidator wakes the window the page is drawn in when an Effect of the page // finishes. Configure uses it instead of the app.Config's; a page the application diff --git a/base/paint.go b/base/paint.go index a3aa76d30..10b543d25 100644 --- a/base/paint.go +++ b/base/paint.go @@ -14,13 +14,14 @@ func (f *Frame) PaintChild(i int32) { f.paintElement(i) } -// paintWithEllipsisTip paints element i under the EllipsisTooltip it sets, -// for its subtree only. The setting is restored here, not by a deferred call -// in paintElement, whose other defers would stop being open-coded. +// paintWithEllipsisTip paints element i under the EllipsisTooltip and +// EllipsisTooltipOn it sets, for its subtree only. The setting is restored +// here, not by a deferred call in paintElement, whose other defers would stop +// being open-coded. func (f *Frame) paintWithEllipsisTip(i int32) { - was := f.setEllipsisTips(f.Exts[f.Nodes[i].Ext].ellipsisTip == ellipsisTipOn) + was := f.setEllipsis(f.ellipsis.under(f.Exts[f.Nodes[i].Ext].ellipsisTip)) f.paintElement(i) - f.setEllipsisTips(was) + f.setEllipsis(was) } func (f *Frame) paintElement(i int32) { @@ -407,7 +408,7 @@ func (f *Frame) paintText(n *Node) { f.paintStrike(line, bounds, style, alignment) } } - if n.TextDecor&textTruncated != 0 && f.ellipsisTips && f.Exts[n.Ext].overflowTip == "" { + if n.TextDecor&textTruncated != 0 && f.ellipsis.on && f.Exts[n.Ext].overflowTip == "" { r.Height = min(r.Height, float32(n.LineCount)*lh) f.Surface.HoverHint(f.page.root, r, n.Text) } diff --git a/base/tooltip.go b/base/tooltip.go index 33c85e540..83f6522b7 100644 --- a/base/tooltip.go +++ b/base/tooltip.go @@ -15,12 +15,22 @@ const TooltipLayer = 1000 // leaves the enclosing row's pointer, focus and accessibility unchanged. Giving // it is the caller's opt-in, so it shows whatever PageConfig.EllipsisTooltips // says. Text truncated by Ellipsis or MaxLines supplies its complete value -// itself where the page or an EllipsisTooltip turned the tooltips on. +// itself where the page or an EllipsisTooltip turned the tooltips on. The +// tooltip opens below, or beside the side the nearest EllipsisTooltipOn gives. func (b Box) OverflowTooltip(text string) Box { b.f.Extra(b.i).overflowTip = text return b } +// HoverHintSide is the side the tooltip of a hint the page painted opens on: +// the one EllipsisTooltipOn gave the text, or below. +func HoverHintSide(hint gfx.HoverHint) TooltipSide { + if hint.Side == 0 { + return TooltipBottom + } + return TooltipSide(hint.Side - 1) +} + // HoveredText returns this page's visible truncation hint under the pointer, as // the page's last paint or pointer event found it. func (p *Page) HoveredText() gfx.HoverHint { @@ -75,7 +85,8 @@ const ( // TooltipOn opens the element's Tooltip beside side rather than below it: an // information icon at the end of a label shows its tip to its right, where the // tip covers neither the label nor the rows under it. Without room on side, the -// tip opens on the opposite one. +// tip opens on the opposite one. The tooltips of shortened text take their side +// from EllipsisTooltipOn instead. // // ui.Button(c, "").Icon(info).Tooltip("Applies to new terminals").TooltipOn(ui.TooltipRight) func (b Box) TooltipOn(side TooltipSide) Box { diff --git a/gfx/canvas.go b/gfx/canvas.go index ab76a5fbe..cd38363b4 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -699,6 +699,7 @@ type Canvas struct { hoverHints []HoverHint hoverHintOwner Scope + hoverHintSide uint8 // hitTexts holds the text geometry of the hits that declared any, in // declaration order; Hit.Text is one more than the entry's index. hitTexts []HitText @@ -1036,7 +1037,7 @@ func (canvas *Canvas) Reset() { canvas.runs = canvas.runs[:0] canvas.hits = canvas.hits[:0] canvas.hoverHints = canvas.hoverHints[:0] - canvas.hoverHintOwner = 0 + canvas.hoverHintOwner, canvas.hoverHintSide = 0, 0 canvas.hitTexts = canvas.hitTexts[:0] canvas.clips = canvas.clips[:0] canvas.overlayClips = canvas.overlayClips[:0] diff --git a/gfx/hover_hint.go b/gfx/hover_hint.go index 2b41a8cc8..a5b270f7a 100644 --- a/gfx/hover_hint.go +++ b/gfx/hover_hint.go @@ -3,10 +3,13 @@ package gfx // HoverHint is a noninteractive description of text hidden by truncation. It // has no pointer target, tab stop or accessibility control. Owner is the page // that paints its tooltip; bounds are clipped and move with the painted text. +// Side is what SetHoverHintSide set when the hint was declared: where its page +// opens the tooltip, in the page's own numbering. type HoverHint struct { Owner Scope Bounds Rect Text string + Side uint8 target ID layer uint16 scope ID @@ -29,7 +32,7 @@ func (canvas *Canvas) HoverHint(owner Scope, bounds Rect, text string, target .. return } hint := HoverHint{ - Owner: owner, Bounds: bounds, Text: text, layer: canvas.currentLayer(), + Owner: owner, Bounds: bounds, Text: text, Side: canvas.hoverHintSide, layer: canvas.currentLayer(), scope: canvas.currentFocusScope(), hitAt: uint32(len(canvas.hits)), } if len(target) > 0 { @@ -53,8 +56,18 @@ func (canvas *Canvas) SetHoverHintOwner(owner Scope) Scope { // reads it. func (canvas *Canvas) HoverHintOwner() Scope { return canvas.hoverHintOwner } +// SetHoverHintSide sets the Side of the hints declared next, every hint of +// whatever owner, and returns the previous one to restore. The page that owns a +// hint gives it the edge its tooltip opens beside; zero after Reset. +func (canvas *Canvas) SetHoverHintSide(side uint8) uint8 { + previous := canvas.hoverHintSide + canvas.hoverHintSide = side + return previous +} + // SameText reports whether two hints describe the same visible text. Changes -// to unrelated pointer targets do not restart the tooltip's delay. +// to unrelated pointer targets do not restart the tooltip's delay, nor does a +// new Side, which only moves the tooltip. func (hint HoverHint) SameText(other HoverHint) bool { return hint.Owner == other.Owner && hint.Bounds == other.Bounds && hint.Text == other.Text && hint.layer == other.layer && hint.scope == other.scope && hint.target == other.target diff --git a/gfx/hover_hint_test.go b/gfx/hover_hint_test.go index 9efe73a24..1ffd8bcb4 100644 --- a/gfx/hover_hint_test.go +++ b/gfx/hover_hint_test.go @@ -13,6 +13,7 @@ func TestHoverHintFollowsReplayAndRewind(t *testing.T) { canvas.BeginFrame() start := canvas.Mark() canvas.HitWithLabel(Item(1), Rect{Width: 100, Height: 40}, "row") + canvas.SetHoverHintSide(2) canvas.HoverHint(owner, Rect{X: 10, Y: 10, Width: 60, Height: 20}, "Complete filename.txt") span := canvas.SpanSince(start) canvas.EndFrame() @@ -20,12 +21,16 @@ func TestHoverHintFollowsReplayAndRewind(t *testing.T) { canvas.Reset() canvas.BeginFrame() canvas.HitWithLabel(Item(2), Rect{X: 200, Width: 30, Height: 30}, "other") + canvas.HoverHint(owner, Rect{X: 200, Width: 30, Height: 30}, "Other complete filename.txt") + if hint := canvas.HoverHintAt(owner, 210, 10); hint.Side != 0 { + t.Fatalf("Reset kept the side of the last frame: %+v", hint) + } mark := canvas.Mark() if _, ok := canvas.ReplayAt(span, 0, 50); !ok { t.Fatal("the unchanged row could not be replayed") } - if hint := canvas.HoverHintAt(owner, 20, 65); hint.Text != "Complete filename.txt" || hint.Bounds.Y != 60 { - t.Fatalf("replayed row lost its tooltip: %+v", hint) + if hint := canvas.HoverHintAt(owner, 20, 65); hint.Text != "Complete filename.txt" || hint.Bounds.Y != 60 || hint.Side != 2 { + t.Fatalf("replayed row lost its tooltip or its side: %+v", hint) } if hint := canvas.HoverHintAt(owner, 20, 15); hint.Text != "" { t.Fatal("the tooltip stayed at the row's old position") @@ -39,6 +44,7 @@ func TestHoverHintFollowsReplayAndRewind(t *testing.T) { func TestHoverHintIsMountedAndClippedWithEmbeddedText(t *testing.T) { var child, page Canvas owner := child.Tree().Feature("page") + child.SetHoverHintSide(3) child.HoverHint(owner, Rect{Width: 80, Height: 20}, "Complete filename.txt", Item(1)) child.HitWithLabel(Item(1), Rect{Width: 80, Height: 20}, "row") mount := testMount(&page, 1) @@ -46,8 +52,8 @@ func TestHoverHintIsMountedAndClippedWithEmbeddedText(t *testing.T) { page.Embed(&child, Point{X: 100, Y: 100}, mount) page.Unclip() mounted := page.Tree().Mount(mount, owner) - if hint := page.HoverHintAt(mounted, 110, 110); hint.Text != "Complete filename.txt" || hint.Bounds != (Rect{X: 100, Y: 100, Width: 40, Height: 20}) { - t.Fatalf("embedded text lost its full value or clip: %+v", hint) + if hint := page.HoverHintAt(mounted, 110, 110); hint.Text != "Complete filename.txt" || hint.Bounds != (Rect{X: 100, Y: 100, Width: 40, Height: 20}) || hint.Side != 3 { + t.Fatalf("embedded text lost its full value, clip or side: %+v", hint) } if page.HoverHintAt(mounted, 150, 110).Text != "" || page.HoverHintAt(owner, 110, 110).Text != "" { t.Fatal("the embedded tooltip escaped its clip or page owner") diff --git a/ui/tooltip_paint.go b/ui/tooltip_paint.go index 829b3f027..0756cfaf5 100644 --- a/ui/tooltip_paint.go +++ b/ui/tooltip_paint.go @@ -3,6 +3,7 @@ package ui import ( "time" + "github.com/vivaui/viva/base" "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" ) @@ -38,7 +39,7 @@ func paintTooltip(f *Frame) { return } components.BeginTooltip(f.Surface, f.Palette, f.GetBounds(), text.Bounds, - components.TooltipOptions{Layer: TooltipLayer, Side: components.TooltipBottom}).Paint(text.Text) + components.TooltipOptions{Layer: TooltipLayer, Side: base.HoverHintSide(text)}).Paint(text.Text) return } } diff --git a/ui/tooltip_test.go b/ui/tooltip_test.go index 56e2f6cdb..e9265bd42 100644 --- a/ui/tooltip_test.go +++ b/ui/tooltip_test.go @@ -375,6 +375,220 @@ func TestEllipsisTooltipSettingRedeclaresAMemo(t *testing.T) { } } +// tipBounds is where the tooltip of shortened text shows: its one line. +func tipBounds(t *testing.T, d *pageDriver) gfx.Rect { + t.Helper() + for _, label := range d.driver.Snapshot().Labels { + if label.Layer == ui.TooltipLayer { + return label.Bounds + } + } + t.Fatal("no tooltip") + return gfx.Rect{} +} + +// beside reports whether tip lies wholly on side of text. +func beside(tip, text gfx.Rect, side ui.TooltipSide) bool { + switch side { + case ui.TooltipTop: + return tip.Y+tip.Height <= text.Y + case ui.TooltipRight: + return tip.X >= text.X+text.Width + case ui.TooltipLeft: + return tip.X+tip.Width <= text.X + } + return tip.Y >= text.Y+text.Height +} + +// The page under the pointer and the bounds of the hint the pointer rests on. +func hoveredHint(t *testing.T, d *pageDriver) gfx.Rect { + t.Helper() + hint := d.page.HoveredText() + if hint.Text == "" { + t.Fatal("no shortened text under the pointer") + } + return hint.Bounds +} + +// openSidesPage opens a page large enough for a tooltip on every side of text +// in its middle. +func openSidesPage(t *testing.T, tips bool, View func(ui.C)) *pageDriver { + t.Helper() + return openPageWith(t, ui.PageConfig{View: View, EllipsisTooltips: tips}, app.Config{Width: 1200, Height: 900}) +} + +// EllipsisTooltipOn opens the tooltip beside the side it names, below by +// default, and on the opposite side where its own has no room. +func TestEllipsisTooltipOn(t *testing.T) { + const full = "Complete filename before the suffix.txt" + for _, side := range []ui.TooltipSide{ui.TooltipTop, ui.TooltipRight, ui.TooltipBottom, ui.TooltipLeft} { + var text ui.Box + d := openSidesPage(t, true, func(c ui.C) { + ui.Column(c).Pad(400).EllipsisTooltipOn(side).Children(func() { + text = ui.Text(c, full).Width(80).Ellipsis() + }) + }) + if err := d.driver.Move(center(text.Rect())); err != nil { + t.Fatal(err) + } + if tip, at := tipBounds(t, d), hoveredHint(t, d); !beside(tip, at, side) { + t.Fatalf("side %d: the tooltip %v is not beside its text %v", side, tip, at) + } + } + var plain, top ui.Box + d := openSidesPage(t, true, func(c ui.C) { + ui.Column(c).Pad(4).EllipsisTooltipOn(ui.TooltipTop).Children(func() { + top = ui.Text(c, full).Width(80).Ellipsis() + }) + ui.Column(c).Pad(400).Children(func() { plain = ui.Text(c, full).Width(80).Ellipsis() }) + }) + if err := d.driver.Move(center(top.Rect())); err != nil { + t.Fatal(err) + } + if tip, at := tipBounds(t, d), hoveredHint(t, d); !beside(tip, at, ui.TooltipBottom) { + t.Fatalf("with no room above, the tooltip %v is not below its text %v", tip, at) + } + if err := d.driver.Move(center(plain.Rect())); err != nil { + t.Fatal(err) + } + if tip, at := tipBounds(t, d), hoveredHint(t, d); !beside(tip, at, ui.TooltipBottom) { + t.Fatalf("without EllipsisTooltipOn, the tooltip %v is not below its text %v", tip, at) + } +} + +// The side follows the subtree apart from the switch: EllipsisTooltip keeps the +// side from further out, the nearest EllipsisTooltipOn wins, either order on one +// element sets both, and the side alone turns nothing on. +func TestEllipsisTooltipOnFollowsTheSubtree(t *testing.T) { + var alone, kept, nearer, reversed ui.Box + d := openSidesPage(t, false, func(c ui.C) { + ui.Column(c).Pad(400).Gap(40).EllipsisTooltipOn(ui.TooltipRight).Children(func() { + alone = ui.Text(c, "Alone: complete filename before the suffix.txt").Width(80).Ellipsis() + ui.Row(c).EllipsisTooltip(true).Children(func() { + kept = ui.Text(c, "Kept: complete filename before the suffix.txt").Width(80).Ellipsis() + }) + ui.Row(c).EllipsisTooltip(true).EllipsisTooltipOn(ui.TooltipTop).Children(func() { + nearer = ui.Text(c, "Nearer: complete filename before the suffix.txt").Width(80).Ellipsis() + }) + ui.Row(c).EllipsisTooltipOn(ui.TooltipLeft).EllipsisTooltip(true).Children(func() { + reversed = ui.Text(c, "Reversed: complete filename before the suffix.txt").Width(80).Ellipsis() + }) + }) + }) + wants := []struct { + at gfx.Rect + side ui.TooltipSide + }{{kept.Rect(), ui.TooltipRight}, {nearer.Rect(), ui.TooltipTop}, {reversed.Rect(), ui.TooltipLeft}} + if err := d.driver.Move(center(alone.Rect())); err != nil { + t.Fatal(err) + } + if got := textTooltip(d); got != "" { + t.Fatalf("EllipsisTooltipOn alone turned the tooltip on: %q", got) + } + for _, want := range wants { + if err := d.driver.Move(center(want.at)); err != nil { + t.Fatal(err) + } + if tip, at := tipBounds(t, d), hoveredHint(t, d); !beside(tip, at, want.side) { + t.Fatalf("side %d: the tooltip %v is not beside its text %v", want.side, tip, at) + } + } +} + +// A Select's list opens its tooltips on the side of the Select, and a Popup +// placed by a rectangle on the side of the element it was declared in. +func TestEllipsisTooltipOnInAPopup(t *testing.T) { + const full = "A complete configuration name far too long for the trigger, and for the list that opens below it, which the window cannot hold either, so the list shortens it with an ellipsis and the tooltip shows the rest" + value := full + var overlay ui.Box + d := openSidesPage(t, true, func(c ui.C) { + ui.Column(c).Pad(400).Children(func() { + ui.Select(c, &value, []string{full, "Short"}, nil).Width(112).EllipsisTooltipOn(ui.TooltipTop) + }) + ui.Column(c).EllipsisTooltipOn(ui.TooltipRight).Children(func() { + ui.Overlay(c, ui.OverlaySpec{Bounds: gfx.Rect{X: 300, Y: 540, Width: 200, Height: 40}}).Children(func() { + overlay = ui.Text(c, "Overlay: complete filename before the suffix.txt").Width(80).Ellipsis() + }) + }) + }) + if err := d.driver.Move(center(overlay.Rect())); err != nil { + t.Fatal(err) + } + if tip, at := tipBounds(t, d), hoveredHint(t, d); !beside(tip, at, ui.TooltipRight) { + t.Fatalf("the overlay's tooltip %v is not right of its text %v", tip, at) + } + trigger := selectTrigger(d) + if err := d.driver.Click(center(trigger.Bounds)); err != nil { + t.Fatal(err) + } + d.repaint() + var row gfx.Hit + for _, hit := range d.driver.Snapshot().Hits { + if hit.Label == full && hit.Role != gfx.RoleCombobox { + row = hit + } + } + if row.Bounds.Width == 0 { + t.Fatal("the list did not open") + } + if err := d.driver.Move(row.Bounds.X+30, row.Bounds.Y+row.Bounds.Height/2); err != nil { + t.Fatal(err) + } + if tip, at := tipBounds(t, d), hoveredHint(t, d); !beside(tip, at, ui.TooltipTop) { + t.Fatalf("the list row's tooltip %v is not above its text %v", tip, at) + } +} + +// OverflowTooltip opens beside the side EllipsisTooltipOn gives, on a page that +// leaves EllipsisTooltips off. +func TestOverflowTooltipOpensOnTheEllipsisSide(t *testing.T) { + const full = "Trust all projects in /workspace/long-directory/projects" + checked := false + d := openSidesPage(t, false, func(c ui.C) { + ui.Column(c).Pad(400).EllipsisTooltipOn(ui.TooltipLeft).Children(func() { + ui.Checkbox(c, &checked, "Trust /workspace/…/projects").OverflowTooltip(full) + }) + }) + if err := d.driver.Move(center(d.hit("Trust /workspace/…/projects").Bounds)); err != nil { + t.Fatal(err) + } + if tip, at := tipBounds(t, d), hoveredHint(t, d); !beside(tip, at, ui.TooltipLeft) { + t.Fatalf("the tooltip %v is not left of its text %v", tip, at) + } +} + +// A Memo's copy is painted again when the side around it changed. +func TestEllipsisTooltipOnRedeclaresAMemo(t *testing.T) { + const full = "Complete filename before the suffix.txt" + side := ui.TooltipRight + var text ui.Box + d := openSidesPage(t, true, func(c ui.C) { + ui.Column(c).Pad(400).EllipsisTooltipOn(side).Children(func() { + ui.Memo(c, 1, func() { text = ui.Text(c, full).Width(80).Ellipsis() }) + }) + }) + at := text.Rect() // a copied Memo declares no Box + d.repaint() // the Memo is copied from here on + if err := d.driver.Move(center(at)); err != nil { + t.Fatal(err) + } + if tip := tipBounds(t, d); !beside(tip, at, ui.TooltipRight) { + t.Fatalf("the tooltip %v is not right of its text %v", tip, at) + } + if err := d.driver.Move(10, 10); err != nil { + t.Fatal(err) + } + side = ui.TooltipLeft + d.repaint() + d.repaint() + if err := d.driver.Move(center(at)); err != nil { + t.Fatal(err) + } + if tip := tipBounds(t, d); !beside(tip, at, ui.TooltipLeft) { + t.Fatalf("a copied Memo kept the old side: the tooltip %v is not left of its text %v", tip, at) + } +} + func TestOverflowTooltipKeepsCheckboxCaptionClickable(t *testing.T) { const full = "Trust all projects in /workspace/long-directory/projects" checked := false From 1397af695169040b40042d289eeefe1ad953d6bd Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 26 Nov 2026 16:45:01 +0800 Subject: [PATCH 7/7] test(gfx): say every row's text costs HoverHintAt the same The benchmark said a query over the first row's text was the worst case because it passed only the hits painted after the row. It passes every hit whatever the row, since a hit painted before the text on a higher layer still covers it. Name the case "on a row's text" and say so. --- gfx/hover_hint_test.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/gfx/hover_hint_test.go b/gfx/hover_hint_test.go index 1ffd8bcb4..1272c4f17 100644 --- a/gfx/hover_hint_test.go +++ b/gfx/hover_hint_test.go @@ -65,10 +65,11 @@ func TestHoverHintIsMountedAndClippedWithEmbeddedText(t *testing.T) { } // BenchmarkHoverHintAt is a page asking for the tooltip under the pointer once -// a frame: a table whose every row is a hit holding shortened text. On the first -// row's text the query passes every hint and every hit painted after the row; -// beside the text it passes every hint alone; with the tooltips off the page -// declares no hints at all. +// a frame: a table whose every row is a hit holding shortened text. Over a row's +// text the query passes every hint and then every hit, since a hit painted +// before the text on a higher layer still covers it, so every row costs the +// same; beside the text no hint holds the pointer and the query passes the hints +// alone; with the tooltips off the page declares no hints at all. func BenchmarkHoverHintAt(b *testing.B) { for _, rows := range []int{100, 1000, 10000} { var canvas Canvas @@ -94,7 +95,7 @@ func BenchmarkHoverHintAt(b *testing.B) { x, y float32 want string }{ - {"on the first row's text", &canvas, owner, 20, 10, "Complete filename.txt"}, + {"on a row's text", &canvas, owner, 20, 10, "Complete filename.txt"}, {"beside the text", &canvas, owner, 300, 10, ""}, {"tooltips off", &off, offOwner, 20, 10, ""}, } {