dynamo-browse/internal/common/ui/commandctrl/ctx.go

101 lines
2.2 KiB
Go
Raw Normal View History

package commandctrl
import (
"context"
2025-11-04 03:24:19 +00:00
tea "github.com/charmbracelet/bubbletea"
2025-11-04 03:24:19 +00:00
"github.com/go-co-op/gocron/v2"
"github.com/pkg/errors"
2025-05-23 12:04:41 +00:00
"ucl.lmika.dev/ucl"
)
type commandCtlKeyType struct{}
var commandCtlKey = commandCtlKeyType{}
2025-05-23 12:04:41 +00:00
type execContext struct {
ctrl *CommandController
requestRefresh bool
}
func PostMsg(ctx context.Context, msg tea.Msg) {
2025-05-23 12:04:41 +00:00
cmdCtl, ok := ctx.Value(commandCtlKey).(*execContext)
if ok {
2025-05-23 12:04:41 +00:00
cmdCtl.ctrl.postMessage(msg)
}
}
func SelectedItemIndex(ctx context.Context) (int, bool) {
2025-05-23 12:04:41 +00:00
cmdCtl, ok := ctx.Value(commandCtlKey).(*execContext)
if !ok {
return 0, false
}
2025-05-23 12:04:41 +00:00
return cmdCtl.ctrl.uiStateProvider.SelectedItemIndex(), true
}
func SetSelectedItemIndex(ctx context.Context, newIdx int) tea.Msg {
2025-05-23 12:04:41 +00:00
cmdCtl, ok := ctx.Value(commandCtlKey).(*execContext)
if !ok {
return nil
}
return cmdCtl.ctrl.uiStateProvider.SetSelectedItemIndex(newIdx)
}
func GetInvoker(ctx context.Context) Invoker {
cmdCtl, ok := ctx.Value(commandCtlKey).(*execContext)
if !ok {
return nil
}
2025-05-23 12:04:41 +00:00
return cmdCtl.ctrl
}
func QueueRefresh(ctx context.Context) {
cmdCtl, ok := ctx.Value(commandCtlKey).(*execContext)
if !ok {
return
}
cmdCtl.requestRefresh = true
}
2025-11-04 03:24:19 +00:00
func CronScheduler(ctx context.Context) gocron.Scheduler {
cmdCtl, ok := ctx.Value(commandCtlKey).(*execContext)
if !ok {
return nil
}
return cmdCtl.ctrl.cronScheduler
}
func ScheduleTask(ctx context.Context, task func(ctx context.Context) error) error {
cmdCtl, ok := ctx.Value(commandCtlKey).(*execContext)
if !ok {
return errors.New("no command controller")
}
select {
case cmdCtl.ctrl.pendingTaskChan <- pendingTask{task: task}:
return nil
default:
return errors.New("task queue is full")
}
}
func ScheduleAuxTask(ctx context.Context, descr string, task func(ctx context.Context) error) error {
cmdCtl, ok := ctx.Value(commandCtlKey).(*execContext)
if !ok {
return errors.New("no command controller")
}
select {
case cmdCtl.ctrl.pendingAuxTaskChan <- pendingTask{descr: descr, task: task}:
return nil
default:
return errors.New("aux task queue is full")
}
}
2025-05-23 12:04:41 +00:00
type Invoker interface {
Invoke(invokable ucl.Invokable, args []any) tea.Msg
Inst() *ucl.Inst
}