diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 899e21754..c63044709 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -159,6 +159,11 @@ func (m *model) page(c ui.C) { (opens as the pointer rests on it, on a click, or on Right/Enter/Space; Left goes back), in a ContextMenu too. - A right-click menu: `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` (Shift+F10 opens it too); items take `.Icon(icon)`, `.Keys(ui.Primary, "c")` (shown, not bound), `.Checked(on)` and `.Chosen(on)`. +- A row a menu cannot say: `menu.ContentPage(40, func(c ui.C, bounds ui.Rect) { ui.ColorSwatch(c, ...) })` declares page controls + in a row of their own (the keyboard passes over it); `menu.Content(height, paint)` is the canvas painter for a row + the page cannot declare. +- `ui.SelectID(c, id, &m.size, choices, nil)` is `ui.Select` for a control the application names: a row's words can be its `LabelFor`, and the application's key and focus routing can target it. +- Color choices: `ui.ColorSwatch(c, color, chosen, "Red")` is a radio (`.Flush()` fills its border with the color, `.TabStop(chosen)` makes one swatch the Tab stop, `ColorSwatchID` keeps an application identity); `ui.ColorPicker(c, &m.picker, &m.color, "Accent")` opens a panel to pick one, `.Draft()` follows the drag before Apply and `.Applied()` says a choice was committed. - A side panel: `ui.Drawer(c, &m.open, "Title", ui.DrawerSpec{Side: ui.DrawerLeft, Size: 320}, body, footer)`; an empty title gives the body the whole panel, `NonModal` keeps the keyboard on the page, `Swipe` adds a handle that a drag toward the edge closes it by (past half its size, or thrown). @@ -564,6 +569,8 @@ ui.Row(c).Fill().Children(func() { ``` (`Splitter` in a `Column` divides top and bottom; the first pane then gets `Height(m.split.Pos)`.) +`.SplitterThickness(1)` makes the divider take one pixel of the layout, as a hairline between the panes, while the +pointer keeps the eight-pixel strip around it. ## Animation and time diff --git a/ui/color.go b/ui/color.go new file mode 100644 index 000000000..9057064c3 --- /dev/null +++ b/ui/color.go @@ -0,0 +1,303 @@ +package ui + +import ( + "strconv" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +// ColorSwatch adds a circular color choice, a radio button in a group of them: color is +// what it shows (a transparent color is "no color", drawn as a slash), selected rings +// it, and label names it for assistive technology. A click is Clicked; the application +// owns the choice. It is as wide and tall as its Size, 28 when it has none. +// +// if ui.ColorSwatch(c.Key(name), color, m.color == color, name).Clicked() { m.color = color } +func ColorSwatch(c C, color Color, selected bool, label string) Box { + return colorSwatch(c, c.page.controlID(pkRadio), color, selected, label) +} + +// ColorSwatchID is ColorSwatch for a choice the application already names. +func ColorSwatchID(c C, id gfx.ID, color Color, selected bool, label string) Box { + return colorSwatch(c, id, color, selected, label) +} + +func colorSwatch(c C, id gfx.ID, color Color, selected bool, label string) Box { + b := Slot(c).Size(28, 28).Shrink(0) + n := b.n() + n.id, n.label = id, label + b.Draw(func(d *DrawContext) { + extra := b.f.extra(b.i) + swatch := components.BeginColorSwatch(d.Canvas, *d.Theme, id, d.Rect, color).Label(label).Selected(selected). + TabStop(!extra.swatchSkipTab) + if extra.swatchFlush { + swatch = swatch.Flush() + } + swatch.Paint() + }) + return b +} + +// Flush makes a ColorSwatch fill its hairline border with its color instead of +// leaving a background-colored ring inside it, for a small swatch whose color +// would otherwise read as faded. Other elements ignore it. +func (b Box) Flush() Box { + b.n() + b.f.extra(b.i).swatchFlush = true + return b +} + +// TabStop says whether Tab may enter a ColorSwatch: a radio set gives its chosen +// swatch the stop and the others false, as components.ColorSwatch's TabStop. Other +// elements ignore it. +func (b Box) TabStop(on bool) Box { + b.n() + b.f.extra(b.i).swatchSkipTab = !on + return b +} + +// ColorPickerState is what a ColorPicker keeps between paints: whether its panel is open +// and the color being staged in it. Keep one per picker in the model; the zero value is +// closed. +type ColorPickerState struct { + open, restoreFocus, applied bool + draft components.ColorPickerValue + hexEditor text.Editor + hex Field + seen, summary string + invalid bool + handlers Handlers + layout components.ColorPickerLayout + target *Color + bound bool +} + +// Open reports whether the picker's panel is open. +func (s *ColorPickerState) Open() bool { return s.open } + +// Draft is the color being staged while the panel is open, which follows the plane, the +// hue bar and the hex field as they change and is not yet the application's: a preview +// that tracks the drag reads it. It reports false when the panel is closed. +func (s *ColorPickerState) Draft() (Color, bool) { + if !s.open { + return Color{}, false + } + return s.draft.Color(), true +} + +// Applied reports whether the user applied (or cleared) a color since the last time it was +// asked, so the application can save it; it reads true once. +func (s *ColorPickerState) Applied() bool { + applied := s.applied + s.applied = false + return applied +} + +// ColorPickerSpec is how a ColorPicker looks: Label names it for assistive technology +// (and heads its panel), Round makes the trigger a disc, Icon draws a glyph over it (a +// pipette for a custom color), Empty shows it as no color whatever its value, and +// Labels override the panel's words. +type ColorPickerSpec struct { + // ID, when set, names the trigger with the application's identity, as + // ColorSwatchID does; the page's own identity names it otherwise. A row's + // words can then be its LabelFor, as for any control the application names. + ID gfx.ID + Label string + Round bool + Icon *gfx.Icon + Empty bool + Labels components.ColorPickerLabels +} + +// ColorPicker adds a color trigger over *color that opens a panel to pick one: a plane for +// saturation and brightness, a hue bar, a hex field and Clear, Cancel and Apply. The +// color is staged while the panel is open and written to *color on Apply (Enter in the +// hex field); Cancel, Escape and a press outside leave it as it was. A transparent +// *color is no color, which Clear sets. The box is the 32 pixel trigger; Applied +// reports a change. +// +// ui.ColorPicker(c, &m.picker, &m.accent, "Accent") +// if m.picker.Applied() { m.save() } +func ColorPicker(c C, state *ColorPickerState, color *Color, label string) Box { + return ColorPickerWith(c, state, ColorPickerSpec{Label: label}, color) +} + +// ColorPickerWith is ColorPicker with a spec. +func ColorPickerWith(c C, s *ColorPickerState, spec ColorPickerSpec, color *Color) Box { + p := c.page + p.forbidInMemo("ColorPicker") + id := spec.ID + if id.IsZero() { + id = p.controlID(pkControl) + } + s.target = color + if !s.bound { + s.hex.Bind(&s.hexEditor) + s.handlers.Key, s.handlers.Pointer = s.key, s.pointer + s.bound = true + } + if s.open { + p.overlay = true + control := Control(c, spec.Label, &s.handlers).Absolute().Left(0).Top(0).Size(0, 0) + control.HitWith(s.handlers.parts.At(8), spec.Label, gfx.HitOptions{Role: gfx.RoleGroup, SkipTab: true, SkipFocus: true}) + p.fields = append(p.fields, fieldEntry{id: s.handlers.parts.At(3), field: &s.hex}) + s.hex.id = s.handlers.parts.At(3) + s.syncHex() + } + b := Slot(c).Size(32, 32).Shrink(0) + n := b.n() + n.id, n.label = id, spec.Label + b.DrawOver(func(d *DrawContext) { s.paint(d, c, id, spec) }) + return b +} + +// parts are the identities the panel's regions take. +func (s *ColorPickerState) ids(trigger gfx.ID) components.ColorPickerIDs { + if !s.open { + return components.ColorPickerIDs{Trigger: trigger} + } + at := s.handlers.parts.At + return components.ColorPickerIDs{Trigger: trigger, Saturation: at(0), Hue: at(1), Hex: at(3), Clear: at(4), Cancel: at(5), Apply: at(6), Dismiss: at(7)} +} + +func (s *ColorPickerState) paint(d *DrawContext, c C, id gfx.ID, spec ColorPickerSpec) { + canvas := d.Canvas + ids := s.ids(id) + if canvas.Clicked(id) { + if s.open { + s.close() + } else { + s.openPanel(spec) + } + return + } + if s.restoreFocus { + canvas.RequestFocus(id) + s.restoreFocus = false + } + labels := spec.Labels + if labels.Color == "" { + labels.Color = spec.Label + } + value, empty := s.draft, false + if !s.open { + value = value.WithColor(*s.target) + empty = s.target.Alpha == 0 + } + empty = empty || spec.Empty + options := components.ColorPickerOptions{ + IDs: ids, Labels: labels, Value: value, Open: s.open, Empty: empty, + RoundTrigger: spec.Round, TriggerIcon: spec.Icon, SaturationText: s.summary, + Viewport: Rect{Width: c.Bounds().Width, Height: c.Bounds().Height}, Layer: c.f.widgetLayer() + 2, + } + if s.open { + options.Scope = s.handlers.parts.At(8) + options.Hex = s.hex.snapshot(c.f, ids.Hex, labels.Hex, "#3B82F6") + if s.invalid { + options.Error = "Invalid color" + } + } + picker := components.BeginColorPicker(canvas, *d.Theme, d.Rect, options) + picker.PaintTrigger() + if !s.open { + return + } + s.layout = picker.PaintPanel() + switch { + case canvas.Clicked(ids.Dismiss), canvas.Clicked(ids.Cancel): + s.close() + case canvas.Clicked(ids.Clear): + *s.target, s.applied = Color{}, true + s.close() + case canvas.Clicked(ids.Apply): + s.apply() + } +} + +func (s *ColorPickerState) openPanel(ColorPickerSpec) { + color := *s.target + if color.Alpha == 0 { + color = Color{Red: 0.231, Green: 0.51, Blue: 0.965, Alpha: 1} // #3B82F6, as the field's placeholder + } + s.setValue(components.ColorPickerValue{}.WithColor(color)) + s.open = true +} + +func (s *ColorPickerState) close() { s.open, s.restoreFocus = false, true } + +func (s *ColorPickerState) apply() { + s.syncHex() + if s.invalid { + return + } + *s.target, s.applied = s.draft.Color(), true + s.close() +} + +func (s *ColorPickerState) setValue(v components.ColorPickerValue) { + s.draft = v + var buf [9]byte + value := string(v.AppendHex(buf[:0], false)) + if s.hexEditor.String() != value { + s.hexEditor = text.Editor{} + s.hexEditor.Insert(value) + } + s.seen, s.invalid = value, false + s.summary = summary(v) +} + +func summary(v components.ColorPickerValue) string { + return strconv.Itoa(int(v.Saturation*100+.5)) + "% / " + strconv.Itoa(int(v.Brightness*100+.5)) + "%" +} + +// syncHex takes what was typed in the hex field as the staged color, when it is one. +func (s *ColorPickerState) syncHex() { + value := s.hexEditor.String() + if value == s.seen { + return + } + s.seen = value + color, valid := components.ParseColorHex(value, false) + s.invalid = !valid + if valid { + s.draft = s.draft.WithColor(color) + s.summary = summary(s.draft) + } +} + +func (s *ColorPickerState) pointer(event gfx.PointerEvent) gfx.EventResult { + if !s.open { + return gfx.EventResult{} + } + value, result := s.layout.Pointer(event, s.draft) + if value != s.draft { + s.setValue(value) + } + return result +} + +func (s *ColorPickerState) key(event gfx.KeyEvent) gfx.EventResult { + if !s.open || event.Release { + return gfx.EventResult{} + } + hex := s.handlers.parts.At(3) + if event.Key == gfx.KeyEscape || event.Key == gfx.KeyEnter && event.Target == hex && event.Modifiers == 0 { + if _, composing := s.hexEditor.Composition(); composing { + return gfx.EventResult{} + } + if !event.Repeat { + if event.Key == gfx.KeyEscape { + s.close() + } else { + s.apply() + } + } + return gfx.EventResult{Handled: true, Repaint: true} + } + value, result := s.layout.Key(event, s.draft) + if value != s.draft { + s.setValue(value) + } + return result +} diff --git a/ui/color_test.go b/ui/color_test.go new file mode 100644 index 000000000..aaf1e05e8 --- /dev/null +++ b/ui/color_test.go @@ -0,0 +1,154 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +func TestColorSwatchChoosesByClick(t *testing.T) { + red, blue := gfx.RGB(220, 38, 38), gfx.RGB(37, 99, 235) + chosen := red + d := openPage(t, func(c ui.C) { + ui.Row(c).Gap(4).Children(func() { + for _, s := range []struct { + name string + col gfx.Color + }{{"Red", red}, {"Blue", blue}} { + if ui.ColorSwatch(c.Key(s.name), s.col, chosen == s.col, s.name).Clicked() { + chosen = s.col + } + } + }) + }) + d.click("Blue") + if chosen != blue { + t.Fatalf("a click chose %v", chosen) + } + n := 0 + for _, h := range d.driver.Snapshot().Hits { + if h.Label == "Blue" { + n++ + } + } + if n != 1 { + t.Fatalf("swatch declares %d hits, want 1", n) + } +} + +func pickerPage(t *testing.T, state *ui.ColorPickerState, color *gfx.Color) *pageDriver { + return openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { ui.ColorPicker(c, state, color, "Accent") }) + }) +} + +func TestColorPickerAppliesATypedHex(t *testing.T) { + var state ui.ColorPickerState + color := gfx.RGB(10, 20, 30) + d := pickerPage(t, &state, &color) + d.click("Accent") + if !state.Open() { + t.Fatal("the trigger did not open the panel") + } + d.click("Hex color") + state.TypeHexForTest("#FF0000") + d.click("OK") + if state.Open() || !state.Applied() { + t.Fatalf("Apply left open=%v", state.Open()) + } + if color != gfx.RGB(255, 0, 0) { + t.Fatalf("applied %v, want red", color) + } +} + +func TestColorPickerCancelAndEscapeKeepTheColor(t *testing.T) { + var state ui.ColorPickerState + color := gfx.RGB(10, 20, 30) + d := pickerPage(t, &state, &color) + d.click("Accent") + d.click("Cancel") + if state.Open() || color != gfx.RGB(10, 20, 30) { + t.Fatalf("Cancel: open=%v color=%v", state.Open(), color) + } + d.click("Accent") + d.key(gfx.KeyEscape) + if state.Open() || color != gfx.RGB(10, 20, 30) { + t.Fatalf("Escape: open=%v color=%v", state.Open(), color) + } + d.click("Accent") + d.click("Clear") + if color.Alpha != 0 || !state.Applied() { + t.Fatalf("Clear left %v", color) + } +} + +func TestColorPickerPlaneAndHueMoveTheStagedColor(t *testing.T) { + var state ui.ColorPickerState + color := gfx.RGB(255, 0, 0) + d := pickerPage(t, &state, &color) + d.click("Accent") + plane := d.hit("Saturation and brightness").Bounds + if err := d.driver.Click(plane.X+plane.Width*0.5, plane.Y+plane.Height*0.5); err != nil { + t.Fatal(err) + } + d.key(gfx.KeyRight) + d.click("OK") + if color == gfx.RGB(255, 0, 0) { + t.Fatal("a press on the plane and an arrow key did not change the staged color") + } +} + +func TestColorPickerDraftFollowsTheDragBeforeApply(t *testing.T) { + var state ui.ColorPickerState + color := gfx.RGB(255, 0, 0) + d := pickerPage(t, &state, &color) + if _, ok := state.Draft(); ok { + t.Fatal("a closed picker has a draft") + } + d.click("Accent") + plane := d.hit("Saturation and brightness").Bounds + if err := d.driver.Click(plane.X+plane.Width*0.5, plane.Y+plane.Height*0.5); err != nil { + t.Fatal(err) + } + draft, ok := state.Draft() + if !ok || draft == gfx.RGB(255, 0, 0) { + t.Fatalf("draft = %v, %v after a press on the plane", draft, ok) + } + if color != gfx.RGB(255, 0, 0) { + t.Fatal("the application's color changed before Apply") + } +} + +// A spec's ID names the trigger with the application's identity, so a row's +// words can be its label: clicking them opens the panel. +func TestColorPickerKeepsTheApplicationID(t *testing.T) { + var state ui.ColorPickerState + color := gfx.RGB(10, 20, 30) + var id gfx.ID + d := openPage(t, func(c ui.C) { + if id.IsZero() { + id = ui.ID(c) + } + ui.Row(c).Children(func() { + words := ui.Text(c, "Accent").LabelFor(id) + _ = words + ui.ColorPickerWith(c, &state, ui.ColorPickerSpec{ID: id, Label: "Accent"}, &color) + }) + }) + var trigger gfx.Rect + for _, hit := range d.driver.Snapshot().Hits { + if hit.ID == id { + trigger = hit.Bounds + } + } + if trigger.Width == 0 { + t.Fatal("the trigger did not take the application identity") + } + if err := d.driver.Click(center(trigger)); err != nil { + t.Fatal(err) + } + if !state.Open() { + t.Fatal("a click on the named trigger did not open the panel") + } +} diff --git a/ui/elements.go b/ui/elements.go index 231a5bc92..5453d0d1e 100644 --- a/ui/elements.go +++ b/ui/elements.go @@ -210,7 +210,14 @@ func Tabs[T comparable](c C, value *T, tabs []T, label func(T) string) Box { // it is none of them); picking an option sets it. Whether its list is open is the // Select's own state. func Select[T comparable](c C, value *T, choices []T, label func(T) string) Box { - return selectOf(c, value, choices, label, nil, false) + return selectOf(c, value, choices, label, nil, false, gfx.ID{}) +} + +// SelectID is Select for a control the application already names: the trigger's +// hit is id, so a row's words can be its LabelFor and the application's key and +// focus routing can target it. The list's options keep the page's own identities. +func SelectID[T comparable](c C, id gfx.ID, value *T, choices []T, label func(T) string) Box { + return selectOf(c, value, choices, label, nil, false, id) } // SelectIcon is Select with an icon before every option: icon names each option's @@ -220,13 +227,13 @@ func Select[T comparable](c C, value *T, choices []T, label func(T) string) Box // // ui.SelectIcon(c, &m.locale, locales, localeName, localeFlag) func SelectIcon[T comparable](c C, value *T, choices []T, label func(T) string, icon func(T) gfx.Icon) Box { - return selectOf(c, value, choices, label, optionIcons(c.page, choices, icon), false) + return selectOf(c, value, choices, label, optionIcons(c.page, choices, icon), false, gfx.ID{}) } // selectOf is Select (or SelectIcon), or SelectBase when base is set: the same // control without the theme's look. icons, when SelectIcon's icon function gave // them, are indexed by option like the labels; nil is the select without icons. -func selectOf[T comparable](c C, value *T, choices []T, label func(T) string, icons []gfx.Icon, base bool) Box { +func selectOf[T comparable](c C, value *T, choices []T, label func(T) string, icons []gfx.Icon, base bool, id gfx.ID) Box { p := c.page scope := p.boundScope(pkSelect, unsafe.Pointer(value)) state := stateIn[SelectState](p, scope, "select") // its open list follows its value @@ -238,7 +245,11 @@ func selectOf[T comparable](c C, value *T, choices []T, label func(T) string, ic b = c.f.Select(scope, state, labels, selected) } b.Icons(icons) + state.trigger = id p.selects = append(p.selects, state) + if p.keyRoute == nil { + p.keyRoute, p.selectRoute = (*Page).routeKey, (*Page).selectKey + } index, ok := b.Picked() pick(c, b, value, choices, index, ok) if state.Open { diff --git a/ui/export_color_test.go b/ui/export_color_test.go new file mode 100644 index 000000000..5321447f3 --- /dev/null +++ b/ui/export_color_test.go @@ -0,0 +1,9 @@ +package ui + +import "github.com/vivaui/viva/text" + +// TypeHexForTest replaces the staged hex text, as typing in the panel's field does. +func (s *ColorPickerState) TypeHexForTest(value string) { + s.hexEditor = text.Editor{} + s.hexEditor.Insert(value) +} diff --git a/ui/field.go b/ui/field.go index 894b025ea..e95050ec8 100644 --- a/ui/field.go +++ b/ui/field.go @@ -40,6 +40,10 @@ type Field struct { // Hint is the description assistive technology reads after the field's name and value, for // what they do not say. It is the application's to set and clear, as Secure is. Hint string + // Alignment places the value inside the field, as components.Input's + // Alignment: gfx.AlignCenter for a value centred in it, gfx.AlignRight (or + // AlignEnd) for one against its end. The zero value starts the text. + Alignment gfx.Alignment editor *text.Editor id gfx.ID @@ -175,7 +179,8 @@ func (field *Field) snapshot(f *frame, id gfx.ID, label, placeholder string) com selection := editor.Selection() snapshot := components.InputSnapshot{ ID: id, Label: label, Value: value, Placeholder: placeholder, Secure: field.Secure, Invalid: field.Invalid, Disabled: field.Disabled, Hint: field.Hint, - Focused: focused, + Alignment: field.Alignment, + Focused: focused, // The field paints its own text, caret, selection and composition, and the // platform's editor is only where input arrives. A platform that lays text out // with its own metrics can put the line a fraction of a pixel away from the diff --git a/ui/field_alignment_test.go b/ui/field_alignment_test.go index 9492eca5e..c5c2b7b51 100644 --- a/ui/field_alignment_test.go +++ b/ui/field_alignment_test.go @@ -1,80 +1,35 @@ -//go:build darwin || windows || linux - -package ui +package ui_test import ( "testing" - "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" ) -// TextEnd reaches the platform through the whole chain: the hit the field declares -// tells the focused editor its alignment, so a number field stays right-aligned -// while it is being edited in, and a field that did not ask stays start-aligned. -func TestFieldTextEndToldToThePlatformEditor(t *testing.T) { - var amount, note Field - var view View - amountID, noteID := tree.ID(page, "amount"), tree.ID(page, "note") - amount.SetText("42") - config := app.Config{ - Tree: &tree, Title: "aligned", Width: 300, Height: 200, - Paint: func(canvas *gfx.Canvas, size gfx.Size) { - view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: size.Width, Height: size.Height}, func(f *Frame) { - f.Column().Fill().Pad(12).Gap(8).Children(func() { - f.Field(&amount, amountID, "Amount", "").TextEnd() - f.Field(¬e, noteID, "Note", "") - }) - }) - }, - TextInput: Fields(&amount, ¬e), - } - var canvas gfx.Canvas - driver, err := app.NewDriver(config, &canvas) - if err != nil { - t.Fatal(err) - } - defer driver.Close() - click := func(id gfx.ID) { - for _, hit := range driver.Snapshot().Hits { - if hit.ID == id { - if err := driver.Click(hit.Bounds.X+hit.Bounds.Width/2, hit.Bounds.Y+hit.Bounds.Height/2); err != nil { - t.Fatal(err) - } - return +// A Field places its value where Alignment says: a centred value starts further +// in than one at the field's start. +func TestFieldAlignmentPlacesTheValue(t *testing.T) { + valueX := func(align gfx.Alignment) float32 { + t.Helper() + var editor text.Editor + editor.Insert("30") + field := ui.Field{Alignment: align} + field.Bind(&editor) + d := openPage(t, func(c ui.C) { + ui.TextFieldID(c, ui.ID(c), &field, "Steps", "").Size(64, 32) + }) + for _, painted := range d.driver.Snapshot().Texts { + if painted.Value == "30" { + return painted.Bounds.X } } - t.Fatalf("no field %v on screen", id) - } - editorAlignment := func() gfx.Alignment { - snapshot := driver.Snapshot() - if snapshot.Editor == nil { - t.Fatal("no focused editor on screen") - } - return snapshot.Editor.Alignment - } - click(amountID) - if got := editorAlignment(); got != gfx.AlignRight { - t.Errorf("the right-aligned field's editor = %v, want AlignRight (resolved from AlignEnd)", got) - } - // The line the editor draws sits at the same right edge the paint put it at, and - // the field's own painted line is right-aligned too. - snapshot := driver.Snapshot() - var line gfx.Text - for _, text := range snapshot.Texts { - if text.Value == "42" && text.Bounds.Width == snapshot.Editor.Bounds.Width { - line = text - break - } - } - if line.Value == "" { - t.Fatalf("the value was not painted: %+v", snapshot.Texts) - } - if line.Bounds.X < snapshot.Editor.Bounds.X+snapshot.Editor.Bounds.Width/2 { - t.Errorf("the painted value starts at %v, left of center: it was not right-aligned", line.Bounds.X) + t.Fatal("the value was not painted") + return 0 } - click(noteID) - if got := editorAlignment(); got != gfx.AlignLeft { - t.Errorf("an ordinary field's editor = %v, want AlignLeft (start for LTR)", got) + left, centre := valueX(gfx.AlignStart), valueX(gfx.AlignCenter) + if centre <= left { + t.Fatalf("a centred value starts at %v, not after the left one at %v", centre, left) } } diff --git a/ui/frame.go b/ui/frame.go index 2c230ef5b..5914f51b9 100644 --- a/ui/frame.go +++ b/ui/frame.go @@ -164,6 +164,7 @@ type node struct { frozen bool rect Rect band uint16 // the compositing band the subtree paints on (Overlay); zero is the page's + focusScope gfx.ID // the focus scope the subtree paints in, when it is not the page's } // placement says where a Popup goes. @@ -216,6 +217,8 @@ type extra struct { focusGroup FocusAxis // FocusGroup: the arrow keys that move the focus between the controls inside; zero is none focusOrder FocusOrder // FocusOrder: how the group chooses the next member; nil is its axis layout Layout // CustomLayout: who measures and places the children + swatchFlush bool // a ColorSwatch fills its border with its color + swatchSkipTab bool // a ColorSwatch takes no Tab stop (TabStop) } // frame is one page being declared. It is handed to the function given to diff --git a/ui/leaves_test.go b/ui/leaves_test.go index fb451b58e..c667ce958 100644 --- a/ui/leaves_test.go +++ b/ui/leaves_test.go @@ -323,3 +323,34 @@ func TestDisabledTakesTheCondition(t *testing.T) { t.Error("a disabled button looks like an enabled one") } } + +// A thin divider takes one pixel of the layout, as a hairline between the panes, +// while the pointer still gets the default eight-pixel strip around it. +func TestSplitterThicknessKeepsTheLineThinAndTheGrabWide(t *testing.T) { + var view View + state := SplitterState{Pos: 200} + var second Box + draw := func(c *gfx.Canvas, size gfx.Size) { + view.Draw(c, gfx.LightTheme(), gfx.Rect{Width: size.Width, Height: size.Height}, func(f *Frame) { + f.Row().Fill().Children(func() { + f.Column().Width(state.Pos).Children(func() {}) + f.Splitter(splitID, &state).SplitterThickness(1) + f.Column().Grow(1).Children(func() { + second = f.Slot().Fill() + }) + }) + }) + } + canvas := testCanvas() + draw(canvas, gfx.Size{Width: 400, Height: 100}) + if got := second.Rect().X; got != 201 { + t.Fatalf("the second pane starts at %v, want the first pane plus a one-pixel line", got) + } + bar := splitterAt(t, canvas) + if bar.Width != splitterThickness { + t.Fatalf("the divider's strip is %v wide, want %v", bar.Width, splitterThickness) + } + if bar.X > 200 || bar.X+bar.Width < 200 { + t.Fatalf("the strip %v does not cover the line at 200", bar) + } +} diff --git a/ui/menu.go b/ui/menu.go index 1048837a2..ba7563d4e 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -193,6 +193,15 @@ func (p *Page) declareMenu(c C, menu *MenuItems, scope gfx.Scope, open *bool, an } popup.Size(width, height).Within(f.bounds.Inset(gfx.All(components.DropdownMenuPadding))) popup.Draw(menu.paint) + if menu.hasPageContent() { + // The page row is a child of the popup: it paints and takes hits in the + // menu's layer and focus scope, over the canvas rows the menu drew under it. + if menu.layer > f.popupLayer { + f.popupLayer = menu.layer + } + f.nodes[popup.i].focusScope = menu.scope.At(menuFocus) + popup.Children(func() { menu.declarePageRows(c, width, height) }) + } p.menus = append(p.menus, menu) if p.menuRoute == nil { p.keyRoute, p.menuRoute = (*Page).routeKey, (*Page).menuKey @@ -200,6 +209,35 @@ func (p *Page) declareMenu(c C, menu *MenuItems, scope gfx.Scope, open *bool, an } } +// hasPageContent reports whether any row is declared in the page. +func (m *MenuItems) hasPageContent() bool { + for i := range m.items { + if m.items[i].kind == menuRowPageContent && m.items[i].pageContent != nil { + return true + } + } + return false +} + +// declarePageRows declares the page controls of every page content row at the +// place the menu's rows and scroll put them. +func (m *MenuItems) declarePageRows(c C, width, height float32) { + pad := float32(components.DropdownMenuPadding) + y := pad - m.scroll.Offset + for i := range m.items { + row := &m.items[i] + if row.kind == menuRowPageContent && row.pageContent != nil && row.height > 0 && + y+row.height > 0 && y < height { + pageY, pageHeight := y, row.height + bounds := Rect{X: pad, Y: pageY, Width: max(width-2*pad, 0), Height: pageHeight} + Column(c).Absolute().Left(bounds.X).Top(bounds.Y).Width(bounds.Width).Height(bounds.Height).Children(func() { + row.pageContent(c, bounds) + }) + } + y += m.rowExtent(i) + } +} + // fresh forgets the submenu a menu had open the last time it was: one that opens // again opens with none. func (m *MenuItems) fresh() { @@ -261,24 +299,17 @@ func (m *MenuItems) size() (width, height float32) { width, height = m.minWidth(), 2*components.DropdownMenuPadding for i := range m.items { item := &m.items[i] + height += m.rowExtent(i) switch item.kind { - case menuRowSeparator: - height += components.DropdownMenuSeparatorHeight - case menuRowLabel: - height += components.DropdownMenuLabelHeight - case menuRowContent: - height += item.height + case menuRowSeparator, menuRowLabel, menuRowContent, menuRowPageContent: default: row := m.row(i) if m.context { - context := contextItem(row) - height += components.ContextMenuItemHeight(*theme, context, m.rowSize) if f.canvas != nil { - width = max(width, components.ContextMenuItemWidth(f.canvas, *theme, context)) + width = max(width, components.ContextMenuItemWidth(f.canvas, *theme, contextItem(row))) } continue } - height += components.DropdownMenuItemHeight(*theme, row) if f.canvas != nil { width = max(width, components.DropdownMenuItemWidth(f.canvas, *theme, row)) } @@ -309,6 +340,7 @@ const ( menuRowLabel menuRowSeparator menuRowContent + menuRowPageContent ) // MenuItems is an open Menu or ContextMenu being declared: what its rows are, and, @@ -443,6 +475,7 @@ type menuRow struct { trailing func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) height float32 // a content row's height content func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) // what paints a content row + pageContent func(c C, bounds Rect) // what a page content row declares checked int8 // 1 a checked checkbox, 2 an unchecked one, 3 a chosen radio, 4 an unchosen one } @@ -556,6 +589,32 @@ func (m *MenuItems) Content(height float32, body func(canvas *gfx.Canvas, bounds m.items = append(m.items, menuRow{kind: menuRowContent, height: height, content: body}) } +// ContentPage adds a row height tall whose controls body declares in the page: +// the room for what a menu row cannot say and a canvas painter cannot host, such +// as a strip of color swatches. It is not an item, so the keyboard passes over it. +// The row is placed where the menu's rows put it; it is for a menu that does not +// scroll its rows. +func (m *MenuItems) ContentPage(height float32, body func(c C, bounds Rect)) { + m.items = append(m.items, menuRow{kind: menuRowPageContent, height: height, pageContent: body}) +} + +// rowExtent is how tall row i is, as size and the page rows' placement both need. +func (m *MenuItems) rowExtent(i int) float32 { + row := &m.items[i] + switch row.kind { + case menuRowSeparator: + return components.DropdownMenuSeparatorHeight + case menuRowLabel: + return components.DropdownMenuLabelHeight + case menuRowContent, menuRowPageContent: + return row.height + } + if m.context { + return components.ContextMenuItemHeight(m.f.theme, contextItem(m.row(i)), m.rowSize) + } + return components.DropdownMenuItemHeight(m.f.theme, m.row(i)) +} + // paintContent calls a content row's painter over its row, inside the menu's clip. func (m *MenuItems) paintContent(canvas *gfx.Canvas, theme gfx.Theme, row *menuRow, bounds gfx.Rect, begin, end func(), menu gfx.Rect) { if bounds.Width <= 0 || row.content == nil { @@ -699,6 +758,8 @@ func (m *MenuItems) paintAt(canvas *gfx.Canvas, theme *Theme, bounds Rect, layer menu.AddLabel(row.label, false) case menuRowContent: m.paintContent(canvas, *theme, row, menu.AddContent(row.height), func() { menu.BeginContent() }, func() { menu.EndContent() }, menu.Bounds()) + case menuRowPageContent: + menu.AddContent(row.height) // the page declares the row's controls default: if row.trailing != nil { r, slot := menu.AddItemSlot(contextItem(m.row(i))) @@ -740,6 +801,8 @@ func (m *MenuItems) paintAt(canvas *gfx.Canvas, theme *Theme, bounds Rect, layer menu.AddLabel(row.label, false) case menuRowContent: m.paintContent(canvas, *theme, row, menu.AddContent(row.height), func() { menu.BeginContent() }, func() { menu.EndContent() }, menu.Bounds()) + case menuRowPageContent: + menu.AddContent(row.height) // the page declares the row's controls default: if row.trailing != nil { r, slot := menu.AddItemSlot(m.row(i)) diff --git a/ui/menu_test.go b/ui/menu_test.go index b3632a29f..33b894e4e 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -662,3 +662,32 @@ func TestMenuItemTrailingControl(t *testing.T) { t.Fatal("pressing the trailing control chose the row") } } + +// A ContentPage row takes room in the menu and declares its controls in the page: +// a swatch there is clicked without closing the menu. +func TestMenuPageContentRow(t *testing.T) { + chosen := false + open := true + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + more := ui.Button(c, "More") + ui.Menu(c, more, &open, func(menu *ui.MenuItems) { + menu.Item("One") + menu.ContentPage(40, func(c ui.C, _ ui.Rect) { + if ui.ColorSwatch(c, gfx.RGB(220, 38, 38), chosen, "Red").Clicked() { + chosen = true + } + }) + menu.Item("Two") + }) + }) + }) + one, two := d.hit("One").Bounds, d.hit("Two").Bounds + if two.Y-one.Y < 40 { + t.Fatalf("the page row took no room: One %v, Two %v", one, two) + } + d.click("Red") + if !chosen || !open { + t.Fatalf("the swatch chose %v, menu open %v", chosen, open) + } +} diff --git a/ui/page.go b/ui/page.go index 1e42ed8fd..f1b29f41d 100644 --- a/ui/page.go +++ b/ui/page.go @@ -311,6 +311,7 @@ type Page struct { roveRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // arrow keys in a Choice or Tabs groupRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // arrow keys in a FocusGroup sliderRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // the keys of a Slider + selectRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // opens and moves the list of a Select comboRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) treeRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) listRoute func(*Page, gfx.KeyEvent) (gfx.EventResult, bool) // moves and chooses rows of a List @@ -487,6 +488,11 @@ func (p *Page) routeKey(event gfx.KeyEvent) (gfx.EventResult, bool) { return result, true } } + if p.selectRoute != nil { + if result, ok := p.selectRoute(p, event); ok { + return result, true + } + } if p.shortcutRoute != nil { if result, ok := p.shortcutRoute(p, event); ok { return result, true diff --git a/ui/page_bases.go b/ui/page_bases.go index 021030457..f1982c96e 100644 --- a/ui/page_bases.go +++ b/ui/page_bases.go @@ -2,6 +2,8 @@ package ui import ( "unsafe" + + "github.com/vivaui/viva/gfx" ) // The Bases of a page are its controls without their look: what each does, as an element @@ -106,7 +108,7 @@ func SliderBase(c C, state *SliderState) Box { // list.Draw(m.paintPanel) // option i is in sel.Part(i) // } func SelectBase[T comparable](c C, value *T, choices []T, label func(T) string) Box { - return selectOf(c, value, choices, label, nil, true) + return selectOf(c, value, choices, label, nil, true, gfx.ID{}) } // TextFieldBase is TextField without a look: the editable text, with no padding, diff --git a/ui/paint.go b/ui/paint.go index 4b62c68f7..b759d191d 100644 --- a/ui/paint.go +++ b/ui/paint.go @@ -9,6 +9,12 @@ import ( func (f *frame) paint(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 + // them reaches them while the menu traps the pointer. + f.canvas.PushFocusScope(n.focusScope) + defer f.canvas.PopFocusScope() + } if n.band != 0 { // An application overlay's subtree paints on its band, over the page and // under Viva's widgets. Hits declared in it capture the same layer, so the diff --git a/ui/select.go b/ui/select.go index f0beddf62..f34b1a84a 100644 --- a/ui/select.go +++ b/ui/select.go @@ -28,6 +28,10 @@ type SelectState struct { scope gfx.Scope selected int visible int + trigger gfx.ID // the trigger's hit: the application's id when it named one + // chosen is 1 + the option a key chose, reported by the next Picked and + // cleared then; 0 when no key chose one. + chosen int wheel float32 // the part of a row a trackpad has scrolled so far typed [16]byte typedLen int @@ -84,15 +88,21 @@ func (s *SelectState) Wheel(event gfx.ScrollEvent) gfx.EventResult { // is never called with one and does nothing. func (s *SelectState) Key(event gfx.KeyEvent) gfx.EventResult { count := len(s.labels) - if count == 0 || event.Text == "" || event.Modifiers&(gfx.ModifierControl|gfx.ModifierMeta|gfx.ModifierAlt) != 0 { + if count == 0 || event.Release { + return gfx.EventResult{} + } + at, onItem := event.Target.In(s.scope) + onTrigger := event.Target == s.triggerID(count) + if result, handled := s.navigate(event, count, at, onTrigger, onItem && at < count); handled { + return result + } + if event.Text == "" || event.Modifiers&(gfx.ModifierControl|gfx.ModifierMeta|gfx.ModifierAlt) != 0 { return gfx.EventResult{} } char, _ := utf8.DecodeRuneInString(event.Text) if char == utf8.RuneError || unicode.IsControl(char) || char == ' ' && s.typedLen == 0 { return gfx.EventResult{} } - at, onItem := event.Target.In(s.scope) - onTrigger := event.Target == s.scope.At(count) if !s.Open && !onTrigger || s.Open && !onItem && !onTrigger { return gfx.EventResult{} } @@ -122,6 +132,148 @@ func (s *SelectState) Key(event gfx.KeyEvent) gfx.EventResult { return gfx.EventResult{Handled: true, Repaint: true, Focus: s.scope.At(match), FocusVisible: true} } +// navigate moves an open list and opens or closes it from the keyboard, as a +// select does: the arrows and Home/End move the focus among its options, Enter or +// Space chooses the focused one, and Escape closes it back onto the trigger. The +// value a key chooses is reported by the next Picked, like a click. +func (s *SelectState) navigate(event gfx.KeyEvent, count, at int, onTrigger, onOption bool) (gfx.EventResult, bool) { + if event.Modifiers&(gfx.ModifierControl|gfx.ModifierMeta|gfx.ModifierAlt) != 0 { + return gfx.EventResult{}, false + } + handled := gfx.EventResult{Handled: true, Repaint: true} + if !s.Open { + if !onTrigger { + return gfx.EventResult{}, false + } + target := -1 + switch event.Key { + case gfx.KeyEnter, gfx.KeySpace: + if event.Repeat { + return gfx.EventResult{}, false + } + target = s.selected + case gfx.KeyDown: + target = s.selected + case gfx.KeyUp: + target = s.lastEnabled() + default: + return gfx.EventResult{}, false + } + if target < 0 || optionDisabled(s.disabled, target) { + target = s.nextEnabled(-1, 1) + } + if target < 0 { + return handled, true + } + s.Open = true + s.reveal(target) + return gfx.EventResult{Handled: true, Repaint: true, Focus: s.scope.At(target), FocusVisible: true}, true + } + if onTrigger { + switch event.Key { + case gfx.KeyDown: + if target := s.nextFocus(s.selected, 1); target >= 0 { + return s.focus(target), true + } + case gfx.KeyUp: + if target := s.nextFocus(s.selected, -1); target >= 0 { + return s.focus(target), true + } + case gfx.KeyHome: + if target := s.firstEnabled(); target >= 0 { + return s.focus(target), true + } + case gfx.KeyEnd: + if target := s.lastEnabled(); target >= 0 { + return s.focus(target), true + } + case gfx.KeyEnter, gfx.KeySpace: + if !event.Repeat { + s.Open = false + } + return handled, true + case gfx.KeyEscape: + s.Open = false + return handled, true + } + return gfx.EventResult{}, false + } + if !onOption { + return gfx.EventResult{}, false + } + switch event.Key { + case gfx.KeyDown: + if target := s.nextFocus(at, 1); target >= 0 { + return s.focus(target), true + } + case gfx.KeyUp: + if target := s.nextFocus(at, -1); target >= 0 { + return s.focus(target), true + } + case gfx.KeyHome: + if target := s.firstEnabled(); target >= 0 { + return s.focus(target), true + } + case gfx.KeyEnd: + if target := s.lastEnabled(); target >= 0 { + return s.focus(target), true + } + case gfx.KeyEnter, gfx.KeySpace: + if event.Repeat || optionDisabled(s.disabled, at) { + return handled, true + } + s.chosen, s.Open = at+1, false + return gfx.EventResult{Handled: true, Repaint: true, Focus: s.triggerID(count), FocusVisible: true}, true + case gfx.KeyEscape: + s.Open = false + return gfx.EventResult{Handled: true, Repaint: true, Focus: s.triggerID(count), FocusVisible: true}, true + } + return gfx.EventResult{}, false +} + +// focus moves the list's focus to option i and keeps it inside the window. +func (s *SelectState) focus(i int) gfx.EventResult { + s.reveal(i) + return gfx.EventResult{Handled: true, Repaint: true, Focus: s.scope.At(i), FocusVisible: true} +} + +// reveal scrolls option i into the list's window. +func (s *SelectState) reveal(i int) { + if s.visible <= 0 { + return + } + if i < s.First { + s.First = i + } + if i >= s.First+s.visible { + s.First = i - s.visible + 1 + } + s.First = min(max(s.First, 0), max(len(s.labels)-s.visible, 0)) +} + +// nextFocus is the enabled option after from in direction step, or -1 at the end. +func (s *SelectState) nextFocus(from, step int) int { + if from < 0 { + from = -1 + if step < 0 { + from = len(s.labels) + } + } + for i := from + step; i >= 0 && i < len(s.labels); i += step { + if !optionDisabled(s.disabled, i) { + return i + } + } + return -1 +} + +// nextEnabled is the first enabled option from the start end of the list. +func (s *SelectState) nextEnabled(from, step int) int { return s.nextFocus(from, step) } + +// firstEnabled and lastEnabled are the ends of the options that can be chosen. +func (s *SelectState) firstEnabled() int { return s.nextFocus(-1, 1) } +func (s *SelectState) lastEnabled() int { return s.nextFocus(len(s.labels), -1) } + // match finds the option the typed text selects, searching on from current: the one // after it when one letter is repeated, current itself when more has been typed. func (s *SelectState) match(current int) int { @@ -369,8 +521,19 @@ func (b Box) Picked() (int, bool) { // pickIn is Picked's work, done once a paint. func (d *selectDecl) pickIn() (int, bool) { + if chosen := d.state.chosen; chosen > 0 { + d.state.chosen, d.state.Open = 0, false + return chosen - 1, true + } canvas := d.canvas count := len(d.labels) + if trigger := d.state.trigger; !trigger.IsZero() && canvas.Clicked(trigger) { + d.state.Open = !d.state.Open + if d.state.Open { + d.state.First = min(max(d.selected-d.visible/2, 0), max(count-d.visible, 0)) + } + return 0, false + } index, ok := canvas.ClickedIn(d.scope) if !ok { return 0, false @@ -379,7 +542,7 @@ func (d *selectDecl) pickIn() (int, bool) { case index < count: d.state.Open = false return index, true - case index == count: // the trigger + case index == count: // the trigger, when it is the page's own d.state.Open = !d.state.Open if d.state.Open { d.state.First = min(max(d.selected-d.visible/2, 0), max(count-d.visible, 0)) @@ -394,6 +557,36 @@ func (d *selectDecl) pickIn() (int, bool) { return 0, false } +// selectKey gives the keys of a focused trigger or an open option to its Select: +// Enter, Space, the arrows and Home/End open and move its list, and Enter chooses. +func (p *Page) selectKey(event gfx.KeyEvent) (gfx.EventResult, bool) { + for _, state := range p.selects { + if state.scope == 0 { + continue + } + if _, ok := event.Target.In(state.scope); !ok { + continue + } + result := state.Key(event) + if result.Handled || result.Repaint { + return result, true + } + return gfx.EventResult{}, false + } + return gfx.EventResult{}, false +} + +// triggerID is the id the trigger paints: the application's when it named one. +func (d *selectDecl) triggerID(count int) gfx.ID { return d.state.triggerID(count) } + +// triggerID is the trigger's identity for the keys, which see no declaration. +func (s *SelectState) triggerID(count int) gfx.ID { + if !s.trigger.IsZero() { + return s.trigger + } + return s.scope.At(count) +} + func (f *frame) measureSelect(n *node) { d := &f.widgets.selects[n.aux] widest := d.state.widestOption(f.canvas, d.labels, f.theme.Metrics.FontSizeM) @@ -412,7 +605,7 @@ func (f *frame) paintSelect(n *node) { count := len(d.labels) trigger := Rect{X: n.rect.X, Y: n.rect.Y, Width: n.rect.Width, Height: n.pref[axisY]} options := components.SelectOptions{ - TriggerID: d.scope.At(count), Label: n.label, Placeholder: n.text, Hint: d.hint, + TriggerID: d.triggerID(count), Label: n.label, Placeholder: n.text, Hint: d.hint, Disabled: n.flags&flagDisabled != 0, Layer: d.layer, Scope: d.scope.At(count + 2), DismissID: d.scope.At(count + 1), Viewport: f.bounds, } diff --git a/ui/select_keys_test.go b/ui/select_keys_test.go new file mode 100644 index 000000000..c33b60ecd --- /dev/null +++ b/ui/select_keys_test.go @@ -0,0 +1,104 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// selectPage opens a page with one Select and puts the keyboard on its trigger, +// as Tab does. +func selectPage(t *testing.T, size *string) *pageDriver { + t.Helper() + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.Select(c, size, []string{"S", "M", "L"}, nil).Placeholder("Size") + }) + }) + d.key(gfx.KeyTab) + if got := d.focused(); got != "Size" { + t.Fatalf("Tab focused %q, want the select's trigger", got) + } + return d +} + +// A Select is usable from the keyboard: Enter opens its list on the first option, +// the arrows move, Enter chooses, and the trigger takes the focus back. +func TestSelectOpensAndChoosesFromTheKeyboard(t *testing.T) { + size := "" + d := selectPage(t, &size) + d.key(gfx.KeyEnter) + if got := d.focused(); got != "S" { + t.Fatalf("Enter opened the list on %q, want the first option", got) + } + d.key(gfx.KeyDown) + if got := d.focused(); got != "M" { + t.Fatalf("Down focused %q", got) + } + d.key(gfx.KeyEnter) + if size != "M" { + t.Fatalf("Enter chose %q", size) + } + if d.has("S") { + t.Fatal("the list stayed open after a keyboard choice") + } + if got := d.focused(); got != "Size" { + t.Fatalf("the focus went to %q, want the trigger", got) + } +} + +// Up on the closed trigger opens on the last option, as a select does. +func TestSelectArrowUpFromTheTriggerStartsAtTheLastOption(t *testing.T) { + size := "" + d := selectPage(t, &size) + d.key(gfx.KeyUp) + if got := d.focused(); got != "L" { + t.Fatalf("Up focused %q, want the last option", got) + } + d.key(gfx.KeyEnter) + if size != "L" { + t.Fatalf("Enter chose %q", size) + } +} + +// Escape closes the list and leaves the value alone. +func TestSelectEscapeClosesTheListFromTheKeyboard(t *testing.T) { + size := "S" + d := selectPage(t, &size) + d.key(gfx.KeyEnter) + d.key(gfx.KeyEscape) + if size != "S" { + t.Fatalf("Escape changed the value to %q", size) + } + if d.has("M") { + t.Fatal("Escape left the list open") + } + if got := d.focused(); got != "Size" { + t.Fatalf("Escape left the focus on %q, want the trigger", got) + } +} + +// SelectID names the trigger with the application's identity, so a row's words +// can be its label and the click still opens and chooses. +func TestSelectIDNamesTheTrigger(t *testing.T) { + size := "" + var trigger gfx.ID + d := openPage(t, func(c ui.C) { + if trigger.IsZero() { + trigger = ui.ID(c) + } + ui.SelectID(c, trigger, &size, []string{"S", "M"}, nil).Label("Size") + }) + if hit := d.hit("Size"); hit.ID != trigger { + t.Fatalf("the trigger's hit is %v, want %v", hit.ID, trigger) + } + d.click("Size") + if !d.has("S") { + t.Fatal("a click on the named trigger did not open the list") + } + d.click("M") + if size != "M" { + t.Fatalf("chose %q", size) + } +} diff --git a/ui/splitter.go b/ui/splitter.go index 032c6af4b..0ed22b73a 100644 --- a/ui/splitter.go +++ b/ui/splitter.go @@ -29,6 +29,7 @@ type SplitterState struct { startPos float32 lo, hi float32 // the limits as of the last layout span float32 // the container's extent along the split + thickness float32 // the room the divider took in that layout } // Dragging reports whether the splitter is being dragged. @@ -64,10 +65,14 @@ func (s *SplitterState) Key(event gfx.KeyEvent) gfx.EventResult { // resize keeps the proportion the user chose. A state that holds Pos in pixels // (Ratio zero) is left alone. func (s *SplitterState) keepRatio() { - if s.Ratio <= 0 || s.span <= splitterThickness { + thickness := s.thickness + if thickness <= 0 { + thickness = splitterThickness + } + if s.Ratio <= 0 || s.span <= thickness { return } - s.Ratio = min(max(s.Pos/(s.span-splitterThickness), 0), 1) + s.Ratio = min(max(s.Pos/(s.span-thickness), 0), 1) } func (s *SplitterState) limit(pos float32) float32 { @@ -81,6 +86,9 @@ type splitDecl struct { state *SplitterState first int32 // the pane before the splitter, or -1 minFirst, minSecond float32 + // thickness is the room the divider takes in the layout; zero is the + // default strip. The pointer's strip is never narrower than that default. + thickness float32 } // Splitter adds a draggable divider between two siblings of a Row (a vertical bar, @@ -112,6 +120,17 @@ func (f *frame) Splitter(id gfx.ID, state *SplitterState) Box { return b } +// SplitterThickness sets how much room the divider takes in the layout, for a +// split whose panes should meet with a hairline between them. The pointer's strip +// stays at least as wide as the default (8), centred on the line, so a one-pixel +// divider is still easy to grab. +func (b Box) SplitterThickness(thickness float32) Box { + if n := b.n(); n.kind == kindSplitter { + b.f.widgets.splits[n.aux].thickness = max(thickness, 0.5) + } + return b +} + // Mins sets the least size of the panes either side of a Splitter, along its container. func (b Box) Mins(first, second float32) Box { if n := b.n(); n.kind == kindSplitter { @@ -126,10 +145,14 @@ func (b Box) Mins(first, second float32) Box { func (f *frame) splitsRow(n *node) bool { return n.parent < 0 || f.nodes[n.parent].dir != column } func (f *frame) measureSplitter(n *node) { + thickness := f.widgets.splits[n.aux].thickness + if thickness <= 0 { + thickness = splitterThickness + } if f.splitsRow(n) { - n.pref = [2]float32{splitterThickness, 0} + n.pref = [2]float32{thickness, 0} } else { - n.pref = [2]float32{0, splitterThickness} + n.pref = [2]float32{0, thickness} } } @@ -186,6 +209,7 @@ func (f *frame) placeSplitRatios(n *node, axis int, avail float32) { first := &f.nodes[d.first] first.raw[axis], first.pref[axis] = pos, pos state.Pos = pos + state.thickness = thickness state.lo, state.hi, state.span = lo, hi, avail } } @@ -202,6 +226,11 @@ func (f *frame) reportSplitters() { s := f.widgets.splits[n.aux].state lo, hi, span := f.splitLimits(n) s.lo, s.hi, s.span = lo, hi, span + axis := axisY + if f.splitsRow(n) { + axis = axisX + } + s.thickness = *extent(&n.rect, axis) if pos := s.limit(s.Pos); pos != s.Pos { s.Pos = pos if f.canvas != nil { @@ -270,5 +299,17 @@ func (f *frame) paintSplitter(n *node) { if label == "" { label = "Resize panes" } - canvas.HitWithOptions(n.id, r, label, gfx.HitOptions{Role: gfx.RoleSlider, Cursor: cursor}) + // The pointer's strip is never narrower than the default, so a hairline + // divider between the panes is still easy to grab. + hit := r + if row { + if pad := (max(d.thickness, splitterThickness) - r.Width) / 2; pad > 0 { + hit.X, hit.Width = hit.X-pad, hit.Width+2*pad + } + } else { + if pad := (max(d.thickness, splitterThickness) - r.Height) / 2; pad > 0 { + hit.Y, hit.Height = hit.Y-pad, hit.Height+2*pad + } + } + canvas.HitWithOptions(n.id, hit, label, gfx.HitOptions{Role: gfx.RoleSlider, Cursor: cursor}) } diff --git a/ui/tabs.go b/ui/tabs.go index d8d97d074..7d0e005fc 100644 --- a/ui/tabs.go +++ b/ui/tabs.go @@ -95,9 +95,15 @@ func (f *frame) measureTabs(n *node) { func (f *frame) paintTabs(n *node) { t := &f.widgets.tabs[n.aux] - bounds := Rect{X: n.rect.X, Y: n.rect.Y, Width: n.rect.Width, Height: tabHeight} + // The strip is as tall as the element: an explicit height is the trigger's, + // and the line variant's measured height keeps the room for its indicator + // below the triggers. + height := n.rect.Height + if t.line && !t.vertical { + height = max(height-tabIndicator, 0) + } + bounds := Rect{X: n.rect.X, Y: n.rect.Y, Width: n.rect.Width, Height: height} if t.vertical { - bounds.Height = n.rect.Height if t.line { bounds.Width = max(bounds.Width-tabIndicator-1, 0) } diff --git a/ui/tabs_test.go b/ui/tabs_test.go index ded147038..1f1378163 100644 --- a/ui/tabs_test.go +++ b/ui/tabs_test.go @@ -44,6 +44,40 @@ func TestTabsArePaintedLikeTheComponent(t *testing.T) { } } +// A Tabs given a height paints its triggers that tall, so a strip fits the row +// sized for it and a line's indicator keeps its room below them. +func TestTabsTakeTheirDeclaredHeight(t *testing.T) { + theme := gfx.LightTheme() + for _, test := range []struct { + name string + declare func(Box) Box + line bool + height float32 + }{ + {"28", func(b Box) Box { return b }, false, 28}, + {"32", func(b Box) Box { return b }, false, 32}, + {"34", func(b Box) Box { return b }, false, 34}, + {"line-40", func(b Box) Box { return b.Line() }, true, 40}, + } { + flexed, direct := testCanvas(), testCanvas() + var view View + view.Draw(flexed, theme, gfx.Rect{Width: 300, Height: 200}, func(f *Frame) { + f.Column().Children(func() { test.declare(f.Tabs(tabsScope, tabLabels, 1).Height(test.height)) }) + }) + stripHeight := test.height + if test.line { + // A line's height keeps the indicator's room below its triggers. + stripHeight -= tabIndicator + } + strip := components.BeginTabList(direct, theme, gfx.Rect{Width: 300, Height: stripHeight}, tabsScope, tabLabels, 1) + if test.line { + strip = strip.Line() + } + strip.Paint() + sameCanvas(t, test.name, flexed, direct) + } +} + func TestTabsReportTheClickedTabAndTheContentFollowsTheIndex(t *testing.T) { theme := gfx.LightTheme() current := 0