Set URL after loading database

This commit is contained in:
Brandon Dyck 2024-11-15 11:55:31 -07:00
parent 0bab92db02
commit beef4523c2
4 changed files with 91 additions and 41 deletions

View File

@ -1,3 +0,0 @@
package app
// TODO: Add your code here

View File

@ -2,9 +2,13 @@ package main
import ( import (
"embed" "embed"
"fmt"
"log" "log"
"log/slog"
"net/http" "net/http"
"net/url"
"git.codemonkeysoftware.net/b/peachy-go"
"git.codemonkeysoftware.net/b/peachy-go/desktop/routes" "git.codemonkeysoftware.net/b/peachy-go/desktop/routes"
"github.com/wailsapp/wails/v3/pkg/application" "github.com/wailsapp/wails/v3/pkg/application"
) )
@ -12,9 +16,64 @@ import (
//go:embed all:static //go:embed all:static
var assets embed.FS var assets embed.FS
func main() { const ListenPort = "9245"
const WindowNameMain = "mainwindow"
r := routes.NewChiRouter() var globalDB *peachy.DB
func closeDB() {
if globalDB != nil {
globalDB.Close()
}
}
// SetURl is a workaround for WebviewWindow.SetURL not adding the base URL
// to relative URLs.
// TODO Report this or something.
func SetURL(win application.Window, path string) application.Window {
slog.Info("setting URL the hard way")
u, _ := url.JoinPath("http://wails.localhost:"+ListenPort+"/", path)
return win.SetURL(u)
}
func setDB(db *peachy.DB) error {
slog.Info("opened DB, setting URL")
globalDB = db
SetURL(application.Get().GetWindowByName(WindowNameMain), "/").SetTitle("you opened a DB")
return nil
}
func createDB(filename string) error {
db, err := peachy.Create(filename)
if err != nil {
return fmt.Errorf("Failed to create database: %w", err)
}
return setDB(db)
}
func openDB(filename string) error {
db, err := peachy.Open(filename)
if err != nil {
return fmt.Errorf("Failed to open database: %w", err)
}
return setDB(db)
}
func showError(err error) {
if err != nil {
application.ErrorDialog().SetMessage(err.Error()).Show()
}
}
func dbFileFilter() []application.FileFilter {
return []application.FileFilter{
{DisplayName: "Peachy database", Pattern: "*.pit"},
{DisplayName: "All Files", Pattern: "*.*"},
}
}
func main() {
r := routes.NewChiRouter(ListenPort)
// Create the application // Create the application
app := application.New(application.Options{ app := application.New(application.Options{
@ -31,14 +90,18 @@ func main() {
ApplicationShouldTerminateAfterLastWindowClosed: true, ApplicationShouldTerminateAfterLastWindowClosed: true,
}, },
}) })
app.OnShutdown(func() {
closeDB()
})
// V3 introduces multiple windows, so we need to create a window // V3 introduces multiple windows, so we need to create a window
app.NewWebviewWindowWithOptions(application.WebviewWindowOptions{ app.NewWebviewWindowWithOptions(application.WebviewWindowOptions{
Name: WindowNameMain,
Title: "Your Project", Title: "Your Project",
Mac: application.MacWindow{ Mac: application.MacWindow{
Backdrop: application.MacBackdropTranslucent, Backdrop: application.MacBackdropTranslucent,
}, },
URL: "/", // URL to load when the window is created URL: "/splash", // URL to load when the window is created
Width: 1080, // Width of the window Width: 1080, // Width of the window
Height: 720, // Height of the window Height: 720, // Height of the window
Centered: false, Centered: false,
@ -52,31 +115,24 @@ func main() {
menu.FindByRole(application.NewFile).OnClick(func(ctx *application.Context) { menu.FindByRole(application.NewFile).OnClick(func(ctx *application.Context) {
d := application.SaveFileDialog() d := application.SaveFileDialog()
d.SetOptions(&application.SaveFileDialogOptions{ d.SetOptions(&application.SaveFileDialogOptions{
Filters: []application.FileFilter{ Filters: dbFileFilter(),
{DisplayName: "Peachy database", Pattern: "*.pit"},
{DisplayName: "All Files", Pattern: "*.*"},
},
AllowOtherFileTypes: true, AllowOtherFileTypes: true,
Title: "Create new database", Title: "Create new database",
}) })
path, err := d.PromptForSingleSelection() path, _ := d.PromptForSingleSelection()
if err != nil {
application.InfoDialog().SetMessage("Error: " + err.Error()).Show()
}
if path != "" { if path != "" {
application.InfoDialog().SetMessage(path).Show() showError(createDB(path))
} else {
application.InfoDialog().SetMessage("No file selected").Show()
} }
}) })
menu.FindByRole(application.Open).OnClick(func(ctx *application.Context) { menu.FindByRole(application.Open).OnClick(func(ctx *application.Context) {
path, _ := application.OpenFileDialog(). d := application.OpenFileDialog()
CanChooseFiles(true). d.SetOptions(&application.OpenFileDialogOptions{
PromptForSingleSelection() Filters: dbFileFilter(),
CanChooseFiles: true,
})
path, _ := d.PromptForSingleSelection()
if path != "" { if path != "" {
application.InfoDialog().SetMessage(path).Show() showError(openDB(path))
} else {
application.InfoDialog().SetMessage("No file selected").Show()
} }
}) })
app.SetMenu(menu) app.SetMenu(menu)

View File

@ -29,6 +29,7 @@ func hxTarget(target string) h.Attrib {
func HomePage() h.ParentElement { func HomePage() h.ParentElement {
return e.Div()( return e.Div()(
e.H1()(h.Text("[untitled]")),
e.Button( e.Button(
a.Type("button"), a.Type("button"),
hxGet("/hello"), hxGet("/hello"),
@ -38,3 +39,7 @@ func HomePage() h.ParentElement {
e.Div(a.Id("hello"))(), e.Div(a.Id("hello"))(),
) )
} }
func Splash() h.Term {
return h.Terms{}
}

View File

@ -14,13 +14,11 @@ import (
/* /*
Create a new chi router, configure it and return it. Create a new chi router, configure it and return it.
*/ */
func NewChiRouter() *chi.Mux { func NewChiRouter(port string) *chi.Mux {
r := chi.NewRouter() r := chi.NewRouter()
// Useful middleware, see : https://pkg.go.dev/github.com/go-chi/httplog/v2@v2.1.1#NewLogger
logger := httplog.NewLogger("app-logger", httplog.Options{ logger := httplog.NewLogger("app-logger", httplog.Options{
// All log
LogLevel: slog.LevelInfo, LogLevel: slog.LevelInfo,
Concise: true, Concise: true,
}) })
@ -40,29 +38,23 @@ func NewChiRouter() *chi.Mux {
}) })
*/ */
// Serve static files.
r.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) r.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
// Home page r.Get("/splash", func(w http.ResponseWriter, r *http.Request) {
slog.Info("we splashin")
HXRender(w, r, pages.Splash)
})
r.Get("/", func(w http.ResponseWriter, r *http.Request) { r.Get("/", func(w http.ResponseWriter, r *http.Request) {
// Render home page slog.Info("we homies")
HXRender(w, r, pages.HomePage) HXRender(w, r, pages.HomePage)
// 200 OK status
w.WriteHeader(http.StatusOK)
}) })
// Hello page
r.Get("/hello", func(w http.ResponseWriter, r *http.Request) { r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
// Render hello
HXRender(w, r, components.HelloWorld) HXRender(w, r, components.HelloWorld)
// 200 OK status
w.WriteHeader(http.StatusOK)
}) })
// Listen to port 3000. go http.ListenAndServe(":"+port, r)
go http.ListenAndServe(":9245", r)
return r return r
} }