From 2a19490ff43a336bdc3bdf1e5dcda85557db2c7c 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] 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/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 +++++++++++++++++++++++ 37 files changed, 673 insertions(+), 94 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 2aa636fb2..45c2283f2 100644 --- a/base/frame.go +++ b/base/frame.go @@ -210,6 +210,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 @@ -417,6 +418,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 { @@ -428,8 +433,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 8ca81d90f..9c39f58fd 100644 --- a/base/page.go +++ b/base/page.go @@ -302,8 +302,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 @@ -570,6 +572,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 @@ -590,6 +598,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 @@ -602,7 +613,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 } @@ -847,6 +859,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 a11b6a9e8..69b1ea845 100644 --- a/base/paint.go +++ b/base/paint.go @@ -165,6 +165,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) @@ -365,6 +369,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 ec28798b8..1b5a834b4 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": {"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 0f2c088eb..931462d69 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 @@ -1025,6 +1028,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] @@ -1073,6 +1078,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) @@ -1083,6 +1089,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/presence.go b/gfx/presence.go index 7fb1eba72..b7df56bf0 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 @@ -150,7 +151,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() @@ -350,7 +351,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 @@ -543,6 +544,9 @@ func reverseTriangles(triangles []Triangle) { // is not worth one per frame, so a label moves with the overlay but keeps its size. func (presence Presence) apply(canvas *Canvas, open presenceOpen, pivot Point, progress float32, leaving bool) { transform := presence.transform(pivot, progress, leaving) + 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{}) fade := presence.Fade if fade && progress < 1 { 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 8db56f88e..bef28ccd3 100644 --- a/gfx/wrap.go +++ b/gfx/wrap.go @@ -51,9 +51,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. @@ -105,6 +110,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 } @@ -121,6 +129,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 d4678a203..87cb97d3e 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 {