Split into category packages; module github.com/ZacharyZhang-NY/MujicaUI

This commit is contained in:
ZacharyZhang-NY committed 2026-10-05 16:18:48 -04:00
1 parent 5a7e921c7e
commit 22b53e9e9e
1822 files changed
+24568 -21314

No files matched your search

+113
View File
@@ -0,0 +1,113 @@
package overlay
import (
"fmt"
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/icons"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/internal"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// AlertDialogOptions configure an AlertDialog. Title is required.
type AlertDialogOptions struct {
Title string
Description string
// ConfirmLabel is "Delete" when empty; CancelLabel is "Cancel".
ConfirmLabel string
CancelLabel string
// ConfirmText, when set, must be typed before Confirm unlocks.
ConfirmText string
}
// AlertDialogResult reports the choice made in this frame.
type AlertDialogResult struct {
Confirmed bool
Canceled bool
}
// alertDialogState is the typed confirmation, kept while the alert shows.
type alertDialogState struct{ typed string }
// AlertDialog confirms a destructive action; Cancel has the focus.
func AlertDialog(c *ui.Context, open *bool, opts AlertDialogOptions) AlertDialogResult {
if opts.Title == "" {
panic("mujica: AlertDialog needs a Title")
}
var res AlertDialogResult
site, focus := core.OverlaySite(c)
if !*open {
focus.Closed(c, site)
return res
}
core.OverlayLayer(c, open)
k := core.Tokens(c)
u := core.Density(c).Unit()
confirmLabel, cancelLabel := opts.ConfirmLabel, opts.CancelLabel
if confirmLabel == "" {
confirmLabel = core.Msg(c, "alert_dialog.confirm")
}
if cancelLabel == "" {
cancelLabel = core.Msg(c, "alert_dialog.cancel")
}
shown, backClicked := true, false
panel := ui.DialogBase(c, &shown, func(back, panel *ui.Element) {
backClicked = back.Clicked()
st := ui.Local(panel, "mujica.alert", func() alertDialogState { return alertDialogState{} })
p := core.OverlayEnter(c, panel)
back.Background(OverlayScrim(k).Alpha(p)).Padding(16)
DialogPanel(c, panel, 420, false, p)
panel.Role(ui.RoleAlertDialog).Label(opts.Title).Description(opts.Description)
ui.Row(c).Gap(u * 3).AlignItems(ui.Start).Shrink(0).Children(func() {
ui.Icon(c, icons.Must("triangle-alert")).Size(22, 22).TextColor(k.Danger).Shrink(0).Margin(1, 0, 0, 0)
ui.Text(c, opts.Title).Font(theme.SerifFont).FontSize(core.FontSize(c, theme.H3Size)).FontWeight(600).Grow(1)
})
if opts.Description != "" {
// A long description scrolls so the field and the actions stay in the window.
ui.Scroll(c).Shrink(1).Padding(0, 0, 0, 22+u*3).Children(func() {
ui.Text(c, opts.Description).TextColor(k.TextMuted)
})
}
if opts.ConfirmText != "" {
alertDialogTyped(c, st, opts.ConfirmText)
}
unlocked := opts.ConfirmText == "" || st.typed == opts.ConfirmText
dialogActions(c, func() {
if input.Button(c, cancelLabel, input.ButtonOptions{Variant: input.Secondary}).AutoFocus().Clicked() {
res.Canceled = true
}
if input.Button(c, confirmLabel, input.ButtonOptions{Variant: input.Danger, Disabled: !unlocked}).Clicked() {
res.Confirmed = true
}
})
})
focus.Shown(panel)
if !shown && !backClicked {
res.Canceled = true // Escape
}
if res.Confirmed {
res.Canceled = false
}
if res.Confirmed || res.Canceled {
slog.Debug("mujica: alert_dialog close", "confirmed", res.Confirmed)
*open = false
}
return res
}
// alertDialogTyped builds the confirmation field; Enter in it never confirms, even mid-composition.
func alertDialogTyped(c *ui.Context, st *alertDialogState, want string) {
k := core.Tokens(c)
d := core.Density(c)
prompt := fmt.Sprintf(core.Msg(c, "alert_dialog.type_to_unlock"), want)
ui.Column(c).Gap(d.Unit()).Shrink(0).Children(func() {
ui.Text(c, prompt).FontSize(core.FontSize(c, theme.CaptionSize)).TextColor(k.TextMuted)
in := ui.TextInputBase(c, &st.typed).Label(prompt).MinHeight(d.ControlHeight()).Padding(0, d.Unit()*3).
Radius(theme.ControlRadius).Background(k.Surface).Border(theme.BorderWidth, k.ControlBorder)
internal.Ring(in, k.Focus, theme.ControlRadius)
})
}
+127
View File
@@ -0,0 +1,127 @@
package overlay
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
type alertApp struct {
open bool
opts AlertDialogOptions
confirmed, canceled int
}
func (a *alertApp) view(c *ui.Context) {
core.Use(c, core.Settings{})
if input.Button(c, "Remove", input.ButtonOptions{}).Clicked() {
a.open = true
}
r := AlertDialog(c, &a.open, a.opts)
if r.Confirmed {
a.confirmed++
}
if r.Canceled {
a.canceled++
}
}
func newAlertApp(opts AlertDialogOptions) (*alertApp, *ui.Tester) {
opts.Title = "Delete the archive?"
a := &alertApp{opts: opts}
tt := ui.NewTester(a.view, 600, 400)
_ = tt.Click("Remove")
return a, tt
}
func TestAlertDialogFocusesCancelAndEnterCancels(t *testing.T) {
a, tt := newAlertApp(AlertDialogOptions{Description: "This cannot be undone."})
if !a.open || !tt.Focused("Cancel") {
t.Fatalf("open %v, Cancel focused %v", a.open, tt.Focused("Cancel"))
}
tt.Key(0, ui.KeyEnter)
if a.confirmed != 0 || a.canceled != 1 || a.open {
t.Fatalf("Enter: confirmed %d canceled %d open %v", a.confirmed, a.canceled, a.open)
}
if !tt.Focused("Remove") {
t.Fatal("focus not restored")
}
}
func TestAlertDialogIgnoresBackdropEscapeCancels(t *testing.T) {
a, tt := newAlertApp(AlertDialogOptions{})
tt.ClickAt(8, 392)
if !a.open || a.canceled != 0 {
t.Fatalf("backdrop click: open %v canceled %d", a.open, a.canceled)
}
tt.Key(0, ui.KeyEscape)
if a.open || a.canceled != 1 || a.confirmed != 0 {
t.Fatalf("Escape: open %v canceled %d confirmed %d", a.open, a.canceled, a.confirmed)
}
}
func TestAlertDialogConfirmOnce(t *testing.T) {
a, tt := newAlertApp(AlertDialogOptions{ConfirmLabel: "Erase"})
if err := tt.Click("Erase"); err != nil {
t.Fatal(err)
}
if a.confirmed != 1 || a.canceled != 0 || a.open {
t.Fatalf("confirmed %d canceled %d open %v", a.confirmed, a.canceled, a.open)
}
}
func TestAlertDialogConfirmTextGatesEnter(t *testing.T) {
a, tt := newAlertApp(AlertDialogOptions{ConfirmText: "archive"})
_ = tt.Click("Delete") // locked
if a.confirmed != 0 || !a.open {
t.Fatal("locked Delete confirmed")
}
if err := tt.Click("Type “archive” to confirm"); err != nil {
t.Fatal(err)
}
tt.Type("archiv")
tt.Key(0, ui.KeyEnter)
if a.confirmed != 0 || !a.open {
t.Fatalf("before the target matched: confirmed %d open %v", a.confirmed, a.open)
}
tt.Type("e")
tt.Key(0, ui.KeyEnter)
if a.confirmed != 0 || !a.open {
t.Fatalf("Enter in the field confirmed: %d", a.confirmed)
}
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyTab)
if !tt.Focused("Delete") {
t.Fatal("Delete not reachable once unlocked")
}
tt.Key(0, ui.KeyEnter)
if a.confirmed != 1 || a.open {
t.Fatalf("typed target: confirmed %d open %v", a.confirmed, a.open)
}
}
// MyGo commits a composition on Enter and then handles the key (ui/editor.go:688).
func TestAlertDialogEnterDuringCompositionDoesNotConfirm(t *testing.T) {
a, tt := newAlertApp(AlertDialogOptions{ConfirmText: "archive"})
if err := tt.Click("Type “archive” to confirm"); err != nil {
t.Fatal(err)
}
tt.Compose("archive", 7)
tt.Key(0, ui.KeyEnter)
if a.confirmed != 0 || !a.open {
t.Fatalf("Enter while composing confirmed: %d", a.confirmed)
}
}
func TestAlertDialogSnapshot(t *testing.T) {
snapshot(t, "alert_dialog", 560, 320, func(c *ui.Context) {
open := true
AlertDialog(c, &open, AlertDialogOptions{
Title: "Burn the old letters?", Description: "Twelve letters will be destroyed. This cannot be undone.",
ConfirmText: "letters",
})
})
}
+54
View File
@@ -0,0 +1,54 @@
package overlay
import (
"log/slog"
"github.com/egoist/mygo/ui"
)
// ContextMenuOptions configure a ContextMenu.
type ContextMenuOptions struct {
Disabled bool
}
// contextMenuState is where the menu opened, relative to the target.
type contextMenuState struct {
open bool
x, y float32
}
// ContextMenu gives the container target an in-window menu at the pointer or below the focus.
func ContextMenu(c *ui.Context, target *ui.Element, opts ContextMenuOptions, build func(m *PopupMenu)) *ui.Element {
if target == nil {
panic("mujica: ContextMenu needs a target")
}
if build == nil {
panic("mujica: ContextMenu needs a build function")
}
st := ui.Local(target, "mujica.contextmenu", func() contextMenuState { return contextMenuState{} })
if opts.Disabled {
st.open = false
return target
}
target.HandleInput(func(ev ui.InputEvent) bool {
if ev.Kind != ui.InputPointerDown || ev.Button != 1 {
return false
}
st.open, st.x, st.y = true, ev.X, ev.Y
slog.Debug("mujica: context_menu open", "by", "pointer")
return true
})
if target.Shortcut(0, ui.KeyContextMenu) || target.Shortcut(ui.Shift, ui.KeyF10) {
st.open, st.x, st.y = true, 0, target.Bounds().H
slog.Debug("mujica: context_menu open", "by", "keyboard")
}
if !st.open {
return target
}
var anchor *ui.Element
target.Children(func() {
anchor = ui.Box(c).Key("mujica.contextmenu.anchor").Absolute().Left(st.x).Top(st.y).Size(1, 1).PassThrough()
})
PopupMenuOpen(c, anchor, &st.open, build)
return target
}
+113
View File
@@ -0,0 +1,113 @@
package overlay
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
func contextMenuTester(a *menuApp, disabled bool) *ui.Tester {
return ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Column(c).Padding(20).Gap(8).Children(func() {
row := ui.Row(c).Height(80).FillWidth().Padding(12).Background(core.Tokens(c).Surface)
row.Children(func() {
input.Button(c, "Letter row", input.ButtonOptions{Variant: input.Ghost})
})
ContextMenu(c, row, ContextMenuOptions{Disabled: disabled}, a.build)
})
}, 500, 320)
}
func TestContextMenuOpensAtPointer(t *testing.T) {
a := &menuApp{}
tt := contextMenuTester(a, false)
tt.RightClickAt(200, 60)
tt.Frame()
r, ok := tt.Find("Rename")
// The label sits past the menu padding and the check column.
if !ok || r.X < 230 || r.X > 250 || r.Y < 60 || r.Y > 110 {
t.Fatalf("menu item %+v not at the pointer (200, 60)", r)
}
if tt.Menu() != nil {
t.Fatal("the system menu opened")
}
_ = tt.Click("Rename")
if len(a.chosen) != 1 || tt.HasText("Rename") {
t.Fatalf("chosen %q", a.chosen)
}
}
func TestContextMenuOnInnerButtonAndEdge(t *testing.T) {
a := &menuApp{}
tt := contextMenuTester(a, false)
b, _ := tt.Find("Letter row")
tt.RightClickAt(b.X+4, b.Y+4)
if !tt.HasText("Rename") {
t.Fatal("right click on an inner button did not open the menu")
}
tt.Key(0, ui.KeyEscape)
tt.RightClickAt(480, 95)
tt.Frame()
last, _ := tt.Find("Burn")
first, _ := tt.Find("Rename")
if last.Y+last.H > 320 || first.Y > 95 || last.X+last.W > 500 {
t.Fatalf("menu not kept in the window: first %+v last %+v", first, last)
}
}
func TestContextMenuKeyboard(t *testing.T) {
for _, key := range []struct {
mods ui.Modifiers
key ui.Key
}{{0, ui.KeyContextMenu}, {ui.Shift, ui.KeyF10}} {
a := &menuApp{}
tt := contextMenuTester(a, false)
tt.Key(0, ui.KeyTab)
tt.Key(key.mods, key.key)
tt.Frame()
if !tt.Focused("Rename") {
t.Fatalf("%v: menu did not open with focus", key)
}
item, _ := tt.Find("Rename")
if item.Y < 100 {
t.Fatalf("%v: keyboard menu %+v not below the focused target", key, item)
}
tt.Key(0, ui.KeyEscape)
if tt.HasText("Rename") || !tt.Focused("Letter row") {
t.Fatalf("%v: Escape did not close and restore", key)
}
}
}
func TestContextMenuDisabled(t *testing.T) {
a := &menuApp{}
tt := contextMenuTester(a, true)
tt.RightClickAt(200, 60)
tt.Key(0, ui.KeyTab)
tt.Key(ui.Shift, ui.KeyF10)
if tt.HasText("Rename") {
t.Fatal("disabled context menu opened")
}
}
func TestContextMenuSnapshot(t *testing.T) {
a := &menuApp{}
snapshotAfter(t, "context_menu", 460, 320, func(c *ui.Context) {
ui.Column(c).Padding(20).Children(func() {
row := ui.Row(c).Height(36).FillWidth().Padding(0, 12).AlignItems(ui.Center).Background(core.Tokens(c).Selection)
row.Children(func() { ui.Text(c, "Letter to the Countess") })
ContextMenu(c, row, ContextMenuOptions{}, a.build)
})
}, func(tt *ui.Tester) {
tt.RightClickAt(160, 40)
r, ok := tt.Find("Pinned")
if !ok {
t.Fatal("menu did not open")
}
tt.Move(r.X+4, r.Y+4) // hover highlight on Pinned
})
}
+130
View File
@@ -0,0 +1,130 @@
package overlay
import (
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/icons"
"github.com/ZacharyZhang-NY/MujicaUI/internal"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// DialogOptions configure a Dialog. Title is required.
type DialogOptions struct {
Title string
Description string
// Width is 440 DIPs when zero; the window always bounds it.
Width float32
// Decorated draws the double border, corner ornaments and title rule.
Decorated bool
// Actions builds the footer, usually buttons, aligned to the end.
Actions func()
// KeepOnBackdrop ignores clicks on the backdrop.
KeepOnBackdrop bool
// KeepOnEscape ignores Escape.
KeepOnEscape bool
// HideClose removes the close button from the header.
HideClose bool
}
// Dialog shows a modal dialog while *open is true, trapping and then restoring the focus.
func Dialog(c *ui.Context, open *bool, opts DialogOptions, content func()) *ui.Element {
if opts.Title == "" {
panic("mujica: Dialog needs a Title")
}
site, focus := core.OverlaySite(c)
if !*open {
focus.Closed(c, site)
return nil
}
core.OverlayLayer(c, open)
k := core.Tokens(c)
shown, backClicked, closed := true, false, false
panel := ui.DialogBase(c, &shown, func(back, panel *ui.Element) {
backClicked = back.Clicked()
p := core.OverlayEnter(c, panel)
back.Background(OverlayScrim(k).Alpha(p)).Padding(16)
DialogPanel(c, panel, opts.Width, opts.Decorated, p)
panel.Label(opts.Title)
if opts.Description != "" {
panel.Description(opts.Description)
}
closed = dialogHeader(c, opts.Title, opts.Decorated, !opts.HideClose, "dialog.close")
// Description and content scroll together so the actions always keep their room.
ui.Scroll(c).Shrink(1).Gap(core.Density(c).Unit() * 3).Children(func() {
if opts.Description != "" {
ui.Text(c, opts.Description).TextColor(k.TextMuted)
}
if content != nil {
content()
}
})
if opts.Actions != nil {
dialogActions(c, opts.Actions)
}
})
focus.Shown(panel)
switch {
case closed:
slog.Debug("mujica: dialog close", "by", "button")
*open = false
case !shown && backClicked && !opts.KeepOnBackdrop:
slog.Debug("mujica: dialog close", "by", "backdrop")
*open = false
case !shown && !backClicked && !opts.KeepOnEscape:
slog.Debug("mujica: dialog close", "by", "escape")
*open = false
}
return panel
}
// DialogPanel styles a centered dialog panel at entrance progress p.
func DialogPanel(c *ui.Context, panel *ui.Element, width float32, decorated bool, p float32) {
k := core.Tokens(c)
u := core.Density(c).Unit()
if width == 0 {
width = 440
}
w, h := c.Size()
core.OverlayStyle(c, panel, p)
panel.Width(width).MaxWidth(w-32).MaxHeight(h-32).Padding(u*6).Gap(u*3).Margin(8*(1-p), 0, 0, 0)
if decorated {
panel.Border(theme.BorderWidth, k.Ornament).Padding(u*6 + 6).DrawOver(func(pt *ui.Painter, r ui.Rect) {
internal.Frame(pt, r, 5, 7, k.Ornament)
})
}
}
// dialogHeader builds the title and close button; it reports a close click.
func dialogHeader(c *ui.Context, title string, decorated, closable bool, closeKey string) bool {
k := core.Tokens(c)
u := core.Density(c).Unit()
clicked := false
ui.Column(c).Gap(u).Shrink(0).Children(func() {
ui.Row(c).Gap(u * 3).AlignItems(ui.Start).Children(func() {
ui.Text(c, title).Font(theme.SerifFont).FontSize(core.FontSize(c, theme.H3Size)).FontWeight(600).Grow(1)
if closable {
clicked = core.IconAction(c, icons.Must("x"), core.Msg(c, closeKey)).Margin(-4, -4, 0, 0).Clicked()
}
})
if decorated {
dialogRule(c, k.Ornament)
}
})
return clicked
}
// dialogRule is the ornament line under a decorated title.
func dialogRule(c *ui.Context, ink ui.Color) {
ui.Box(c).FillWidth().Height(9).Margin(2, 0, 2, 0).Draw(func(p *ui.Painter, r ui.Rect) {
internal.RuleDiamond(p, r, 10, 7, ink)
})
}
// dialogActions lays out a dialog footer.
func dialogActions(c *ui.Context, actions func()) {
u := core.Density(c).Unit()
ui.Row(c).Gap(u*2).Justify(ui.End).Wrap().Shrink(0).Margin(u*2, 0, 0, 0).Children(actions)
}
+230
View File
@@ -0,0 +1,230 @@
package overlay
import (
"testing"
"time"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
type dialogApp struct {
open bool
opts DialogOptions
saved int
name string
densities theme.Density
}
func (a *dialogApp) view(c *ui.Context) {
core.Use(c, core.Settings{Mode: core.Light, Density: a.densities})
if input.Button(c, "Rename", input.ButtonOptions{}).Clicked() {
a.open = true
}
a.opts.Actions = func() {
if input.Button(c, "Cancel", input.ButtonOptions{Variant: input.Secondary}).Clicked() {
a.open = false
}
if input.Button(c, "Save", input.ButtonOptions{}).Clicked() {
a.saved++
a.open = false
}
}
Dialog(c, &a.open, a.opts, func() {
ui.TextInput(c, &a.name)
})
}
func newDialogApp(opts DialogOptions) (*dialogApp, *ui.Tester) {
opts.Title = "Rename"
a := &dialogApp{opts: opts}
tt := ui.NewTester(a.view, 600, 400)
tt.SetPreferences(ui.Preferences{ReduceMotion: true, TextScale: 1})
return a, tt
}
func TestDialogOpenFocusTrapRestore(t *testing.T) {
a, tt := newDialogApp(DialogOptions{Description: "Pick a new name."})
if err := tt.Click("Rename"); err != nil {
t.Fatal(err)
}
if !a.open || !tt.HasText("Pick a new name.") {
t.Fatalf("open %v, texts %q", a.open, tt.Texts())
}
if !tt.Focused("Close") {
t.Fatalf("focus did not move into the dialog")
}
// Tab cycles Close, input, Cancel, Save and back to Close.
for range 3 {
tt.Key(0, ui.KeyTab)
}
if !tt.Focused("Save") {
t.Fatalf("tab order left the dialog")
}
tt.Key(0, ui.KeyTab)
if !tt.Focused("Close") {
t.Fatalf("tab did not wrap inside the dialog")
}
tt.Key(0, ui.KeyEscape)
if a.open {
t.Fatal("Escape did not close")
}
if !tt.Focused("Rename") {
t.Fatal("focus not restored to the opener")
}
}
func TestDialogActionsAndClose(t *testing.T) {
a, tt := newDialogApp(DialogOptions{})
_ = tt.Click("Rename")
if err := tt.Click("Save"); err != nil {
t.Fatal(err)
}
if a.saved != 1 || a.open {
t.Fatalf("saved %d open %v", a.saved, a.open)
}
_ = tt.Click("Rename")
if err := tt.Click("Close"); err != nil {
t.Fatal(err)
}
if a.open || a.saved != 1 {
t.Fatalf("close button: open %v saved %d", a.open, a.saved)
}
}
func TestDialogCloseRules(t *testing.T) {
a, tt := newDialogApp(DialogOptions{})
_ = tt.Click("Rename")
tt.ClickAt(10, 390)
if a.open {
t.Fatal("backdrop click did not close")
}
a, tt = newDialogApp(DialogOptions{KeepOnBackdrop: true, KeepOnEscape: true, HideClose: true})
_ = tt.Click("Rename")
tt.ClickAt(10, 390)
tt.Key(0, ui.KeyEscape)
if !a.open {
t.Fatal("kept dialog closed")
}
if tt.HasText("Close") {
t.Fatal("close button shown with HideClose")
}
if _, ok := tt.Find("Close"); ok {
t.Fatal("close button present with HideClose")
}
}
func TestDialogEscapeGoesToNestedPopoverFirst(t *testing.T) {
open, inner := true, false
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
Dialog(c, &open, DialogOptions{Title: "Outer"}, func() {
b := input.Button(c, "More", input.ButtonOptions{})
if b.Clicked() {
inner = true
}
Popover(c, b, &inner, PopoverOptions{}, func() { ui.Text(c, "Inner") })
})
}, 600, 400)
_ = tt.Click("More")
if !inner {
t.Fatal("popover did not open")
}
tt.Key(0, ui.KeyEscape)
if inner || !open {
t.Fatalf("after one Escape inner %v outer %v", inner, open)
}
tt.Key(0, ui.KeyEscape)
if open {
t.Fatal("second Escape did not close the dialog")
}
}
func TestDialogNeedsTitle(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("no panic")
}
}()
open := true
ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
Dialog(c, &open, DialogOptions{}, nil)
}, 300, 200)
}
func dialogSnapshotView(d theme.Density, decorated bool) func(c *ui.Context) {
return func(c *ui.Context) {
mode := core.Light
if core.Tokens(c).Dark {
mode = core.Dark
}
core.Use(c, core.Settings{Mode: mode, Density: d})
open := true
name := "Ophelia"
ui.Column(c).Padding(24).Children(func() { ui.Text(c, "Behind the dialog") })
Dialog(c, &open, DialogOptions{
Title: "Rename the chamber", Description: "The new name shows in every hall.", Decorated: decorated,
Actions: func() {
input.Button(c, "Cancel", input.ButtonOptions{Variant: input.Secondary})
input.Button(c, "Rename", input.ButtonOptions{})
},
}, func() { ui.TextInput(c, &name) })
}
}
func TestDialogEscapeHidesTooltipBeforeClosing(t *testing.T) {
open := true
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
Dialog(c, &open, DialogOptions{Title: "Outer", HideClose: true}, func() {
b := input.Button(c, "Seal", input.ButtonOptions{})
Tooltip(c, b, "Seal with wax", TooltipOptions{Delay: time.Millisecond})
})
}, 600, 400)
tt.Key(0, ui.KeyTab) // keyboard focus on Seal
if !overlayUntil(tt, func() bool { return tt.HasText("Seal with wax") }) {
t.Fatal("tooltip did not show in the dialog")
}
tt.Key(0, ui.KeyEscape)
if tt.HasText("Seal with wax") || !open {
t.Fatalf("first Escape: tip shown %v, dialog open %v", tt.HasText("Seal with wax"), open)
}
tt.Key(0, ui.KeyEscape)
if open {
t.Fatal("second Escape did not close the dialog")
}
}
func TestDialogFocusFallsBackWhenOpenerIsGone(t *testing.T) {
open, gone := false, false
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Column(c).Children(func() {
input.Button(c, "First", input.ButtonOptions{})
if !gone && input.Button(c, "Open", input.ButtonOptions{}).Clicked() {
open, gone = true, true
}
Dialog(c, &open, DialogOptions{Title: "Gone"}, nil)
input.Button(c, "Next", input.ButtonOptions{})
})
}, 600, 400)
_ = tt.Click("Open")
tt.Key(0, ui.KeyEscape)
if open {
t.Fatal("Escape did not close")
}
tt.Key(0, ui.KeyTab)
if !tt.Focused("Next") {
t.Fatal("focus did not fall back to the dialog's place in the window")
}
}
func TestDialogSnapshot(t *testing.T) {
snapshot(t, "dialog", 560, 360, dialogSnapshotView(theme.Default, true))
snapshot(t, "dialog-compact", 560, 360, dialogSnapshotView(theme.Compact, false))
snapshot(t, "dialog-comfortable", 560, 400, dialogSnapshotView(theme.Comfortable, true))
}
+2
View File
@@ -0,0 +1,2 @@
// Package overlay holds MujicaUI dialogs, drawers, popovers, tooltips and menus that float above the view.
package overlay
+154
View File
@@ -0,0 +1,154 @@
package overlay
import (
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// DrawerSide is the window edge a Drawer comes from. The zero value is DrawerRight.
type DrawerSide int
const (
DrawerRight DrawerSide = iota
DrawerLeft
DrawerTop
DrawerBottom
)
// DrawerOptions configure a Drawer. Title is required.
type DrawerOptions struct {
Title string
Side DrawerSide
// Size is the width or height (360 or 280 when zero), kept within 160 DIPs and 90% of the window.
Size float32
// NonModal leaves the window usable and the focus free.
NonModal bool
// Actions builds the footer, aligned to the end.
Actions func()
}
// Drawer shows a panel along a window edge while *open is true; Escape closes it.
func Drawer(c *ui.Context, open *bool, opts DrawerOptions, content func()) *ui.Element {
if opts.Title == "" {
panic("mujica: Drawer needs a Title")
}
if opts.Side < DrawerRight || opts.Side > DrawerBottom {
panic("mujica: Drawer Side out of range")
}
if opts.Size < 0 {
panic("mujica: Drawer Size is negative")
}
site, focus := core.OverlaySite(c)
if !*open {
focus.Closed(c, site)
return nil
}
k := core.Tokens(c)
size := drawerSize(c, opts)
closed := false
body := func(panel *ui.Element, p float32) {
drawerPanel(c, panel, opts.Side, size, p)
panel.Label(opts.Title)
closed = dialogHeader(c, opts.Title, false, true, "drawer.close")
if content != nil {
ui.Scroll(c).Grow(1).Shrink(1).Children(content)
}
if opts.Actions != nil {
dialogActions(c, opts.Actions)
}
}
var panel *ui.Element
escaped := false
if opts.NonModal {
ui.Overlay(c, func() {
panel = ui.Column(c).Absolute().Role(ui.RoleDialog)
p := core.OverlayEnter(c, panel)
drawerPlace(c, panel, opts.Side, size*p)
panel.Children(func() { body(panel, p) })
})
escaped = core.OverlayEscape(c, open)
} else {
core.OverlayLayer(c, open)
shown := true
panel = ui.DialogBase(c, &shown, func(back, panel *ui.Element) {
p := core.OverlayEnter(c, panel)
back.Background(OverlayScrim(k).Alpha(p))
drawerBackdrop(back, opts.Side)
body(panel, p)
})
escaped = !shown
}
focus.Shown(panel)
if closed || escaped {
slog.Debug("mujica: drawer close", "escape", escaped)
*open = false
}
return panel
}
func drawerSize(c *ui.Context, opts DrawerOptions) float32 {
w, h := c.Size()
extent, size := w, opts.Size
if opts.Side == DrawerTop || opts.Side == DrawerBottom {
extent = h
if size == 0 {
size = 280
}
} else if size == 0 {
size = 360
}
return max(min(size, extent*0.9), min(160, extent))
}
func drawerHorizontal(s DrawerSide) bool { return s == DrawerLeft || s == DrawerRight }
// drawerBackdrop lines the panel up against its edge inside a modal backdrop.
func drawerBackdrop(back *ui.Element, s DrawerSide) {
if drawerHorizontal(s) {
back.Row()
}
back.AlignItems(ui.Stretch).Justify(ui.Start)
if s == DrawerRight || s == DrawerBottom {
back.Justify(ui.End)
}
}
// drawerPlace puts a non-modal panel against its edge, shown by size.
func drawerPlace(c *ui.Context, panel *ui.Element, s DrawerSide, size float32) {
w, h := c.Size()
switch s {
case DrawerRight:
panel.Left(w - size).Top(0).Height(h)
case DrawerLeft:
panel.Left(0).Top(0).Height(h)
case DrawerTop:
panel.Left(0).Top(0).Width(w)
case DrawerBottom:
panel.Left(0).Top(h - size).Width(w)
}
}
// drawerPanel styles the panel at entrance progress p, sliding in from its edge.
func drawerPanel(c *ui.Context, panel *ui.Element, s DrawerSide, size, p float32) {
k := core.Tokens(c)
u := core.Density(c).Unit()
off := -(1 - p) * size
panel.Background(k.Surface).TextColor(k.Text).Opacity(p).Padding(u*6).Gap(u*3).
Shadow(0, 0, 24, 0, ui.RGBA(0, 0, 0, 0.18*p))
bw := theme.BorderWidth
switch s {
case DrawerRight:
panel.Width(size).BorderWidth(0, 0, 0, bw).Margin(0, off, 0, 0)
case DrawerLeft:
panel.Width(size).BorderWidth(0, bw, 0, 0).Margin(0, 0, 0, off)
case DrawerTop:
panel.Height(size).BorderWidth(0, 0, bw, 0).Margin(off, 0, 0, 0)
case DrawerBottom:
panel.Height(size).BorderWidth(bw, 0, 0, 0).Margin(0, 0, off, 0)
}
panel.BorderColor(k.Border)
}
+132
View File
@@ -0,0 +1,132 @@
package overlay
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
type drawerApp struct {
open bool
opts DrawerOptions
clicked int
panel ui.Rect
}
func (a *drawerApp) view(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Row(c).Gap(8).Children(func() {
if input.Button(c, "Filters", input.ButtonOptions{}).Clicked() {
a.open = true
}
if input.Button(c, "Behind", input.ButtonOptions{}).Clicked() {
a.clicked++
}
})
if p := Drawer(c, &a.open, a.opts, func() {
input.Button(c, "Apply", input.ButtonOptions{})
}); p != nil {
a.panel = p.Bounds()
}
}
func newDrawerApp(opts DrawerOptions) (*drawerApp, *ui.Tester) {
opts.Title = "Filters panel"
a := &drawerApp{opts: opts}
tt := ui.NewTester(a.view, 800, 500)
tt.SetPreferences(ui.Preferences{ReduceMotion: true, TextScale: 1})
_ = tt.Click("Filters")
tt.Frame()
return a, tt
}
func TestDrawerSides(t *testing.T) {
for _, tc := range []struct {
side DrawerSide
x, y, w, h float32
}{
{DrawerRight, 440, 0, 360, 500},
{DrawerLeft, 0, 0, 360, 500},
{DrawerTop, 0, 0, 800, 280},
{DrawerBottom, 0, 220, 800, 280},
} {
for _, nonModal := range []bool{false, true} {
a, _ := newDrawerApp(DrawerOptions{Side: tc.side, NonModal: nonModal})
got := a.panel
if got.X != tc.x || got.Y != tc.y || got.W != tc.w || got.H != tc.h {
t.Errorf("side %d nonModal %v: panel %+v", tc.side, nonModal, got)
}
}
}
}
func TestDrawerSizeLimits(t *testing.T) {
a, _ := newDrawerApp(DrawerOptions{Size: 5000})
if a.panel.W != 720 {
t.Errorf("oversize width %v, want 720 (90%%)", a.panel.W)
}
a, _ = newDrawerApp(DrawerOptions{Size: 40})
if a.panel.W != 160 {
t.Errorf("undersize width %v, want 160", a.panel.W)
}
}
func TestDrawerModalTrapsAndRestores(t *testing.T) {
a, tt := newDrawerApp(DrawerOptions{})
_ = tt.Click("Behind")
if a.clicked != 0 {
t.Fatal("modal drawer let a click through")
}
a.open = true
tt.Frame()
if !tt.Focused("Close") {
t.Fatal("focus not in the drawer")
}
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyTab)
if !tt.Focused("Close") {
t.Fatal("tab left the modal drawer")
}
tt.Key(0, ui.KeyEscape)
if a.open || !tt.Focused("Filters") {
t.Fatalf("Escape: open %v, opener focused %v", a.open, tt.Focused("Filters"))
}
}
func TestDrawerNonModalLeavesWindowUsable(t *testing.T) {
a, tt := newDrawerApp(DrawerOptions{NonModal: true})
if err := tt.Click("Behind"); err != nil {
t.Fatal(err)
}
if a.clicked != 1 || !a.open {
t.Fatalf("clicked %d open %v", a.clicked, a.open)
}
if err := tt.Click("Close"); err != nil {
t.Fatal(err)
}
if a.open {
t.Fatal("close button did not close")
}
a.open = true
tt.Frame()
tt.Key(0, ui.KeyEscape)
if a.open {
t.Fatal("Escape did not close the non-modal drawer")
}
}
func TestDrawerSnapshot(t *testing.T) {
snapshot(t, "drawer", 640, 360, func(c *ui.Context) {
open := true
ui.Column(c).Padding(24).Children(func() { ui.Text(c, "The gallery behind") })
Drawer(c, &open, DrawerOptions{Title: "Seating chart", Size: 300, Actions: func() {
input.Button(c, "Reset", input.ButtonOptions{Variant: input.Secondary})
input.Button(c, "Apply", input.ButtonOptions{})
}}, func() {
ui.Text(c, "Guests are placed by rank, then by arrival.").TextColor(core.Tokens(c).TextMuted)
})
})
}
+41
View File
@@ -0,0 +1,41 @@
package overlay
import (
"log/slog"
"github.com/egoist/mygo/ui"
)
// DropdownMenuOptions configure a DropdownMenu.
type DropdownMenuOptions struct {
// Icon goes before the label.
Icon *ui.SVG
Disabled bool
// Label names an icon-only trigger for assistive technology.
Label string
}
// DropdownMenu is a button opening an in-window menu that build fills; it returns the button.
func DropdownMenu(c *ui.Context, label string, opts DropdownMenuOptions, build func(m *PopupMenu)) *ui.Element {
if build == nil {
panic("mujica: DropdownMenu needs a build function")
}
if label == "" && opts.Label == "" {
panic("mujica: DropdownMenu needs a label or Label")
}
b := ui.ButtonBase(c).Role(ui.RoleMenuButton).Disabled(opts.Disabled)
if opts.Label != "" {
b.Label(opts.Label)
}
open := ui.Local(b, "mujica.dropdown", func() bool { return false })
if opts.Disabled {
*open = false
}
if b.Clicked() || b.Shortcut(0, ui.KeyDown) {
*open = true
slog.Debug("mujica: dropdown_menu open")
}
popupMenuTrigger(c, b, label, opts.Icon, *open)
PopupMenuOpen(c, b, open, build)
return b
}
+230
View File
@@ -0,0 +1,230 @@
package overlay
import (
"strings"
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
type menuApp struct {
chosen []string
pinned bool
locked bool
pinDisabled bool
}
func (a *menuApp) build(m *PopupMenu) {
m.Group("Letter", func() {
if m.Item("Rename", PopupMenuItemOptions{}) {
a.chosen = append(a.chosen, "Rename")
}
if m.Check("Pinned", &a.pinned, PopupMenuItemOptions{KeepOpen: true, Disabled: a.pinDisabled}) {
a.chosen = append(a.chosen, "Pinned")
}
})
m.Group("Move", func() {
m.Submenu("Move to", PopupMenuItemOptions{}, func(m *PopupMenu) {
for _, f := range []string{"Archive", "Drafts"} {
if m.Item(f, PopupMenuItemOptions{}) {
a.chosen = append(a.chosen, f)
}
}
})
})
m.Separator()
if m.Item("Burn", PopupMenuItemOptions{Disabled: !a.locked}) {
a.chosen = append(a.chosen, "Burn")
}
}
func (a *menuApp) view(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Column(c).Padding(20).Gap(8).AlignItems(ui.Start).Children(func() {
DropdownMenu(c, "Actions", DropdownMenuOptions{}, a.build)
input.Button(c, "After", input.ButtonOptions{})
})
}
func TestDropdownMenuChooseClosesAndRestores(t *testing.T) {
a := &menuApp{}
tt := ui.NewTester(a.view, 500, 400)
if err := tt.Click("Actions"); err != nil {
t.Fatal(err)
}
if !tt.HasText("Letter") || !tt.Focused("Rename") {
t.Fatalf("menu not open with focus on the first item: %q", tt.Texts())
}
_ = tt.Click("Rename")
if len(a.chosen) != 1 || a.chosen[0] != "Rename" || tt.HasText("Letter") {
t.Fatalf("chosen %q, still open %v", a.chosen, tt.HasText("Letter"))
}
if !tt.Focused("Actions") {
t.Fatal("focus not back on the trigger")
}
}
func TestDropdownMenuCheckKeepsOpenAndDisabledBlocks(t *testing.T) {
a := &menuApp{}
tt := ui.NewTester(a.view, 500, 400)
_ = tt.Click("Actions")
_ = tt.Click("Pinned")
if !a.pinned || !tt.HasText("Letter") {
t.Fatalf("pinned %v, open %v", a.pinned, tt.HasText("Letter"))
}
_ = tt.Click("Burn")
if len(a.chosen) != 1 || !tt.HasText("Letter") {
t.Fatalf("disabled item acted: %q", a.chosen)
}
}
func TestDropdownMenuKeyboard(t *testing.T) {
a := &menuApp{}
tt := ui.NewTester(a.view, 500, 400)
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyDown)
if !tt.Focused("Rename") {
t.Fatal("Down did not open the menu on the first item")
}
tt.Key(0, ui.KeyDown)
tt.Key(0, ui.KeyDown)
if !tt.Focused("Move to") {
t.Fatal("arrows did not reach Move to")
}
tt.Key(0, ui.KeyDown) // Burn is disabled: wraps to Rename
if !tt.Focused("Rename") {
t.Fatal("arrow did not skip the disabled item")
}
tt.Key(0, ui.KeyEnd)
tt.Key(0, ui.KeyRight)
if !tt.Focused("Archive") {
t.Fatalf("Right did not enter the submenu: %q", tt.Texts())
}
tt.Key(0, ui.KeyLeft)
if !tt.Focused("Move to") || tt.HasText("Archive") {
t.Fatal("Left did not close the submenu")
}
tt.Key(0, ui.KeyRight)
tt.Key(0, ui.KeyDown)
tt.Key(0, ui.KeyEnter)
if len(a.chosen) != 1 || a.chosen[0] != "Drafts" || tt.HasText("Letter") {
t.Fatalf("submenu choice %q, open %v", a.chosen, tt.HasText("Letter"))
}
tt.Key(0, ui.KeyEnter)
tt.Key(0, ui.KeyEscape)
if tt.HasText("Letter") || !tt.Focused("Actions") {
t.Fatal("Escape did not close and restore")
}
}
func TestDropdownMenuSubmenuFlips(t *testing.T) {
a := &menuApp{}
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Row(c).Fill().Justify(ui.End).Padding(20).Children(func() {
DropdownMenu(c, "Actions", DropdownMenuOptions{}, a.build)
})
}, 420, 400)
_ = tt.Click("Actions")
r, _ := tt.Find("Move to")
tt.Move(r.X+5, r.Y+5)
tt.Frame()
s, ok := tt.Find("Archive")
if !ok || s.X+s.W > 420 || s.X > r.X {
t.Fatalf("submenu %+v not flipped left of %+v", s, r)
}
}
func TestDropdownMenuCheckDisabledThisFrameKeepsValue(t *testing.T) {
a := &menuApp{}
tt := ui.NewTester(a.view, 500, 400)
_ = tt.Click("Actions")
tt.Key(0, ui.KeyDown)
if !tt.Focused("Pinned") {
t.Fatal("Pinned not focused")
}
a.pinDisabled = true // takes effect in the frame that handles the key
tt.Key(0, ui.KeySpace)
if a.pinned || len(a.chosen) != 0 {
t.Fatalf("disabled check flipped: pinned %v chosen %q", a.pinned, a.chosen)
}
}
func TestDropdownMenuWideSubmenuStaysInWindow(t *testing.T) {
wide := strings.Repeat("Wide ", 30)
var sub ui.Rect
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Row(c).Fill().Padding(20, 0, 0, 200).Children(func() {
DropdownMenu(c, "Actions", DropdownMenuOptions{}, func(m *PopupMenu) {
m.Item(wide, PopupMenuItemOptions{})
m.Submenu("Move to", PopupMenuItemOptions{}, func(m *PopupMenu) {
m.Item(wide+"archive", PopupMenuItemOptions{})
})
})
})
}, 800, 400)
_ = tt.Click("Actions")
r, _ := tt.Find("Move to")
tt.Move(r.X+5, r.Y+5)
tt.Frame()
s, ok := tt.Find(wide + "archive")
if !ok {
t.Fatal("submenu did not open")
}
sub = s
if sub.X < 4 || sub.X+sub.W > 796 {
t.Fatalf("submenu item %+v outside the 800 DIP window", sub)
}
}
func TestDropdownMenuDisabled(t *testing.T) {
a := &menuApp{}
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
DropdownMenu(c, "Actions", DropdownMenuOptions{Disabled: true}, a.build)
}, 300, 300)
_ = tt.Click("Actions")
if tt.HasText("Letter") {
t.Fatal("disabled trigger opened")
}
}
func TestDropdownMenuTabInSubmenuClosesMenu(t *testing.T) {
a := &menuApp{}
tt := ui.NewTester(a.view, 500, 400)
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyDown)
tt.Key(0, ui.KeyEnd)
tt.Key(0, ui.KeyRight)
if !tt.Focused("Archive") {
t.Fatal("submenu not entered")
}
tt.Key(0, ui.KeyTab)
if tt.HasText("Archive") || tt.HasText("Rename") {
t.Fatal("Tab in a submenu left the menu open")
}
if !tt.Focused("Actions") {
t.Fatal("focus did not return to the trigger")
}
}
func TestDropdownMenuSnapshot(t *testing.T) {
a := &menuApp{pinned: true}
snapshotAfter(t, "dropdown_menu", 520, 320, func(c *ui.Context) {
ui.Column(c).Padding(20).AlignItems(ui.Start).Children(func() {
DropdownMenu(c, "Actions", DropdownMenuOptions{}, a.build)
})
}, func(tt *ui.Tester) {
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyDown) // opens with the first item focused
tt.Key(0, ui.KeyEnd)
tt.Key(0, ui.KeyRight) // opens Move to, focus ring on Archive
if !tt.Focused("Archive") {
t.Fatal("submenu did not open")
}
})
}
+23
View File
@@ -0,0 +1,23 @@
package overlay_test
import (
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/overlay"
)
func ExampleSplitButton() {
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
r := overlay.SplitButton(c, "Save", overlay.SplitButtonOptions{}, func(m *overlay.PopupMenu) {
if m.Item("Save as…", overlay.PopupMenuItemOptions{}) {
// ask for a file name
}
})
if r.Changed() {
// save
}
}
ui.Render(view, 400, 300, 1)
}
+169
View File
@@ -0,0 +1,169 @@
package overlay_test
import (
"fmt"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/overlay"
)
func ExampleDialog() {
open := true
name := "Ophelia"
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if input.Button(c, "Rename…", input.ButtonOptions{}).Clicked() {
open = true
}
overlay.Dialog(c, &open, overlay.DialogOptions{
Title: "Rename the chamber",
Description: "The new name shows in every hall.",
Decorated: true,
Actions: func() {
if input.Button(c, "Cancel", input.ButtonOptions{Variant: input.Secondary}).Clicked() {
open = false
}
if input.Button(c, "Rename", input.ButtonOptions{}).Clicked() {
open = false
}
},
}, func() {
ui.TextInput(c, &name)
})
}
ui.Render(view, 400, 300, 1)
}
func ExampleAlertDialog() {
open := true
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if input.Button(c, "Delete archive", input.ButtonOptions{Variant: input.Danger}).Clicked() {
open = true
}
r := overlay.AlertDialog(c, &open, overlay.AlertDialogOptions{
Title: "Delete the archive?",
Description: "Twelve letters will be destroyed.",
ConfirmText: "archive",
})
if r.Confirmed {
fmt.Println("deleted")
}
}
ui.Render(view, 400, 300, 1)
}
func ExampleDrawer() {
open := true
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if input.Button(c, "Filters", input.ButtonOptions{}).Clicked() {
open = true
}
overlay.Drawer(c, &open, overlay.DrawerOptions{Title: "Filters", Side: overlay.DrawerRight, Size: 320}, func() {
ui.Text(c, "Guests are placed by rank.")
})
}
ui.Render(view, 400, 300, 1)
}
func ExamplePopover() {
open := true
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
b := input.Button(c, "Guests", input.ButtonOptions{Variant: input.Secondary})
if b.Clicked() {
open = !open
}
overlay.Popover(c, b, &open, overlay.PopoverOptions{Title: "Guest list"}, func() {
ui.Text(c, "Twelve guests confirmed.")
})
}
ui.Render(view, 400, 300, 1)
}
func ExampleTooltip() {
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
b := input.Button(c, "Seal", input.ButtonOptions{})
overlay.Tooltip(c, b, "Seal the letter with wax", overlay.TooltipOptions{})
}
ui.Render(view, 400, 300, 1)
}
func ExampleHoverCard() {
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
b := input.Button(c, "Lady Sakiko", input.ButtonOptions{Variant: input.Ghost})
overlay.HoverCard(c, b, overlay.HoverCardOptions{}, func() {
ui.Text(c, "Keyboardist of the court.")
})
}
ui.Render(view, 400, 300, 1)
}
func ExampleDropdownMenu() {
pinned := false
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
overlay.DropdownMenu(c, "Actions", overlay.DropdownMenuOptions{}, func(m *overlay.PopupMenu) {
m.Group("Letter", func() {
if m.Item("Rename", overlay.PopupMenuItemOptions{}) {
fmt.Println("rename")
}
m.Check("Pinned", &pinned, overlay.PopupMenuItemOptions{KeepOpen: true})
})
m.Submenu("Move to", overlay.PopupMenuItemOptions{}, func(m *overlay.PopupMenu) {
m.Item("Archive", overlay.PopupMenuItemOptions{})
})
m.Separator()
m.Item("Burn", overlay.PopupMenuItemOptions{Disabled: true})
})
}
ui.Render(view, 400, 300, 1)
}
func ExampleContextMenu() {
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
row := ui.Row(c).Padding(12).Children(func() {
ui.Text(c, "Letter to the Countess")
})
overlay.ContextMenu(c, row, overlay.ContextMenuOptions{}, func(m *overlay.PopupMenu) {
if m.Item("Reply", overlay.PopupMenuItemOptions{}) {
fmt.Println("reply")
}
m.Item("Delete", overlay.PopupMenuItemOptions{})
})
}
ui.Render(view, 400, 300, 1)
}
func ExamplePopconfirm() {
open := false
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
b := input.Button(c, "Archive", input.ButtonOptions{Variant: input.Secondary})
if b.Clicked() {
open = true
}
if overlay.Popconfirm(c, b, &open, overlay.PopconfirmOptions{Title: "Archive this letter?"}).Confirmed {
fmt.Println("archived")
}
}
ui.Render(view, 400, 300, 1)
}
func ExampleOverlay() {
open := true
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
overlay.Overlay(c, &open, overlay.OverlayOptions{Place: overlay.OverlayBottomRight, Label: "Now playing"}, func() {
ui.Text(c, "Symbol I: △")
})
}
ui.Render(view, 400, 300, 1)
}
+30
View File
@@ -0,0 +1,30 @@
package overlay
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/internal/snaptest"
)
// snapshot compares view in both themes with testdata/snapshots/<os>/<name>-<mode>.png.
func snapshot(t *testing.T, name string, w, h int, view func(c *ui.Context)) {
t.Helper()
snaptest.Run(t, name, w, h, snapshotTheme, view, nil)
}
// snapshotAfter is snapshot with drive sending input before the capture.
func snapshotAfter(t *testing.T, name string, w, h int, view func(c *ui.Context), drive func(tt *ui.Tester)) {
t.Helper()
snaptest.Run(t, name, w, h, snapshotTheme, view, drive)
}
func snapshotTheme(c *ui.Context, mode string) {
m := core.Light
if mode == "dark" {
m = core.Dark
}
core.Use(c, core.Settings{Mode: m})
}
+114
View File
@@ -0,0 +1,114 @@
package overlay
import (
"log/slog"
"time"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
)
// HoverCardOptions configure a HoverCard.
type HoverCardOptions struct {
// OpenDelay is 500 ms and CloseDelay 300 ms when zero.
OpenDelay time.Duration
CloseDelay time.Duration
// Width is 280 DIPs when zero.
Width float32
// Label names the card for assistive technology.
Label string
}
// hoverCardState is what a card keeps between frames while its anchor lives.
type hoverCardState struct {
open, dismissed, focusIn bool
enterAt, leaveAt time.Time
panel ui.Rect
}
// HoverCard previews content by a hovered or focused anchor; nil while hidden.
func HoverCard(c *ui.Context, anchor *ui.Element, opts HoverCardOptions, content func()) *ui.Element {
if anchor == nil {
panic("mujica: HoverCard needs an anchor")
}
if opts.OpenDelay < 0 || opts.CloseDelay < 0 {
panic("mujica: HoverCard delays must not be negative")
}
openDelay, closeDelay := opts.OpenDelay, opts.CloseDelay
if openDelay == 0 {
openDelay = 500 * time.Millisecond
}
if closeDelay == 0 {
closeDelay = 300 * time.Millisecond
}
st := ui.Local(anchor, "mujica.hovercard", func() hoverCardState { return hoverCardState{} })
b := anchor.Bounds()
keyboard := anchor.FocusVisible()
pointer := anchor.Hovered()
if st.open {
// The popover's backdrop covers the anchor, so test the pointer by geometry.
x, y, in := c.Root().PointerPosition()
pointer = pointer || in && (b.Contains(x, y) || st.panel.Contains(x, y))
}
hot := pointer || keyboard || st.focusIn
if !hot {
st.dismissed = false
}
if st.dismissed {
return nil
}
now := c.Now()
if hot {
st.leaveAt = time.Time{}
if !st.open {
if st.enterAt.IsZero() {
st.enterAt = now
}
if wait := openDelay - now.Sub(st.enterAt); wait > 0 {
c.After(wait)
return nil
}
slog.Debug("mujica: hover_card open", "keyboard", keyboard)
st.open = true
}
} else {
st.enterAt = time.Time{}
if !st.open {
return nil
}
if st.leaveAt.IsZero() {
st.leaveAt = now
}
if wait := closeDelay - now.Sub(st.leaveAt); wait > 0 {
c.After(wait)
} else {
slog.Debug("mujica: hover_card close")
st.open, st.focusIn, st.leaveAt = false, false, time.Time{}
return nil
}
}
width := opts.Width
if width == 0 {
width = 280
}
core.OverlayLayer(c, st)
// A popover keeps the card in the anchor's focus order and modal scope, even inside a Dialog.
shown := true
panel := ui.PopoverBase(c, anchor, &shown, func(panel *ui.Element) {
core.OverlayStyle(c, panel, OverlayAnchored(c, panel, b))
panel.Margin(6, 0, 0, 0).Width(PopoverWide(c, width)).Padding(core.Density(c).Unit() * 4).Gap(core.Density(c).Unit() * 2).
Label(opts.Label).MaxHeight(PopoverRoom(c, b))
ui.Scroll(c).Shrink(1).Children(content)
})
if !shown {
slog.Debug("mujica: hover_card dismiss")
if keyboard || st.focusIn {
anchor.Focus() // at once, so the anchor stays hot and the card stays dismissed
}
st.open, st.dismissed, st.focusIn = false, true, false
return panel
}
st.panel, st.focusIn = panel.Bounds(), panel.FocusWithin()
return panel
}
+178
View File
@@ -0,0 +1,178 @@
package overlay
import (
"testing"
"time"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
const hoverCardTestDelay = 150 * time.Millisecond
type hoverCardApp struct {
follows, next int
inDialog bool
}
func (a *hoverCardApp) card(c *ui.Context) {
b := input.Button(c, "Lady Sakiko", input.ButtonOptions{Variant: input.Ghost})
HoverCard(c, b, HoverCardOptions{OpenDelay: hoverCardTestDelay, CloseDelay: hoverCardTestDelay}, func() {
ui.Text(c, "Keyboardist of the court")
if input.Button(c, "Follow", input.ButtonOptions{}).Clicked() {
a.follows++
}
})
if input.Button(c, "Next", input.ButtonOptions{}).Clicked() {
a.next++
}
}
func (a *hoverCardApp) view(c *ui.Context) {
core.Use(c, core.Settings{})
if a.inDialog {
open := true
Dialog(c, &open, DialogOptions{Title: "Court", HideClose: true}, func() {
ui.Column(c).Gap(80).AlignItems(ui.Start).Children(func() { a.card(c) })
})
return
}
ui.Column(c).Padding(40).Gap(80).AlignItems(ui.Start).Children(func() { a.card(c) })
}
func hoverCardShown(tt *ui.Tester) func() bool {
return func() bool { return tt.HasText("Keyboardist of the court") }
}
// hoverCardSettle waits past both delays so any pending open or close has happened.
func hoverCardSettle(tt *ui.Tester) {
time.Sleep(hoverCardTestDelay + 30*time.Millisecond)
tt.Frame()
}
func TestHoverCardPointerCanEnterCard(t *testing.T) {
a := &hoverCardApp{}
tt := ui.NewTester(a.view, 500, 400)
r, _ := tt.Find("Lady Sakiko")
start := time.Now()
tt.Move(r.X+5, r.Y+5)
if time.Since(start) < hoverCardTestDelay && tt.HasText("Keyboardist of the court") {
t.Fatal("opened before the delay")
}
if !overlayUntil(tt, hoverCardShown(tt)) {
t.Fatalf("card did not open: %q", tt.Texts())
}
// The pointer inside the card keeps it open past the close delay.
k, _ := tt.Find("Keyboardist of the court")
tt.Move(k.X+5, k.Y+5)
hoverCardSettle(tt)
if !tt.HasText("Follow") {
t.Fatal("card closed with the pointer inside it")
}
if err := tt.Click("Follow"); err != nil {
t.Fatal(err)
}
if a.follows != 1 || !tt.Focused("Follow") {
t.Fatalf("follows %d, Follow focused %v", a.follows, tt.Focused("Follow"))
}
// With the focus inside, leaving keeps it; a click outside closes it.
tt.Move(490, 390)
hoverCardSettle(tt)
if !tt.HasText("Follow") {
t.Fatal("card closed with the focus inside it")
}
tt.ClickAt(490, 390)
if tt.HasText("Follow") {
t.Fatal("outside click did not close the card")
}
}
func TestHoverCardCloseDelay(t *testing.T) {
a := &hoverCardApp{}
tt := ui.NewTester(a.view, 500, 400)
r, _ := tt.Find("Lady Sakiko")
tt.Move(r.X+5, r.Y+5)
if !overlayUntil(tt, hoverCardShown(tt)) {
t.Fatal("card did not open")
}
start := time.Now()
tt.Move(490, 390)
if time.Since(start) < hoverCardTestDelay && !tt.HasText("Follow") {
t.Fatal("closed without the close delay")
}
if !overlayUntil(tt, func() bool { return !tt.HasText("Follow") }) {
t.Fatal("card stayed open after the close delay")
}
}
func TestHoverCardKeyboardEntersAndEscapes(t *testing.T) {
a := &hoverCardApp{}
tt := ui.NewTester(a.view, 500, 400)
tt.Key(0, ui.KeyTab)
if !overlayUntil(tt, hoverCardShown(tt)) {
t.Fatal("no card on keyboard focus")
}
tt.Key(0, ui.KeyTab)
if !tt.Focused("Follow") {
t.Fatal("Tab did not enter the card")
}
tt.Key(0, ui.KeyEnter)
if a.follows != 1 {
t.Fatalf("follows %d", a.follows)
}
tt.Key(0, ui.KeyEscape)
if tt.HasText("Follow") || !tt.Focused("Lady Sakiko") {
t.Fatalf("Escape: card shown %v, anchor focused %v", tt.HasText("Follow"), tt.Focused("Lady Sakiko"))
}
hoverCardSettle(tt)
if tt.HasText("Follow") {
t.Fatal("dismissed card came back while focused")
}
tt.Key(0, ui.KeyTab)
if !tt.Focused("Next") || a.next != 0 {
t.Fatal("Tab after the card did not reach Next")
}
}
func TestHoverCardInsideDialog(t *testing.T) {
a := &hoverCardApp{inDialog: true}
tt := ui.NewTester(a.view, 600, 500)
r, _ := tt.Find("Lady Sakiko")
tt.Move(r.X+5, r.Y+5)
if !overlayUntil(tt, hoverCardShown(tt)) {
t.Fatal("card did not open in the dialog")
}
if err := tt.Click("Follow"); err != nil {
t.Fatal(err)
}
if a.follows != 1 || !tt.Focused("Follow") {
t.Fatalf("follows %d, focus kept on Follow %v", a.follows, tt.Focused("Follow"))
}
tt.Key(ui.Shift, ui.KeyTab)
if !tt.Focused("Lady Sakiko") {
t.Fatal("Shift+Tab from the card did not reach its anchor in the dialog")
}
}
func TestHoverCardSnapshot(t *testing.T) {
snapshotAfter(t, "hover_card", 420, 240, func(c *ui.Context) {
ui.Column(c).Padding(24).AlignItems(ui.Start).Children(func() {
b := input.Button(c, "Lady Uika", input.ButtonOptions{Variant: input.Ghost})
HoverCard(c, b, HoverCardOptions{OpenDelay: time.Millisecond}, func() {
ui.Column(c).Gap(8).AlignItems(ui.Start).Children(func() {
ui.Text(c, "Lady Uika").FontWeight(600)
ui.Text(c, "Vocalist and guitarist; keeps the ledger of the masquerade.").TextColor(core.Tokens(c).TextMuted)
input.Button(c, "Follow", input.ButtonOptions{Variant: input.Outline})
})
})
})
}, func(tt *ui.Tester) {
r, _ := tt.Find("Lady Uika")
tt.Move(r.X+5, r.Y+5)
if !overlayUntil(tt, func() bool { return tt.HasText("Follow") }) {
t.Fatal("card did not open")
}
})
}
+152
View File
@@ -0,0 +1,152 @@
package overlay
import (
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// OverlayPlace is where an Overlay sits in the window. The zero value is OverlayCenter.
type OverlayPlace int
const (
OverlayCenter OverlayPlace = iota
OverlayTop
OverlayBottom
OverlayLeft
OverlayRight
OverlayTopLeft
OverlayTopRight
OverlayBottomLeft
OverlayBottomRight
)
// OverlayOptions configure an Overlay.
type OverlayOptions struct {
Place OverlayPlace
// Inset keeps the panel from the window edges; 16 DIPs when zero.
Inset float32
// Modal traps the focus, makes the window inert and closes on a backdrop click.
Modal bool
// Dim darkens the window behind a modal overlay. It requires Modal.
Dim bool
// Label names the layer for assistive technology.
Label string
}
// Overlay shows content in a layer above the window while *open is true; Escape closes it.
func Overlay(c *ui.Context, open *bool, opts OverlayOptions, content func()) *ui.Element {
if opts.Dim && !opts.Modal {
panic("mujica: Overlay Dim requires Modal")
}
if opts.Place < OverlayCenter || opts.Place > OverlayBottomRight {
panic("mujica: Overlay Place out of range")
}
site, focus := core.OverlaySite(c)
if !*open {
focus.Closed(c, site)
return nil
}
k := core.Tokens(c)
inset := opts.Inset
if inset == 0 {
inset = 16
}
fx, fy := overlayFractions(opts.Place)
if opts.Modal {
core.OverlayLayer(c, open)
var backClicked bool
shown := true
panel := ui.DialogBase(c, &shown, func(back, panel *ui.Element) {
backClicked = back.Clicked()
p := core.OverlayEnter(c, panel)
back.Padding(inset).Justify(overlayAlign(fy)).AlignItems(overlayAlign(fx))
if opts.Dim {
back.Background(OverlayScrim(k).Alpha(p))
}
core.OverlayStyle(c, panel, p)
w, h := c.Size()
panel.Label(opts.Label).Padding(core.Density(c).Unit() * 4).MaxWidth(w - 2*inset).MaxHeight(h - 2*inset)
ui.Scroll(c).Shrink(1).Children(content)
})
focus.Shown(panel)
if !shown {
slog.Debug("mujica: overlay close", "backdrop", backClicked)
*open = false
}
return panel
}
var panel *ui.Element
ui.Overlay(c, func() {
w, h := c.Size()
panel = ui.Column(c).Absolute().Role(ui.RoleDialog).Label(opts.Label).Padding(core.Density(c).Unit() * 4).
MaxWidth(w - 2*inset).MaxHeight(h - 2*inset)
b := panel.Bounds()
panel.Left(inset + (w-2*inset-b.W)*fx).Top(inset + (h-2*inset-b.H)*fy)
p := core.OverlayEnter(c, panel)
if b.W == 0 {
p = 0 // not measured yet
c.AnimationFrame()
}
core.OverlayStyle(c, panel, p)
panel.Children(func() { ui.Scroll(c).Shrink(1).Children(content) })
})
focus.Shown(panel)
if core.OverlayEscape(c, open) {
slog.Debug("mujica: overlay close", "escape", true)
*open = false
}
return panel
}
func overlayFractions(p OverlayPlace) (fx, fy float32) {
switch p {
case OverlayTop:
return 0.5, 0
case OverlayBottom:
return 0.5, 1
case OverlayLeft:
return 0, 0.5
case OverlayRight:
return 1, 0.5
case OverlayTopLeft:
return 0, 0
case OverlayTopRight:
return 1, 0
case OverlayBottomLeft:
return 0, 1
case OverlayBottomRight:
return 1, 1
}
return 0.5, 0.5
}
func overlayAlign(f float32) ui.Align {
switch f {
case 0:
return ui.Start
case 1:
return ui.End
}
return ui.Center
}
// OverlayScrim is the color dimming the window behind a modal layer.
func OverlayScrim(k theme.Tokens) ui.Color {
if k.Dark {
return ui.RGBA(0, 0, 0, 0.6)
}
return k.Text.Alpha(0.42)
}
// OverlayAnchored is overlayEnter, held at 0 until the anchor b has been laid out.
func OverlayAnchored(c *ui.Context, panel *ui.Element, b ui.Rect) float32 {
if b.W == 0 && b.H == 0 {
c.AnimationFrame()
return 0
}
return core.OverlayEnter(c, panel)
}
+70
View File
@@ -0,0 +1,70 @@
package overlay
import (
"strings"
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
// overlayLongText is about 372 characters of description.
var overlayLongText = strings.Repeat("The east wing stays sealed until the court returns. ", 7)
// overlayInWindow fails unless every label lies fully inside a w×h window.
func overlayInWindow(t *testing.T, tt *ui.Tester, w, h float32, labels ...string) {
t.Helper()
for _, l := range labels {
r, ok := tt.Find(l)
if !ok || r.W == 0 || r.H == 0 || r.Y < 0 || r.X < 0 || r.Y+r.H > h || r.X+r.W > w {
t.Errorf("%q at %+v (found %v) outside the %v×%v window", l, r, ok, w, h)
}
}
}
func TestDialogActionsStayInWindowAtLargeText(t *testing.T) {
open, name := true, "Ophelia"
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
Dialog(c, &open, DialogOptions{Title: "Rename", Description: overlayLongText, Actions: func() {
input.Button(c, "Cancel", input.ButtonOptions{Variant: input.Secondary})
input.Button(c, "Save", input.ButtonOptions{})
}}, func() { ui.TextInput(c, &name) })
}, 800, 600)
tt.SetPreferences(ui.Preferences{TextScale: 2})
tt.Frame()
overlayInWindow(t, tt, 800, 600, "Cancel", "Save")
}
func TestAlertDialogActionsStayInWindowAtLargeText(t *testing.T) {
open := true
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
AlertDialog(c, &open, AlertDialogOptions{Title: "Burn?", Description: overlayLongText, ConfirmText: "letters"})
}, 800, 600)
tt.SetPreferences(ui.Preferences{TextScale: 2})
tt.Frame()
overlayInWindow(t, tt, 800, 600, "Cancel", "Delete", "Type “letters” to confirm")
}
func TestOverlayPanelFitsWindow(t *testing.T) {
for _, modal := range []bool{true, false} {
open := true
var panel ui.Rect
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
if p := Overlay(c, &open, OverlayOptions{Modal: modal}, func() {
ui.Text(c, strings.Repeat(overlayLongText, 6))
input.Button(c, "Done", input.ButtonOptions{})
}); p != nil {
panel = p.Bounds()
}
}, 600, 400)
tt.Frame()
if panel.X < 16 || panel.Y < 16 || panel.X+panel.W > 584 || panel.Y+panel.H > 384 {
t.Errorf("modal %v: panel %+v outside the window minus Inset", modal, panel)
}
}
}
+20
View File
@@ -0,0 +1,20 @@
package overlay
import (
"time"
"github.com/egoist/mygo/ui"
)
// overlayUntil draws frames until cond holds, for at most 5 s of wall time.
func overlayUntil(tt *ui.Tester, cond func() bool) bool {
end := time.Now().Add(5 * time.Second)
for !cond() {
if time.Now().After(end) {
return false
}
time.Sleep(2 * time.Millisecond)
tt.Frame()
}
return true
}
+305
View File
@@ -0,0 +1,305 @@
package overlay
import (
"runtime"
"testing"
"time"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
type overlayApp struct {
open bool
opts OverlayOptions
behind int
panel ui.Rect
}
func (a *overlayApp) view(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Row(c).Padding(20).Gap(8).Children(func() {
if input.Button(c, "Show", input.ButtonOptions{}).Clicked() {
a.open = true
}
if input.Button(c, "Behind", input.ButtonOptions{}).Clicked() {
a.behind++
}
})
if p := Overlay(c, &a.open, a.opts, func() {
ui.Text(c, "Layer")
if input.Button(c, "Done", input.ButtonOptions{}).Clicked() {
a.open = false
}
}); p != nil {
a.panel = p.Bounds()
}
}
func newOverlayApp(opts OverlayOptions) (*overlayApp, *ui.Tester) {
a := &overlayApp{opts: opts}
tt := ui.NewTester(a.view, 600, 400)
tt.SetPreferences(ui.Preferences{ReduceMotion: true, TextScale: 1})
_ = tt.Click("Show")
tt.Frame()
return a, tt
}
func TestOverlayPlaces(t *testing.T) {
for _, modal := range []bool{false, true} {
for _, tc := range []struct {
place OverlayPlace
fx, fy float32
}{{OverlayCenter, 0.5, 0.5}, {OverlayTopLeft, 0, 0}, {OverlayBottomRight, 1, 1}, {OverlayTop, 0.5, 0}} {
a, _ := newOverlayApp(OverlayOptions{Place: tc.place, Modal: modal})
p := a.panel
wantX := 16 + (600-32-p.W)*tc.fx
wantY := 16 + (400-32-p.H)*tc.fy
if abs(p.X-wantX) > 1 || abs(p.Y-wantY) > 1 {
t.Errorf("modal %v place %d: panel %+v, want at (%v, %v)", modal, tc.place, p, wantX, wantY)
}
}
}
}
func abs(v float32) float32 {
if v < 0 {
return -v
}
return v
}
func TestOverlayModal(t *testing.T) {
a, tt := newOverlayApp(OverlayOptions{Modal: true, Dim: true})
if !tt.Focused("Done") {
t.Fatal("modal overlay did not take the focus")
}
_ = tt.Click("Behind")
if a.behind != 0 || a.open {
t.Fatalf("backdrop: behind %d open %v", a.behind, a.open)
}
if !tt.Focused("Show") {
t.Fatal("focus not restored")
}
}
func TestOverlayNonModal(t *testing.T) {
a, tt := newOverlayApp(OverlayOptions{Place: OverlayBottomRight})
_ = tt.Click("Behind")
if a.behind != 1 || !a.open {
t.Fatalf("behind %d open %v", a.behind, a.open)
}
tt.Key(0, ui.KeyEscape)
if a.open {
t.Fatal("Escape did not close")
}
}
func TestOverlayEscapeClosesTopNonModalLayerFirst(t *testing.T) {
bottom, top := false, false
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
if input.Button(c, "Show", input.ButtonOptions{}).Absolute().Right(10).Top(10).Clicked() {
if bottom {
top = true
}
bottom = true
}
Overlay(c, &top, OverlayOptions{Place: OverlayTopRight}, func() { ui.Text(c, "Top layer") })
Drawer(c, &bottom, DrawerOptions{Title: "Bottom layer", NonModal: true, Side: DrawerLeft}, nil)
}, 600, 400)
tt.SetPreferences(ui.Preferences{ReduceMotion: true, TextScale: 1})
_ = tt.Click("Show")
_ = tt.Click("Show") // the overlay opens after the drawer, though built before it
if !bottom || !top {
t.Fatalf("bottom %v top %v", bottom, top)
}
tt.Key(0, ui.KeyEscape)
if top || !bottom {
t.Fatalf("first Escape: top %v bottom %v", top, bottom)
}
tt.Key(0, ui.KeyEscape)
if bottom {
t.Fatal("second Escape did not close the drawer")
}
}
func TestOverlayNonModalRestoresFocusToItsPlace(t *testing.T) {
open := true
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Column(c).Children(func() {
input.Button(c, "First", input.ButtonOptions{})
Overlay(c, &open, OverlayOptions{}, func() { input.Button(c, "Inside", input.ButtonOptions{}) })
input.Button(c, "Next", input.ButtonOptions{})
})
}, 600, 400)
if err := tt.Click("Inside"); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeyEscape)
if open {
t.Fatal("Escape did not close")
}
tt.Key(0, ui.KeyTab)
if !tt.Focused("Next") {
t.Fatal("focus lost on close instead of staying at the overlay's place")
}
}
func TestOverlayDimNeedsModal(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("no panic")
}
}()
open := true
ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
Overlay(c, &open, OverlayOptions{Dim: true}, func() {})
}, 200, 200)
}
// overlayCase drives one component open and closed through real input.
type overlayCase struct {
name string
view func(c *ui.Context, open *bool)
open, close func(tt *ui.Tester)
marker string
}
func overlayCases() []overlayCase {
clickAnchor := func(tt *ui.Tester) { _ = tt.Click("Anchor") }
escape := func(tt *ui.Tester) { tt.Key(0, ui.KeyEscape) }
hover := func(tt *ui.Tester) {
r, _ := tt.Find("Anchor")
tt.Move(r.X+4, r.Y+4)
}
leave := func(tt *ui.Tester) { tt.Move(590, 390) }
anchor := func(c *ui.Context, open *bool) *ui.Element {
b := input.Button(c, "Anchor", input.ButtonOptions{})
if b.Clicked() {
*open = true
}
return b
}
body := func(c *ui.Context) func() { return func() { ui.Text(c, "Layer body") } }
return []overlayCase{
{"Dialog", func(c *ui.Context, open *bool) {
anchor(c, open)
Dialog(c, open, DialogOptions{Title: "T"}, body(c))
}, clickAnchor, escape, "Layer body"},
{"AlertDialog", func(c *ui.Context, open *bool) {
anchor(c, open)
AlertDialog(c, open, AlertDialogOptions{Title: "Layer body", ConfirmText: "x"})
}, clickAnchor, escape, "Layer body"},
{"Drawer", func(c *ui.Context, open *bool) {
anchor(c, open)
Drawer(c, open, DrawerOptions{Title: "T"}, body(c))
}, clickAnchor, escape, "Layer body"},
{"DrawerNonModal", func(c *ui.Context, open *bool) {
anchor(c, open)
Drawer(c, open, DrawerOptions{Title: "T", NonModal: true}, body(c))
}, clickAnchor, escape, "Layer body"},
{"Popover", func(c *ui.Context, open *bool) {
Popover(c, anchor(c, open), open, PopoverOptions{}, body(c))
}, clickAnchor, escape, "Layer body"},
{"Tooltip", func(c *ui.Context, open *bool) {
Tooltip(c, anchor(c, open), "Layer body", TooltipOptions{Delay: time.Millisecond})
}, hover, leave, "Layer body"},
{"HoverCard", func(c *ui.Context, open *bool) {
HoverCard(c, anchor(c, open), HoverCardOptions{OpenDelay: time.Millisecond, CloseDelay: time.Millisecond}, body(c))
}, hover, leave, "Layer body"},
{"DropdownMenu", func(c *ui.Context, open *bool) {
DropdownMenu(c, "Anchor", DropdownMenuOptions{}, (&menuApp{}).build)
}, clickAnchor, escape, "Rename"},
{"ContextMenu", func(c *ui.Context, open *bool) {
row := ui.Row(c)
row.Children(func() { input.Button(c, "Anchor", input.ButtonOptions{}) })
ContextMenu(c, row, ContextMenuOptions{}, (&menuApp{}).build)
}, func(tt *ui.Tester) {
clickAnchor(tt)
tt.Key(ui.Shift, ui.KeyF10)
}, escape, "Rename"},
{"Popconfirm", func(c *ui.Context, open *bool) {
Popconfirm(c, anchor(c, open), open, PopconfirmOptions{Title: "Layer body"})
}, clickAnchor, escape, "Layer body"},
{"Overlay", func(c *ui.Context, open *bool) {
anchor(c, open)
Overlay(c, open, OverlayOptions{Modal: true}, body(c))
}, clickAnchor, escape, "Layer body"},
}
}
// TestOverlayLifecycle opens and closes every overlay 100 times; goroutines, heap objects and elements must not grow.
func TestOverlayLifecycle(t *testing.T) {
for _, oc := range overlayCases() {
open := false
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
oc.view(c, &open)
}, 600, 400)
tt.SetPreferences(ui.Preferences{ReduceMotion: true, TextScale: 1})
shown := func() bool { return tt.HasText(oc.marker) }
cycle := func(i int) {
oc.open(tt)
if !overlayUntil(tt, shown) {
t.Fatalf("%s: cycle %d did not open", oc.name, i)
}
oc.close(tt)
if !overlayUntil(tt, func() bool { return !shown() }) {
t.Fatalf("%s: cycle %d did not close", oc.name, i)
}
}
for i := range 20 {
cycle(i)
}
texts := len(tt.Texts())
before := heapObjects()
goroutines := runtime.NumGoroutine()
for i := range 100 {
cycle(i)
}
if got := len(tt.Texts()); got != texts {
t.Errorf("%s: texts %d -> %d", oc.name, texts, got)
}
// A fired c.After timer (ui/runtime.go:596) runs briefly in its own goroutine; only lasting growth counts.
if g := overlayGoroutines(goroutines); g > goroutines {
t.Errorf("%s: goroutines %d -> %d", oc.name, goroutines, g)
}
if after := heapObjects(); after > before+2000 {
t.Errorf("%s: heap objects %d -> %d", oc.name, before, after)
}
}
}
// overlayGoroutines waits up to 2 s for the goroutine count to fall to want, and returns it.
func overlayGoroutines(want int) int {
end := time.Now().Add(2 * time.Second)
g := runtime.NumGoroutine()
for g > want && time.Now().Before(end) {
time.Sleep(10 * time.Millisecond)
g = runtime.NumGoroutine()
}
return g
}
func heapObjects() uint64 {
runtime.GC()
var m runtime.MemStats
runtime.ReadMemStats(&m)
return m.HeapObjects
}
func TestOverlaySnapshot(t *testing.T) {
snapshot(t, "overlay", 480, 260, func(c *ui.Context) {
open := true
ui.Column(c).Padding(24).Children(func() { ui.Text(c, "Score of the second act") })
Overlay(c, &open, OverlayOptions{Place: OverlayBottomRight, Label: "Now playing"}, func() {
ui.Text(c, "Now playing").FontWeight(600)
ui.Text(c, "Symbol I: △").TextColor(core.Tokens(c).TextMuted)
})
})
}
+108
View File
@@ -0,0 +1,108 @@
package overlay
import (
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/icons"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
// PopconfirmOptions configure a Popconfirm. Title is required.
type PopconfirmOptions struct {
Title string
Description string
// ConfirmLabel is "Confirm" and CancelLabel "Cancel" when empty.
ConfirmLabel string
CancelLabel string
// Danger paints the confirm button as destructive.
Danger bool
}
// PopconfirmResult reports the choice made in this frame.
type PopconfirmResult struct {
Confirmed bool
Canceled bool
}
// Popconfirm asks for a light confirmation by anchor; use AlertDialog for high-risk actions.
func Popconfirm(c *ui.Context, anchor *ui.Element, open *bool, opts PopconfirmOptions) PopconfirmResult {
if anchor == nil {
panic("mujica: Popconfirm needs an anchor")
}
if opts.Title == "" {
panic("mujica: Popconfirm needs a Title")
}
var res PopconfirmResult
if !*open {
return res
}
core.OverlayLayer(c, open)
u := core.Density(c).Unit()
confirm, cancel := opts.ConfirmLabel, opts.CancelLabel
if confirm == "" {
confirm = core.Msg(c, "popconfirm.confirm")
}
if cancel == "" {
cancel = core.Msg(c, "popconfirm.cancel")
}
variant := input.Primary
if opts.Danger {
variant = input.Danger
}
b := anchor.Bounds()
shown := true
ui.PopoverBase(c, anchor, &shown, func(panel *ui.Element) {
core.OverlayStyle(c, panel, OverlayAnchored(c, panel, b))
panel.Margin(6, 0, 0, 0).Padding(u * 3).Gap(u * 3).MaxWidth(PopoverWide(c, 320)).MaxHeight(PopoverRoom(c, b)).Role(ui.RoleAlertDialog).
Label(opts.Title).Description(opts.Description)
// The text scrolls so the actions stay in the window.
ui.Scroll(c).Shrink(1).Children(func() { popconfirmText(c, opts) })
ui.Row(c).Gap(u * 2).Justify(ui.End).Shrink(0).Children(func() {
// Danger focuses Cancel, so a second Enter never runs the destructive action.
cb := input.Button(c, cancel, input.ButtonOptions{Variant: input.Secondary})
if opts.Danger {
cb.AutoFocus()
}
if cb.Clicked() {
res.Canceled = true
}
ok := input.Button(c, confirm, input.ButtonOptions{Variant: variant})
if !opts.Danger {
ok.AutoFocus()
}
if ok.Clicked() {
res.Confirmed = true
}
})
})
if !shown {
res.Canceled = true
}
if res.Confirmed || res.Canceled {
slog.Debug("mujica: popconfirm close", "confirmed", res.Confirmed)
*open = false
}
return res
}
// popconfirmText is the icon, title and description of a Popconfirm.
func popconfirmText(c *ui.Context, opts PopconfirmOptions) {
k := core.Tokens(c)
u := core.Density(c).Unit()
ui.Row(c).Gap(u * 2).AlignItems(ui.Start).Children(func() {
color := k.Warning
if opts.Danger {
color = k.Danger
}
ui.Icon(c, icons.Must("circle-alert")).Size(18, 18).TextColor(color).Shrink(0).Margin(1, 0, 0, 0)
ui.Column(c).Gap(u).Shrink(1).Children(func() {
ui.Text(c, opts.Title).FontWeight(600)
if opts.Description != "" {
ui.Text(c, opts.Description).TextColor(k.TextMuted)
}
})
})
}
+116
View File
@@ -0,0 +1,116 @@
package overlay
import (
"strings"
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
type popconfirmApp struct {
open bool
confirmed, canceled int
}
func (a *popconfirmApp) view(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Column(c).Padding(30).AlignItems(ui.Start).Children(func() {
b := input.Button(c, "Archive", input.ButtonOptions{Variant: input.Secondary})
if b.Clicked() {
a.open = true
}
r := Popconfirm(c, b, &a.open, PopconfirmOptions{Title: "Archive this letter?", Description: "It leaves the inbox."})
if r.Confirmed {
a.confirmed++
}
if r.Canceled {
a.canceled++
}
})
}
func TestPopconfirmConfirmByKeyboard(t *testing.T) {
a := &popconfirmApp{}
tt := ui.NewTester(a.view, 400, 300)
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyEnter)
if !a.open || !tt.Focused("Confirm") {
t.Fatalf("open %v, Confirm focused %v", a.open, tt.Focused("Confirm"))
}
tt.Key(0, ui.KeyEnter)
if a.confirmed != 1 || a.canceled != 0 || a.open {
t.Fatalf("confirmed %d canceled %d open %v", a.confirmed, a.canceled, a.open)
}
if !tt.Focused("Archive") {
t.Fatal("focus not restored to the anchor")
}
}
func TestPopconfirmDangerFocusesCancel(t *testing.T) {
open, confirmed := false, 0
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
b := input.Button(c, "Dismiss", input.ButtonOptions{})
if b.Clicked() {
open = true
}
if Popconfirm(c, b, &open, PopconfirmOptions{Title: "Dismiss the guard?", Danger: true}).Confirmed {
confirmed++
}
}, 400, 300)
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyEnter)
if !open || !tt.Focused("Cancel") {
t.Fatalf("open %v, Cancel focused %v", open, tt.Focused("Cancel"))
}
tt.Key(0, ui.KeyEnter)
if confirmed != 0 || open {
t.Fatalf("second Enter: confirmed %d open %v", confirmed, open)
}
}
func TestPopconfirmCancelPaths(t *testing.T) {
a := &popconfirmApp{}
tt := ui.NewTester(a.view, 400, 300)
_ = tt.Click("Archive")
_ = tt.Click("Cancel")
_ = tt.Click("Archive")
tt.Key(0, ui.KeyEscape)
_ = tt.Click("Archive")
tt.ClickAt(390, 290)
if a.canceled != 3 || a.confirmed != 0 || a.open {
t.Fatalf("canceled %d confirmed %d open %v", a.canceled, a.confirmed, a.open)
}
}
func TestPopconfirmKeepsActionsInWindow(t *testing.T) {
long := strings.Repeat("The east gate stays unwatched tonight. ", 60)
open := true
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Column(c).Padding(30).Children(func() {
b := input.Button(c, "Archive", input.ButtonOptions{})
Popconfirm(c, b, &open, PopconfirmOptions{Title: "Archive?", Description: long})
})
}, 400, 300)
tt.Frame()
for _, label := range []string{"Confirm", "Cancel"} {
r, ok := tt.Find(label)
if !ok || r.Y < 0 || r.Y+r.H > 300 || r.X+r.W > 400 {
t.Fatalf("%s at %+v outside the 400×300 window", label, r)
}
}
}
func TestPopconfirmSnapshot(t *testing.T) {
snapshot(t, "popconfirm", 420, 220, func(c *ui.Context) {
open := true
ui.Column(c).Padding(24).AlignItems(ui.Start).Children(func() {
b := input.Button(c, "Dismiss the guard", input.ButtonOptions{Variant: input.Secondary})
Popconfirm(c, b, &open, PopconfirmOptions{Title: "Dismiss the guard?", Description: "The east gate stays unwatched tonight.", Danger: true})
})
})
}
+66
View File
@@ -0,0 +1,66 @@
package overlay
import (
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// PopoverOptions configure a Popover.
type PopoverOptions struct {
// Title shows in serif at the top and names the panel.
Title string
// Width fixes the panel width; zero fits the content, at least the anchor's width.
Width float32
// Label names an untitled panel for assistive technology.
Label string
}
// Popover shows content below anchor, or above it, inside the window while *open is true.
func Popover(c *ui.Context, anchor *ui.Element, open *bool, opts PopoverOptions, content func()) *ui.Element {
if anchor == nil {
panic("mujica: Popover needs an anchor")
}
if !*open {
return nil
}
core.OverlayLayer(c, open)
u := core.Density(c).Unit()
b := anchor.Bounds()
label := opts.Label
if opts.Title != "" {
label = opts.Title
}
panel := ui.PopoverBase(c, anchor, open, func(panel *ui.Element) {
core.OverlayStyle(c, panel, OverlayAnchored(c, panel, b))
panel.Margin(6, 0, 0, 0).Padding(u * 3).Gap(u * 2).MinWidth(PopoverWide(c, b.W)).MaxHeight(PopoverRoom(c, b)).Label(label)
if opts.Width > 0 {
panel.Width(PopoverWide(c, opts.Width))
} else {
panel.MaxWidth(PopoverWide(c, 360))
}
if opts.Title != "" {
ui.Text(c, opts.Title).Font(theme.SerifFont).FontSize(core.FontSize(c, theme.BodySize+2)).FontWeight(600).Shrink(0)
}
ui.Scroll(c).Shrink(1).Children(content)
})
if !*open {
slog.Debug("mujica: popover close")
}
return panel
}
// PopoverRoom is the tallest a panel below or above anchor b may be.
func PopoverRoom(c *ui.Context, b ui.Rect) float32 {
_, h := c.Size()
return max(b.Y, h-b.Y-b.H) - 16
}
// PopoverWide caps a panel width w to the window.
func PopoverWide(c *ui.Context, w float32) float32 {
ww, _ := c.Size()
return min(w, ww-8)
}
+127
View File
@@ -0,0 +1,127 @@
package overlay
import (
"strings"
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
type popoverApp struct {
open bool
top float32
panel, anchor ui.Rect
behind, applied int
}
func (a *popoverApp) view(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Column(c).Padding(a.top, 0, 0, 40).Gap(8).Children(func() {
b := input.Button(c, "Filter", input.ButtonOptions{})
if b.Clicked() {
a.open = !a.open
}
a.anchor = b.Bounds()
if input.Button(c, "Behind", input.ButtonOptions{}).Clicked() {
a.behind++
}
if p := Popover(c, b, &a.open, PopoverOptions{Title: "Filter rows"}, func() {
if input.Button(c, "Apply", input.ButtonOptions{}).Clicked() {
a.applied++
a.open = false
}
}); p != nil {
a.panel = p.Bounds()
}
})
}
func TestPopoverOpensBelowAndFlips(t *testing.T) {
a := &popoverApp{top: 20}
tt := ui.NewTester(a.view, 400, 300)
_ = tt.Click("Filter")
tt.Frame()
if !a.open || a.panel.Y < a.anchor.Y+a.anchor.H {
t.Fatalf("below: open %v panel %+v anchor %+v", a.open, a.panel, a.anchor)
}
a = &popoverApp{top: 240}
tt = ui.NewTester(a.view, 400, 300)
_ = tt.Click("Filter")
tt.Frame()
if a.panel.Y+a.panel.H > a.anchor.Y {
t.Fatalf("no flip: panel %+v anchor %+v", a.panel, a.anchor)
}
}
func TestPopoverOutsideClickAndEscape(t *testing.T) {
a := &popoverApp{top: 20}
tt := ui.NewTester(a.view, 400, 300)
_ = tt.Click("Filter")
tt.ClickAt(390, 290)
if a.open || a.behind != 0 {
t.Fatalf("outside click: open %v behind %d", a.open, a.behind)
}
_ = tt.Click("Filter")
tt.Key(0, ui.KeyTab) // focus follows the anchor into the panel
if !tt.Focused("Apply") {
t.Fatal("Tab did not enter the popover")
}
tt.Key(0, ui.KeyEscape)
if a.open || !tt.Focused("Filter") {
t.Fatalf("Escape: open %v anchor focused %v", a.open, tt.Focused("Filter"))
}
_ = tt.Click("Filter")
_ = tt.Click("Apply")
if a.applied != 1 || a.open {
t.Fatalf("applied %d open %v", a.applied, a.open)
}
}
func TestPopoverFitsWindow(t *testing.T) {
open := true
var panel ui.Rect
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Column(c).Padding(30).Children(func() {
b := input.Button(c, "Filter", input.ButtonOptions{})
if p := Popover(c, b, &open, PopoverOptions{Width: 1000}, func() {
ui.Text(c, strings.Repeat("Long row of guests. ", 200))
input.Button(c, "Bottom", input.ButtonOptions{})
}); p != nil {
panel = p.Bounds()
}
})
}, 400, 300)
tt.Frame()
if panel.W > 400 || panel.X < 0 || panel.Y+panel.H > 300 {
t.Fatalf("panel %+v outside the 400×300 window", panel)
}
}
func TestPopoverNeedsAnchor(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("no panic")
}
}()
open := true
ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
Popover(c, nil, &open, PopoverOptions{}, nil)
}, 200, 200)
}
func TestPopoverSnapshot(t *testing.T) {
snapshot(t, "popover", 420, 260, func(c *ui.Context) {
open := true
ui.Column(c).Padding(24).AlignItems(ui.Start).Children(func() {
b := input.Button(c, "Guests", input.ButtonOptions{Variant: input.Secondary})
Popover(c, b, &open, PopoverOptions{Title: "Guest list", Width: 240}, func() {
ui.Text(c, "Twelve guests confirmed; three await a reply.").TextColor(core.Tokens(c).TextMuted)
})
})
})
}
+252
View File
@@ -0,0 +1,252 @@
package overlay
import (
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/icons"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/internal"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// PopupMenuItemOptions configure one item of a PopupMenu.
type PopupMenuItemOptions struct {
Disabled bool
// KeepOpen keeps the menu open after the item is chosen.
KeepOpen bool
}
// PopupMenu builds the items of a DropdownMenu or ContextMenu, reporting choices as they happen.
type PopupMenu struct {
c *ui.Context
root *popupMenuRoot
level *popupMenuLevel
subs []popupMenuSub
seq, rows int
autofocus bool
}
// popupMenuRoot carries what every level of one open menu shares in a frame.
type popupMenuRoot struct{ close bool }
// popupMenuLevel is what one menu level keeps while it shows.
type popupMenuLevel struct {
open int // seq of the open submenu, 0 for none
byKey bool // the open submenu was opened from the keyboard
}
type popupMenuSub struct {
item *ui.Element
seq int
build func(m *PopupMenu)
}
// Item adds an item and reports its choice, which closes the menu unless KeepOpen.
func (m *PopupMenu) Item(label string, opts PopupMenuItemOptions) bool {
it := m.row(ui.ButtonBase(m.c), opts.Disabled, false)
m.content(it, label, false, false)
if !it.Clicked() {
return false
}
slog.Debug("mujica: popup_menu choose", "item", label)
m.root.close = m.root.close || !opts.KeepOpen
return true
}
// Check adds an item toggling *checked and reports whether it changed.
func (m *PopupMenu) Check(label string, checked *bool, opts PopupMenuItemOptions) bool {
// The base toggles as it is built, so a disabled wrapper comes first.
var base *ui.Element
ui.Column(m.c).Shrink(0).Disabled(opts.Disabled).Children(func() { base = ui.CheckboxBase(m.c, checked) })
it := m.row(base, opts.Disabled, false)
m.content(it, label, *checked, false)
if opts.Disabled || !it.Changed() {
return false
}
slog.Debug("mujica: popup_menu check", "item", label, "checked", *checked)
m.root.close = m.root.close || !opts.KeepOpen
return true
}
// Submenu adds an item opening a nested menu that build fills.
func (m *PopupMenu) Submenu(label string, opts PopupMenuItemOptions, build func(m *PopupMenu)) {
if build == nil {
panic("mujica: PopupMenu Submenu needs a build function")
}
it := m.row(ui.ButtonBase(m.c), opts.Disabled, true)
seq := m.seq
m.content(it, label, false, true)
if opts.Disabled {
return
}
if it.Clicked() || it.Shortcut(0, ui.KeyRight) {
m.level.open, m.level.byKey = seq, it.FocusVisible()
slog.Debug("mujica: popup_menu submenu", "item", label)
}
m.subs = append(m.subs, popupMenuSub{it, seq, build})
}
// Group adds a captioned group of items, separated from what comes before.
func (m *PopupMenu) Group(label string, fn func()) {
k := core.Tokens(m.c)
u := core.Density(m.c).Unit()
if m.rows > 0 {
m.Separator()
}
if label != "" {
ui.Text(m.c, label).FontSize(core.FontSize(m.c, theme.CaptionSize)).TextColor(k.TextMuted).Padding(u, u*3, u/2, u*3+16+u*2).Shrink(0)
}
fn()
}
// Separator adds a line between items.
func (m *PopupMenu) Separator() {
u := core.Density(m.c).Unit()
ui.Box(m.c).Height(theme.BorderWidth).Margin(u, u*2).Background(core.Tokens(m.c).Border).Shrink(0)
}
// row styles an item element and runs the hover, focus and highlight logic.
func (m *PopupMenu) row(it *ui.Element, disabled, sub bool) *ui.Element {
c := m.c
k := core.Tokens(c)
d := core.Density(c)
m.seq++
m.rows++
seq := m.seq
it.Justify(ui.Start).MinHeight(max(theme.MinHitSize, d.ControlHeight()-4)).Padding(0, d.Unit()*3).
Gap(d.Unit() * 2).Radius(theme.ControlRadius).Disabled(disabled).TextColor(k.Text)
internal.Ring(it, k.Focus, theme.ControlRadius)
if disabled {
return it
}
if m.autofocus {
it.AutoFocus()
m.autofocus = false
}
hovered := it.Hovered()
was := ui.Local(it, "mujica.menu.hover", func() bool { return false })
if hovered && !*was {
it.Focus() // focus follows the pointer
if sub {
m.level.open, m.level.byKey = seq, false
} else {
m.level.open = 0
}
}
*was = hovered
if hovered || it.FocusVisible() || m.level.open == seq {
it.Background(k.Selection).Draw(func(p *ui.Painter, r ui.Rect) {
p.Fill(ui.Rect{X: r.X, Y: r.Y + 4, W: 2, H: r.H - 8}, k.AccentText, 1)
})
}
return it
}
// content lays out the check column, label and submenu chevron of an item.
func (m *PopupMenu) content(it *ui.Element, label string, checked, sub bool) {
c := m.c
k := core.Tokens(c)
it.Children(func() {
mark := ui.Box(c).Size(16, 16).Shrink(0)
if checked {
mark.Children(func() { ui.Icon(c, icons.Must("check")).Size(16, 16).TextColor(k.AccentText) })
}
ui.Text(c, label).SingleLine().Grow(1)
if sub {
ui.Icon(c, icons.Must("chevron-right")).Size(14, 14).TextColor(k.TextMuted).Shrink(0)
}
})
}
// PopupMenuOpen shows the menu build fills below anchor while *open is true.
func PopupMenuOpen(c *ui.Context, anchor *ui.Element, open *bool, build func(m *PopupMenu)) *ui.Element {
if !*open {
return nil
}
core.OverlayLayer(c, open)
b := anchor.Bounds()
root := &popupMenuRoot{}
panel := ui.PopoverBase(c, anchor, open, func(panel *ui.Element) {
core.OverlayStyle(c, panel, OverlayAnchored(c, panel, b))
panel.Margin(4, 0, 0, 0).MinWidth(PopoverWide(c, max(b.W, 200))).MaxWidth(PopoverWide(c, 360)).MaxHeight(PopoverRoom(c, b))
popupMenuLevelBuild(c, panel, root, build, true)
// The panel holds every level, so Tab in a submenu closes the whole menu too.
if panel.Shortcut(0, ui.KeyTab) || panel.Shortcut(ui.Shift, ui.KeyTab) {
root.close = true
}
})
if root.close {
*open = false
}
if !*open {
slog.Debug("mujica: popup_menu close")
}
return panel
}
// popupMenuLevelBuild builds one level's items in outer, then its open submenu.
func popupMenuLevelBuild(c *ui.Context, outer *ui.Element, root *popupMenuRoot, build func(m *PopupMenu), autofocus bool) {
u := core.Density(c).Unit()
// The padding leaves room for the items' focus rings inside the clipping scroll.
items := ui.Scroll(c).Shrink(1).Padding(u + theme.FocusGap + theme.FocusWidth).FocusGroup(ui.Vertical)
m := &PopupMenu{c: c, root: root, autofocus: autofocus}
m.level = ui.Local(items, "mujica.menu.level", func() popupMenuLevel { return popupMenuLevel{} })
outer.Role(ui.RolePopup)
items.Children(func() { build(m) })
for _, s := range m.subs {
if m.level.open == s.seq {
popupMenuSubmenu(c, outer, root, m.level, s)
}
}
}
// popupMenuSubmenu builds a submenu beside its item, flipped to stay in the window.
func popupMenuSubmenu(c *ui.Context, outer *ui.Element, root *popupMenuRoot, lv *popupMenuLevel, s popupMenuSub) {
u := core.Density(c).Unit()
ob, ib := outer.Bounds(), s.item.Bounds()
ww, wh := c.Size()
box := ui.Column(c).Absolute().Key(s.seq).MinWidth(min(180, ww-8)).MaxWidth(min(360, ww-8))
sb := box.Bounds()
left, top := ib.X+ib.W+u-ob.X, ib.Y-u-ob.Y
if ob.X+left+sb.W > ww-4 {
left = ib.X - u - sb.W - ob.X
}
// Flipped or not, the submenu stays inside the window.
left = max(4-ob.X, min(left, ww-4-sb.W-ob.X))
top = max(4-ob.Y, min(top, wh-4-sb.H-ob.Y))
box.Left(left).Top(top).MaxHeight(wh - 8)
p := core.OverlayEnter(c, box)
if sb.W == 0 || ob.W == 0 {
p = 0 // not measured yet
c.AnimationFrame()
}
core.OverlayStyle(c, box, p)
box.Children(func() { popupMenuLevelBuild(c, box, root, s.build, lv.byKey) })
if box.Shortcut(0, ui.KeyLeft) || box.Shortcut(0, ui.KeyEscape) {
lv.open = 0
s.item.Focus()
}
}
// popupMenuTrigger styles a menu trigger button with a trailing chevron.
func popupMenuTrigger(c *ui.Context, b *ui.Element, label string, icon *ui.SVG, open bool) {
k := core.Tokens(c)
d := core.Density(c)
b.MinHeight(d.ControlHeight()).MinWidth(theme.MinHitSize).Padding(0, d.Unit()*3, 0, d.Unit()*4).
Gap(d.Unit() * 2).Radius(theme.ControlRadius)
internal.Ring(b, k.Focus, theme.ControlRadius)
bg, fg, border := input.ButtonColors(k, input.Secondary, b.Hovered() && !b.IsDisabled(), b.Pressed() || open)
b.Background(bg).TextColor(fg).Border(theme.BorderWidth, border)
b.Children(func() {
if icon != nil {
ui.Icon(c, icon).Size(16, 16)
}
if label != "" {
ui.Text(c, label).SingleLine()
}
ui.Icon(c, icons.Must("chevron-down")).Size(14, 14).TextColor(k.TextMuted)
})
}
+88
View File
@@ -0,0 +1,88 @@
package overlay
import (
"fmt"
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/icons"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/internal"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// SplitButtonOptions configure a SplitButton.
type SplitButtonOptions struct {
// Variant is Primary (the zero value) or Secondary.
Variant input.ButtonVariant
Icon *ui.SVG
// MenuLabel names the menu half; empty uses "More options".
MenuLabel string
Disabled bool
}
// SplitButton runs its main action from the left half and opens build's menu from the right; each half takes focus.
func SplitButton(c *ui.Context, label string, opts SplitButtonOptions, build func(m *PopupMenu)) core.ChoiceResult {
if label == "" || build == nil {
panic("mujica: SplitButton needs a label and a menu")
}
if opts.Variant != input.Primary && opts.Variant != input.Secondary {
panic(fmt.Sprintf("mujica: SplitButton Variant %d must be Primary or Secondary", opts.Variant))
}
k := core.Tokens(c)
d := core.Density(c)
menuName := opts.MenuLabel
if menuName == "" {
menuName = core.Msg(c, "split_button.more")
}
group := ui.Row(c).AlignItems(ui.Stretch).Disabled(opts.Disabled)
disabled := group.IsDisabled()
open := ui.Local(group, "split_button.open", func() bool { return false })
if disabled {
*open = false
}
var clicked bool
group.Children(func() {
main := ui.ButtonBase(c).MinHeight(d.ControlHeight()).Padding(0, d.Unit()*4).Gap(d.Unit()*2).
Radius(theme.ControlRadius, 0, 0, theme.ControlRadius)
splitButtonLook(c, k, main, opts.Variant, false)
main.Children(func() {
if opts.Icon != nil {
ui.Icon(c, opts.Icon).Size(16, 16)
}
ui.Text(c, label).SingleLine()
})
clicked = main.Clicked() && !disabled
if opts.Variant == input.Primary {
ui.Box(c).Width(theme.BorderWidth).Background(k.OnAccent.Alpha(0.45)).Role(ui.RoleNone)
}
more := ui.ButtonBase(c).Role(ui.RoleMenuButton).Label(menuName).MinHeight(d.ControlHeight()).Width(theme.MinHitSize+d.Unit()).
Radius(0, theme.ControlRadius, theme.ControlRadius, 0).Tooltip(menuName)
splitButtonLook(c, k, more, opts.Variant, *open)
if opts.Variant == input.Secondary {
more.BorderWidth(theme.BorderWidth, theme.BorderWidth, theme.BorderWidth, 0)
}
more.Children(func() { ui.Icon(c, icons.Must("chevron-down")).Size(14, 14) })
if !disabled && (more.Clicked() || more.Shortcut(0, ui.KeyDown)) {
*open = true
slog.Debug("mujica: split_button open")
}
PopupMenuOpen(c, group, open, build)
})
if clicked {
slog.Debug("mujica: split_button action", "label", label)
}
return core.NewChoiceResult(group, clicked)
}
// splitButtonLook colors one half as a Button of variant v would be.
func splitButtonLook(c *ui.Context, k theme.Tokens, b *ui.Element, v input.ButtonVariant, open bool) {
internal.Ring(b, k.Focus, theme.ControlRadius)
bg, fg, border := input.ButtonColors(k, v, b.Hovered() && !b.IsDisabled(), b.Pressed() || open)
b.Background(bg).TextColor(fg).Transition(core.ColorFade)
if border.A > 0 {
b.Border(theme.BorderWidth, border)
}
}
+102
View File
@@ -0,0 +1,102 @@
package overlay
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
func splitButtonTester(dis *bool, runs *int, chosen *string) *ui.Tester {
return ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Row(c).Padding(20).Children(func() {
r := SplitButton(c, "Save", SplitButtonOptions{Disabled: *dis}, func(m *PopupMenu) {
for _, s := range []string{"Save as…", "Save all"} {
if m.Item(s, PopupMenuItemOptions{}) {
*chosen = s
}
}
})
if r.Changed() {
*runs++
}
})
}, 500, 300)
}
func TestSplitButtonMainAndMenu(t *testing.T) {
dis, runs, chosen := false, 0, ""
tt := splitButtonTester(&dis, &runs, &chosen)
if err := tt.Click("Save"); err != nil {
t.Fatal(err)
}
if runs != 1 || tt.HasText("Save all") {
t.Fatalf("main click: runs %d, menu open %v", runs, tt.HasText("Save all"))
}
if err := tt.Click("More options"); err != nil {
t.Fatal(err)
}
if err := tt.Click("Save all"); err != nil {
t.Fatal(err)
}
if chosen != "Save all" || runs != 1 || tt.HasText("Save as…") {
t.Fatalf("menu choice %q runs %d", chosen, runs)
}
}
func TestSplitButtonKeyboardHalves(t *testing.T) {
dis, runs, chosen := false, 0, ""
tt := splitButtonTester(&dis, &runs, &chosen)
tt.Key(0, ui.KeyTab)
if !tt.Focused("Save") {
t.Fatal("first Tab misses the main half")
}
tt.Key(0, ui.KeyEnter)
tt.Key(0, ui.KeyTab)
if !tt.Focused("More options") {
t.Fatal("second Tab misses the menu half")
}
tt.Key(0, ui.KeyDown)
if runs != 1 || !tt.HasText("Save as…") {
t.Fatalf("runs %d, menu %v", runs, tt.HasText("Save as…"))
}
tt.Key(0, ui.KeyEnter)
if chosen != "Save as…" {
t.Fatalf("Enter chose %q", chosen)
}
}
func TestSplitButtonDisabled(t *testing.T) {
dis, runs, chosen := true, 0, ""
tt := splitButtonTester(&dis, &runs, &chosen)
_ = tt.Click("Save")
_ = tt.Click("More options")
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyEnter)
if runs != 0 || tt.HasText("Save all") {
t.Fatalf("disabled: runs %d menu %v", runs, tt.HasText("Save all"))
}
defer func() {
if recover() == nil {
t.Fatal("Danger variant accepted")
}
}()
ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
SplitButton(c, "x", SplitButtonOptions{Variant: input.Danger}, func(*PopupMenu) {})
}, 200, 100)
}
func TestSplitButtonSnapshot(t *testing.T) {
snapshot(t, "split_button", 460, 80, func(c *ui.Context) {
ui.Row(c).Padding(16).Gap(12).Children(func() {
menu := func(m *PopupMenu) { m.Item("Other", PopupMenuItemOptions{}) }
SplitButton(c, "Publish", SplitButtonOptions{}, menu)
SplitButton(c, "Export", SplitButtonOptions{Variant: input.Secondary}, menu)
SplitButton(c, "Merge", SplitButtonOptions{Disabled: true}, menu)
})
})
}
+84
View File
@@ -0,0 +1,84 @@
package overlay
import (
"log/slog"
"time"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// TooltipOptions configure a Tooltip.
type TooltipOptions struct {
// Delay is how long hover or focus rests before the tip shows: 500 ms when zero.
Delay time.Duration
}
// TooltipState tracks when the anchor became hot and whether Escape hid the tip.
type TooltipState struct {
Since time.Time
Dismissed bool
}
const tooltipMaxWidth = 240
// Tooltip shows a non-interactive tip by anchor after hover or keyboard focus rests on it for Delay.
func Tooltip(c *ui.Context, anchor *ui.Element, text string, opts TooltipOptions) *ui.Element {
if anchor == nil {
panic("mujica: Tooltip needs an anchor")
}
if opts.Delay < 0 {
panic("mujica: Tooltip Delay is negative")
}
if text == "" {
return anchor
}
anchor.Description(text)
st := ui.Local(anchor, "mujica.tooltip", func() TooltipState { return TooltipState{} })
hot := anchor.Hovered() || anchor.FocusVisible()
if !hot {
st.Since, st.Dismissed = time.Time{}, false
return anchor
}
if st.Dismissed {
return anchor
}
if st.Since.IsZero() {
st.Since = c.Now()
}
delay := opts.Delay
if delay == 0 {
delay = 500 * time.Millisecond
}
if wait := delay - c.Now().Sub(st.Since); wait > 0 {
c.After(wait)
return anchor
}
if core.OverlayEscape(c, st) {
slog.Debug("mujica: tooltip dismiss")
st.Dismissed = true
return anchor
}
tooltipShow(c, anchor.Bounds(), text)
return anchor
}
// tooltipShow draws the tip below a, or above it when there is no room.
func tooltipShow(c *ui.Context, a ui.Rect, text string) {
k := core.Tokens(c)
u := core.Density(c).Unit()
size := core.FontSize(c, theme.CaptionSize+1)
tw, th := c.MeasureText(tooltipMaxWidth, ui.Span{Text: text, Size: size, Font: c.Theme().Font})
padX, padY := u*2.5, u*1.5
w, h := tw+2*(padX+theme.BorderWidth)+1, th+2*(padY+theme.BorderWidth)
x, y := core.PlaceOverlay(c, ui.Rect{X: a.X + a.W/2 - w/2, Y: a.Y, W: w, H: a.H}, w, h, 6)
ui.Overlay(c, func() {
ui.Box(c).Absolute().Left(x).Top(y).Width(w).Padding(padY, padX).Radius(theme.ControlRadius).
Background(k.Text).TextColor(k.Background).Border(theme.BorderWidth, k.Text).
PassThrough().Role(ui.RoleTooltip).Children(func() {
ui.Text(c, text).FontSize(size)
})
})
}
+116
View File
@@ -0,0 +1,116 @@
package overlay
import (
"testing"
"time"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
const tooltipTestDelay = 150 * time.Millisecond
func tooltipTester(x, y float32) (*ui.Tester, *int) {
clicks := 0
tt := ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Column(c).Padding(y, 0, 0, x).Children(func() {
b := input.Button(c, "Share", input.ButtonOptions{})
if b.Clicked() {
clicks++
}
Tooltip(c, b, "Share with the court", TooltipOptions{Delay: tooltipTestDelay})
})
}, 400, 300)
return tt, &clicks
}
// waitTooltip waits until the tip shows, however slow the machine.
func waitTooltip(tt *ui.Tester) bool {
return overlayUntil(tt, func() bool { return tt.HasText("Share with the court") })
}
func TestTooltipHoverDelay(t *testing.T) {
tt, clicks := tooltipTester(40, 40)
r, _ := tt.Find("Share")
start := time.Now()
tt.Move(r.X+4, r.Y+4)
if time.Since(start) < tooltipTestDelay && tt.HasText("Share with the court") {
t.Fatal("tip showed before the delay")
}
waitTooltip(tt)
tip, ok := tt.Find("Share with the court")
if !ok || tip.Y < r.Y+r.H {
t.Fatalf("tip %+v ok %v below %+v", tip, ok, r)
}
tt.Move(400, 300)
tt.Frame()
if tt.HasText("Share with the court") {
t.Fatal("tip stayed after leave")
}
_ = tt.Click("Share")
if *clicks != 1 {
t.Fatalf("clicks %d", *clicks)
}
}
func TestTooltipFocusAndEscape(t *testing.T) {
tt, _ := tooltipTester(40, 40)
tt.Key(0, ui.KeyTab)
if !waitTooltip(tt) {
t.Fatal("no tip on keyboard focus")
}
tt.Key(0, ui.KeyEscape)
if tt.HasText("Share with the court") {
t.Fatal("Escape did not hide the tip")
}
time.Sleep(tooltipTestDelay + 30*time.Millisecond)
tt.Frame()
if tt.HasText("Share with the court") {
t.Fatal("tip came back while still focused")
}
}
func TestTooltipEdgeFlips(t *testing.T) {
tt, _ := tooltipTester(330, 262)
r, _ := tt.Find("Share")
tt.Move(r.X+4, r.Y+4)
waitTooltip(tt)
tip, ok := tt.Find("Share with the court")
if !ok || tip.Y > r.Y || tip.X+tip.W > 400 {
t.Fatalf("tip %+v not above and inside for anchor %+v", tip, r)
}
}
func TestTooltipScalesWithText(t *testing.T) {
widths := map[float32]float32{}
for _, scale := range []float32{1, 1.5} {
tt, _ := tooltipTester(20, 20)
tt.SetPreferences(ui.Preferences{TextScale: scale})
tt.Key(0, ui.KeyTab)
if !overlayUntil(tt, func() bool { return tt.HasText("Share with the court") }) {
t.Fatalf("scale %v: no tip", scale)
}
r, _ := tt.Find("Share with the court")
widths[scale] = r.W
}
if widths[1.5] < widths[1]*1.3 {
t.Fatalf("tip text width %v at 1.5x, %v at 1x: not scaled", widths[1.5], widths[1])
}
}
func TestTooltipSnapshot(t *testing.T) {
snapshotAfter(t, "tooltip", 360, 140, func(c *ui.Context) {
ui.Column(c).Padding(24).AlignItems(ui.Start).Children(func() {
b := input.Button(c, "Seal", input.ButtonOptions{Variant: input.Secondary})
Tooltip(c, b, "Seal the letter with wax", TooltipOptions{Delay: time.Millisecond})
})
}, func(tt *ui.Tester) {
tt.Key(0, ui.KeyTab)
if !overlayUntil(tt, func() bool { return tt.HasText("Seal the letter with wax") }) {
t.Fatal("tip did not show")
}
})
}