Sfoglia il codice sorgente

refactor: create app.go

ayn2op 1 anno fa
parent
commit
5a01e54627
2 ha cambiato i file con 56 aggiunte e 32 eliminazioni
  1. 52 0
      cmd/application.go
  2. 4 32
      cmd/run.go

+ 52 - 0
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()
+}

+ 4 - 32
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)
 }