From 5a01e54627bc2c5241017e718dfc0463385f60ec Mon Sep 17 00:00:00 2001 From: ayn2op Date: Fri, 20 Sep 2024 01:26:38 +0530 Subject: [PATCH] refactor: create app.go --- cmd/application.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++ cmd/run.go | 36 ++++---------------------------- 2 files changed, 56 insertions(+), 32 deletions(-) create mode 100644 cmd/application.go diff --git a/cmd/application.go b/cmd/application.go new file mode 100644 index 0000000..5b0246f --- /dev/null +++ b/cmd/application.go @@ -0,0 +1,52 @@ +package cmd + +import ( + "log/slog" + + "github.com/rivo/tview" +) + +type Application struct { + *tview.Application +} + +func newApplication() *Application { + app := &Application{ + Application: tview.NewApplication(), + } + + app.EnableMouse(cfg.Mouse) + return app +} + +func (app *Application) Show(token string) error { + if token == "" { + loginForm := NewLoginForm(func(token string, err error) { + if err != nil { + slog.Error("failed to login", "err", err) + return + } + + if err := app.Show(token); err != nil { + slog.Error("failed to show app", "err", err) + } + }) + app.SetRoot(loginForm, true) + } else { + if err := openState(token); err != nil { + return err + } + + app.SetRoot(mainFlex, true) + } + + return nil +} + +func (app *Application) Run(token string) error { + if err := app.Show(token); err != nil { + return err + } + + return app.Application.Run() +} diff --git a/cmd/run.go b/cmd/run.go index 450837a..8786102 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -1,18 +1,15 @@ package cmd import ( - "log/slog" - "github.com/ayn2op/discordo/internal/config" "github.com/ayn2op/discordo/internal/logger" - "github.com/rivo/tview" ) var ( discordState *State cfg *config.Config - app = tview.NewApplication() + app *Application mainFlex *MainFlex ) @@ -27,34 +24,9 @@ func Run(token string) error { return err } + // app must be initialized after configuration is loaded + app = newApplication() // mainFlex must be initialized before opening a new state. mainFlex = newMainFlex() - if token == "" { - lf := NewLoginForm(func(token string, err error) { - if err != nil { - app.Stop() - slog.Error("failed to login", "err", err) - return - } - - if err := openState(token); err != nil { - app.Stop() - slog.Error("failed to open state", "err", err) - return - } - - app.SetRoot(mainFlex, true) - }) - - app.SetRoot(lf, true) - } else { - if err := openState(token); err != nil { - return err - } - - app.SetRoot(mainFlex, true) - } - - app.EnableMouse(cfg.Mouse) - return app.Run() + return app.Run(token) }