refactor: create app.go

This commit is contained in:
ayn2op 2024-09-20 01:26:38 +05:30
parent e56edc7caf
commit 5a01e54627
2 changed files with 56 additions and 32 deletions

52
cmd/application.go Normal file
View file

@ -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()
}

View file

@ -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)
}