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

+108
View File
@@ -0,0 +1,108 @@
package account
import (
"fmt"
"log/slog"
"strings"
"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"
)
// AccentColorPickerOptions configure an AccentColorPicker.
type AccentColorPickerOptions struct {
// Candidates defaults to the built-in court palette.
Candidates []ui.Color
Disabled bool
}
// accentPickerColors offers readable accents and marked low-contrast examples.
var accentPickerColors = []ui.Color{
ui.Hex("#7D2034"), ui.Hex("#355E80"), ui.Hex("#326247"), ui.Hex("#4B3A5A"),
ui.Hex("#805714"), ui.Hex("#211C1D"), ui.Hex("#AD9164"), ui.Hex("#D9A5B3"),
}
// accentPickerReadable reports whether accent carries OnAccent text at 4.5:1.
func accentPickerReadable(k theme.Tokens, accent ui.Color) bool {
return theme.Contrast(k.OnAccent, accent) >= 4.5
}
// AccentColorPicker selects an accent and marks insufficient contrast.
func AccentColorPicker(c *ui.Context, color *ui.Color, opts AccentColorPickerOptions) core.ChoiceResult {
cands := opts.Candidates
if cands == nil {
cands = accentPickerColors
}
if len(cands) == 0 {
panic("mujica: AccentColorPicker needs candidates")
}
k := core.Tokens(c)
d := core.Density(c)
var r core.ChoiceResult
r.Element = ui.Column(c).Gap(d.Unit() * 2)
r.Element.Children(func() {
low := false
ui.Row(c).Gap(d.Unit() * 2).Wrap().Role(ui.RoleRadioGroup).Label(core.Msg(c, "accent_color_picker.label")).
FocusGroup(ui.Horizontal).Disabled(opts.Disabled).Children(func() {
selected := color
if r.Element.IsDisabled() || opts.Disabled {
copy := *color
selected = &copy
}
for _, col := range cands {
ok := accentPickerReadable(k, col)
low = low || !ok
hex := strings.ToUpper(input.ColorPickerHex(col))
sw := ui.RadioBase(c, selected, col).Size(36, 36).Center().Radius(theme.CardRadius).Label(hex)
if !ok {
sw.Description(core.Msg(c, "accent_color_picker.low"))
}
if sw.Changed() && !sw.IsDisabled() {
r = core.NewChoiceResult(r.Element, true)
slog.Debug("mujica: accent_color_picker chose", "color", hex)
}
internal.Ring(sw, k.Focus, theme.CardRadius)
on := *color == col
sw.Draw(func(p *ui.Painter, rect ui.Rect) {
p.Fill(rect, col, theme.CardRadius)
p.Stroke(rect, k.Border, theme.CardRadius, 1)
if on {
p.Stroke(ui.Rect{X: rect.X - 3, Y: rect.Y - 3, W: rect.W + 6, H: rect.H + 6}, k.Text, theme.CardRadius+3, 1.5)
}
})
sw.Children(func() {
switch {
case on:
ui.Icon(c, icons.Must("check")).Size(16, 16).TextColor(accentPickerMark(col))
case !ok:
ui.Icon(c, icons.Must("triangle-alert")).Size(14, 14).TextColor(accentPickerMark(col))
}
})
}
})
if low {
ui.Row(c).Gap(d.Unit()).AlignItems(ui.Center).TextColor(k.TextMuted).Children(func() {
ui.Icon(c, icons.Must("triangle-alert")).Size(12, 12)
ui.Text(c, core.Msg(c, "accent_color_picker.low_note")).FontSize(core.FontSize(c, theme.CaptionSize))
})
}
if !accentPickerReadable(k, *color) {
ui.Text(c, fmt.Sprintf(core.Msg(c, "accent_color_picker.chosen_low"), strings.ToUpper(input.ColorPickerHex(*color)))).
TextColor(k.Warning).FontSize(core.FontSize(c, theme.CaptionSize)).Role(ui.RoleStatus)
}
})
return r
}
// accentPickerMark is black or white, whichever reads on col.
func accentPickerMark(col ui.Color) ui.Color {
if theme.Contrast(col, ui.RGB(255, 255, 255)) >= theme.Contrast(col, ui.RGB(0, 0, 0)) {
return ui.RGB(255, 255, 255)
}
return ui.RGB(0, 0, 0)
}
+74
View File
@@ -0,0 +1,74 @@
package account
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
func TestAccentColorPickerMarksLowContrast(t *testing.T) {
col, n := ui.Hex("#7D2034"), 0
cands := []ui.Color{ui.Hex("#7D2034"), ui.Hex("#F0E68C")}
tt := accountTester(400, 200, func(c *ui.Context) {
if AccentColorPicker(c, &col, AccentColorPickerOptions{Candidates: cands}).Changed() {
n++
}
})
k := theme.Light()
if !accentPickerReadable(k, cands[0]) || accentPickerReadable(k, cands[1]) {
t.Fatal("contrast check wrong")
}
if !tt.HasText("Marked colors are too faint for text on them.") {
t.Fatalf("no low-contrast note: %q", tt.Texts())
}
if err := tt.Click("#F0E68C"); err != nil {
t.Fatal(err)
}
if col != cands[1] || n != 1 || !tt.HasText("#F0E68C has low contrast; text on it may be hard to read.") {
t.Fatalf("pick: %v %d %q", col, n, tt.Texts())
}
tt.Key(0, ui.KeyLeft)
tt.Key(0, ui.KeySpace)
if col != cands[0] || n != 2 {
t.Fatalf("keys: %v", col)
}
}
// Built-in accents meet their promised light-theme contrast.
func TestAccentColorPickerDefaults(t *testing.T) {
low := 0
for _, col := range accentPickerColors {
if !accentPickerReadable(theme.Light(), col) {
low++
}
}
if low != 2 {
t.Fatalf("%d defaults fail; the palette shows two faint ones on purpose", low)
}
}
func TestAccentColorPickerSnapshot(t *testing.T) {
snapshot(t, "accent_color_picker", 420, 120, func(c *ui.Context) {
col := ui.Local(c.Root(), "col", func() ui.Color { return ui.Hex("#355E80") })
ui.Column(c).Padding(16).Children(func() { AccentColorPicker(c, col, AccentColorPickerOptions{}) })
})
}
func TestAccentColorPickerDisabledAndEmptyCandidates(t *testing.T) {
col := ui.Hex("#7D2034")
tt := accountTester(600, 300, func(c *ui.Context) {
ui.Column(c).Disabled(true).Children(func() { AccentColorPicker(c, &col, AccentColorPickerOptions{}) })
})
if err := tt.Click("#355E80"); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyRight)
tt.Key(0, ui.KeySpace)
if col != ui.Hex("#7D2034") {
t.Fatal("disabled swatch changes")
}
accountPanics(t, func(c *ui.Context) { AccentColorPicker(c, &col, AccentColorPickerOptions{Candidates: []ui.Color{}}) })
}
+155
View File
@@ -0,0 +1,155 @@
package account
import (
"fmt"
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/data"
"github.com/ZacharyZhang-NY/MujicaUI/display"
"github.com/ZacharyZhang-NY/MujicaUI/icons"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/internal"
"github.com/ZacharyZhang-NY/MujicaUI/overlay"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// Account is a signed-in account a user can switch to.
type Account struct {
ID, Name, Email string
Avatar *ui.Bitmap
}
// AccountSwitcherOptions configure an AccountSwitcher.
type AccountSwitcherOptions struct {
Disabled bool
}
// AccountSwitcherResult reports account changes and addition requests.
type AccountSwitcherResult struct {
Element *ui.Element
changed bool
add bool
}
// Changed reports a switch to another account.
func (r AccountSwitcherResult) Changed() bool { return r.changed }
// Add reports a request to sign in another account.
func (r AccountSwitcherResult) Add() bool { return r.add }
// AccountSwitcher offers account switching and an addition action.
func AccountSwitcher(c *ui.Context, current *string, accounts []Account, opts AccountSwitcherOptions) AccountSwitcherResult {
var cur *Account
for i := range accounts {
if accounts[i].ID == "" || accounts[i].Name == "" {
panic("mujica: Account needs an ID and a Name")
}
if accounts[i].ID == *current {
cur = &accounts[i]
}
}
if cur == nil {
panic(fmt.Sprintf("mujica: AccountSwitcher current %q is not an account", *current))
}
var r AccountSwitcherResult
b := accountTrigger(c, cur.Name, cur.Email, cur.Avatar, opts.Disabled)
r.Element = b
open := ui.Local(b, "open", func() bool { return false })
if b.IsDisabled() {
*open = false
} else if b.Clicked() || b.Shortcut(0, ui.KeyDown) {
*open = true
}
if len(accounts) > 8 {
accountSwitcherLarge(c, b, open, current, accounts, &r)
return r
}
overlay.PopupMenuOpen(c, b, open, func(m *overlay.PopupMenu) {
m.Group(core.Msg(c, "account_switcher.accounts"), func() {
for _, a := range accounts {
on := a.ID == *current
label := a.Name
if a.Email != "" {
label += " · " + a.Email
}
ui.Column(c).Key(a.ID).Shrink(0).Children(func() {
if m.Check(label, &on, overlay.PopupMenuItemOptions{}) && a.ID != *current && !b.IsDisabled() {
*current, r.changed = a.ID, true
slog.Debug("mujica: account_switcher switched")
}
})
}
})
m.Separator()
if m.Item(core.Msg(c, "account_switcher.add"), overlay.PopupMenuItemOptions{}) && !b.IsDisabled() {
r.add = true
slog.Debug("mujica: account_switcher add")
}
})
return r
}
func accountSwitcherLarge(c *ui.Context, b *ui.Element, open *bool, current *string, accounts []Account, r *AccountSwitcherResult) {
overlay.Popover(c, b, open, overlay.PopoverOptions{Label: core.Msg(c, "account_switcher.accounts"), Width: 320}, func() {
cursor := ui.Local(b, "cursor", func() int { return -1 })
rows := ui.Local(b, "list", func() ui.ListState { return ui.ListState{} })
rows.Key = func(i int) any { return accounts[i].ID }
rows.Label = func(i int) string { return accounts[i].Name }
rows.Selected = cursor
restore := data.DataSelectTheme(c, 0)
list := ui.List(c, rows, len(accounts), func(i int) {
a := accounts[i]
row := workspaceRow(c, Workspace{ID: a.ID, Name: a.Name, Detail: a.Email}, a.ID == *current, i == *cursor)
if row.Focused() && !b.IsDisabled() {
*cursor = i
}
if row.Clicked() && !row.IsDisabled() && !b.IsDisabled() {
r.changed, *current, *open = a.ID != *current, a.ID, false
}
}).Height(280).MinHeight(0).AutoFocus()
restore()
internal.Ring(list, core.Tokens(c).Focus, theme.ControlRadius)
if list.Changed() && !b.IsDisabled() {
list.Focus()
}
if list.Submitted() && !b.IsDisabled() && *cursor >= 0 && *cursor < len(accounts) {
id := accounts[*cursor].ID
r.changed, *current, *open = id != *current, id, false
}
if input.Button(c, core.Msg(c, "account_switcher.add"), input.ButtonOptions{Variant: input.Ghost}).Clicked() && !b.IsDisabled() {
r.add, *open = true, false
}
})
if r.changed || r.add {
slog.Debug("mujica: account_switcher action", "changed", r.changed, "add", r.add)
}
}
// accountTrigger displays an avatar, name and detail.
func accountTrigger(c *ui.Context, name, detail string, avatar *ui.Bitmap, disabled bool) *ui.Element {
k := core.Tokens(c)
d := core.Density(c)
b := ui.ButtonBase(c).Role(ui.RoleMenuButton).MinHeight(d.ControlHeight()+d.Unit()*2).Padding(d.Unit(), d.Unit()*3, d.Unit(), d.Unit()*2).
Gap(d.Unit() * 2).Radius(theme.ControlRadius).Justify(ui.Start).Disabled(disabled).Label(name).Transition(core.ColorFade)
internal.Ring(b, k.Focus, theme.ControlRadius)
switch {
case b.Pressed():
b.Background(k.Selection)
case b.Hovered():
b.Background(k.SurfaceHover)
}
b.Children(func() {
display.Avatar(c, name, display.AvatarOptions{Image: avatar, Size: 28})
ui.Column(c).Grow(1).MinWidth(0).Children(func() {
ui.Text(c, name).FontWeight(600).SingleLine().Ellipsis("…")
if detail != "" {
ui.Text(c, detail).TextColor(k.TextMuted).FontSize(core.FontSize(c, theme.CaptionSize)).SingleLine().Ellipsis("…")
}
})
ui.Icon(c, icons.Must("chevron-down")).Size(14, 14).TextColor(k.TextMuted)
})
return b
}
+139
View File
@@ -0,0 +1,139 @@
package account
import (
"fmt"
"testing"
"github.com/egoist/mygo/ui"
)
var switcherAccounts = []Account{{ID: "a", Name: "Sakiko Togawa", Email: "sakiko@court"}, {ID: "b", Name: "Oblivionis", Email: "ob@mask"}}
func TestAccountSwitcherSwitchesAndAdds(t *testing.T) {
cur, n, adds := "a", 0, 0
disabled := false
tt := accountTester(500, 400, func(c *ui.Context) {
r := AccountSwitcher(c, &cur, switcherAccounts, AccountSwitcherOptions{Disabled: disabled})
if r.Changed() {
n++
}
if r.Add() {
adds++
}
})
if err := tt.Click("Sakiko Togawa"); err != nil {
t.Fatal(err)
}
if err := tt.Click("Oblivionis · ob@mask"); err != nil {
t.Fatal(err)
}
if cur != "b" || n != 1 {
t.Fatalf("switch: %q %d", cur, n)
}
tt.Key(0, ui.KeyDown)
if err := tt.Click("Add account…"); err != nil {
t.Fatal(err)
}
if adds != 1 || cur != "b" {
t.Fatal("add not reported")
}
disabled = true
tt.Frame()
_ = tt.Click("Oblivionis")
if tt.HasText("Add account…") {
t.Fatal("disabled switcher opened")
}
defer func() {
if recover() == nil {
t.Fatal("unknown current accepted")
}
}()
bad := "z"
accountTester(100, 100, func(c *ui.Context) { AccountSwitcher(c, &bad, switcherAccounts, AccountSwitcherOptions{}) })
}
func TestAccountSwitcherSnapshot(t *testing.T) {
snapshot(t, "account_switcher", 300, 90, func(c *ui.Context) {
cur := ui.Local(c.Root(), "cur", func() string { return "a" })
ui.Column(c).Padding(16).AlignItems(ui.Start).Children(func() { AccountSwitcher(c, cur, switcherAccounts, AccountSwitcherOptions{}) })
})
}
func TestAccountSwitcherLargeDataBuildsVisibleRows(t *testing.T) {
items := make([]Account, 100000)
for i := range items {
items[i] = Account{ID: fmt.Sprint(i), Name: fmt.Sprintf("Account %d", i)}
}
cur := "0"
tt := accountTester(500, 500, func(c *ui.Context) { AccountSwitcher(c, &cur, items, AccountSwitcherOptions{}) })
if err := tt.Click("Account 0"); err != nil {
t.Fatal(err)
}
if n := len(tt.Texts()); n > 100 {
t.Fatalf("built %d text elements for a bounded viewport", n)
}
tt.Key(0, ui.KeyEnd)
tt.Key(0, ui.KeyEnter)
if cur != "99999" {
t.Fatalf("large-list keyboard choice %q", cur)
}
}
func TestAccountSwitcherTabChoosesFocusedLargeRow(t *testing.T) {
items := make([]Account, 9)
for i := range items {
items[i] = Account{ID: fmt.Sprint(i), Name: fmt.Sprintf("Account %d", i)}
}
cur := "0"
tt := accountTester(500, 500, func(c *ui.Context) { AccountSwitcher(c, &cur, items, AccountSwitcherOptions{}) })
if err := tt.Click("Account 0"); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyTab)
if !tt.Focused("Account 1") {
t.Fatal("Tab did not reach the second account")
}
tt.Key(0, ui.KeyEnter)
if cur != "1" {
t.Fatal("Enter did not choose the focused account")
}
}
func TestAccountSwitcherFocusFollowsReorderedID(t *testing.T) {
items := []Account{{ID: "a", Name: "A"}, {ID: "b", Name: "B"}, {ID: "c", Name: "C"}}
cur := "a"
tt := accountTester(500, 500, func(c *ui.Context) { AccountSwitcher(c, &cur, items, AccountSwitcherOptions{}) })
if err := tt.Click("A"); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeyDown)
if !tt.Focused("B") {
t.Fatal("Down did not reach B")
}
items[1], items[2] = items[2], items[1]
tt.Frame()
tt.Key(0, ui.KeyEnter)
if cur != "b" {
t.Fatalf("reordered focus chose %q", cur)
}
}
func TestAccountSwitcherArrowsContinueFromTabFocus(t *testing.T) {
items := make([]Account, 9)
for i := range items {
items[i] = Account{ID: fmt.Sprint(i), Name: fmt.Sprintf("Account %d", i)}
}
cur := "0"
tt := accountTester(500, 500, func(c *ui.Context) { AccountSwitcher(c, &cur, items, AccountSwitcherOptions{}) })
if err := tt.Click("Account 0"); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyDown)
tt.Key(0, ui.KeyEnter)
if cur != "2" {
t.Fatalf("arrow choice after Tab: %q", cur)
}
}
+208
View File
@@ -0,0 +1,208 @@
package account
import (
"fmt"
"log/slog"
"slices"
"strings"
"time"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/feedback"
"github.com/ZacharyZhang-NY/MujicaUI/icons"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/overlay"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// APIKey contains public metadata and the visible prefix.
type APIKey struct {
ID, Name, Prefix string
Created, LastUsed time.Time
}
// ApiKeyManagerState holds creation, confirmation and one-time reveal state.
type ApiKeyManagerState struct {
creating, pending bool
name, secret string
err string
revoking string
keys []APIKey
index map[string]APIKey
}
// Reveal presents the generated secret until dismissal.
func (s *ApiKeyManagerState) Reveal(secret string) {
if !s.pending || secret == "" {
panic("mujica: ApiKeyManagerState.Reveal needs a create in progress and a secret")
}
s.pending, s.secret, s.err = false, secret, ""
slog.Debug("mujica: api_key_manager revealed")
}
// Fail displays a caller-provided creation error.
func (s *ApiKeyManagerState) Fail(err string) {
if !s.pending {
panic("mujica: ApiKeyManagerState.Fail needs a create in progress")
}
s.creating, s.pending, s.err = true, false, err
}
// ApiKeyManagerOptions configure an ApiKeyManager.
type ApiKeyManagerOptions struct {
Disabled bool
}
// ApiKeyManagerResult reports creation and revocation requests.
type ApiKeyManagerResult struct {
Element *ui.Element
create, revoke string
}
// Create returns the requested name; finish with Reveal or Fail.
func (r ApiKeyManagerResult) Create() (string, bool) { return r.create, r.create != "" }
// Revoked returns the confirmed key ID.
func (r ApiKeyManagerResult) Revoked() (string, bool) { return r.revoke, r.revoke != "" }
// ApiKeyManager masks stored keys and confirms revocation.
func ApiKeyManager(c *ui.Context, s *ApiKeyManagerState, keys []APIKey, opts ApiKeyManagerOptions) ApiKeyManagerResult {
k := core.Tokens(c)
d := core.Density(c)
var r ApiKeyManagerResult
r.Element = ui.Column(c).Gap(d.Unit() * 3).MinWidth(460).Disabled(opts.Disabled)
disabled := r.Element.IsDisabled()
if disabled {
s.creating = s.creating && (s.pending || s.err != "")
s.revoking, s.secret = "", ""
}
if s.index == nil || !slices.Equal(s.keys, keys) {
s.keys, s.index = slices.Clone(keys), map[string]APIKey{}
for _, key := range keys {
if key.ID == "" || key.Name == "" || key.Prefix == "" {
panic("mujica: APIKey needs an ID, a Name and a Prefix")
}
if _, ok := s.index[key.ID]; ok {
panic("mujica: APIKey IDs must be unique")
}
s.index[key.ID] = key
}
}
byID := s.index
r.Element.Children(func() {
ui.Row(c).Children(func() {
if input.Button(c, core.Msg(c, "api_key_manager.create"), input.ButtonOptions{Icon: icons.Must("plus"), Disabled: disabled}).Clicked() && !disabled {
s.creating, s.name, s.err = true, "", ""
}
})
if len(keys) == 0 {
feedback.EmptyState(c, feedback.EmptyStateOptions{Title: core.Msg(c, "api_key_manager.empty")})
}
accountRows(c, len(keys), func(i int) any { return keys[i].ID }, func(i int) {
key := keys[i]
ui.Row(c).Key(key.ID).MinHeight(d.ControlHeight()+d.Unit()*4).Gap(d.Unit()*3).AlignItems(ui.Center).
BorderWidth(0, 0, theme.BorderWidth, 0).BorderColor(k.Border).Children(func() {
ui.Column(c).Grow(1).MinWidth(0).Gap(2).Children(func() {
ui.Text(c, key.Name).FontWeight(600).SingleLine()
ui.Text(c, apiKeyMasked(key.Prefix)).Font(theme.MonoFont).TextColor(k.TextMuted).SingleLine()
ui.Text(c, apiKeyDates(c, key)).TextColor(k.TextMuted).FontSize(core.FontSize(c, theme.CaptionSize))
})
b := input.Button(c, core.Msg(c, "api_key_manager.revoke"), input.ButtonOptions{Variant: input.Secondary, Disabled: disabled}).
Label(fmt.Sprintf(core.Msg(c, "api_key_manager.revoke_named"), key.Name))
if b.Clicked() && !disabled {
s.revoking = key.ID
}
})
})
})
if name, ok := apiKeyCreateDialog(c, s, disabled); ok && !disabled {
r.create = name
slog.Debug("mujica: api_key_manager create")
}
victim, exists := byID[s.revoking]
open := s.revoking != "" && exists
res := overlay.AlertDialog(c, &open, overlay.AlertDialogOptions{Title: fmt.Sprintf(core.Msg(c, "api_key_manager.revoke_title"), victim.Name),
Description: core.Msg(c, "api_key_manager.revoke_text"), ConfirmLabel: core.Msg(c, "api_key_manager.revoke")})
if res.Confirmed && !disabled {
r.revoke = victim.ID
slog.Debug("mujica: api_key_manager revoke")
}
if !open {
s.revoking = ""
}
return r
}
// apiKeyMasked shows the prefix and hides the rest.
func apiKeyMasked(prefix string) string { return prefix + strings.Repeat("•", 12) }
// apiKeyDates says when a key was made and last used.
func apiKeyDates(c *ui.Context, key APIKey) string {
used := core.Msg(c, "api_key_manager.never")
if !key.LastUsed.IsZero() {
used = key.LastUsed.Format("2006-01-02")
}
return fmt.Sprintf(core.Msg(c, "api_key_manager.dates"), key.Created.Format("2006-01-02"), used)
}
// apiKeyCreateDialog collects a name and reveals the generated secret.
func apiKeyCreateDialog(c *ui.Context, s *ApiKeyManagerState, disabled bool) (string, bool) {
k := core.Tokens(c)
d := core.Density(c)
open := !disabled && (s.creating || s.pending || s.secret != "")
was := open
asked := false
title := core.Msg(c, "api_key_manager.create_title")
if s.secret != "" {
title = core.Msg(c, "api_key_manager.secret_title")
}
overlay.Dialog(c, &open, overlay.DialogOptions{Title: title, KeepOnBackdrop: true, KeepOnEscape: s.pending, HideClose: s.pending, Actions: func() {
switch {
case s.secret != "":
if input.Button(c, core.Msg(c, "api_key_manager.done"), input.ButtonOptions{}).Clicked() {
open = false
}
default:
if input.Button(c, core.Msg(c, "api_key_manager.cancel"), input.ButtonOptions{Variant: input.Secondary, Disabled: s.pending}).Clicked() {
open = false
}
ok := strings.TrimSpace(s.name) != ""
if input.Button(c, core.Msg(c, "api_key_manager.create"), input.ButtonOptions{Loading: s.pending, Disabled: !ok}).Clicked() && ok && !s.pending {
asked = true
}
}
}}, func() {
if s.secret != "" {
ui.Row(c).Gap(d.Unit() * 2).AlignItems(ui.Start).Padding(d.Unit() * 3).Radius(theme.ControlRadius).Background(k.Warning.Alpha(0.12)).Children(func() {
ui.Icon(c, icons.Must("triangle-alert")).Size(16, 16).TextColor(k.Warning).Shrink(0)
ui.Text(c, core.Msg(c, "api_key_manager.once")).Grow(1)
})
ui.Row(c).Gap(d.Unit()*2).AlignItems(ui.Center).Padding(d.Unit()*2, d.Unit()*3).Radius(theme.ControlRadius).
Background(k.Background).Border(theme.BorderWidth, k.Border).Children(func() {
ui.Text(c, s.secret).Font(theme.MonoFont).Selectable().Label(core.Msg(c, "api_key_manager.secret_title")).Grow(1).MinWidth(0)
if core.IconAction(c, icons.Must("copy"), core.Msg(c, "api_key_manager.copy")).Clicked() {
c.WriteClipboard(s.secret)
c.Announce(core.Msg(c, "api_key_manager.copied"))
}
})
return
}
res := input.TextInput(c, &s.name, input.TextInputOptions{Label: core.Msg(c, "api_key_manager.name"), Placeholder: core.Msg(c, "api_key_manager.name"),
Disabled: s.pending, Error: s.err})
res.Input.AutoFocus()
if res.Submitted() && strings.TrimSpace(s.name) != "" && !s.pending {
asked = true
}
})
if was && !open && !s.pending {
// Dismissing wipes the one-time secret.
s.creating, s.secret, s.name = false, "", ""
}
if asked {
s.pending, s.err = true, ""
return strings.TrimSpace(s.name), true
}
return "", false
}
+201
View File
@@ -0,0 +1,201 @@
package account
import (
"fmt"
"strings"
"testing"
"time"
"github.com/egoist/mygo/ui"
)
var apiKeys = []APIKey{{ID: "k1", Name: "Deploy bot", Prefix: "mk_live_9f2c", Created: time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)}}
func TestApiKeyManagerCreateRevealOnceAndRevoke(t *testing.T) {
logs := accountLogs(t)
const secret = "mk_live_9f2c_SECRET_DO_NOT_LOG"
var s ApiKeyManagerState
var created, revoked []string
tt := accountTester(700, 600, func(c *ui.Context) {
r := ApiKeyManager(c, &s, apiKeys, ApiKeyManagerOptions{})
if name, ok := r.Create(); ok {
created = append(created, name)
}
if id, ok := r.Revoked(); ok {
revoked = append(revoked, id)
}
})
if !tt.HasText("mk_live_9f2c••••••••••••") || !tt.HasText("Created 2026-09-01 · last used never") {
t.Fatalf("masked list: %q", tt.Texts())
}
_ = tt.Click("Create key")
tt.Type("CI")
tt.Key(0, ui.KeyEnter)
tt.Key(0, ui.KeyEnter)
if len(created) != 1 || created[0] != "CI" {
t.Fatalf("created %v", created)
}
s.Reveal(secret)
tt.Frame()
if s.secret != secret || !tt.HasText("Copy key") {
t.Fatal("new key not shown")
}
if err := tt.Click("Copy key"); err != nil {
t.Fatal(err)
}
if tt.Clipboard() != secret {
t.Fatal("copy did not take the key")
}
_ = tt.Click("I've saved it")
if tt.HasText("Copy key") || s.secret != "" {
t.Fatal("key still shown or kept after dismissal")
}
if strings.Contains(logs.String(), secret) {
t.Fatal("the key reached the log")
}
_ = tt.Click("Revoke Deploy bot")
if !tt.Focused("Cancel") {
t.Fatal("revoke confirmation not focused on Cancel")
}
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyEnter)
if len(revoked) != 1 || revoked[0] != "k1" {
t.Fatalf("revoked %v", revoked)
}
}
func TestApiKeyManagerFailAndDisabled(t *testing.T) {
var s ApiKeyManagerState
disabled, made := false, 0
tt := accountTester(700, 600, func(c *ui.Context) {
if _, ok := ApiKeyManager(c, &s, nil, ApiKeyManagerOptions{Disabled: disabled}).Create(); ok {
made++
}
})
if !tt.HasText("No API keys") {
t.Fatal("no empty state")
}
_ = tt.Click("Create key")
tt.Type("x")
tt.Key(0, ui.KeyEnter)
tt.Key(0, ui.KeyEscape)
if made != 1 || !s.pending {
t.Fatal("escape left a pending create")
}
s.Fail("Key limit reached.")
tt.Frame()
if !tt.HasText("Key limit reached.") {
t.Fatalf("failure: %q", tt.Texts())
}
tt.Key(0, ui.KeyEscape)
disabled = true
tt.Frame()
_ = tt.Click("Create key")
if tt.HasText("New API key") {
t.Fatal("disabled manager opened the dialog")
}
}
func TestApiKeyManagerSnapshot(t *testing.T) {
snapshot(t, "api_key_manager", 560, 220, func(c *ui.Context) {
s := ui.Local(c.Root(), "s", func() ApiKeyManagerState { return ApiKeyManagerState{} })
ui.Column(c).Padding(16).Children(func() { ApiKeyManager(c, s, apiKeys, ApiKeyManagerOptions{}) })
})
}
func TestApiKeyManagerDisablingClosesEveryDialog(t *testing.T) {
for _, phase := range []string{"name", "pending", "secret", "revoke"} {
t.Run(phase, func(t *testing.T) {
var s ApiKeyManagerState
disabled := false
tt := accountTester(700, 600, func(c *ui.Context) {
ui.Column(c).Disabled(disabled).Children(func() { ApiKeyManager(c, &s, apiKeys, ApiKeyManagerOptions{}) })
})
if phase == "revoke" {
if err := tt.Click("Revoke Deploy bot"); err != nil {
t.Fatal(err)
}
} else {
if err := tt.Click("Create key"); err != nil {
t.Fatal(err)
}
if phase != "name" {
tt.Type("CI")
tt.Key(0, ui.KeyEnter)
}
if phase == "secret" {
s.Reveal("one-time-test-secret")
tt.Frame()
}
}
disabled = true
tt.Frame()
if tt.HasText("New API key") || tt.HasText("Copy your new key") || tt.HasText("Revoke Deploy bot?") || s.secret != "" {
t.Fatal("disabled manager retains an active dialog or secret")
}
})
}
}
func TestApiKeyManagerRemovedKeyCancelsConfirmation(t *testing.T) {
var s ApiKeyManagerState
keys := apiKeys
tt := accountTester(700, 600, func(c *ui.Context) { ApiKeyManager(c, &s, keys, ApiKeyManagerOptions{}) })
if err := tt.Click("Revoke Deploy bot"); err != nil {
t.Fatal(err)
}
keys = nil
tt.Frame()
if s.revoking != "" || tt.HasText("Apps using this key stop working at once.") {
t.Fatal("removed key keeps confirmation open")
}
}
func TestApiKeyManagerLargeDataBuildsVisibleRows(t *testing.T) {
items := make([]APIKey, 100000)
for i := range items {
items[i] = APIKey{ID: fmt.Sprint(i), Name: fmt.Sprintf("Key %d", i), Prefix: "public"}
}
var s ApiKeyManagerState
tt := accountTester(600, 500, func(c *ui.Context) { ApiKeyManager(c, &s, items, ApiKeyManagerOptions{}) })
if n := len(tt.Texts()); n > 100 {
t.Fatalf("built %d text elements for a bounded viewport", n)
}
}
func TestApiKeyManagerFailureSurvivesDisabledRequest(t *testing.T) {
for _, whileDisabled := range []bool{false, true} {
t.Run(fmt.Sprint(whileDisabled), func(t *testing.T) {
var s ApiKeyManagerState
disabled, requests := false, 0
tt := accountTester(700, 600, func(c *ui.Context) {
if _, ok := ApiKeyManager(c, &s, nil, ApiKeyManagerOptions{Disabled: disabled}).Create(); ok {
requests++
}
})
if err := tt.Click("Create key"); err != nil {
t.Fatal(err)
}
tt.Type("CI")
tt.Key(0, ui.KeyEnter)
disabled = true
tt.Frame()
if whileDisabled {
s.Fail("Create failed")
tt.Frame()
}
disabled = false
if !whileDisabled {
s.Fail("Create failed")
}
tt.Frame()
if !tt.HasText("Create failed") || s.name != "CI" || s.pending {
t.Fatal("disabled request lost its failure or draft")
}
tt.Key(0, ui.KeyEnter)
if requests != 2 || !s.pending {
t.Fatal("failed request cannot be retried")
}
})
}
}
+96
View File
@@ -0,0 +1,96 @@
package account
import (
"fmt"
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/overlay"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// CoachmarkStep uses an anchor built in the current frame.
type CoachmarkStep struct {
Anchor *ui.Element
Title, Body string
}
// CoachmarkResult reports tour completion or dismissal.
type CoachmarkResult struct {
Element *ui.Element
finished, dismissed bool
}
// Finished reports Done on the last step.
func (r CoachmarkResult) Finished() bool { return r.finished }
// Dismissed reports Escape, a click outside or Skip.
func (r CoachmarkResult) Dismissed() bool { return r.dismissed }
// Coachmark provides anchored tips and keyboard-accessible step navigation.
func Coachmark(c *ui.Context, open *bool, step *int, steps []CoachmarkStep) CoachmarkResult {
if len(steps) == 0 || *step < 0 || *step >= len(steps) {
panic(fmt.Sprintf("mujica: Coachmark step %d outside %d steps", *step, len(steps)))
}
var r CoachmarkResult
if !*open {
return r
}
cur := steps[*step]
if cur.Anchor == nil || cur.Title == "" {
panic("mujica: CoachmarkStep needs an Anchor and a Title")
}
if cur.Anchor.IsDisabled() {
*open = false
return r
}
k := core.Tokens(c)
d := core.Density(c)
if b := cur.Anchor.Bounds(); b.W > 0 {
const pad = 4
ui.Overlay(c, func() {
ui.Box(c).Absolute().Left(b.X-pad).Top(b.Y-pad).Size(b.W+2*pad, b.H+2*pad).PassThrough().Role(ui.RoleNone).
Border(2, k.AccentText).Radius(theme.CardRadius)
})
}
from := *step
r.Element = overlay.Popover(c, cur.Anchor, open, overlay.PopoverOptions{Title: cur.Title, Width: 300}, func() {
ui.Column(c).Gap(d.Unit() * 3).Children(func() {
if cur.Body != "" {
ui.Text(c, cur.Body)
}
ui.Row(c).Gap(d.Unit() * 2).AlignItems(ui.Center).Children(func() {
ui.Text(c, fmt.Sprintf(core.Msg(c, "coachmark.count"), *step+1, len(steps))).TextColor(k.TextMuted).
FontSize(core.FontSize(c, theme.CaptionSize)).Grow(1)
if *step < len(steps)-1 && input.Button(c, core.Msg(c, "coachmark.skip"), input.ButtonOptions{Variant: input.Ghost}).Clicked() {
*open, r.dismissed = false, true
}
if *step > 0 && input.Button(c, core.Msg(c, "coachmark.back"), input.ButtonOptions{Variant: input.Secondary}).Clicked() {
*step--
}
last := *step == len(steps)-1
next := core.Msg(c, "coachmark.next")
if last {
next = core.Msg(c, "coachmark.done")
}
if input.Button(c, next, input.ButtonOptions{}).AutoFocus().Clicked() {
if last {
*open, r.finished = false, true
} else {
*step++
}
}
})
})
})
if !*open && !r.finished {
r.dismissed = true
}
if *step != from || !*open {
slog.Debug("mujica: coachmark step", "step", *step, "open", *open)
}
return r
}
+81
View File
@@ -0,0 +1,81 @@
package account
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
func coachmarkView(c *ui.Context, open *bool, step *int, r *CoachmarkResult) {
var a, b *ui.Element
ui.Row(c).Gap(40).Padding(20).Children(func() {
a = input.Button(c, "Compose", input.ButtonOptions{})
b = input.Button(c, "Archive", input.ButtonOptions{Variant: input.Secondary})
})
*r = Coachmark(c, open, step, []CoachmarkStep{
{Anchor: a, Title: "Write here", Body: "Start a new letter."},
{Anchor: b, Title: "Keep it tidy", Body: "Archive finished threads."},
})
}
func TestCoachmarkStepsAndEscape(t *testing.T) {
open, step := true, 0
var r CoachmarkResult
done, dismissed := 0, 0
tt := accountTester(600, 400, func(c *ui.Context) {
coachmarkView(c, &open, &step, &r)
if r.Finished() {
done++
}
if r.Dismissed() {
dismissed++
}
})
tt.Frame()
if !tt.HasText("Write here") || !tt.HasText("1 of 2") {
t.Fatalf("first: %q", tt.Texts())
}
tt.Key(0, ui.KeyEnter)
if step != 1 || !tt.HasText("Keep it tidy") {
t.Fatalf("next: %d", step)
}
_ = tt.Click("Done")
if done != 1 || open {
t.Fatal("done not reported")
}
open, step = true, 0
tt.Frame()
tt.Key(0, ui.KeyEscape)
if open || dismissed != 1 || done != 1 {
t.Fatalf("escape: open %v dismissed %d", open, dismissed)
}
}
func TestCoachmarkSnapshot(t *testing.T) {
snapshot(t, "coachmark", 420, 230, func(c *ui.Context) {
open := ui.Local(c.Root(), "open", func() bool { return true })
step := ui.Local(c.Root(), "step", func() int { return 0 })
var r CoachmarkResult
coachmarkView(c, open, step, &r)
})
}
func TestCoachmarkDisabledAnchorCloses(t *testing.T) {
open, step, disabled := true, 0, false
tt := accountTester(600, 400, func(c *ui.Context) {
a := input.Button(c, "Compose", input.ButtonOptions{Disabled: disabled})
Coachmark(c, &open, &step, []CoachmarkStep{{Anchor: a, Title: "Write here"}})
})
disabled = true
tt.Frame()
if open || tt.HasText("Write here") {
t.Fatal("disabled anchor retains coachmark")
}
}
func TestCoachmarkInvalidStep(t *testing.T) {
open, step := true, 1
accountPanics(t, func(c *ui.Context) { Coachmark(c, &open, &step, []CoachmarkStep{{Title: "Only step"}}) })
}
+2
View File
@@ -0,0 +1,2 @@
// Package account holds MujicaUI settings and account management.
package account
+242
View File
@@ -0,0 +1,242 @@
package account_test
import (
"fmt"
"time"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/account"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
func ExampleSettingsLayout() {
page := ""
sound := true
pages := []account.SettingsPage{{ID: "general", Label: "General"}, {ID: "privacy", Label: "Privacy"}}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
account.SettingsLayout(c, &page, pages, account.SettingsLayoutOptions{}, func(id string) {
account.SettingsSection(c, "Notifications", func() {
account.SettingsRow(c, "Sound", account.SettingsRowOptions{ID: "sound"}, func() *ui.Element {
return input.Switch(c, &sound, "", input.SwitchOptions{})
})
})
})
}
ui.Render(view, 400, 300, 1)
}
func ExampleSettingsSearch() {
query, page := "", "general"
entries := []account.SettingEntry{{ID: "sound", Page: "general", Label: "Sound", Keywords: []string{"audio"}}}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if e, ok := account.SettingsSearch(c, &query, entries, account.SettingsSearchOptions{}).Chosen(); ok {
page = e.Page
}
fmt.Println("page", page)
}
ui.Render(view, 400, 300, 1)
}
func ExampleThemeSelector() {
mode := core.System
view := func(c *ui.Context) {
core.Use(c, core.Settings{Mode: mode})
account.ThemeSelector(c, &mode, account.ThemeSelectorOptions{})
}
ui.Render(view, 400, 300, 1)
}
func ExampleAccentColorPicker() {
accent := ui.Hex("#7D2034")
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
account.AccentColorPicker(c, &accent, account.AccentColorPickerOptions{})
}
ui.Render(view, 400, 300, 1)
}
func ExampleShortcutRecorder() {
palette := account.Shortcut{Mods: ui.Cmd | ui.Shift, Key: ui.KeyP}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
account.ShortcutRecorder(c, &palette, account.ShortcutRecorderOptions{
Label: "Command palette",
Taken: []account.ShortcutBinding{{Action: "Save", Shortcut: account.Shortcut{Mods: ui.Cmd, Key: ui.KeyS}}},
})
}
ui.Render(view, 400, 300, 1)
}
func ExampleKeyboardShortcutsList() {
query := ""
groups := []account.ShortcutGroup{{Title: "General", Bindings: []account.ShortcutBinding{
{Action: "Command palette", Shortcut: account.Shortcut{Mods: ui.Cmd | ui.Shift, Key: ui.KeyP}},
}}}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
account.KeyboardShortcutsList(c, &query, groups, account.KeyboardShortcutsListOptions{})
}
ui.Render(view, 400, 300, 1)
}
func ExampleLoginForm() {
var state account.LoginFormState
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
account.LoginForm(c, &state, account.LoginFormOptions{OnSubmit: func(account, password string, remember bool) {
// Submit credentials through the caller-provided auth service.
state.EndSubmit("")
}})
}
ui.Render(view, 400, 300, 1)
}
func ExampleOAuthButtons() {
providers := []account.OAuthProvider{{ID: "sso", Name: "Company SSO"}}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if id, ok := account.OAuthButtons(c, providers, account.OAuthButtonsOptions{}).Chosen(); ok {
fmt.Println("start sign-in with", id)
}
}
ui.Render(view, 400, 300, 1)
}
func ExampleTwoFactorInput() {
code := ""
resendAt := time.Now().Add(30 * time.Second)
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
r := account.TwoFactorInput(c, &code, account.TwoFactorInputOptions{ResendAt: resendAt})
if r.Completed() {
fmt.Println("verify the code")
}
}
ui.Render(view, 400, 300, 1)
}
func ExampleProfileEditor() {
saved := account.Profile{Name: "Sakiko", Bio: "Keyboard."}
profile := saved
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if account.ProfileEditor(c, &profile, account.ProfileEditorOptions{Saved: saved}).Save() {
saved = profile
}
}
ui.Render(view, 400, 300, 1)
}
func ExampleAccountSwitcher() {
current := "a"
accounts := []account.Account{{ID: "a", Name: "Sakiko Togawa", Email: "sakiko@court"}, {ID: "b", Name: "Oblivionis"}}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if account.AccountSwitcher(c, &current, accounts, account.AccountSwitcherOptions{}).Add() {
fmt.Println("sign in another account")
}
}
ui.Render(view, 400, 300, 1)
}
func ExampleWorkspaceSwitcher() {
current := "ave"
spaces := []account.Workspace{{ID: "ave", Name: "Ave Mujica"}, {ID: "mygo", Name: "MyGO!!!!!"}}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
account.WorkspaceSwitcher(c, &current, spaces, account.WorkspaceSwitcherOptions{})
}
ui.Render(view, 400, 300, 1)
}
func ExampleUserMenu() {
status := account.UserStatusOnline
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if account.UserMenu(c, &status, account.UserMenuOptions{Name: "Sakiko Togawa"}).SignOut() {
fmt.Println("sign out")
}
}
ui.Render(view, 400, 300, 1)
}
func ExampleSessionList() {
sessions := []account.Session{{ID: "s1", Device: "MacBook Pro", Current: true}, {ID: "s2", Device: "iPhone", Location: "Osaka"}}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if id, ok := account.SessionList(c, sessions, account.SessionListOptions{}).Revoked(); ok {
fmt.Println("sign out", id)
}
}
ui.Render(view, 400, 300, 1)
}
func ExampleApiKeyManager() {
var state account.ApiKeyManagerState
keys := []account.APIKey{{ID: "k1", Name: "Deploy bot", Prefix: "mk_live_9f2c"}}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if name, ok := account.ApiKeyManager(c, &state, keys, account.ApiKeyManagerOptions{}).Create(); ok {
fmt.Println("create", name)
state.Reveal("secret from your key service")
}
}
ui.Render(view, 400, 300, 1)
}
func ExampleUsageQuota() {
items := []account.QuotaItem{{Label: "API calls", Used: 4200, Limit: 10000}, {Label: "Storage", Used: 9, Limit: 10, Unit: "GB"}}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
account.UsageQuota(c, items, account.UsageQuotaOptions{ResetAt: time.Now().Add(72 * time.Hour)})
}
ui.Render(view, 400, 300, 1)
}
func ExampleOnboardingWizard() {
step := 0
steps := []account.WizardStep{{Title: "Welcome"}, {Title: "Pick a theme"}, {Title: "Done"}}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if account.OnboardingWizard(c, &step, steps, account.OnboardingWizardOptions{}).Finished() {
fmt.Println("onboarded")
}
}
ui.Render(view, 400, 300, 1)
}
func ExampleCoachmark() {
open, step := true, 0
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
compose := input.Button(c, "Compose", input.ButtonOptions{})
account.Coachmark(c, &open, &step, []account.CoachmarkStep{{Anchor: compose, Title: "Write here", Body: "Start a new letter."}})
}
ui.Render(view, 400, 300, 1)
}
func ExampleWhatsNewDialog() {
open, hide := true, false
releases := []account.Release{{Version: "1.1", Changes: []account.ReleaseChange{{Kind: account.ChangeNew, Text: "500 components."}}}}
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
account.WhatsNewDialog(c, &open, &hide, releases, account.WhatsNewDialogOptions{})
}
ui.Render(view, 400, 300, 1)
}
func ExampleFeedbackWidget() {
var state account.FeedbackWidgetState
view := func(c *ui.Context) {
core.Use(c, core.Settings{})
if f, ok := account.FeedbackWidget(c, &state, account.FeedbackWidgetOptions{}).Submitted(); ok {
fmt.Println("send", f.Kind)
state.EndSubmit("")
}
}
ui.Render(view, 400, 300, 1)
}
+122
View File
@@ -0,0 +1,122 @@
package account
import (
"fmt"
"log/slog"
"strings"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/navigation"
)
// FeedbackKind is what the feedback is about.
type FeedbackKind int
const (
FeedbackBug FeedbackKind = iota
FeedbackIdea
FeedbackPraise
FeedbackOther
)
// Feedback is what a FeedbackWidget sends.
type Feedback struct {
Kind FeedbackKind
Text string
}
// FeedbackWidgetState holds the draft and its form state.
type FeedbackWidgetState struct {
Draft Feedback
Form input.FormState
}
// EndSubmit clears successful drafts and preserves failed ones.
func (s *FeedbackWidgetState) EndSubmit(err string) {
s.Form.EndSubmit(err)
if err == "" {
s.Draft.Text = ""
}
}
// FeedbackWidgetOptions configure a FeedbackWidget.
type FeedbackWidgetOptions struct {
// Attachments builds the caller-provided screenshot or file slot.
Attachments func()
// MinLength is the fewest characters accepted; zero means 10.
MinLength int
Disabled bool
}
// FeedbackWidgetResult carries the submitted feedback.
type FeedbackWidgetResult struct {
Element *ui.Element
feedback Feedback
submitted bool
}
// Submitted returns feedback; finish the request with EndSubmit.
func (r FeedbackWidgetResult) Submitted() (Feedback, bool) { return r.feedback, r.submitted }
// FeedbackWidget validates feedback and submits it once.
func FeedbackWidget(c *ui.Context, s *FeedbackWidgetState, opts FeedbackWidgetOptions) FeedbackWidgetResult {
if opts.MinLength < 0 {
panic("mujica: FeedbackWidget MinLength cannot be negative")
}
if s.Draft.Kind < FeedbackBug || s.Draft.Kind > FeedbackOther || opts.MinLength > 2000 {
panic("mujica: FeedbackWidget invalid kind or length")
}
minLen := opts.MinLength
if minLen == 0 {
minLen = 10
}
d := core.Density(c)
var r FeedbackWidgetResult
r.Element = ui.Column(c).Gap(d.Unit() * 4).Width(420).Disabled(opts.Disabled)
disabled := r.Element.IsDisabled()
if disabled {
frozen := *s
frozen.Form.Order = append([]string(nil), s.Form.Order...)
frozen.Form.Fields = make(map[string]*input.FormFieldState, len(s.Form.Fields))
for name, field := range s.Form.Fields {
copy := *field
frozen.Form.Fields[name] = &copy
}
frozen.Form.Requested, frozen.Form.Awaiting = false, false
s = &frozen
}
locked := disabled || s.Form.Submitting()
r.Element.Children(func() {
kind := int(s.Draft.Kind)
var segs []navigation.Segment
for f := FeedbackBug; f <= FeedbackOther; f++ {
segs = append(segs, navigation.Segment{Label: core.Msg(c, fmt.Sprintf("feedback_widget.kind%d", f))})
}
navigation.SegmentedControl(c, &kind, segs, navigation.SegmentedControlOptions{Equal: true, Label: core.Msg(c, "feedback_widget.kind"), Disabled: locked})
if !locked {
s.Draft.Kind = FeedbackKind(kind)
}
res := input.Form(c, &s.Form, input.FormOptions{SubmitLabel: core.Msg(c, "feedback_widget.send"), ResetLabel: core.Msg(c, "feedback_widget.clear")}, func(f *input.FormScope) {
input.FormItem(c, f, "text", &s.Draft.Text, input.FormItemOptions[string]{Label: core.Msg(c, "feedback_widget.message"), Required: true,
Validate: func(v string) string {
if n := len([]rune(strings.TrimSpace(v))); n < minLen {
return fmt.Sprintf(core.Msg(c, "feedback_widget.short"), minLen)
}
return ""
}}, func() *ui.Element {
return input.TextArea(c, &s.Draft.Text, input.TextAreaOptions{MinHeight: 96, MaxLength: 2000, Disabled: locked}).Input
})
if opts.Attachments != nil {
ui.Column(c).Gap(d.Unit()).Disabled(locked).Children(opts.Attachments)
}
})
if res.Submitted() && !disabled {
r.feedback, r.submitted = s.Draft, true
slog.Debug("mujica: feedback_widget submitted", "kind", s.Draft.Kind)
}
})
return r
}
+123
View File
@@ -0,0 +1,123 @@
package account
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
func TestFeedbackWidgetValidatesSubmitsOnce(t *testing.T) {
var s FeedbackWidgetState
var sent []Feedback
attached := false
tt := accountTester(500, 500, func(c *ui.Context) {
r := FeedbackWidget(c, &s, FeedbackWidgetOptions{Attachments: func() { attached = true; ui.Text(c, "screenshot slot") }})
if f, ok := r.Submitted(); ok {
sent = append(sent, f)
}
})
if !attached || !tt.HasText("screenshot slot") {
t.Fatal("attachment slot not built")
}
_ = tt.Click("Idea")
_ = tt.Click("Message")
tt.Type("short")
_ = tt.Click("Send feedback")
if len(sent) != 0 || !tt.HasText("Write at least 10 characters.") {
t.Fatalf("short sent: %q", tt.Texts())
}
_ = tt.Click("Message")
tt.Type(" but now long enough")
_ = tt.Click("Send feedback")
_ = tt.Click("Send feedback")
if len(sent) != 1 || sent[0].Kind != FeedbackIdea || sent[0].Text != "short but now long enough" {
t.Fatalf("sent %+v", sent)
}
s.EndSubmit("")
tt.Frame()
if s.Draft.Text != "" {
t.Fatal("sent draft kept")
}
}
func TestFeedbackWidgetDisabled(t *testing.T) {
s := FeedbackWidgetState{Draft: Feedback{Text: "A long enough message."}}
sent := 0
tt := accountTester(500, 500, func(c *ui.Context) {
if _, ok := FeedbackWidget(c, &s, FeedbackWidgetOptions{Disabled: true}).Submitted(); ok {
sent++
}
})
_ = tt.Click("Bug")
_ = tt.Click("Praise")
_ = tt.Click("Send feedback")
if sent != 0 || s.Draft.Kind != FeedbackBug {
t.Fatal("disabled widget acted")
}
}
func TestFeedbackWidgetSnapshot(t *testing.T) {
snapshot(t, "feedback_widget", 460, 400, func(c *ui.Context) {
s := ui.Local(c.Root(), "s", func() FeedbackWidgetState {
return FeedbackWidgetState{Draft: Feedback{Kind: FeedbackBug, Text: "The ticker stutters on resize."}}
})
ui.Column(c).Padding(16).Children(func() {
FeedbackWidget(c, s, FeedbackWidgetOptions{Attachments: func() {
input.Button(c, "Attach screenshot", input.ButtonOptions{Variant: input.Secondary})
}})
})
})
}
func TestFeedbackWidgetPendingFreezesDraftAndAttachments(t *testing.T) {
s := FeedbackWidgetState{Draft: Feedback{Kind: FeedbackIdea, Text: "A long enough message."}}
attachments := 0
tt := accountTester(500, 500, func(c *ui.Context) {
FeedbackWidget(c, &s, FeedbackWidgetOptions{Attachments: func() {
if input.Button(c, "Attach", input.ButtonOptions{}).Clicked() {
attachments++
}
}})
})
if err := tt.Click("Send feedback"); err != nil {
t.Fatal(err)
}
if err := tt.Click("Praise"); err != nil {
t.Fatal(err)
}
if err := tt.Click("Message"); err != nil {
t.Fatal(err)
}
tt.Type("modified")
if err := tt.Click("Attach"); err != nil {
t.Fatal(err)
}
if s.Draft.Kind != FeedbackIdea || s.Draft.Text != "A long enough message." || attachments != 0 {
t.Fatal("pending feedback changes its draft or attachments")
}
}
func TestFeedbackWidgetFailurePreservesDraftAndInvalidLength(t *testing.T) {
s := FeedbackWidgetState{Draft: Feedback{Kind: FeedbackIdea, Text: "A long enough message."}}
tt := accountTester(600, 500, func(c *ui.Context) { FeedbackWidget(c, &s, FeedbackWidgetOptions{}) })
if err := tt.Click("Send feedback"); err != nil {
t.Fatal(err)
}
s.EndSubmit("Send failed.")
tt.Frame()
if s.Draft.Text != "A long enough message." || !tt.HasText("Send failed.") {
t.Fatal("failed feedback loses its draft or message")
}
accountPanics(t, func(c *ui.Context) { FeedbackWidget(c, &s, FeedbackWidgetOptions{MinLength: 2001}) })
}
func TestFeedbackWidgetDisabledKeepsFormState(t *testing.T) {
s := FeedbackWidgetState{Draft: Feedback{Text: "A long enough message."}}
s.Form.Submit()
accountTester(600, 500, func(c *ui.Context) { FeedbackWidget(c, &s, FeedbackWidgetOptions{Disabled: true}) })
if s.Form.Submitting() || !s.Form.Requested || s.Form.Fields != nil {
t.Fatal("disabled frame edits form state")
}
}
+24
View File
@@ -0,0 +1,24 @@
package account
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)
}
func snapshotTheme(c *ui.Context, mode string) {
m := core.Light
if mode == "dark" {
m = core.Dark
}
core.Use(c, core.Settings{Mode: m})
}
+112
View File
@@ -0,0 +1,112 @@
package account
import (
"reflect"
"slices"
"strings"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/feedback"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// ShortcutGroup is a titled group of bindings in a KeyboardShortcutsList.
type ShortcutGroup struct {
Title string
Bindings []ShortcutBinding
}
// KeyboardShortcutsListOptions configure a KeyboardShortcutsList.
type KeyboardShortcutsListOptions struct {
// Label names the search field; empty uses the built-in one.
Label string
}
type shortcutsListRow struct{ group, binding int }
type shortcutsListState struct {
groups []ShortcutGroup
query string
rows []shortcutsListRow
ready bool
}
// KeyboardShortcutsList displays searchable, grouped shortcuts using visible rows.
func KeyboardShortcutsList(c *ui.Context, query *string, groups []ShortcutGroup, opts KeyboardShortcutsListOptions) *ui.Element {
k := core.Tokens(c)
d := core.Density(c)
label := opts.Label
if label == "" {
label = core.Msg(c, "keyboard_shortcuts_list.search")
}
e := ui.Column(c).Gap(d.Unit() * 4).MinWidth(320)
st := ui.Local(e, "shortcuts", func() shortcutsListState { return shortcutsListState{} })
e.Children(func() {
input.SearchInput(c, query, input.SearchInputOptions{Placeholder: label, Label: label})
shortcutsListPlan(st, groups, strings.ToLower(strings.TrimSpace(*query)))
if len(st.rows) == 0 {
feedback.EmptyState(c, feedback.EmptyStateOptions{Kind: feedback.EmptyNoResults, Query: *query})
return
}
accountRows(c, len(st.rows), func(i int) any { return st.rows[i] }, func(i int) {
r := st.rows[i]
g := groups[r.group]
if r.binding < 0 {
ui.Text(c, g.Title).Font(theme.SerifFont).FontWeight(600).TextColor(k.Text).Padding(d.Unit()*2, 0).Role(ui.RoleGroup).Label(g.Title)
return
}
b := g.Bindings[r.binding]
ui.Row(c).MinHeight(d.ControlHeight()).AlignItems(ui.Center).Gap(d.Unit()*4).
BorderWidth(0, 0, theme.BorderWidth, 0).BorderColor(k.Border).Role(ui.RoleRow).
Label(b.Action + ", " + b.Shortcut.String()).Children(func() {
ui.Text(c, b.Action).Grow(1).MinWidth(0).Role(ui.RoleNone)
shortcutKbd(c, b.Shortcut)
})
})
})
return e
}
func shortcutsListPlan(st *shortcutsListState, groups []ShortcutGroup, q string) {
if st.ready && st.query == q && reflect.DeepEqual(st.groups, groups) {
return
}
st.ready, st.query = true, q
st.groups = slices.Clone(groups)
st.rows = st.rows[:0]
for gi, g := range groups {
st.groups[gi].Bindings = slices.Clone(g.Bindings)
header := false
for bi, b := range g.Bindings {
if b.Action == "" {
panic("mujica: KeyboardShortcutsList binding needs an Action")
}
if q != "" && !strings.Contains(strings.ToLower(b.Action), q) && !strings.Contains(strings.ToLower(b.Shortcut.String()), q) {
continue
}
if !header && g.Title != "" {
st.rows = append(st.rows, shortcutsListRow{gi, -1})
header = true
}
st.rows = append(st.rows, shortcutsListRow{gi, bi})
}
}
}
func accountRows(c *ui.Context, n int, key func(int) any, row func(int)) *ui.Element {
if n <= 8 {
return ui.Column(c).Children(func() {
for i := range n {
ui.Column(c).Key(key(i)).Children(func() { row(i) })
}
})
}
site := ui.Column(c).MinHeight(0).Shrink(1)
st := ui.Local(site, "rows", func() ui.ListState { return ui.ListState{} })
st.Key = key
site.Children(func() { ui.List(c, st, n, row).Height(320).MinHeight(0).Shrink(1) })
return site
}
+106
View File
@@ -0,0 +1,106 @@
package account
import (
"fmt"
"testing"
"github.com/egoist/mygo/ui"
)
var shortcutGroups = []ShortcutGroup{
{Title: "General", Bindings: []ShortcutBinding{{"Command palette", Shortcut{ui.Ctrl | ui.Shift, ui.KeyP}}, {"Settings", Shortcut{ui.Ctrl, ui.KeyComma}}}},
{Title: "Editing", Bindings: []ShortcutBinding{{"Duplicate line", Shortcut{ui.Alt | ui.Shift, ui.KeyDown}}, {"Toggle comment", Shortcut{}}}},
}
func TestKeyboardShortcutsListGroupsAndSearch(t *testing.T) {
query := ""
tt := accountTester(500, 500, func(c *ui.Context) { KeyboardShortcutsList(c, &query, shortcutGroups, KeyboardShortcutsListOptions{}) })
for _, want := range []string{"General", "Editing", "Command palette", "Toggle comment", "—"} {
if !tt.HasText(want) {
t.Fatalf("missing %q in %q", want, tt.Texts())
}
}
if _, ok := tt.Find("Duplicate line, alt+shift+down"); !ok {
t.Fatal("row not spoken with its keys")
}
_ = tt.Click("Search shortcuts")
tt.Type("comment")
if tt.HasText("General") || !tt.HasText("Toggle comment") {
t.Fatalf("search: %q", tt.Texts())
}
tt.Key(ui.Cmd, ui.KeyA)
tt.Type("ctrl+,")
if !tt.HasText("Settings") || tt.HasText("Editing") {
t.Fatalf("key search: %q", tt.Texts())
}
tt.Key(ui.Cmd, ui.KeyA)
tt.Type("zzz")
if !tt.HasText("No results") {
t.Fatalf("empty: %q", tt.Texts())
}
}
func TestKeyboardShortcutsListSnapshot(t *testing.T) {
snapshot(t, "keyboard_shortcuts_list", 460, 320, func(c *ui.Context) {
q := ui.Local(c.Root(), "q", func() string { return "" })
ui.Column(c).Padding(16).Children(func() { KeyboardShortcutsList(c, q, shortcutGroups, KeyboardShortcutsListOptions{}) })
})
}
func TestKeyboardShortcutsListLargeDataBuildsVisibleRows(t *testing.T) {
items := make([]ShortcutBinding, 100000)
for i := range items {
items[i] = ShortcutBinding{Action: fmt.Sprintf("Action %d", i)}
}
query := ""
tt := accountTester(500, 500, func(c *ui.Context) {
KeyboardShortcutsList(c, &query, []ShortcutGroup{{Title: "General", Bindings: items}}, KeyboardShortcutsListOptions{})
})
if n := len(tt.Texts()); n > 100 {
t.Fatalf("built %d text elements for a bounded viewport", n)
}
if err := tt.Click("Search shortcuts"); err != nil {
t.Fatal(err)
}
tt.Type("99999")
if !tt.HasText("Action 99999") || tt.HasText("Action 99998") {
t.Fatal("large-list search does not reach last binding")
}
}
func TestKeyboardShortcutsListDisabledSearchAndInvalidBinding(t *testing.T) {
q := ""
tt := accountTester(600, 500, func(c *ui.Context) {
ui.Column(c).Disabled(true).Children(func() { KeyboardShortcutsList(c, &q, shortcutGroups, KeyboardShortcutsListOptions{}) })
})
if err := tt.Click("Search shortcuts"); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeyTab)
tt.Type("save")
if q != "" {
t.Fatal("disabled search edits")
}
accountPanics(t, func(c *ui.Context) {
KeyboardShortcutsList(c, &q, []ShortcutGroup{{Bindings: []ShortcutBinding{{}}}}, KeyboardShortcutsListOptions{})
})
}
func TestKeyboardShortcutsListCachedPlanSeesInPlaceChanges(t *testing.T) {
st := shortcutsListState{}
groups := []ShortcutGroup{{Title: "General", Bindings: []ShortcutBinding{{Action: "Save"}}}}
shortcutsListPlan(&st, groups, "save")
if len(st.rows) != 2 {
t.Fatal("missing header or binding")
}
before := &st.rows[0]
shortcutsListPlan(&st, groups, "save")
if before != &st.rows[0] {
t.Fatal("unchanged data rebuilt shortcut plan")
}
groups[0].Bindings[0].Action = "Open"
shortcutsListPlan(&st, groups, "save")
if len(st.rows) != 0 {
t.Fatal("cached list misses in-place binding change")
}
}
+101
View File
@@ -0,0 +1,101 @@
package account
import (
"log/slog"
"strings"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/icons"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
// LoginFormState holds the form; only OnSubmit sees the password.
type LoginFormState struct {
Account string
Remember bool
password string
tried bool
submitting bool
err string
}
// EndSubmit finishes a sign-in, shows err and wipes the password.
func (s *LoginFormState) EndSubmit(err string) {
if !s.submitting {
panic("mujica: LoginFormState.EndSubmit without a submit in progress")
}
s.submitting, s.err, s.password = false, err, ""
slog.Debug("mujica: login_form submit ended", "failed", err != "")
}
// LoginFormOptions configure a LoginForm. OnSubmit is required.
type LoginFormOptions struct {
// OnSubmit alone receives the credentials; then call EndSubmit.
OnSubmit func(account, password string, remember bool)
// AccountLabel replaces the built-in "Email or username".
AccountLabel string
Disabled bool
}
// LoginForm collects credentials; it never checks or stores them.
func LoginForm(c *ui.Context, s *LoginFormState, opts LoginFormOptions) *ui.Element {
if opts.OnSubmit == nil {
panic("mujica: LoginForm needs OnSubmit")
}
k := core.Tokens(c)
d := core.Density(c)
accountLabel := opts.AccountLabel
if accountLabel == "" {
accountLabel = core.Msg(c, "login_form.account")
}
e := ui.Column(c).Gap(d.Unit() * 4).Width(340).Disabled(opts.Disabled)
disabled := e.IsDisabled()
missing := func(v string) string {
if s.tried && strings.TrimSpace(v) == "" {
return core.Msg(c, "form.required")
}
return ""
}
submit := false
var acc, pw input.InputResult
e.Children(func() {
input.FormField(c, accountLabel, input.FormFieldOptions{Required: true}, func() *ui.Element {
acc = input.TextInput(c, &s.Account, input.TextInputOptions{Disabled: disabled || s.submitting, Error: missing(s.Account)})
return acc.Input
})
input.FormField(c, core.Msg(c, "login_form.password"), input.FormFieldOptions{Required: true}, func() *ui.Element {
pw = input.PasswordInput(c, &s.password, input.PasswordInputOptions{Disabled: disabled || s.submitting, Error: missing(s.password)})
return pw.Input
})
if acc.Changed() || pw.Changed() {
s.err = ""
}
input.Checkbox(c, &s.Remember, core.Msg(c, "login_form.remember"), input.CheckboxOptions{Disabled: disabled || s.submitting})
if s.err != "" {
ui.Row(c).Gap(d.Unit() * 2).AlignItems(ui.Start).TextColor(k.Danger).Role(ui.RoleStatus).Children(func() {
ui.Icon(c, icons.Must("circle-alert")).Size(16, 16).Shrink(0)
ui.Text(c, s.err).Grow(1)
})
}
b := input.Button(c, core.Msg(c, "login_form.submit"), input.ButtonOptions{Loading: s.submitting, Disabled: disabled})
b.FillWidth()
submit = b.Clicked() || acc.Submitted() || pw.Submitted()
})
if submit && !disabled && !s.submitting {
s.tried = true
switch {
case strings.TrimSpace(s.Account) == "":
acc.Input.Focus()
return e
case s.password == "":
pw.Input.Focus()
return e
}
s.submitting, s.err = true, ""
slog.Debug("mujica: login_form submitted")
opts.OnSubmit(strings.TrimSpace(s.Account), s.password, s.Remember)
}
return e
}
+93
View File
@@ -0,0 +1,93 @@
package account
import (
"bytes"
"log/slog"
"strings"
"testing"
"github.com/egoist/mygo/ui"
)
// accountLogs records every debug log until the test ends.
func accountLogs(t *testing.T) *bytes.Buffer {
t.Helper()
var b bytes.Buffer
saved := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&b, &slog.HandlerOptions{Level: slog.LevelDebug})))
t.Cleanup(func() { slog.SetDefault(saved) })
return &b
}
type loginCall struct {
account, password string
remember bool
}
func loginTester(s *LoginFormState, calls *[]loginCall, disabled *bool) *ui.Tester {
return accountTester(420, 400, func(c *ui.Context) {
LoginForm(c, s, LoginFormOptions{Disabled: *disabled, OnSubmit: func(a, p string, r bool) {
*calls = append(*calls, loginCall{a, p, r})
}})
})
}
func TestLoginFormSubmitsOnceThroughCallback(t *testing.T) {
logs := accountLogs(t)
const secret = "s3cret-Sakiko"
var s LoginFormState
var calls []loginCall
disabled := false
tt := loginTester(&s, &calls, &disabled)
_ = tt.Click("Email or username")
tt.Type(" sakiko@court ")
_ = tt.Click("Password")
tt.Type(secret)
_ = tt.Click("Remember me")
tt.Key(ui.Shift, ui.KeyTab)
tt.Key(ui.Shift, ui.KeyTab)
tt.Key(0, ui.KeyEnter)
_ = tt.Click("Sign in")
if len(calls) != 1 || calls[0].account != "sakiko@court" || calls[0].password != secret || !calls[0].remember {
t.Fatalf("%d calls", len(calls))
}
if strings.Contains(logs.String(), secret) {
t.Fatal("the password reached the log")
}
s.EndSubmit("Too many attempts. Try again in 5 minutes.")
tt.Frame()
if !tt.HasText("Too many attempts. Try again in 5 minutes.") || s.password != "" || s.Account != " sakiko@court " {
t.Fatalf("shown %v wiped %v account %q", tt.HasText("Too many attempts. Try again in 5 minutes."), s.password == "", s.Account)
}
}
func TestLoginFormRequiresBothAndBlocksDisabled(t *testing.T) {
var s LoginFormState
var calls []loginCall
disabled := false
tt := loginTester(&s, &calls, &disabled)
_ = tt.Click("Sign in")
if len(calls) != 0 || !tt.HasText("Required") || !tt.Focused("Email or username") {
t.Fatalf("empty submit: %d calls", len(calls))
}
tt.Type("uika")
tt.Key(0, ui.KeyEnter)
if len(calls) != 0 || !tt.Focused("Password") {
t.Fatal("submitted without a password")
}
disabled = true
tt.Type("pw")
_ = tt.Click("Sign in")
if len(calls) != 0 || s.password != "" {
t.Fatal("disabled form took input or submitted")
}
}
func TestLoginFormSnapshot(t *testing.T) {
snapshot(t, "login_form", 400, 330, func(c *ui.Context) {
s := ui.Local(c.Root(), "s", func() LoginFormState {
return LoginFormState{Account: "sakiko@court", err: "Wrong account or password."}
})
LoginForm(c, s, LoginFormOptions{OnSubmit: func(string, string, bool) {}})
})
}
+61
View File
@@ -0,0 +1,61 @@
package account
import (
"fmt"
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
// OAuthProvider is a sign-in provider; icons are plain, not trademarks.
type OAuthProvider struct {
ID, Name string
Icon *ui.SVG
}
// OAuthButtonsOptions configure OAuthButtons.
type OAuthButtonsOptions struct {
// Pending is the provider signing in; the others are blocked.
Pending string
Disabled bool
}
// OAuthButtonsResult carries the selected provider.
type OAuthButtonsResult struct {
Element *ui.Element
chosen string
}
// Chosen returns the ID of the provider the user picked.
func (r OAuthButtonsResult) Chosen() (string, bool) { return r.chosen, r.chosen != "" }
// OAuthButtons offers a button per provider; the caller signs in.
func OAuthButtons(c *ui.Context, providers []OAuthProvider, opts OAuthButtonsOptions) OAuthButtonsResult {
if len(providers) == 0 {
panic("mujica: OAuthButtons needs providers")
}
d := core.Density(c)
var r OAuthButtonsResult
r.Element = ui.Column(c).Gap(d.Unit() * 2).Width(340).Disabled(opts.Disabled)
disabled := r.Element.IsDisabled()
r.Element.Children(func() {
for _, p := range providers {
if p.ID == "" || p.Name == "" {
panic("mujica: OAuthProvider needs an ID and a Name")
}
label := fmt.Sprintf(core.Msg(c, "oauth_buttons.continue"), p.Name)
ui.Column(c).Key(p.ID).AlignItems(ui.Stretch).Children(func() {
b := input.Button(c, label, input.ButtonOptions{Variant: input.Secondary, Icon: p.Icon, Loading: opts.Pending == p.ID,
Disabled: opts.Pending != "" && opts.Pending != p.ID})
if b.Clicked() && !disabled && opts.Pending == "" {
r.chosen = p.ID
slog.Debug("mujica: oauth_buttons chosen", "provider", p.ID)
}
})
}
})
return r
}
+62
View File
@@ -0,0 +1,62 @@
package account
import (
"testing"
"github.com/egoist/mygo/ui"
)
var oauthProviders = []OAuthProvider{{ID: "gh", Name: "GitHub"}, {ID: "sso", Name: "Company SSO"}}
func TestOAuthButtonsChooseAndPending(t *testing.T) {
var chosen []string
opts := OAuthButtonsOptions{}
tt := accountTester(420, 200, func(c *ui.Context) {
if id, ok := OAuthButtons(c, oauthProviders, opts).Chosen(); ok {
chosen = append(chosen, id)
}
})
if err := tt.Click("Continue with Company SSO"); err != nil {
t.Fatal(err)
}
opts.Pending = "sso"
tt.Frame()
_ = tt.Click("Continue with GitHub")
_ = tt.Click("Continue with Company SSO")
if len(chosen) != 1 || chosen[0] != "sso" {
t.Fatalf("chosen %v", chosen)
}
opts = OAuthButtonsOptions{Disabled: true}
tt.Frame()
_ = tt.Click("Continue with GitHub")
if len(chosen) != 1 {
t.Fatal("disabled buttons chose")
}
defer func() {
if recover() == nil {
t.Fatal("nameless provider accepted")
}
}()
accountTester(100, 100, func(c *ui.Context) { OAuthButtons(c, []OAuthProvider{{ID: "x"}}, OAuthButtonsOptions{}) })
}
func TestOAuthButtonsSnapshot(t *testing.T) {
snapshot(t, "oauth_buttons", 380, 130, func(c *ui.Context) {
ui.Column(c).Padding(16).Children(func() { OAuthButtons(c, oauthProviders, OAuthButtonsOptions{Pending: "gh"}) })
})
}
func TestOAuthButtonsKeyboard(t *testing.T) {
chosen := ""
tt := accountTester(600, 300, func(c *ui.Context) {
if id, ok := OAuthButtons(c, oauthProviders, OAuthButtonsOptions{}).Chosen(); ok {
chosen = id
}
})
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyEnter)
if chosen != "sso" {
t.Fatalf("keyboard provider %q", chosen)
}
}
+100
View File
@@ -0,0 +1,100 @@
package account
import (
"fmt"
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/navigation"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// WizardStep is one page of an OnboardingWizard.
type WizardStep struct {
Title, Description string
Content func()
// Ready, when set, must return true before Next is allowed.
Ready func() bool
}
// OnboardingWizardOptions configure an OnboardingWizard.
type OnboardingWizardOptions struct {
// NoSkip hides the Skip action.
NoSkip bool
}
// OnboardingWizardResult reports completion or skipping.
type OnboardingWizardResult struct {
Element *ui.Element
finished, skipped bool
}
// Finished reports Finish on the last step.
func (r OnboardingWizardResult) Finished() bool { return r.finished }
// Skipped reports that the user skipped the rest.
func (r OnboardingWizardResult) Skipped() bool { return r.skipped }
// OnboardingWizard provides progress and step navigation.
func OnboardingWizard(c *ui.Context, step *int, steps []WizardStep, opts OnboardingWizardOptions) OnboardingWizardResult {
if len(steps) == 0 || *step < 0 || *step >= len(steps) {
panic(fmt.Sprintf("mujica: OnboardingWizard step %d outside %d steps", *step, len(steps)))
}
k := core.Tokens(c)
d := core.Density(c)
var r OnboardingWizardResult
from := *step
r.Element = ui.Column(c).Gap(d.Unit()*5).Width(520).Padding(d.Unit()*6).Radius(theme.CardRadius).
Background(k.Surface).Border(theme.BorderWidth, k.Border)
r.Element.Children(func() {
head := make([]navigation.Step, len(steps))
for i, s := range steps {
if s.Title == "" {
panic("mujica: WizardStep needs a Title")
}
head[i] = navigation.Step{Title: s.Title}
}
at := *step
navigation.Steps(c, &at, head, navigation.StepsOptions{Label: core.Msg(c, "onboarding_wizard.progress")})
cur := steps[*step]
ui.Column(c).Key(*step).Gap(d.Unit() * 3).Children(func() {
ui.Text(c, fmt.Sprintf(core.Msg(c, "onboarding_wizard.count"), *step+1, len(steps))).TextColor(k.TextMuted).FontSize(core.FontSize(c, theme.CaptionSize))
ui.Text(c, cur.Title).Font(theme.SerifFont).FontSize(core.FontSize(c, theme.H2Size)).FontWeight(600)
if cur.Description != "" {
ui.Text(c, cur.Description).TextColor(k.TextMuted)
}
if cur.Content != nil {
cur.Content()
}
})
last := *step == len(steps)-1
ready := cur.Ready == nil || cur.Ready()
ui.Row(c).Gap(d.Unit() * 3).AlignItems(ui.Center).Children(func() {
if !opts.NoSkip && !last && input.Button(c, core.Msg(c, "onboarding_wizard.skip"), input.ButtonOptions{Variant: input.Ghost}).Clicked() {
r.skipped = true
}
ui.Box(c).Grow(1)
if *step > 0 && input.Button(c, core.Msg(c, "onboarding_wizard.back"), input.ButtonOptions{Variant: input.Secondary}).Clicked() {
*step--
}
next := core.Msg(c, "onboarding_wizard.next")
if last {
next = core.Msg(c, "onboarding_wizard.finish")
}
if input.Button(c, next, input.ButtonOptions{Disabled: !ready}).AutoFocus().Clicked() && ready {
if last {
r.finished = true
} else {
*step++
}
}
})
})
if *step != from || r.finished || r.skipped {
slog.Debug("mujica: onboarding_wizard step", "step", *step, "finished", r.finished, "skipped", r.skipped)
}
return r
}
+96
View File
@@ -0,0 +1,96 @@
package account
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
func TestOnboardingWizardStepsSkipFinish(t *testing.T) {
step, name := 0, ""
var finished, skipped int
steps := []WizardStep{
{Title: "Welcome", Description: "A short tour."},
{Title: "Your name", Ready: func() bool { return name != "" }, Content: func() {}},
{Title: "Done"},
}
tt := accountTester(600, 500, func(c *ui.Context) {
steps[1].Content = func() { input.TextInput(c, &name, input.TextInputOptions{Label: "Name"}) }
r := OnboardingWizard(c, &step, steps, OnboardingWizardOptions{})
if r.Finished() {
finished++
}
if r.Skipped() {
skipped++
}
})
if !tt.HasText("Step 1 of 3") || !tt.Focused("Next") {
t.Fatalf("first step: %q", tt.Texts())
}
tt.Key(0, ui.KeyEnter)
_ = tt.Click("Next")
if step != 1 {
t.Fatalf("not ready but moved: %d", step)
}
_ = tt.Click("Name")
tt.Type("Sakiko")
_ = tt.Click("Next")
_ = tt.Click("Back")
_ = tt.Click("Next")
if step != 2 || tt.HasText("Skip") {
t.Fatalf("step %d", step)
}
_ = tt.Click("Finish")
if finished != 1 || skipped != 0 {
t.Fatalf("finished %d", finished)
}
step = 0
tt.Frame()
_ = tt.Click("Skip")
if skipped != 1 {
t.Fatal("skip not reported")
}
}
func TestOnboardingWizardSnapshot(t *testing.T) {
snapshot(t, "onboarding_wizard", 580, 330, func(c *ui.Context) {
step := ui.Local(c.Root(), "step", func() int { return 1 })
ui.Column(c).Padding(16).Children(func() {
OnboardingWizard(c, step, []WizardStep{{Title: "Welcome"}, {Title: "Pick a theme", Description: "You can change it later in Settings."}, {Title: "Done"}}, OnboardingWizardOptions{})
})
})
}
func TestOnboardingWizardDisabledAndSingleStep(t *testing.T) {
step, done := 0, 0
disabled := true
tt := accountTester(600, 500, func(c *ui.Context) {
ui.Column(c).Disabled(disabled).Children(func() {
if OnboardingWizard(c, &step, []WizardStep{{Title: "Only step"}}, OnboardingWizardOptions{NoSkip: true}).Finished() {
done++
}
})
})
if err := tt.Click("Finish"); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyEnter)
if done != 0 || step != 0 || tt.HasText("Skip") || tt.HasText("Back") {
t.Fatal("disabled single step acts")
}
disabled = false
tt.Frame()
if err := tt.Click("Finish"); err != nil {
t.Fatal(err)
}
if done != 1 {
t.Fatal("single step cannot finish")
}
step = 1
accountPanics(t, func(c *ui.Context) {
OnboardingWizard(c, &step, []WizardStep{{Title: "Only step"}}, OnboardingWizardOptions{})
})
}
+106
View File
@@ -0,0 +1,106 @@
package account
import (
"log/slog"
"strings"
"unicode/utf8"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/display"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/internal"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// Profile is what a ProfileEditor edits.
type Profile struct {
Name, Bio string
}
// ProfileEditorOptions configure a ProfileEditor.
type ProfileEditorOptions struct {
// Saved is the baseline for detecting unsaved edits.
Saved Profile
// Avatar is the current picture; nil shows initials.
Avatar *ui.Bitmap
// BioLimit bounds the saved biography; zero means 160.
BioLimit int
// Saving shows the save in progress and blocks edits.
Saving bool
Disabled bool
}
// ProfileEditorResult reports save, avatar and discard requests.
type ProfileEditorResult struct {
Element *ui.Element
save, avatar, reset bool
}
// Save reports a request to store the edited profile.
func (r ProfileEditorResult) Save() bool { return r.save }
// ChangeAvatar reports a request to pick a new picture.
func (r ProfileEditorResult) ChangeAvatar() bool { return r.avatar }
// Discarded reports that the edits went back to Saved.
func (r ProfileEditorResult) Discarded() bool { return r.reset }
// ProfileEditor edits name and biography, marking unsaved changes.
func ProfileEditor(c *ui.Context, p *Profile, opts ProfileEditorOptions) ProfileEditorResult {
if opts.BioLimit < 0 {
panic("mujica: ProfileEditor BioLimit cannot be negative")
}
limit := opts.BioLimit
if limit == 0 {
limit = 160
}
k := core.Tokens(c)
d := core.Density(c)
var r ProfileEditorResult
r.Element = ui.Column(c).Gap(d.Unit() * 4).Width(420).Disabled(opts.Disabled)
locked := r.Element.IsDisabled() || opts.Saving
dirty := *p != opts.Saved
nameErr := ""
if strings.TrimSpace(p.Name) == "" {
nameErr = core.Msg(c, "form.required")
}
r.Element.Children(func() {
ui.Row(c).Gap(d.Unit() * 4).AlignItems(ui.Center).Children(func() {
display.Avatar(c, p.Name, display.AvatarOptions{Image: opts.Avatar, Size: 64})
if input.Button(c, core.Msg(c, "profile_editor.avatar"), input.ButtonOptions{Variant: input.Secondary, Disabled: locked}).Clicked() && !locked {
r.avatar = true
}
})
input.FormField(c, core.Msg(c, "profile_editor.name"), input.FormFieldOptions{Required: true}, func() *ui.Element {
return input.TextInput(c, &p.Name, input.TextInputOptions{Disabled: locked, Error: nameErr}).Input
})
input.FormField(c, core.Msg(c, "profile_editor.bio"), input.FormFieldOptions{}, func() *ui.Element {
return input.TextArea(c, &p.Bio, input.TextAreaOptions{MaxLength: limit, Disabled: locked}).Input
})
ui.Row(c).Gap(d.Unit() * 3).AlignItems(ui.Center).Children(func() {
if dirty {
ui.Row(c).Gap(d.Unit()).AlignItems(ui.Center).Grow(1).Role(ui.RoleStatus).Children(func() {
ui.Box(c).Size(10, 10).Draw(func(pt *ui.Painter, rect ui.Rect) {
pt.FillPath(internal.Diamond(internal.Snap(pt, rect.X+5), internal.Snap(pt, rect.Y+5), 10), k.Warning)
})
ui.Text(c, core.Msg(c, "profile_editor.unsaved")).TextColor(k.Warning).FontSize(core.FontSize(c, theme.CaptionSize)).FontWeight(600)
})
} else {
ui.Box(c).Grow(1)
}
if input.Button(c, core.Msg(c, "profile_editor.discard"), input.ButtonOptions{Variant: input.Ghost, Disabled: locked || !dirty}).Clicked() && !locked {
*p, r.reset = opts.Saved, true
}
valid := strings.TrimSpace(p.Name) != "" && utf8.RuneCountInString(p.Bio) <= limit
if input.Button(c, core.Msg(c, "profile_editor.save"), input.ButtonOptions{Loading: opts.Saving, Disabled: r.Element.IsDisabled() || !dirty || !valid}).Clicked() && !locked && valid {
r.save = true
}
})
})
if r.save || r.reset || r.avatar {
slog.Debug("mujica: profile_editor action", "save", r.save, "discard", r.reset, "avatar", r.avatar)
}
return r
}
+104
View File
@@ -0,0 +1,104 @@
package account
import (
"testing"
"github.com/egoist/mygo/ui"
)
func TestProfileEditorUnsavedSaveAndDiscard(t *testing.T) {
saved := Profile{Name: "Sakiko", Bio: "Keyboard."}
p := saved
var saves, avatars, discards int
opts := ProfileEditorOptions{Saved: saved}
tt := accountTester(480, 500, func(c *ui.Context) {
r := ProfileEditor(c, &p, opts)
if r.Save() {
saves++
}
if r.ChangeAvatar() {
avatars++
}
if r.Discarded() {
discards++
}
})
if tt.HasText("Unsaved changes") {
t.Fatal("clean profile marked unsaved")
}
_ = tt.Click("Save")
if saves != 0 {
t.Fatal("saved without changes")
}
_ = tt.Click("Name")
tt.Type(" Togawa")
if !tt.HasText("Unsaved changes") || p.Name != "Sakiko Togawa" {
t.Fatalf("edit: %q", p.Name)
}
_ = tt.Click("Save")
_ = tt.Click("Change picture")
if saves != 1 || avatars != 1 {
t.Fatalf("saves %d avatars %d", saves, avatars)
}
_ = tt.Click("Discard")
if p != saved || discards != 1 || tt.HasText("Unsaved changes") {
t.Fatalf("discard: %+v", p)
}
_ = tt.Click("Name")
tt.Key(ui.Cmd, ui.KeyA)
tt.Key(0, ui.KeyBackspace)
_ = tt.Click("Save")
if saves != 1 || !tt.HasText("Required") {
t.Fatal("saved an empty name")
}
}
func TestProfileEditorSavingBlocksEdits(t *testing.T) {
p := Profile{Name: "Uika"}
tt := accountTester(480, 500, func(c *ui.Context) {
ProfileEditor(c, &p, ProfileEditorOptions{Saved: Profile{Name: "Misumi"}, Saving: true})
})
_ = tt.Click("Name")
tt.Type("x")
if p.Name != "Uika" {
t.Fatal("edited while saving")
}
}
func TestProfileEditorSnapshot(t *testing.T) {
snapshot(t, "profile_editor", 460, 400, func(c *ui.Context) {
p := ui.Local(c.Root(), "p", func() Profile { return Profile{Name: "Sakiko Togawa", Bio: "Keyboard, Ave Mujica."} })
ui.Column(c).Padding(16).Children(func() { ProfileEditor(c, p, ProfileEditorOptions{Saved: Profile{Name: "Sakiko"}}) })
})
}
func TestProfileEditorDisabledAndBioLimit(t *testing.T) {
p := Profile{Name: "Uika"}
disabled := false
saves := 0
tt := accountTester(600, 500, func(c *ui.Context) {
if ProfileEditor(c, &p, ProfileEditorOptions{Saved: Profile{Name: "Uika"}, BioLimit: 3, Disabled: disabled}).Save() {
saves++
}
})
if err := tt.Click("Bio"); err != nil {
t.Fatal(err)
}
tt.Type("初音未来")
if err := tt.Click("Save"); err != nil {
t.Fatal(err)
}
if p.Bio != "初音未来" || saves != 0 {
t.Fatal("over-limit bio is saved or modified")
}
disabled = true
tt.Frame()
tt.Type("edit")
if err := tt.Click("Discard"); err != nil {
t.Fatal(err)
}
if p.Bio != "初音未来" {
t.Fatal("disabled profile changes")
}
accountPanics(t, func(c *ui.Context) { ProfileEditor(c, &p, ProfileEditorOptions{BioLimit: -1}) })
}
+128
View File
@@ -0,0 +1,128 @@
package account
import (
"fmt"
"log/slog"
"slices"
"time"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/display"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/overlay"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// Session describes a device without carrying its authentication token.
type Session struct {
ID, Device, Location string
LastActive time.Time
// Current marks the session this window runs in.
Current bool
}
// SessionListOptions configure a SessionList.
type SessionListOptions struct {
Disabled bool
}
// SessionListResult reports individual and bulk sign-out requests.
type SessionListResult struct {
Element *ui.Element
revoke string
others bool
}
// Revoked returns the ID of a session to sign out.
func (r SessionListResult) Revoked() (string, bool) { return r.revoke, r.revoke != "" }
// OthersRevoked reports confirmed bulk sign-out.
func (r SessionListResult) OthersRevoked() bool { return r.others }
type sessionListState struct {
confirm bool
source []Session
others int
ready bool
}
// SessionList displays devices and requests sign-out through events.
func SessionList(c *ui.Context, sessions []Session, opts SessionListOptions) SessionListResult {
k := core.Tokens(c)
d := core.Density(c)
var r SessionListResult
r.Element = ui.Column(c).Gap(d.Unit() * 3).MinWidth(420).Disabled(opts.Disabled)
st := ui.Local(r.Element, "sessions", func() sessionListState { return sessionListState{} })
disabled := r.Element.IsDisabled()
if !st.ready || !slices.Equal(st.source, sessions) {
st.source, st.others, st.ready = slices.Clone(sessions), 0, true
ids := map[string]bool{}
for _, s := range sessions {
if s.ID == "" || s.Device == "" || ids[s.ID] {
panic("mujica: Session needs a unique ID and a Device")
}
ids[s.ID] = true
if !s.Current {
st.others++
}
}
}
others := st.others
r.Element.Children(func() {
ui.Column(c).Role(ui.RoleList).Label(core.Msg(c, "session_list.label")).Children(func() {
accountRows(c, len(sessions), func(i int) any { return sessions[i].ID }, func(i int) {
s := sessions[i]
ui.Row(c).Key(s.ID).MinHeight(d.ControlHeight()+d.Unit()*4).Gap(d.Unit()*3).AlignItems(ui.Center).
BorderWidth(0, 0, theme.BorderWidth, 0).BorderColor(k.Border).Role(ui.RoleListItem).Children(func() {
ui.Column(c).Grow(1).MinWidth(0).Gap(2).Children(func() {
ui.Row(c).Gap(d.Unit() * 2).AlignItems(ui.Center).Children(func() {
ui.Text(c, s.Device).FontWeight(600).SingleLine()
if s.Current {
display.Badge(c, display.BadgeOptions{Text: core.Msg(c, "session_list.current")}, nil)
}
})
ui.Text(c, sessionListDetail(c, s)).TextColor(k.TextMuted).FontSize(core.FontSize(c, theme.CaptionSize)).SingleLine()
})
if !s.Current {
b := input.Button(c, core.Msg(c, "session_list.sign_out"), input.ButtonOptions{Variant: input.Secondary, Disabled: disabled}).
Label(fmt.Sprintf(core.Msg(c, "session_list.sign_out_of"), s.Device))
if b.Clicked() && !disabled {
r.revoke = s.ID
}
}
})
})
})
ui.Row(c).Children(func() {
if input.Button(c, core.Msg(c, "session_list.sign_out_others"), input.ButtonOptions{Variant: input.Danger, Disabled: disabled || others == 0}).Clicked() && !disabled {
st.confirm = true
}
})
})
if disabled || others == 0 {
st.confirm = false
}
res := overlay.AlertDialog(c, &st.confirm, overlay.AlertDialogOptions{Title: core.Msg(c, "session_list.confirm_title"),
Description: fmt.Sprintf(core.Msg(c, "session_list.confirm_text"), others), ConfirmLabel: core.Msg(c, "session_list.sign_out_others")})
r.others = res.Confirmed && !disabled
if r.revoke != "" || r.others {
slog.Debug("mujica: session_list sign out", "others", r.others)
}
return r
}
// sessionListDetail formats the location and last active time.
func sessionListDetail(c *ui.Context, s Session) string {
when := core.Msg(c, "session_list.now")
if ago := c.Now().Sub(s.LastActive); s.LastActive.IsZero() {
when = core.Msg(c, "session_list.unknown")
} else if ago >= time.Minute {
when = s.LastActive.Format("2006-01-02 15:04")
}
if s.Location == "" {
return when
}
return s.Location + " · " + when
}
+80
View File
@@ -0,0 +1,80 @@
package account
import (
"fmt"
"testing"
"time"
"github.com/egoist/mygo/ui"
)
func sessionSample(now time.Time) []Session {
return []Session{
{ID: "s1", Device: "MacBook Pro · Safari", Location: "Tokyo", LastActive: now, Current: true},
{ID: "s2", Device: "iPhone · App", Location: "Osaka", LastActive: time.Date(2026, 10, 1, 9, 30, 0, 0, time.Local)},
{ID: "s3", Device: "Windows · Edge"},
}
}
func TestSessionListRevokeOneAndOthers(t *testing.T) {
var revoked []string
others := 0
disabled := false
tt := accountTester(600, 500, func(c *ui.Context) {
r := SessionList(c, sessionSample(c.Now()), SessionListOptions{Disabled: disabled})
if id, ok := r.Revoked(); ok {
revoked = append(revoked, id)
}
if r.OthersRevoked() {
others++
}
})
for _, want := range []string{"This device", "Tokyo · Active now", "Osaka · 2026-10-01 09:30", "Last active unknown"} {
if !tt.HasText(want) {
t.Fatalf("missing %q in %q", want, tt.Texts())
}
}
if _, ok := tt.Find("Sign out of MacBook Pro · Safari"); ok {
t.Fatal("current session offers sign out")
}
if err := tt.Click("Sign out of iPhone · App"); err != nil {
t.Fatal(err)
}
_ = tt.Click("Sign out of other sessions")
if !tt.Focused("Cancel") || !tt.HasText("2 other sessions will need to sign in again.") {
t.Fatalf("confirm: %q", tt.Texts())
}
tt.Key(0, ui.KeyEnter)
if others != 0 {
t.Fatal("Enter on Cancel signed out")
}
_ = tt.Click("Sign out of other sessions")
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyEnter)
if len(revoked) != 1 || revoked[0] != "s2" || others != 1 {
t.Fatalf("revoked %v others %d", revoked, others)
}
disabled = true
tt.Frame()
_ = tt.Click("Sign out of Windows · Edge")
if len(revoked) != 1 {
t.Fatal("disabled list signed out")
}
}
func TestSessionListSnapshot(t *testing.T) {
snapshot(t, "session_list", 560, 300, func(c *ui.Context) {
ui.Column(c).Padding(16).Children(func() { SessionList(c, sessionSample(c.Now()), SessionListOptions{}) })
})
}
func TestSessionListLargeDataBuildsVisibleRows(t *testing.T) {
items := make([]Session, 100000)
for i := range items {
items[i] = Session{ID: fmt.Sprint(i), Device: fmt.Sprintf("Device %d", i), Current: i == 0}
}
tt := accountTester(600, 500, func(c *ui.Context) { SessionList(c, items, SessionListOptions{}) })
if n := len(tt.Texts()); n > 100 {
t.Fatalf("built %d text elements for a bounded viewport", n)
}
}
+141
View File
@@ -0,0 +1,141 @@
package account
import (
"log/slog"
"time"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/navigation"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// SettingsPage is one page of a SettingsLayout's navigation.
type SettingsPage struct {
ID, Label string
Icon *ui.SVG
}
// SettingsLayoutOptions configure a SettingsLayout.
type SettingsLayoutOptions struct {
// Title heads the navigation; empty uses the built-in "Settings".
Title string
}
// SettingsLayout builds section navigation and independently scrolling content.
func SettingsLayout(c *ui.Context, page *string, pages []SettingsPage, opts SettingsLayoutOptions, content func(id string)) core.ChoiceResult {
if len(pages) == 0 || content == nil {
panic("mujica: SettingsLayout needs pages and content")
}
found := false
items := make([]navigation.SidebarItem, len(pages))
for i, p := range pages {
if p.ID == "" || p.Label == "" {
panic("mujica: SettingsLayout page needs an ID and a Label")
}
found = found || p.ID == *page
items[i] = navigation.SidebarItem{ID: p.ID, Label: p.Label, Icon: p.Icon}
}
if *page == "" {
*page, found = pages[0].ID, true
}
if !found {
panic("mujica: SettingsLayout page " + *page + " is not one of pages")
}
title := opts.Title
if title == "" {
title = core.Msg(c, "settings_layout.title")
}
k := core.Tokens(c)
d := core.Density(c)
var r core.ChoiceResult
r.Element = ui.Row(c).Fill().AlignItems(ui.Stretch).Background(k.Background)
r.Element.Children(func() {
nav := navigation.Sidebar(c, page, []navigation.SidebarSection{{Title: title, Items: items}}, navigation.SidebarOptions{Width: 220})
if nav.Changed() {
r = core.NewChoiceResult(r.Element, true)
slog.Debug("mujica: settings_layout page", "page", *page)
}
ui.Scroll(c).Grow(1).MinWidth(0).Padding(d.Unit()*6, d.Unit()*8).Children(func() {
ui.Column(c).Key(*page).MaxWidth(720).Gap(d.Unit() * 8).Children(func() { content(*page) })
})
})
return r
}
// SettingsSection groups rows under a serif heading.
func SettingsSection(c *ui.Context, title string, rows func()) *ui.Element {
k := core.Tokens(c)
d := core.Density(c)
e := ui.Column(c).Gap(d.Unit() * 2).Role(ui.RoleGroup).Label(title)
e.Children(func() {
ui.Text(c, title).Font(theme.SerifFont).FontSize(core.FontSize(c, theme.H3Size)).FontWeight(600).Role(ui.RoleNone)
ui.Column(c).Radius(theme.CardRadius).Background(k.Surface).Border(theme.BorderWidth, k.Border).Padding(0, d.Unit()*4).
Dividers(theme.BorderWidth, k.Border).Children(rows)
})
return e
}
// SettingsRowOptions configure a SettingsRow.
type SettingsRowOptions struct {
Description string
// ID identifies this row for SettingsSearch navigation.
ID string
}
type settingsRevealKey struct{}
// settingsReveal queues focus and scrolling for the matching row.
func settingsReveal(c *ui.Context, id string) {
*ui.Local(c.Root(), settingsRevealKey{}, func() string { return "" }) = id
}
type settingsRowState struct{ at time.Time }
// SettingsRow associates a label and description with its control.
func SettingsRow(c *ui.Context, label string, opts SettingsRowOptions, control func() *ui.Element) *ui.Element {
if label == "" || control == nil {
panic("mujica: SettingsRow needs a label and a control")
}
k := core.Tokens(c)
d := core.Density(c)
row := ui.Row(c).MinHeight(d.ControlHeight()+d.Unit()*4).Gap(d.Unit()*4).AlignItems(ui.Center).Padding(d.Unit()*3, 0)
if opts.ID != "" {
row.Key(opts.ID)
}
st := ui.Local(row, "reveal", func() settingsRowState { return settingsRowState{} })
reveal := ui.Local(c.Root(), settingsRevealKey{}, func() string { return "" })
var ctrl, text *ui.Element
row.Children(func() {
text = ui.Column(c).Grow(1).MinWidth(0).Gap(d.Unit())
text.Children(func() {
ui.Text(c, label).FontWeight(500).Role(ui.RoleNone)
if opts.Description != "" {
ui.Text(c, opts.Description).TextColor(k.TextMuted).FontSize(core.FontSize(c, theme.CaptionSize)).Role(ui.RoleNone)
}
})
ui.Row(c).Shrink(0).Children(func() { ctrl = control() })
})
if ctrl == nil {
panic("mujica: SettingsRow " + label + ": control returned nil")
}
ctrl.Label(label).Description(opts.Description)
if text.Clicked() && !ctrl.IsDisabled() {
ctrl.Focus()
}
if opts.ID != "" && *reveal == opts.ID {
*reveal = ""
st.at = c.Now()
ctrl.Focus().ScrollIntoView()
slog.Debug("mujica: settings_layout reveal", "row", opts.ID)
}
// A revealed row's face fades from the selection color.
if dur := core.Motion(c, theme.StateDuration); !st.at.IsZero() && dur > 0 {
if t := c.Now().Sub(st.at); t < dur {
row.Background(k.Selection.Alpha(1 - float32(t)/float32(dur)))
c.AnimationFrame()
}
}
return row
}
+106
View File
@@ -0,0 +1,106 @@
package account
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
// accountTester runs a themed view inside a padded column.
func accountTester(w, h int, view func(c *ui.Context)) *ui.Tester {
return ui.NewTester(func(c *ui.Context) {
core.Use(c, core.Settings{})
ui.Column(c).Padding(10).Fill().Children(func() { view(c) })
}, w, h)
}
var settingsPages = []SettingsPage{{ID: "general", Label: "General"}, {ID: "privacy", Label: "Privacy"}}
func settingsView(c *ui.Context, page *string, sound, track *bool, changes *int) {
if SettingsLayout(c, page, settingsPages, SettingsLayoutOptions{}, func(id string) {
switch id {
case "general":
SettingsSection(c, "Notifications", func() {
SettingsRow(c, "Sound", SettingsRowOptions{ID: "sound", Description: "Chime on new messages."}, func() *ui.Element {
return input.Switch(c, sound, "", input.SwitchOptions{})
})
})
case "privacy":
SettingsSection(c, "Data", func() {
SettingsRow(c, "Usage reports", SettingsRowOptions{ID: "track"}, func() *ui.Element {
return input.Switch(c, track, "", input.SwitchOptions{})
})
})
}
}).Changed() {
*changes++
}
}
func TestSettingsLayoutNavigatesAndLabelsRows(t *testing.T) {
page, sound, track, n := "", false, false, 0
tt := accountTester(900, 500, func(c *ui.Context) { settingsView(c, &page, &sound, &track, &n) })
if page != "general" || !tt.HasText("Chime on new messages.") {
t.Fatalf("first page: %q", page)
}
if err := tt.Click("Chime on new messages."); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeySpace)
if !tt.Focused("Sound") || !sound {
t.Fatal("row label does not reach its control")
}
if err := tt.Click("Privacy"); err != nil {
t.Fatal(err)
}
if page != "privacy" || n != 1 || !tt.HasText("Usage reports") || tt.HasText("Sound") {
t.Fatalf("page %q changes %d texts %q", page, n, tt.Texts())
}
}
func TestSettingsLayoutRejectsUnknownPage(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("unknown page accepted")
}
}()
page := "nope"
accountTester(400, 300, func(c *ui.Context) { SettingsLayout(c, &page, settingsPages, SettingsLayoutOptions{}, func(string) {}) })
}
func TestSettingsLayoutSnapshot(t *testing.T) {
snapshot(t, "settings_layout", 860, 360, func(c *ui.Context) {
st := ui.Local(c.Root(), "snap", func() [3]bool { return [3]bool{false, true, false} })
page := "general"
ui.Box(c).Fill().Children(func() { settingsView(c, &page, &st[1], &st[2], new(int)) })
})
}
func accountPanics(t *testing.T, view func(*ui.Context)) {
t.Helper()
defer func() {
if recover() == nil {
t.Fatal("invalid options accepted")
}
}()
accountTester(600, 500, view)
}
func TestSettingsLayoutDisabledNavigationAndControl(t *testing.T) {
page, sound, track, changes := "general", false, false, 0
tt := accountTester(900, 500, func(c *ui.Context) {
ui.Column(c).Fill().Disabled(true).Children(func() { settingsView(c, &page, &sound, &track, &changes) })
})
if err := tt.Click("Privacy"); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyDown)
tt.Key(0, ui.KeySpace)
if page != "general" || sound || track || changes != 0 {
t.Fatal("disabled settings change state")
}
}
+190
View File
@@ -0,0 +1,190 @@
package account
import (
"log/slog"
"reflect"
"slices"
"strings"
"unicode/utf8"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/internal"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// SettingEntry identifies a searchable setting and its destination.
type SettingEntry struct {
ID, Page string
Label string
Description string
// Keywords match too, as synonyms.
Keywords []string
}
// SettingsSearchOptions configure a SettingsSearch.
type SettingsSearchOptions struct {
// Limit caps the results shown; zero means 8.
Limit int
}
// SettingsSearchResult carries the selected destination.
type SettingsSearchResult struct {
Element *ui.Element
chosen *SettingEntry
}
// Chosen returns the selected entry and reveals its row.
func (r SettingsSearchResult) Chosen() (SettingEntry, bool) {
if r.chosen == nil {
return SettingEntry{}, false
}
return *r.chosen, true
}
type settingsSearchState struct {
cursor int
source []SettingEntry
query string
limit int
hits []int
ready bool
}
// SettingsSearch highlights matches and navigates to settings.
func SettingsSearch(c *ui.Context, query *string, entries []SettingEntry, opts SettingsSearchOptions) SettingsSearchResult {
if opts.Limit < 0 {
panic("mujica: SettingsSearch Limit cannot be negative")
}
limit := opts.Limit
if limit == 0 {
limit = 8
}
d := core.Density(c)
var r SettingsSearchResult
r.Element = ui.Column(c).Gap(d.Unit() * 2).MinWidth(280)
st := ui.Local(r.Element, "search", func() settingsSearchState { return settingsSearchState{} })
r.Element.Children(func() {
res := input.SearchInput(c, query, input.SearchInputOptions{Placeholder: core.Msg(c, "settings_search.placeholder"), Label: core.Msg(c, "settings_search.placeholder")})
in := res.Input
q := strings.ToLower(strings.TrimSpace(*query))
settingsSearchPlan(st, entries, q, limit)
hits := st.hits
st.cursor = max(0, min(st.cursor, len(hits)-1))
if res.Changed() {
st.cursor = 0
}
disabled := in.IsDisabled()
before := st.cursor
switch {
case disabled || len(hits) == 0:
case in.Shortcut(0, ui.KeyDown):
st.cursor = (st.cursor + 1) % len(hits)
case in.Shortcut(0, ui.KeyUp):
st.cursor = (st.cursor + len(hits) - 1) % len(hits)
}
if res.Submitted() && len(hits) > 0 && !disabled {
r.chosen = &entries[hits[st.cursor]]
}
if q != "" && len(hits) == 0 {
ui.Text(c, core.Msg(c, "settings_search.none")).TextColor(core.Tokens(c).TextMuted).Role(ui.RoleStatus)
}
list := accountRows(c, len(hits), func(n int) any { return entries[hits[n]].ID }, func(n int) {
i := hits[n]
if settingsSearchHit(c, entries[i], q, n == st.cursor) {
r.chosen = &entries[i]
}
})
list.Role(ui.RoleList)
if len(hits) > 8 && (st.cursor != before || res.Changed()) {
ui.Local(list, "rows", func() ui.ListState { return ui.ListState{} }).ScrollIntoView(st.cursor)
}
})
if r.chosen != nil {
settingsReveal(c, r.chosen.ID)
*query, st.cursor = "", 0
slog.Debug("mujica: settings_search chosen", "id", r.chosen.ID)
}
return r
}
func settingsSearchPlan(st *settingsSearchState, entries []SettingEntry, q string, limit int) {
if st.ready && st.query == q && st.limit == limit && reflect.DeepEqual(st.source, entries) {
return
}
st.ready, st.query, st.limit = true, q, limit
st.source = slices.Clone(entries)
st.hits = st.hits[:0]
ids := map[string]bool{}
for i, e := range entries {
if e.ID == "" || e.Page == "" || e.Label == "" || ids[e.ID] {
panic("mujica: SettingEntry needs a unique ID, Page and Label")
}
ids[e.ID] = true
st.source[i].Keywords = slices.Clone(e.Keywords)
text := strings.ToLower(e.Label + " " + e.Description + " " + strings.Join(e.Keywords, " "))
if q != "" && strings.Contains(text, q) && len(st.hits) < limit {
st.hits = append(st.hits, i)
}
}
}
// settingsSearchHit builds a marked, clickable search result.
func settingsSearchHit(c *ui.Context, e SettingEntry, q string, current bool) bool {
k := core.Tokens(c)
d := core.Density(c)
b := ui.ButtonBase(c).Key(e.ID).MinHeight(d.ControlHeight()).Padding(d.Unit(), d.Unit()*3).Justify(ui.Start).
Radius(theme.ControlRadius).Role(ui.RoleListItem).Label(e.Label).Description(e.Description).Selected(current).Gap(d.Unit() * 2)
internal.Ring(b, k.Focus, theme.ControlRadius)
switch {
case current:
b.Background(k.Selection)
case b.Hovered():
b.Background(k.SurfaceHover)
}
b.Children(func() {
ui.Box(c).Size(8, 8).Shrink(0).Role(ui.RoleNone).Draw(func(p *ui.Painter, r ui.Rect) {
if current {
p.FillPath(internal.Diamond(internal.Snap(p, r.X+4), internal.Snap(p, r.Y+4), 8), k.AccentText)
}
})
ui.Column(c).Gap(2).Children(func() {
ui.RichText(c, settingsSearchSpans(c, e.Label, q, theme.BodySize)...)
if e.Description != "" {
ui.RichText(c, settingsSearchSpans(c, e.Description, q, theme.CaptionSize)...).TextColor(k.TextMuted)
}
})
})
return b.Clicked() && !b.IsDisabled()
}
// settingsSearchSpans highlights matches while preserving original Unicode text.
func settingsSearchSpans(c *ui.Context, s, q string, size float32) []ui.Span {
k := core.Tokens(c)
size = core.FontSize(c, size)
plain := func(t string) ui.Span { return ui.Span{Text: t, Size: size, Color: k.Text} }
if q == "" {
return []ui.Span{plain(s)}
}
var out []ui.Span
low := strings.ToLower(s)
original := []rune(s)
for {
i := strings.Index(low, q)
if i < 0 {
break
}
start, count := utf8.RuneCountInString(low[:i]), utf8.RuneCountInString(q)
if start > 0 {
out = append(out, plain(string(original[:start])))
}
out = append(out, ui.Span{Text: string(original[start : start+count]), Size: size, Weight: 700, Background: k.Selection, Color: k.Text})
original, low = original[start+count:], low[i+len(q):]
}
if len(original) > 0 {
out = append(out, plain(string(original)))
}
return out
}
+124
View File
@@ -0,0 +1,124 @@
package account
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
)
var settingEntries = []SettingEntry{
{ID: "sound", Page: "general", Label: "Sound", Description: "Chime on new messages.", Keywords: []string{"audio"}},
{ID: "track", Page: "privacy", Label: "Usage reports", Description: "Send anonymous usage."},
}
func TestSettingsSearchFindsHighlightsAndReveals(t *testing.T) {
page, query, sound, track, n := "privacy", "", false, false, 0
var chosen SettingEntry
tt := accountTester(1000, 600, func(c *ui.Context) {
ui.Row(c).Fill().Children(func() {
ui.Box(c).Width(300).Children(func() {
if e, ok := SettingsSearch(c, &query, settingEntries, SettingsSearchOptions{}).Chosen(); ok {
chosen, page = e, e.Page
}
})
ui.Box(c).Grow(1).FillHeight().Children(func() { settingsView(c, &page, &sound, &track, &n) })
})
})
_ = tt.Click("Search settings")
tt.Type("AUD")
if _, ok := tt.Find("Sound"); !ok || tt.HasText("Send anonymous usage.") {
t.Fatalf("keyword search: %q", tt.Texts())
}
_ = tt.Click("Search settings")
tt.Key(ui.Cmd, ui.KeyA)
tt.Type("ou")
if !tt.HasText("ou") || !tt.HasText("nd") || !tt.HasText("Usage reports") {
t.Fatalf("match not split for marking: %q", tt.Texts())
}
tt.Key(0, ui.KeyDown)
tt.Key(0, ui.KeyDown)
tt.Key(0, ui.KeyEnter)
if chosen.ID != "sound" || page != "general" {
t.Fatalf("chose %q page %q", chosen.ID, page)
}
tt.Frame()
if !tt.Focused("Sound") || query != "" {
t.Fatalf("row not revealed, query %q", query)
}
_ = tt.Click("Search settings")
tt.Type("zzz")
if !tt.HasText("No settings match") {
t.Fatal("no empty result")
}
}
func TestSettingsSearchSnapshot(t *testing.T) {
snapshot(t, "settings_search", 360, 220, func(c *ui.Context) {
q := ui.Local(c.Root(), "q", func() string { return "us" })
ui.Column(c).Padding(16).Children(func() { SettingsSearch(c, q, settingEntries, SettingsSearchOptions{}) })
})
}
func TestSettingsSearchHighlightsUnicodeCaseMapping(t *testing.T) {
var spans []ui.Span
tt := accountTester(400, 220, func(c *ui.Context) {
q := "i"
spans = settingsSearchSpans(c, "İstanbul", q, 14)
SettingsSearch(c, &q, []SettingEntry{{ID: "language", Page: "general", Label: "İstanbul"}}, SettingsSearchOptions{})
})
if len(spans) != 2 || spans[0].Text != "İ" || spans[0].Weight != 700 || spans[1].Text != "stanbul" || !tt.HasText("İstanbul") {
t.Fatal("Unicode case mapping loses match highlighting")
}
}
func TestSettingsSearchPlainSpansHaveReadableColor(t *testing.T) {
accountTester(400, 220, func(c *ui.Context) {
for _, span := range settingsSearchSpans(c, "Usage reports", "us", 14) {
if span.Color != core.Tokens(c).Text {
t.Error("search text does not use the readable Text token")
}
}
})
}
func TestSettingsSearchCachedPlanSeesInPlaceChanges(t *testing.T) {
st := settingsSearchState{}
entries := []SettingEntry{{ID: "theme", Page: "general", Label: "Appearance", Keywords: []string{"theme"}}}
settingsSearchPlan(&st, entries, "theme", 8)
if len(st.hits) != 1 {
t.Fatal("initial keyword fails")
}
before := &st.hits[0]
settingsSearchPlan(&st, entries, "theme", 8)
if before != &st.hits[0] {
t.Fatal("unchanged data rebuilt search plan")
}
entries[0].Keywords[0] = "color"
settingsSearchPlan(&st, entries, "theme", 8)
if len(st.hits) != 0 {
t.Fatal("cached search misses in-place keyword change")
}
}
func TestSettingsSearchDisabledAndLimit(t *testing.T) {
q, chosen := "o", 0
tt := accountTester(600, 500, func(c *ui.Context) {
ui.Column(c).Disabled(true).Children(func() {
if _, ok := SettingsSearch(c, &q, settingEntries, SettingsSearchOptions{Limit: 1}).Chosen(); ok {
chosen++
}
})
})
if err := tt.Click("Sound"); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyEnter)
tt.Type("edited")
if q != "o" || chosen != 0 || tt.HasText("Send anonymous usage.") {
t.Fatal("disabled or limited search acts incorrectly")
}
accountPanics(t, func(c *ui.Context) { SettingsSearch(c, &q, settingEntries, SettingsSearchOptions{Limit: -1}) })
}
+219
View File
@@ -0,0 +1,219 @@
package account
import (
"fmt"
"log/slog"
"runtime"
"strings"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/display"
"github.com/ZacharyZhang-NY/MujicaUI/icons"
"github.com/ZacharyZhang-NY/MujicaUI/internal"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// Shortcut combines modifiers and a key; zero means unassigned.
type Shortcut struct {
Mods ui.Modifiers
Key ui.Key
}
// IsZero reports an empty shortcut.
func (s Shortcut) IsZero() bool { return s == Shortcut{} }
// keys returns platform-ordered key names.
func (s Shortcut) keys() []string {
var out []string
mac := runtime.GOOS == "darwin"
add := func(m ui.Modifiers, name string) {
if s.Mods&m != 0 {
out = append(out, name)
}
}
if mac {
add(ui.Ctrl, "ctrl")
add(ui.Alt, "alt")
add(ui.Shift, "shift")
add(ui.Super, "mod")
} else {
add(ui.Ctrl, "ctrl")
add(ui.Super, "Win")
add(ui.Alt, "alt")
add(ui.Shift, "shift")
}
return append(out, shortcutKeyName(s.Key))
}
// String spells s as keys joined by "+", as "ctrl+shift+K".
func (s Shortcut) String() string {
if s.IsZero() {
return ""
}
return strings.Join(s.keys(), "+")
}
// shortcutKeyName is the Kbd name of key.
func shortcutKeyName(k ui.Key) string {
switch {
case k >= ui.KeyA && k <= ui.KeyZ:
return string(rune('A' + k - ui.KeyA))
case k >= ui.Key0 && k <= ui.Key9:
return string(rune('0' + k - ui.Key0))
case k >= ui.KeyF1 && k <= ui.KeyF12:
return fmt.Sprintf("F%d", k-ui.KeyF1+1)
}
if n, ok := shortcutNames[k]; ok {
return n
}
panic(fmt.Sprintf("mujica: Shortcut key %d has no name", k))
}
var shortcutNames = map[ui.Key]string{
ui.KeyEnter: "enter", ui.KeyEscape: "esc", ui.KeyBackspace: "backspace", ui.KeyTab: "tab", ui.KeySpace: "Space",
ui.KeyDelete: "delete", ui.KeyHome: "Home", ui.KeyEnd: "End", ui.KeyPageUp: "PgUp", ui.KeyPageDown: "PgDn",
ui.KeyLeft: "left", ui.KeyRight: "right", ui.KeyUp: "up", ui.KeyDown: "down", ui.KeyMinus: "-", ui.KeyEqual: "=",
ui.KeyComma: ",", ui.KeyPeriod: ".", ui.KeySlash: "/", ui.KeySemicolon: ";", ui.KeyQuote: "'",
ui.KeyBracketLeft: "[", ui.KeyBracketRight: "]", ui.KeyBackslash: "\\", ui.KeyBackquote: "`",
ui.KeyInsert: "Insert", ui.KeyContextMenu: "Menu", ui.KeyBack: "Back", ui.KeyForward: "Forward",
}
// shortcutKbd displays keycaps or a muted unassigned mark.
func shortcutKbd(c *ui.Context, s Shortcut) {
if s.IsZero() {
ui.Text(c, "—").TextColor(core.Tokens(c).TextMuted)
return
}
display.Kbd(c, s.keys()...)
}
// ShortcutBinding names an action that already owns a shortcut.
type ShortcutBinding struct {
Action string
Shortcut Shortcut
}
// ShortcutRecorderOptions configure a ShortcutRecorder.
type ShortcutRecorderOptions struct {
// Taken lists occupied shortcuts; conflicts preserve the previous value.
Taken []ShortcutBinding
// Label names the recorder, as the action it sets.
Label string
Disabled bool
}
type shortcutRecorderState struct {
recording, needMod bool
caught *Shortcut
conflict string
}
// ShortcutRecorder records key combinations; Escape cancels.
func ShortcutRecorder(c *ui.Context, value *Shortcut, opts ShortcutRecorderOptions) core.ChoiceResult {
if opts.Label == "" {
panic("mujica: ShortcutRecorder needs a Label")
}
d := core.Density(c)
var r core.ChoiceResult
r.Element = ui.Column(c).Gap(d.Unit()).AlignItems(ui.Start).Disabled(opts.Disabled)
r.Element.Children(func() {
b := ui.ButtonBase(c).MinHeight(d.ControlHeight()).MinWidth(160).Padding(0, d.Unit()*3).Gap(d.Unit() * 2).
Radius(theme.ControlRadius).Justify(ui.SpaceBetween)
st := ui.Local(b, "rec", func() shortcutRecorderState { return shortcutRecorderState{} })
disabled := b.IsDisabled()
if disabled || !b.Focused() {
st.recording, st.caught = false, nil
}
if st.caught != nil {
s := *st.caught
st.caught, st.recording, st.conflict = nil, false, ""
for _, t := range opts.Taken {
if t.Shortcut == s && s != *value {
st.conflict = fmt.Sprintf(core.Msg(c, "shortcut_recorder.conflict"), s.String(), t.Action)
}
}
if st.conflict == "" && s != *value {
*value, r = s, core.NewChoiceResult(r.Element, true)
slog.Debug("mujica: shortcut_recorder set", "shortcut", s.String())
}
}
if b.Clicked() && !disabled {
st.recording, st.conflict, st.needMod = true, "", false
slog.Debug("mujica: shortcut_recorder recording")
}
if st.recording {
b.HandleInput(func(ev ui.InputEvent) bool {
if b.IsDisabled() {
return false
}
return shortcutRecorderKey(st, ev)
})
}
shortcutRecorderLook(c, b, st, *value, opts.Label)
shortcutRecorderNote(c, st)
})
return r
}
// shortcutRecorderKey captures keys during recording.
func shortcutRecorderKey(st *shortcutRecorderState, ev ui.InputEvent) bool {
switch {
case ev.Kind == ui.InputText:
return true
case ev.Kind != ui.InputKeyDown || ev.Key == ui.KeyUnknown:
return false
case ev.Key == ui.KeyTab && ev.Mods&^ui.Shift == 0:
return false
case ev.Key == ui.KeyEscape && ev.Mods == 0:
st.recording = false
case ev.Mods&^ui.Shift == 0 && !(ev.Key >= ui.KeyF1 && ev.Key <= ui.KeyF12):
st.needMod = true
default:
s := Shortcut{ev.Mods, ev.Key}
st.caught = &s
}
return true
}
// shortcutRecorderLook displays the shortcut or recording prompt.
func shortcutRecorderLook(c *ui.Context, b *ui.Element, st *shortcutRecorderState, value Shortcut, name string) {
k := core.Tokens(c)
internal.Ring(b, k.Focus, theme.ControlRadius)
label := name + ": " + value.String()
if value.IsZero() {
label = name + ": " + core.Msg(c, "shortcut_recorder.none")
}
b.Label(label)
bg, border := k.Surface, k.ControlBorder
if st.recording {
bg, border = k.Selection, k.AccentText
} else if b.Hovered() {
bg = k.SurfaceHover
}
b.Background(bg).Border(theme.BorderWidth, border)
b.Children(func() {
if st.recording {
ui.Text(c, core.Msg(c, "shortcut_recorder.press")).TextColor(k.AccentText).SingleLine()
} else {
shortcutKbd(c, value)
}
ui.Icon(c, icons.Must("command")).Size(14, 14).TextColor(k.TextMuted)
})
}
// shortcutRecorderNote displays conflict and modifier guidance.
func shortcutRecorderNote(c *ui.Context, st *shortcutRecorderState) {
text := st.conflict
if st.needMod && st.recording {
text = core.Msg(c, "shortcut_recorder.needs_modifier")
}
if text == "" {
return
}
ui.Row(c).Gap(4).AlignItems(ui.Center).TextColor(core.Tokens(c).Warning).Role(ui.RoleStatus).Children(func() {
ui.Icon(c, icons.Must("triangle-alert")).Size(14, 14)
ui.Text(c, text).FontSize(core.FontSize(c, theme.CaptionSize))
})
}
+126
View File
@@ -0,0 +1,126 @@
package account
import (
"fmt"
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/input"
)
func shortcutRecorderTester(v *Shortcut, opts *ShortcutRecorderOptions, n *int) *ui.Tester {
return accountTester(400, 160, func(c *ui.Context) {
if ShortcutRecorder(c, v, *opts).Changed() {
*n++
}
})
}
func TestShortcutRecorderRecordsAndCancels(t *testing.T) {
v, n := Shortcut{}, 0
opts := ShortcutRecorderOptions{Label: "Open palette"}
tt := shortcutRecorderTester(&v, &opts, &n)
if _, ok := tt.Find("Open palette: none"); !ok {
t.Fatal("empty value not named")
}
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyEnter)
if !tt.HasText("Press keys…") {
t.Fatalf("not recording: %q", tt.Texts())
}
tt.TypeKey(0, ui.KeyK, "k")
if !tt.HasText("Add Ctrl, Alt or Command; F-keys may stand alone.") || n != 0 {
t.Fatal("bare letter accepted")
}
tt.Key(ui.Ctrl|ui.Shift, ui.KeyK)
if v != (Shortcut{ui.Ctrl | ui.Shift, ui.KeyK}) || n != 1 || tt.HasText("Press keys…") {
t.Fatalf("recorded %+v", v)
}
if v.String() != "ctrl+shift+K" {
t.Fatalf("spelled %q", v.String())
}
tt.Key(0, ui.KeySpace)
tt.Key(0, ui.KeyEscape)
tt.Key(0, ui.KeyF5)
if v.Key != ui.KeyK || tt.HasText("Press keys…") {
t.Fatal("escape did not cancel")
}
}
func TestShortcutRecorderConflictAndDisabled(t *testing.T) {
v, n := Shortcut{ui.Ctrl, ui.KeyP}, 0
opts := ShortcutRecorderOptions{Label: "Print", Taken: []ShortcutBinding{{Action: "Save", Shortcut: Shortcut{ui.Ctrl, ui.KeyS}}}}
tt := shortcutRecorderTester(&v, &opts, &n)
_ = tt.Click("Print: ctrl+P")
tt.Key(ui.Ctrl, ui.KeyS)
if v.Key != ui.KeyP || n != 0 || !tt.HasText("ctrl+S is already used by Save") {
t.Fatalf("conflict: %+v %q", v, tt.Texts())
}
tt.Key(0, ui.KeySpace)
opts.Disabled = true
tt.Key(ui.Ctrl, ui.KeyJ)
if v.Key != ui.KeyP {
t.Fatal("disabled recorder recorded")
}
}
func TestShortcutRecorderSnapshot(t *testing.T) {
snapshot(t, "shortcut_recorder", 300, 110, func(c *ui.Context) {
a := ui.Local(c.Root(), "a", func() Shortcut { return Shortcut{ui.Ctrl | ui.Shift, ui.KeyK} })
b := ui.Local(c.Root(), "b", func() Shortcut { return Shortcut{} })
ui.Column(c).Padding(16).Gap(12).Children(func() {
ShortcutRecorder(c, a, ShortcutRecorderOptions{Label: "Command palette"})
ShortcutRecorder(c, b, ShortcutRecorderOptions{Label: "Zen mode"})
})
})
}
func TestShortcutRecorderFunctionKeyAndTabCancellation(t *testing.T) {
v, n := Shortcut{}, 0
opts := ShortcutRecorderOptions{Label: "Refresh"}
tt := accountTester(400, 200, func(c *ui.Context) {
if ShortcutRecorder(c, &v, opts).Changed() {
n++
}
input.Button(c, "Next control", input.ButtonOptions{})
})
if err := tt.Click("Refresh: none"); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeyF5)
if v != (Shortcut{Key: ui.KeyF5}) || n != 1 {
t.Fatal("standalone function key fails")
}
if err := tt.Click("Refresh: F5"); err != nil {
t.Fatal(err)
}
tt.Key(0, ui.KeyTab)
tt.Key(ui.Ctrl, ui.KeyP)
if v.Key != ui.KeyF5 || n != 1 {
t.Fatal("recorder retains keys after Tab")
}
accountPanics(t, func(c *ui.Context) { ShortcutRecorder(c, &v, ShortcutRecorderOptions{}) })
}
func TestShortcutRecorderNamesEveryDeliveredKey(t *testing.T) {
for _, key := range []ui.Key{ui.KeyInsert, ui.KeyContextMenu, ui.KeyBack, ui.KeyForward} {
t.Run(fmt.Sprint(key), func(t *testing.T) {
defer func() {
if recover() != nil {
t.Fatal("recording a valid MyGo key panicked")
}
}()
v, n := Shortcut{}, 0
opts := ShortcutRecorderOptions{Label: "Action"}
tt := shortcutRecorderTester(&v, &opts, &n)
if err := tt.Click("Action: none"); err != nil {
t.Fatal(err)
}
tt.Key(ui.Ctrl, key)
if v != (Shortcut{ui.Ctrl, key}) || n != 1 || v.String() == "" {
t.Fatal("valid key was not recorded and named")
}
})
}
}
+89
View File
@@ -0,0 +1,89 @@
package account
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/internal"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// ThemeSelectorOptions configure a ThemeSelector.
type ThemeSelectorOptions struct {
Disabled bool
}
// ThemeSelector selects an appearance using preview cards.
func ThemeSelector(c *ui.Context, mode *core.Mode, opts ThemeSelectorOptions) core.ChoiceResult {
if *mode != core.System && *mode != core.Light && *mode != core.Dark {
panic(fmt.Sprintf("mujica: ThemeSelector mode %d is not System, Light or Dark", *mode))
}
k := core.Tokens(c)
d := core.Density(c)
var r core.ChoiceResult
r.Element = ui.Row(c).Gap(d.Unit() * 3).Wrap().Role(ui.RoleRadioGroup).Label(core.Msg(c, "theme_selector.label")).
FocusGroup(ui.Horizontal).Disabled(opts.Disabled)
selected := mode
if r.Element.IsDisabled() {
copy := *mode
selected = &copy
}
r.Element.Children(func() {
for _, m := range []core.Mode{core.System, core.Light, core.Dark} {
card := ui.RadioBase(c, selected, m).Column().Gap(d.Unit() * 2).Padding(d.Unit() * 2).Radius(theme.CardRadius).AlignItems(ui.Stretch).Transition(core.ColorFade)
if card.Changed() && !card.IsDisabled() {
r = core.NewChoiceResult(r.Element, true)
slog.Debug("mujica: theme_selector chose", "mode", m.String())
}
on := *mode == m
internal.Ring(card, k.Focus, theme.CardRadius)
border, width := k.Border, theme.BorderWidth
switch {
case on:
border, width = k.AccentText, 2
card.Background(k.Selection)
case card.Hovered():
card.Background(k.SurfaceHover)
}
card.Border(width, border)
card.Children(func() {
ui.Box(c).Size(132, 84).Role(ui.RoleNone).Draw(func(p *ui.Painter, rect ui.Rect) {
switch m {
case core.Light:
themePreview(p, rect, theme.Light())
case core.Dark:
themePreview(p, rect, theme.Dark())
default:
half := ui.Rect{X: rect.X, Y: rect.Y, W: rect.W / 2, H: rect.H}
p.Clip(half, 0, func() { themePreview(p, rect, theme.Light()) })
p.Clip(ui.Rect{X: half.X + half.W, Y: rect.Y, W: rect.W / 2, H: rect.H}, 0, func() { themePreview(p, rect, theme.Dark()) })
}
})
ui.Row(c).Gap(d.Unit()).AlignItems(ui.Center).Children(func() {
if on {
ui.Icon(c, icons.Must("check")).Size(14, 14).TextColor(k.AccentText)
}
ui.Text(c, core.Msg(c, "theme_selector."+m.String())).SingleLine()
})
})
}
})
return r
}
// themePreview paints a miniature themed window.
func themePreview(p *ui.Painter, r ui.Rect, t theme.Tokens) {
p.Fill(r, t.Background, theme.ControlRadius)
p.Stroke(r, t.Border, theme.ControlRadius, 1)
p.Fill(ui.Rect{X: r.X + 1, Y: r.Y + 1, W: r.W - 2, H: 12}, t.Surface, theme.ControlRadius)
p.Fill(ui.Rect{X: r.X + 1, Y: r.Y + 13, W: r.W * 0.28, H: r.H - 14}, t.Surface, 0)
x := r.X + r.W*0.36
for i, w := range []float32{0.5, 0.38, 0.44} {
p.Fill(ui.Rect{X: x, Y: r.Y + 22 + float32(i)*10, W: r.W * w, H: 4}, t.TextMuted, 2)
}
p.Fill(ui.Rect{X: x, Y: r.Y + r.H - 20, W: 30, H: 12}, t.Accent, 2)
}
+50
View File
@@ -0,0 +1,50 @@
package account
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
)
func TestThemeSelectorPicksByPointerAndKeys(t *testing.T) {
mode, n := core.System, 0
disabled := false
tt := accountTester(600, 220, func(c *ui.Context) {
if ThemeSelector(c, &mode, ThemeSelectorOptions{Disabled: disabled}).Changed() {
n++
}
})
if err := tt.Click("Dark"); err != nil {
t.Fatal(err)
}
if mode != core.Dark || n != 1 {
t.Fatalf("click: %v %d", mode, n)
}
tt.Key(0, ui.KeyLeft)
tt.Key(0, ui.KeySpace)
if mode != core.Light || n != 2 {
t.Fatalf("keys: %v %d", mode, n)
}
disabled = true
tt.Frame()
_ = tt.Click("System")
if mode != core.Light {
t.Fatal("disabled selector changed")
}
defer func() {
if recover() == nil {
t.Fatal("unknown mode accepted")
}
}()
bad := core.Mode(9)
accountTester(100, 100, func(c *ui.Context) { ThemeSelector(c, &bad, ThemeSelectorOptions{}) })
}
func TestThemeSelectorSnapshot(t *testing.T) {
snapshot(t, "theme_selector", 520, 170, func(c *ui.Context) {
m := ui.Local(c.Root(), "m", func() core.Mode { return core.Dark })
ui.Column(c).Padding(16).Children(func() { ThemeSelector(c, m, ThemeSelectorOptions{}) })
})
}
+77
View File
@@ -0,0 +1,77 @@
package account
import (
"fmt"
"log/slog"
"strings"
"time"
"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/theme"
)
// TwoFactorInputOptions configure a TwoFactorInput.
type TwoFactorInputOptions struct {
// ResendAt sets when resending becomes available.
ResendAt time.Time
// Error displays the caller-provided verification failure.
Error string
Disabled bool
}
// TwoFactorResult reports completion and resend events.
type TwoFactorResult struct {
Element *ui.Element
completed, resend bool
}
// Completed reports a transition to six filled digits.
func (r TwoFactorResult) Completed() bool { return r.completed }
// Resend reports a request for a new code.
func (r TwoFactorResult) Resend() bool { return r.resend }
// TwoFactorInput collects six digits and displays a resend countdown.
func TwoFactorInput(c *ui.Context, code *string, opts TwoFactorInputOptions) TwoFactorResult {
if code == nil || len(*code) > 6 || strings.Trim(*code, "0123456789") != "" {
panic("mujica: TwoFactorInput needs up to six digits")
}
k := core.Tokens(c)
d := core.Density(c)
var r TwoFactorResult
r.Element = ui.Column(c).Gap(d.Unit() * 3).Disabled(opts.Disabled)
disabled := r.Element.IsDisabled()
r.Element.Children(func() {
pin := input.PinInput(c, code, input.PinInputOptions{Length: 6, Label: core.Msg(c, "two_factor_input.label"), Disabled: disabled, Invalid: opts.Error != ""})
r.completed = pin.Completed() && !disabled
if opts.Error != "" {
ui.Row(c).Gap(d.Unit()).AlignItems(ui.Center).TextColor(k.Danger).Role(ui.RoleStatus).Children(func() {
ui.Icon(c, icons.Must("circle-alert")).Size(14, 14)
ui.Text(c, opts.Error).FontSize(core.FontSize(c, theme.CaptionSize))
})
}
wait := opts.ResendAt.Sub(c.Now())
label := core.Msg(c, "two_factor_input.resend")
if wait > 0 {
secs := int((wait + time.Second - 1) / time.Second)
label = fmt.Sprintf(core.Msg(c, "two_factor_input.resend_in"), secs/60, secs%60)
// Wake when the shown second changes.
c.After(wait - time.Duration(secs-1)*time.Second)
}
ui.Row(c).Children(func() {
b := input.Button(c, label, input.ButtonOptions{Variant: input.Ghost, Icon: icons.Must("refresh-cw"), Disabled: disabled || wait > 0})
if b.Clicked() && !disabled && wait <= 0 {
r.resend = true
slog.Debug("mujica: two_factor_input resend")
}
})
})
if r.completed {
slog.Debug("mujica: two_factor_input completed")
}
return r
}
+96
View File
@@ -0,0 +1,96 @@
package account
import (
"fmt"
"strings"
"testing"
"time"
"github.com/egoist/mygo/ui"
)
func TestTwoFactorInputPasteCompleteAndResend(t *testing.T) {
logs := accountLogs(t)
code, done, resent := "", 0, 0
opts := TwoFactorInputOptions{ResendAt: time.Now().Add(-time.Second)}
tt := accountTester(420, 220, func(c *ui.Context) {
r := TwoFactorInput(c, &code, opts)
if r.Completed() {
done++
}
if r.Resend() {
resent++
}
})
tt.Key(0, ui.KeyTab)
tt.SetClipboard("381 942")
tt.Command("paste")
if code != "381942" || done != 1 {
t.Fatalf("paste: %d digits, %d completions", len(code), done)
}
if strings.Contains(logs.String(), "381942") {
t.Fatal("the code reached the log")
}
if err := tt.Click("Resend code"); err != nil {
t.Fatal(err)
}
if resent != 1 {
t.Fatal("resend not reported")
}
opts.ResendAt = time.Now().Add(65 * time.Second)
opts.Error = "That code has expired."
tt.Frame()
if !tt.HasText("Resend in 1:05") && !tt.HasText("Resend in 1:04") || !tt.HasText("That code has expired.") {
t.Fatalf("countdown: %q", tt.Texts())
}
_ = tt.Click("Resend in 1:05")
if resent != 1 {
t.Fatal("resent during countdown")
}
}
func TestTwoFactorInputDisabled(t *testing.T) {
code := "12"
tt := accountTester(420, 220, func(c *ui.Context) {
TwoFactorInput(c, &code, TwoFactorInputOptions{Disabled: true})
})
tt.Key(0, ui.KeyTab)
tt.Type("3456")
if code != "12" {
t.Fatal("disabled input changed")
}
}
func TestTwoFactorInputSnapshot(t *testing.T) {
snapshot(t, "two_factor_input", 420, 160, func(c *ui.Context) {
code := ui.Local(c.Root(), "code", func() string { return "3819" })
ui.Column(c).Padding(16).Children(func() {
TwoFactorInput(c, code, TwoFactorInputOptions{ResendAt: c.Now().Add(42 * time.Second)})
})
})
}
func TestTwoFactorInputCountdownRoundsUp(t *testing.T) {
tt := accountTester(420, 220, func(c *ui.Context) {
code := ""
TwoFactorInput(c, &code, TwoFactorInputOptions{ResendAt: c.Now().Add(100 * time.Millisecond)})
})
if !tt.HasText("Resend in 0:01") {
t.Fatal("positive wait must show one remaining second")
}
}
func TestTwoFactorInputInvalidValueKeepsSecretOutOfPanic(t *testing.T) {
const secret = "1234567"
defer func() {
v := recover()
if v == nil {
t.Fatal("oversized code accepted")
}
if strings.Contains(fmt.Sprint(v), secret) {
t.Fatal("code appears in panic")
}
}()
code := secret
accountTester(420, 220, func(c *ui.Context) { TwoFactorInput(c, &code, TwoFactorInputOptions{}) })
}
+95
View File
@@ -0,0 +1,95 @@
package account
import (
"fmt"
"math"
"time"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/data"
"github.com/ZacharyZhang-NY/MujicaUI/icons"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// QuotaItem is one metered resource: Used of Limit, in Unit.
type QuotaItem struct {
Label string
Used, Limit float64
Unit string
}
// UsageQuotaOptions configure a UsageQuota.
type UsageQuotaOptions struct {
// ResetAt provides the reset timestamp; zero hides it.
ResetAt time.Time
// Warn sets the warning threshold; zero means 0.8.
Warn float64
}
// UsageQuota displays usage bars and reset time.
func UsageQuota(c *ui.Context, items []QuotaItem, opts UsageQuotaOptions) *ui.Element {
warn := opts.Warn
if warn == 0 {
warn = 0.8
}
if warn < 0 || warn > 1 || math.IsNaN(warn) {
panic("mujica: UsageQuota Warn must be between 0 and 1")
}
k := core.Tokens(c)
d := core.Density(c)
e := ui.Column(c).Gap(d.Unit() * 4).MinWidth(320)
e.Children(func() {
for i, it := range items {
if it.Label == "" || !(it.Limit > 0) || it.Used < 0 || math.IsNaN(it.Used) || math.IsInf(it.Used, 0) || math.IsInf(it.Limit, 0) {
panic(fmt.Sprintf("mujica: QuotaItem %q needs a Label, a positive Limit and Used of zero or more", it.Label))
}
share := it.Used / it.Limit
col, icon, note := k.AccentText, "", ""
switch {
case share >= 1:
col, icon, note = k.Danger, "circle-x", core.Msg(c, "usage_quota.over")
case share >= warn:
col, icon, note = k.Warning, "triangle-alert", core.Msg(c, "usage_quota.near")
}
amount := fmt.Sprintf(core.Msg(c, "usage_quota.amount"), data.StatisticFormat(it.Used, 0), data.StatisticFormat(it.Limit, 0), it.Unit)
ui.Column(c).Key(i).Gap(d.Unit()).Role(ui.RoleMeter).Label(it.Label).
Description(fmt.Sprintf("%s, %s%% %s", amount, data.StatisticFormat(share*100, 0), note)).Children(func() {
ui.Row(c).Gap(d.Unit() * 2).AlignItems(ui.Center).Children(func() {
ui.Text(c, it.Label).FontWeight(500).Grow(1)
if icon != "" {
ui.Row(c).Gap(d.Unit() / 2).AlignItems(ui.Center).TextColor(col).Children(func() {
ui.Icon(c, icons.Must(icon)).Size(12, 12)
ui.Text(c, note).FontSize(core.FontSize(c, theme.CaptionSize)).FontWeight(600)
})
}
ui.Text(c, amount).TextColor(k.TextMuted).FontSize(core.FontSize(c, theme.CaptionSize)).FontFeatures("tnum")
})
ui.Box(c).Height(6).FillWidth().Draw(func(p *ui.Painter, r ui.Rect) {
p.Fill(r, k.SurfaceHover, theme.ControlRadius)
p.Fill(ui.Rect{X: r.X, Y: r.Y, W: r.W * float32(math.Min(1, share)), H: r.H}, col, theme.ControlRadius)
})
})
}
if !opts.ResetAt.IsZero() {
ui.Row(c).Gap(d.Unit()).AlignItems(ui.Center).TextColor(k.TextMuted).Children(func() {
ui.Icon(c, icons.Must("clock")).Size(12, 12)
ui.Text(c, usageQuotaReset(c, opts.ResetAt)).FontSize(core.FontSize(c, theme.CaptionSize))
})
}
})
return e
}
// usageQuotaReset formats hours or the reset date.
func usageQuotaReset(c *ui.Context, at time.Time) string {
left := at.Sub(c.Now())
switch {
case left <= 0:
return core.Msg(c, "usage_quota.reset_due")
case left < 24*time.Hour:
return fmt.Sprintf(core.Msg(c, "usage_quota.reset_hours"), int(math.Ceil(left.Hours())))
}
return fmt.Sprintf(core.Msg(c, "usage_quota.reset_on"), at.Format("2006-01-02"))
}
+60
View File
@@ -0,0 +1,60 @@
package account
import (
"fmt"
"math"
"testing"
"time"
"github.com/egoist/mygo/ui"
)
var quotaItems = []QuotaItem{{Label: "API calls", Used: 4200, Limit: 10000}, {Label: "Storage", Used: 9, Limit: 10, Unit: "GB"}, {Label: "Seats", Used: 12, Limit: 10}}
func TestUsageQuotaLevelsAndReset(t *testing.T) {
reset := time.Duration(5 * time.Hour)
tt := accountTester(500, 400, func(c *ui.Context) {
UsageQuota(c, quotaItems, UsageQuotaOptions{ResetAt: c.Now().Add(reset)})
})
for _, want := range []string{"4,200 of 10,000 ", "9 of 10 GB", "Near limit", "Limit reached", "Resets in 5 h"} {
if !tt.HasText(want) {
t.Fatalf("missing %q in %q", want, tt.Texts())
}
}
reset = 72 * time.Hour
tt.Frame()
if tt.HasText("Resets in 5 h") {
t.Fatalf("far reset: %q", tt.Texts())
}
defer func() {
if recover() == nil {
t.Fatal("zero limit accepted")
}
}()
accountTester(100, 100, func(c *ui.Context) { UsageQuota(c, []QuotaItem{{Label: "x"}}, UsageQuotaOptions{}) })
}
func TestUsageQuotaSnapshot(t *testing.T) {
snapshot(t, "usage_quota", 440, 230, func(c *ui.Context) {
ui.Column(c).Padding(16).Children(func() {
UsageQuota(c, quotaItems, UsageQuotaOptions{ResetAt: c.Now().Add(5*time.Hour + time.Minute)})
})
})
}
func TestUsageQuotaRejectsNonFiniteValues(t *testing.T) {
for _, tc := range []struct{ used, limit, warn float64 }{
{1, 10, math.NaN()}, {math.Inf(1), 10, 0}, {1, math.Inf(1), 0}, {math.NaN(), 10, 0}, {1, math.NaN(), 0},
} {
t.Run(fmt.Sprint(tc), func(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("non-finite quota accepted")
}
}()
accountTester(500, 300, func(c *ui.Context) {
UsageQuota(c, []QuotaItem{{Label: "Calls", Used: tc.used, Limit: tc.limit}}, UsageQuotaOptions{Warn: tc.warn})
})
})
}
}
+113
View File
@@ -0,0 +1,113 @@
package account
import (
"fmt"
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/display"
"github.com/ZacharyZhang-NY/MujicaUI/internal"
"github.com/ZacharyZhang-NY/MujicaUI/overlay"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// UserStatus is the presence a user shows to others.
type UserStatus int
const (
UserStatusOnline UserStatus = iota
UserStatusAway
UserStatusBusy
UserStatusInvisible
)
// UserMenuOptions configure a UserMenu. Name is required.
type UserMenuOptions struct {
Name, Email string
Avatar *ui.Bitmap
Disabled bool
}
// UserMenuResult reports presence, settings and sign-out events.
type UserMenuResult struct {
Element *ui.Element
changed, settings, leave bool
}
// StatusChanged reports a new presence in *status.
func (r UserMenuResult) StatusChanged() bool { return r.changed }
// Settings reports a request to open settings.
func (r UserMenuResult) Settings() bool { return r.settings }
// SignOut reports a request to sign out.
func (r UserMenuResult) SignOut() bool { return r.leave }
// UserMenu opens presence, settings and sign-out actions.
func UserMenu(c *ui.Context, status *UserStatus, opts UserMenuOptions) UserMenuResult {
if opts.Name == "" {
panic("mujica: UserMenu needs a Name")
}
if *status < UserStatusOnline || *status > UserStatusInvisible {
panic(fmt.Sprintf("mujica: UserMenu status %d is unknown", *status))
}
k := core.Tokens(c)
var r UserMenuResult
word := core.Msg(c, fmt.Sprintf("user_menu.status%d", *status))
b := ui.ButtonBase(c).Role(ui.RoleMenuButton).Size(36, 36).Radius(18).Disabled(opts.Disabled).
Label(fmt.Sprintf(core.Msg(c, "user_menu.label"), opts.Name, word))
r.Element = b
internal.Ring(b, k.Focus, 18)
open := ui.Local(b, "open", func() bool { return false })
disabled := b.IsDisabled()
if disabled {
*open = false
} else if b.Clicked() || b.Shortcut(0, ui.KeyDown) {
*open = true
}
st := *status
b.Children(func() { display.Avatar(c, opts.Name, display.AvatarOptions{Image: opts.Avatar, Size: 32}) })
b.DrawOver(func(p *ui.Painter, rect ui.Rect) { userMenuDot(p, k, rect.X+rect.W-6, rect.Y+rect.H-6, st) })
overlay.PopupMenuOpen(c, b, open, func(m *overlay.PopupMenu) {
head := opts.Name
if opts.Email != "" {
head += " · " + opts.Email
}
m.Group(head, func() {
for s := UserStatusOnline; s <= UserStatusInvisible; s++ {
on := s == *status
if m.Check(core.Msg(c, fmt.Sprintf("user_menu.status%d", s)), &on, overlay.PopupMenuItemOptions{}) && s != *status && !disabled {
*status, r.changed = s, true
slog.Debug("mujica: user_menu status", "status", s)
}
}
})
m.Separator()
r.settings = m.Item(core.Msg(c, "user_menu.settings"), overlay.PopupMenuItemOptions{}) && !disabled
r.leave = m.Item(core.Msg(c, "user_menu.sign_out"), overlay.PopupMenuItemOptions{}) && !disabled
})
if r.settings || r.leave {
slog.Debug("mujica: user_menu chose", "settings", r.settings, "sign_out", r.leave)
}
return r
}
// userMenuDot distinguishes presence using shapes and colors.
func userMenuDot(p *ui.Painter, k theme.Tokens, cx, cy float32, s UserStatus) {
const d = 11
r := ui.Rect{X: cx - d/2, Y: cy - d/2, W: d, H: d}
p.Fill(ui.Rect{X: r.X - 2, Y: r.Y - 2, W: d + 4, H: d + 4}, k.Surface, d)
switch s {
case UserStatusOnline:
p.Fill(r, k.Success, d)
case UserStatusAway:
p.Stroke(r, k.Warning, d, 3)
case UserStatusBusy:
p.Fill(r, k.Danger, d)
p.Fill(ui.Rect{X: r.X + 2.5, Y: cy - 1, W: d - 5, H: 2}, k.Surface, 0)
default:
p.Stroke(r, k.TextMuted, d, 1.5)
}
}
+76
View File
@@ -0,0 +1,76 @@
package account
import (
"testing"
"github.com/egoist/mygo/ui"
)
func TestUserMenuStatusSettingsSignOut(t *testing.T) {
status := UserStatusOnline
var changes, settings, leaves int
tt := accountTester(500, 400, func(c *ui.Context) {
r := UserMenu(c, &status, UserMenuOptions{Name: "Sakiko Togawa", Email: "sakiko@court"})
if r.StatusChanged() {
changes++
}
if r.Settings() {
settings++
}
if r.SignOut() {
leaves++
}
})
if err := tt.Click("Sakiko Togawa, Online"); err != nil {
t.Fatal(err)
}
if !tt.HasText("Sakiko Togawa · sakiko@court") {
t.Fatalf("header: %q", tt.Texts())
}
_ = tt.Click("Do not disturb")
if status != UserStatusBusy || changes != 1 {
t.Fatalf("status %v", status)
}
tt.Key(0, ui.KeyTab)
tt.Key(0, ui.KeyDown)
_ = tt.Click("Settings")
_ = tt.Click("Sakiko Togawa, Do not disturb")
_ = tt.Click("Sign out")
if settings != 1 || leaves != 1 {
t.Fatalf("settings %d sign out %d", settings, leaves)
}
}
func TestUserMenuSnapshot(t *testing.T) {
snapshot(t, "user_menu", 220, 90, func(c *ui.Context) {
ui.Row(c).Padding(20).Gap(16).Children(func() {
for s := UserStatusOnline; s <= UserStatusInvisible; s++ {
st := s
ui.Box(c).Key(int(s)).Children(func() { UserMenu(c, &st, UserMenuOptions{Name: "Sakiko Togawa"}) })
}
})
})
}
func TestUserMenuDisabledAndInvalidStatus(t *testing.T) {
status, disabled, actions := UserStatusOnline, false, 0
tt := accountTester(600, 500, func(c *ui.Context) {
ui.Column(c).Disabled(disabled).Children(func() {
r := UserMenu(c, &status, UserMenuOptions{Name: "User"})
if r.StatusChanged() || r.Settings() || r.SignOut() {
actions++
}
})
})
if err := tt.Click("User, Online"); err != nil {
t.Fatal(err)
}
disabled = true
tt.Key(0, ui.KeyDown)
tt.Key(0, ui.KeyEnter)
if status != UserStatusOnline || actions != 0 || tt.HasText("Sign out") {
t.Fatal("disabled user menu acts")
}
status = UserStatus(99)
accountPanics(t, func(c *ui.Context) { UserMenu(c, &status, UserMenuOptions{Name: "User"}) })
}
+103
View File
@@ -0,0 +1,103 @@
package account
import (
"fmt"
"log/slog"
"github.com/egoist/mygo/ui"
"github.com/ZacharyZhang-NY/MujicaUI/core"
"github.com/ZacharyZhang-NY/MujicaUI/display"
"github.com/ZacharyZhang-NY/MujicaUI/input"
"github.com/ZacharyZhang-NY/MujicaUI/overlay"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// ChangeKind tags a release note.
type ChangeKind int
const (
ChangeNew ChangeKind = iota
ChangeImproved
ChangeFixed
)
// ReleaseChange is one line of release notes.
type ReleaseChange struct {
Kind ChangeKind
Text string
}
// Release is a version's notes.
type Release struct {
Version, Date string
Changes []ReleaseChange
}
// WhatsNewDialogOptions configure a WhatsNewDialog.
type WhatsNewDialogOptions struct {
// Title replaces the built-in "What's new".
Title string
}
// WhatsNewDialog displays release notes and a persistent hide choice.
func WhatsNewDialog(c *ui.Context, open *bool, hide *bool, releases []Release, opts WhatsNewDialogOptions) core.ChoiceResult {
if len(releases) == 0 {
panic("mujica: WhatsNewDialog needs releases")
}
for _, rel := range releases {
if rel.Version == "" {
panic("mujica: Release needs a Version")
}
for _, change := range rel.Changes {
if change.Kind < ChangeNew || change.Kind > ChangeFixed || change.Text == "" {
panic("mujica: ReleaseChange needs a valid Kind and Text")
}
}
}
if ui.Box(c).IsDisabled() {
*open = false
}
k := core.Tokens(c)
d := core.Density(c)
title := opts.Title
if title == "" {
title = core.Msg(c, "whats_new_dialog.title")
}
var r core.ChoiceResult
was := *open
before := *hide
r.Element = overlay.Dialog(c, open, overlay.DialogOptions{Title: title, Width: 480, Decorated: true, Actions: func() {
input.Checkbox(c, hide, core.Msg(c, "whats_new_dialog.hide"), input.CheckboxOptions{})
ui.Box(c).Grow(1)
if input.Button(c, core.Msg(c, "whats_new_dialog.close"), input.ButtonOptions{}).AutoFocus().Clicked() {
*open = false
}
}}, func() {
for i, rel := range releases {
if rel.Version == "" {
panic("mujica: Release needs a Version")
}
ui.Column(c).Key(i).Gap(d.Unit() * 2).Role(ui.RoleGroup).Label(rel.Version).Children(func() {
ui.Row(c).Gap(d.Unit() * 2).AlignItems(ui.End).Children(func() {
ui.Text(c, rel.Version).Font(theme.SerifFont).FontSize(core.FontSize(c, theme.H3Size)).FontWeight(600)
if rel.Date != "" {
ui.Text(c, rel.Date).TextColor(k.TextMuted).FontSize(core.FontSize(c, theme.CaptionSize))
}
})
for _, ch := range rel.Changes {
ui.Row(c).Gap(d.Unit() * 2).AlignItems(ui.Start).Children(func() {
tone := map[ChangeKind]display.BadgeTone{ChangeNew: display.BadgeAccent, ChangeImproved: display.BadgeInfo, ChangeFixed: display.BadgeSuccess}[ch.Kind]
display.Badge(c, display.BadgeOptions{Text: core.Msg(c, fmt.Sprintf("whats_new_dialog.kind%d", ch.Kind)), Tone: tone}, nil).Shrink(0)
ui.Text(c, ch.Text).Grow(1).MinWidth(0)
})
}
})
}
})
r = core.NewChoiceResult(r.Element, *hide != before)
if was && !*open {
slog.Debug("mujica: whats_new_dialog close", "hide", *hide)
}
return r
}
+67
View File
@@ -0,0 +1,67 @@
package account
import (
"testing"
"github.com/egoist/mygo/ui"
)
var releases = []Release{
{Version: "1.1", Date: "2026-10-05", Changes: []ReleaseChange{{ChangeNew, "500 components."}, {ChangeFixed, "Snapshots no longer drift."}}},
{Version: "1.0", Changes: []ReleaseChange{{ChangeImproved, "Court-gothic theme."}}},
}
func TestWhatsNewDialogListsAndHides(t *testing.T) {
open, hide, n := true, false, 0
tt := accountTester(700, 600, func(c *ui.Context) {
if WhatsNewDialog(c, &open, &hide, releases, WhatsNewDialogOptions{}).Changed() {
n++
}
})
for _, want := range []string{"What's new", "1.1", "2026-10-05", "New", "Fixed", "Improved", "Court-gothic theme."} {
if !tt.HasText(want) {
t.Fatalf("missing %q in %q", want, tt.Texts())
}
}
_ = tt.Click("Don't show again")
if !hide || n != 1 {
t.Fatal("hide not set")
}
_ = tt.Click("Got it")
if open {
t.Fatal("not closed")
}
open = true
tt.Frame()
tt.Key(0, ui.KeyEscape)
if open || !hide {
t.Fatal("escape did not close or lost hide")
}
}
func TestWhatsNewDialogSnapshot(t *testing.T) {
snapshot(t, "whats_new_dialog", 560, 460, func(c *ui.Context) {
open := ui.Local(c.Root(), "open", func() bool { return true })
hide := ui.Local(c.Root(), "hide", func() bool { return false })
WhatsNewDialog(c, open, hide, releases, WhatsNewDialogOptions{})
})
}
func TestWhatsNewDialogDisabledParentCloses(t *testing.T) {
open, hide, disabled := true, false, false
tt := accountTester(700, 600, func(c *ui.Context) {
ui.Column(c).Disabled(disabled).Children(func() { WhatsNewDialog(c, &open, &hide, releases, WhatsNewDialogOptions{}) })
})
disabled = true
tt.Frame()
if open || hide || tt.HasText("What's new") {
t.Fatal("disabled parent retains dialog")
}
}
func TestWhatsNewDialogInvalidChange(t *testing.T) {
open, hide := true, false
accountPanics(t, func(c *ui.Context) {
WhatsNewDialog(c, &open, &hide, []Release{{Version: "1", Changes: []ReleaseChange{{Kind: ChangeKind(99), Text: "Change"}}}}, WhatsNewDialogOptions{})
})
}
+144
View File
@@ -0,0 +1,144 @@
package account
import (
"fmt"
"log/slog"
"slices"
"strings"
"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/overlay"
"github.com/ZacharyZhang-NY/MujicaUI/theme"
)
// Workspace is a place a user can switch to.
type Workspace struct {
ID, Name string
// Detail supplies the workspace summary.
Detail string
}
// WorkspaceSwitcherOptions configure a WorkspaceSwitcher.
type WorkspaceSwitcherOptions struct {
Disabled bool
}
type workspaceSwitcherState struct {
open bool
query string
cursor int
source []Workspace
hits []int
filtered string
ready bool
}
// WorkspaceSwitcher filters workspaces and changes the current selection.
func WorkspaceSwitcher(c *ui.Context, current *string, spaces []Workspace, opts WorkspaceSwitcherOptions) core.ChoiceResult {
var cur *Workspace
for i := range spaces {
if spaces[i].ID == "" || spaces[i].Name == "" {
panic("mujica: Workspace needs an ID and a Name")
}
if spaces[i].ID == *current {
cur = &spaces[i]
}
}
if cur == nil {
panic(fmt.Sprintf("mujica: WorkspaceSwitcher current %q is not a workspace", *current))
}
var r core.ChoiceResult
b := accountTrigger(c, cur.Name, cur.Detail, nil, opts.Disabled)
r.Element = b
st := ui.Local(b, "ws", func() workspaceSwitcherState { return workspaceSwitcherState{} })
disabled := b.IsDisabled()
if disabled {
st.open = false
} else if b.Clicked() || b.Shortcut(0, ui.KeyDown) {
st.open, st.query, st.cursor = true, "", 0
}
choose := func(i int) {
if !disabled && spaces[i].ID != *current {
*current, r = spaces[i].ID, core.NewChoiceResult(r.Element, true)
slog.Debug("mujica: workspace_switcher switched")
}
st.open = false
}
overlay.Popover(c, b, &st.open, overlay.PopoverOptions{Width: 300, Label: core.Msg(c, "workspace_switcher.label")}, func() {
res := input.SearchInput(c, &st.query, input.SearchInputOptions{Placeholder: core.Msg(c, "workspace_switcher.search"), Label: core.Msg(c, "workspace_switcher.search")})
in := res.Input
in.AutoFocus()
q := strings.ToLower(strings.TrimSpace(st.query))
if !st.ready || st.filtered != q || !slices.Equal(st.source, spaces) {
st.source, st.filtered, st.ready = slices.Clone(spaces), q, true
st.hits, st.cursor = st.hits[:0], 0
for i, w := range spaces {
if q == "" || strings.Contains(strings.ToLower(w.Name+" "+w.Detail), q) {
st.hits = append(st.hits, i)
}
}
}
hits := st.hits
st.cursor = max(0, min(st.cursor, len(hits)-1))
before := st.cursor
switch {
case disabled || in.IsDisabled() || len(hits) == 0:
case in.Shortcut(0, ui.KeyDown):
st.cursor = (st.cursor + 1) % len(hits)
case in.Shortcut(0, ui.KeyUp):
st.cursor = (st.cursor + len(hits) - 1) % len(hits)
}
if res.Submitted() && len(hits) > 0 {
choose(hits[st.cursor])
}
if len(hits) == 0 {
ui.Text(c, core.Msg(c, "workspace_switcher.none")).TextColor(core.Tokens(c).TextMuted).Padding(core.Density(c).Unit() * 2).Role(ui.RoleStatus)
}
list := accountRows(c, len(hits), func(n int) any { return spaces[hits[n]].ID }, func(n int) {
i := hits[n]
row := workspaceRow(c, spaces[i], spaces[i].ID == *current, n == st.cursor)
if row.Clicked() && !row.IsDisabled() {
choose(i)
}
})
if len(hits) > 8 && (st.cursor != before || res.Changed()) {
rows := ui.Local(list, "rows", func() ui.ListState { return ui.ListState{} })
rows.ScrollIntoView(st.cursor)
}
})
return r
}
// workspaceRow displays a clickable workspace with a selection mark.
func workspaceRow(c *ui.Context, w Workspace, current, cursor bool) *ui.Element {
k := core.Tokens(c)
d := core.Density(c)
b := ui.ButtonBase(c).Key(w.ID).MinHeight(d.ControlHeight()).Padding(d.Unit(), d.Unit()*2).Gap(d.Unit() * 2).
Justify(ui.Start).Radius(theme.ControlRadius).Role(ui.RoleListItem).Label(w.Name).Selected(current)
internal.Ring(b, k.Focus, theme.ControlRadius)
switch {
case cursor || current:
b.Background(k.Selection)
case b.Hovered():
b.Background(k.SurfaceHover)
}
b.Children(func() {
ui.Box(c).Size(16, 16).Shrink(0).Children(func() {
if current {
ui.Icon(c, icons.Must("check")).Size(16, 16).TextColor(k.AccentText)
}
})
ui.Column(c).Grow(1).MinWidth(0).Children(func() {
ui.Text(c, w.Name).SingleLine().Ellipsis("…")
if w.Detail != "" {
ui.Text(c, w.Detail).TextColor(k.TextMuted).FontSize(core.FontSize(c, theme.CaptionSize)).SingleLine()
}
})
})
return b
}
+93
View File
@@ -0,0 +1,93 @@
package account
import (
"fmt"
"testing"
"github.com/egoist/mygo/ui"
)
var switcherSpaces = []Workspace{{ID: "ave", Name: "Ave Mujica", Detail: "5 members"}, {ID: "mygo", Name: "MyGO!!!!!", Detail: "5 members"}, {ID: "crychic", Name: "CRYCHIC", Detail: "Archived"}}
func TestWorkspaceSwitcherSearchAndSwitch(t *testing.T) {
cur, n := "ave", 0
tt := accountTester(500, 500, func(c *ui.Context) {
if WorkspaceSwitcher(c, &cur, switcherSpaces, WorkspaceSwitcherOptions{}).Changed() {
n++
}
})
if err := tt.Click("Ave Mujica"); err != nil {
t.Fatal(err)
}
if !tt.Focused("Find a workspace") || !tt.HasText("CRYCHIC") {
t.Fatalf("open: %q", tt.Texts())
}
tt.Type("arch")
if tt.HasText("MyGO!!!!!") || !tt.HasText("CRYCHIC") {
t.Fatalf("search: %q", tt.Texts())
}
tt.Key(0, ui.KeyEnter)
if cur != "crychic" || n != 1 || tt.HasText("Find a workspace") {
t.Fatalf("enter: %q", cur)
}
_ = tt.Click("CRYCHIC")
tt.Key(0, ui.KeyDown)
tt.Key(0, ui.KeyEnter)
if cur != "mygo" || n != 2 {
t.Fatalf("arrow: %q", cur)
}
_ = tt.Click("MyGO!!!!!")
tt.Type("zzz")
if !tt.HasText("No workspace matches") {
t.Fatal("no empty state")
}
tt.Key(0, ui.KeyEscape)
if tt.HasText("No workspace matches") || cur != "mygo" {
t.Fatal("escape did not close")
}
}
func TestWorkspaceSwitcherSnapshot(t *testing.T) {
snapshot(t, "workspace_switcher", 300, 90, func(c *ui.Context) {
cur := ui.Local(c.Root(), "cur", func() string { return "ave" })
ui.Column(c).Padding(16).AlignItems(ui.Start).Children(func() { WorkspaceSwitcher(c, cur, switcherSpaces, WorkspaceSwitcherOptions{}) })
})
}
func TestWorkspaceSwitcherLargeDataBuildsVisibleRows(t *testing.T) {
items := make([]Workspace, 100000)
for i := range items {
items[i] = Workspace{ID: fmt.Sprint(i), Name: fmt.Sprintf("Workspace %d", i)}
}
cur := "0"
tt := accountTester(500, 500, func(c *ui.Context) { WorkspaceSwitcher(c, &cur, items, WorkspaceSwitcherOptions{}) })
if err := tt.Click("Workspace 0"); err != nil {
t.Fatal(err)
}
if n := len(tt.Texts()); n > 100 {
t.Fatalf("built %d text elements for a bounded viewport", n)
}
tt.Type("99999")
tt.Key(0, ui.KeyEnter)
if cur != "99999" {
t.Fatalf("large-list search choice %q", cur)
}
}
func TestWorkspaceSwitcherDisablingClosesAndInvalidCurrent(t *testing.T) {
cur, disabled := "ave", false
tt := accountTester(600, 500, func(c *ui.Context) {
ui.Column(c).Disabled(disabled).Children(func() { WorkspaceSwitcher(c, &cur, switcherSpaces, WorkspaceSwitcherOptions{}) })
})
if err := tt.Click("Ave Mujica"); err != nil {
t.Fatal(err)
}
disabled = true
tt.Key(0, ui.KeyDown)
tt.Key(0, ui.KeyEnter)
if tt.HasText("Find a workspace") || cur != "ave" {
t.Fatal("disabled workspace popup stays active")
}
cur = "unknown"
accountPanics(t, func(c *ui.Context) { WorkspaceSwitcher(c, &cur, switcherSpaces, WorkspaceSwitcherOptions{}) })
}