Complete old home page hmc-related refactor

This commit is contained in:
Teajey 2026-11-17 23:29:34 +09:00
parent 658884c2cc
commit b5dfb135df
Signed by: Teajey
GPG Key ID: 970E790FE834A713
6 changed files with 178 additions and 70 deletions

View File

@ -3,6 +3,7 @@ package resources
import ( import (
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/templates" "lishwist/http/templates"
"net/url"
"github.com/Teajey/hmc" "github.com/Teajey/hmc"
) )
@ -14,6 +15,8 @@ type LinksList struct {
type HomeProps struct { type HomeProps struct {
hmc.Namespace hmc.Namespace
Error string
Warning string
Navbar templates.NavCollapse `json:"-"` Navbar templates.NavCollapse `json:"-"`
Wishlist Wishlist `json:"wishlist"` Wishlist Wishlist `json:"wishlist"`
Todo Wishlist `json:"todo"` Todo Wishlist `json:"todo"`
@ -28,9 +31,8 @@ type Wish struct {
type Wishes struct { type Wishes struct {
Items []Wish `json:"items"` Items []Wish `json:"items"`
Claim *hmc.Input `json:"claim,omitempty" xml:",omitempty"` Select hmc.Select
Complete *hmc.Input `json:"complete,omitempty" xml:",omitempty"` Intent hmc.Select
Delete *hmc.Input `json:"delete,omitempty" xml:",omitempty"`
} }
type Wishlist struct { type Wishlist struct {
@ -40,30 +42,24 @@ type Wishlist struct {
} }
func InitialWishlist(currentUserId string, wishes []lishwist.Wish) Wishlist { func InitialWishlist(currentUserId string, wishes []lishwist.Wish) Wishlist {
wishInputs := make([]Wish, len(wishes)) wishInputs := make([]hmc.Option, len(wishes))
items := make([]Wish, len(wishes))
for i, w := range wishes { for i, w := range wishes {
isMine := w.ClaimantId == currentUserId wsh := hmc.Option{
// createdByMe := w.CreatorId == currentUserId
// anothersIdea := w.RecipientId != w.CreatorId
wsh := Wish{
Input: hmc.Input{
Label: w.Name, Label: w.Name,
Type: "checkbox", Value: w.Id,
},
}
if isMine {
wsh.Input.Name = "claimed"
wsh.Input.Value = w.Id
} else if w.ClaimantId != "" {
wsh.Input.Disabled = true
} else {
wsh.Input.Name = "unclaimed"
wsh.Input.Value = w.Id
} }
wishInputs[i] = wsh wishInputs[i] = wsh
items[i] = Wish{
Input: hmc.Input{
Label: w.Name,
Value: w.Id,
Type: "checkbox",
Name: "wish",
},
}
} }
return Wishlist{ return Wishlist{
@ -71,12 +67,22 @@ func InitialWishlist(currentUserId string, wishes []lishwist.Wish) Wishlist {
Wishes: hmc.Form[Wishes]{ Wishes: hmc.Form[Wishes]{
Method: "POST", Method: "POST",
Elements: Wishes{ Elements: Wishes{
Items: wishInputs, Items: items,
Delete: &hmc.Input{ Select: hmc.Select{
Label: "Delete", Label: "Wishes",
Type: "submit", Multiple: true,
Name: "wish",
Required: true,
Options: wishInputs,
},
Intent: hmc.Select{
Label: "Intent",
Required: true,
Name: "intent", Name: "intent",
Options: []hmc.Option{{
Label: "Delete",
Value: "delete", Value: "delete",
}},
}, },
}, },
}, },
@ -92,6 +98,7 @@ func InitialWishlist(currentUserId string, wishes []lishwist.Wish) Wishlist {
func InitialTodo(todo []lishwist.Wish) Wishlist { func InitialTodo(todo []lishwist.Wish) Wishlist {
wishInputs := make([]Wish, len(todo)) wishInputs := make([]Wish, len(todo))
options := make([]hmc.Option, len(todo))
for i, w := range todo { for i, w := range todo {
wsh := Wish{ wsh := Wish{
@ -105,15 +112,21 @@ func InitialTodo(todo []lishwist.Wish) Wishlist {
}, },
Sent: w.Sent, Sent: w.Sent,
} }
opt := hmc.Option{
Label: w.Name,
Value: w.Id,
}
if w.Sent { if w.Sent {
wsh.Input.Disabled = true wsh.Input.Disabled = true
opt.Disabled = true
} else { } else {
wsh.Input.Name = "claimed" wsh.Input.Name = "todo"
wsh.Input.Value = w.Id wsh.Input.Value = w.Id
} }
wishInputs[i] = wsh wishInputs[i] = wsh
options[i] = opt
} }
return Wishlist{ return Wishlist{
@ -122,19 +135,45 @@ func InitialTodo(todo []lishwist.Wish) Wishlist {
Method: "POST", Method: "POST",
Elements: Wishes{ Elements: Wishes{
Items: wishInputs, Items: wishInputs,
Claim: &hmc.Input{ Select: hmc.Select{
Label: "Todos",
Multiple: true,
Name: "todo",
Required: true,
Options: options,
},
Intent: hmc.Select{
Label: "Intent",
Required: true,
Name: "intent",
Options: []hmc.Option{
{
Label: "Unclaim", Label: "Unclaim",
Type: "submit",
Name: "intent",
Value: "unclaim_todo", Value: "unclaim_todo",
}, },
Complete: &hmc.Input{ {
Label: "Complete", Label: "Complete",
Type: "submit", Value: "complete_todo",
Name: "intent", },
Value: "unclaim_todo", },
}, },
}, },
}, },
} }
} }
func (w Wishlist) ExtractFormValues(form url.Values) {
if w.NewWish != nil {
w.NewWish.Elements.ExtractFormValue(form)
}
err := w.Wishes.Elements.Select.ExtractFormValue(form)
if err != nil {
w.Wishes.Elements.Select.Error = err.Error()
}
err = w.Wishes.Elements.Intent.ExtractFormValue(form)
if err != nil {
w.Wishes.Elements.Intent.Error = err.Error()
}
}

View File

@ -3,7 +3,9 @@ package routing
import ( import (
"fmt" "fmt"
"log" "log"
"maps"
"net/http" "net/http"
"slices"
lishwist "lishwist/core" lishwist "lishwist/core"
"lishwist/http/resources" "lishwist/http/resources"
@ -15,7 +17,19 @@ import (
"github.com/Teajey/rsvp" "github.com/Teajey/rsvp"
) )
func mapKeysIntersect(a, b map[string][]string) []string {
var out []string
for k := range a {
if _, ok := b[k]; ok {
out = append(out, k)
}
}
return out
}
func Home(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { func Home(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body {
w.DefaultTemplateName("home.gotmpl")
gifts, err := app.GetWishes() gifts, err := app.GetWishes()
if err != nil { if err != nil {
log.Printf("Failed to get gifts: %s\n", err) log.Printf("Failed to get gifts: %s\n", err)
@ -39,9 +53,11 @@ func Home(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter
Href: fmt.Sprintf("groups/%s", g.Reference), Href: fmt.Sprintf("groups/%s", g.Reference),
} }
} }
navbar := templates.UserNavCollapse(user.Name, user.Reference, user.PasswordFromAdmin)
navbar.Links = nil
p := resources.HomeProps{ p := resources.HomeProps{
Namespace: hmc.NS(), Namespace: hmc.NS(),
Navbar: templates.UserNavCollapse(user.Name, user.Reference, user.PasswordFromAdmin), Navbar: navbar,
Wishlist: resources.InitialWishlist(user.Id, gifts), Wishlist: resources.InitialWishlist(user.Id, gifts),
Todo: resources.InitialTodo(todo), Todo: resources.InitialTodo(todo),
GroupsList: resources.LinksList{ GroupsList: resources.LinksList{
@ -49,21 +65,67 @@ func Home(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter
Links: groupLinks, Links: groupLinks,
}, },
} }
return response.Data("home.gotmpl", p)
if r.Method == http.MethodGet {
return rsvp.Data(p)
} }
func HomePost(app *lishwist.Session, session *session.Session, w rsvp.ResponseWriter, r *http.Request) rsvp.Body { err = r.ParseForm()
err := r.ParseForm()
if err != nil { if err != nil {
return response.Error("Failed to parse form").StatusBadRequest() p.Error = "Failed to parse form"
return rsvp.Data(p).StatusUnprocessableEntity()
} }
switch r.Form.Get("intent") { if len(r.Form) < 1 {
case "add_idea": p.Error = "No parameters provided"
return WishlistAdd(app, w, r) return rsvp.Data(p).StatusBadRequest()
case "delete_idea": }
return WishlistDelete(app, w, r)
default: wishForm := maps.Clone(r.Form)
return TodoUpdate(app, w, r) p.Wishlist.ExtractFormValues(wishForm)
p.Todo.ExtractFormValues(r.Form)
extra := mapKeysIntersect(wishForm, r.Form)
if len(extra) > 0 {
p.Warning = "Extraneous form values"
}
if p.Wishlist.Wishes.Elements.Intent.Value() == "delete" {
wishesToDelete := slices.Collect(p.Wishlist.Wishes.Elements.Select.Values())
err := app.RevokeWishes(wishesToDelete...)
if err != nil {
log.Printf("Failed to revoke wishes: %s\n", err)
p.Wishlist.Wishes.Elements.Intent.Error = "Something went wrong"
return rsvp.Data(p).StatusInternalServerError()
} }
} }
if p.Wishlist.NewWish.Elements.Value != "" {
_, err := app.MakeWish(p.Wishlist.NewWish.Elements.Value)
if err != nil {
log.Printf("Failed to make wish: %s\n", err)
p.Wishlist.NewWish.Elements.Error = "Something went wrong"
return rsvp.Data(p).StatusInternalServerError()
}
}
todosToChange := slices.Collect(p.Todo.Wishes.Elements.Select.Values())
if p.Todo.Wishes.Elements.Intent.Value() == "unclaim_todo" {
err := app.ClaimWishes([]string{}, todosToChange)
if err != nil {
log.Printf("Failed to unclaim wish: %s\n", err)
p.Todo.Wishes.Elements.Intent.Error = "Something went wrong"
return rsvp.Data(p).StatusInternalServerError()
}
} else if p.Todo.Wishes.Elements.Intent.Value() == "complete_todo" {
err := app.CompleteWishes(todosToChange)
if err != nil {
log.Printf("Failed to complete wish: %s\n", err)
p.Todo.Wishes.Elements.Intent.Error = "Something went wrong"
return rsvp.Data(p).StatusInternalServerError()
}
}
return rsvp.Data(p).StatusSeeOther(".")
}

View File

@ -72,11 +72,10 @@ func Create(useSecureCookies bool) *mux.Serve {
r.Private.HandleFunc("POST /account", routing.AccountPost) r.Private.HandleFunc("POST /account", routing.AccountPost)
r.Private.HandleFunc("POST /groups/{groupReference}", routing.GroupPost) r.Private.HandleFunc("POST /groups/{groupReference}", routing.GroupPost)
r.Private.HandleFunc("POST /home", routing.HomePost)
r.Private.HandleFunc("POST /lists/{userReference}", routing.ForeignWishlistPost) r.Private.HandleFunc("POST /lists/{userReference}", routing.ForeignWishlistPost)
r.Private.HandleFunc("POST /logout", routing.LogoutPost) r.Private.HandleFunc("POST /logout", routing.LogoutPost)
r.Private.HandleFunc("POST /users/{userReference}", routing.UserPost) r.Private.HandleFunc("POST /users/{userReference}", routing.UserPost)
r.Private.HandleFunc("POST /{$}", routing.HomePost) r.Private.HandleFunc("POST /{$}", routing.Home)
// Deprecated // Deprecated
r.HandleFunc("GET /group/{groupReference}", middleware.PrefixMovedPermanently("/group/", "/groups/")) r.HandleFunc("GET /group/{groupReference}", middleware.PrefixMovedPermanently("/group/", "/groups/"))

View File

@ -70,6 +70,7 @@
<div class="flex-grow-1"></div> <div class="flex-grow-1"></div>
{{with .User}} {{with .User}}
<ul class="navbar-nav"> <ul class="navbar-nav">
{{ if .Link -}}
<li class="nav-item"> <li class="nav-item">
<button <button
class="btn btn-success" class="btn btn-success"
@ -77,23 +78,28 @@
{{.Link.Label}} {{.Link.Label}}
</button> </button>
</li> </li>
{{ end -}}
<li class="nav-item"> <li class="nav-item">
<div class="dropdown"> <div class="dropdown">
<button class="nav-link dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"> <button class="nav-link dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
{{.Label}}{{if .Alert}} <span class="badge text-bg-danger">!</span>{{end}} {{.Label}}{{if .Alert}} <span class="badge text-bg-danger">!</span>{{end}}
</button> </button>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
{{ if .Account -}}
<li> <li>
<a class="dropdown-item" href="{{.Account.Href}}">{{.Account.Label}}{{if .Alert}} <span <a class="dropdown-item" href="{{.Account.Href}}">{{.Account.Label}}{{if .Alert}} <span
class="badge text-bg-danger">!</span>{{end}}</a> class="badge text-bg-danger">!</span>{{end}}</a>
</li> </li>
{{ end -}}
{{- with .Logout}}
<li> <li>
<form class="d-contents" method="{{.Logout.Method}}" action="{{.Logout.Action}}"> <form class="d-contents" method="{{.Method}}" action="{{.Action}}">
{{- with .Logout.Element}} {{- with .Elements}}
<button class="dropdown-item" type="{{.Type}}">{{.Label}}</button> <button class="dropdown-item" type="{{.Type}}">{{.Label}}</button>
{{- end}} {{- end}}
</form> </form>
</li> </li>
{{- end}}
</ul> </ul>
</div> </div>
</li> </li>

View File

@ -15,7 +15,7 @@
<div class="card-body"> <div class="card-body">
<h2>{{.Label}}</h2> <h2>{{.Label}}</h2>
{{with .Wishes.Elements}} {{with .Wishes.Elements}}
<form method="post" onchange="acceptNames(this, 'deleteSubmit', 'gift')" autocomplete="off"> <form method="post" onchange="acceptNames(this, 'deleteSubmit', 'wish')" autocomplete="off">
<ul class="list-group mb-3"> <ul class="list-group mb-3">
{{range .Items}} {{range .Items}}
<li class="list-group-item"> <li class="list-group-item">
@ -27,8 +27,8 @@
</li> </li>
{{end}} {{end}}
</ul> </ul>
<button id="deleteSubmit" class="btn btn-danger mb-3" type="{{.Delete.Type}}" name="{{.Delete.Name}}" value="{{.Delete.Value}}" <button id="deleteSubmit" class="btn btn-danger mb-3" name="intent" value="delete"
disabled>{{.Delete.Label}}</button> disabled>Delete</button>
</form> </form>
{{else}} {{else}}
<p>Your list is empty. Think of some things to add!</p> <p>Your list is empty. Think of some things to add!</p>
@ -53,7 +53,7 @@
<h2>{{.Label}}</h2> <h2>{{.Label}}</h2>
{{with .Wishes}} {{with .Wishes}}
<form method="{{.Method}}" <form method="{{.Method}}"
onchange="acceptNames(this, 'unclaimSubmit', 'gift'); acceptNames(this, 'completeSubmit', 'gift')" onchange="acceptNames(this, 'unclaimSubmit', 'todo'); acceptNames(this, 'completeSubmit', 'todo')"
autocomplete="off"> autocomplete="off">
{{- with .Elements}} {{- with .Elements}}
<ul class="list-group mb-3"> <ul class="list-group mb-3">
@ -76,14 +76,15 @@
</li> </li>
{{end}} {{end}}
</ul> </ul>
{{- with .Claim}} {{ range .Intent.Options -}}
<button id="unclaimSubmit" class="btn btn-warning" type="{{.Type}}" name="{{.Name}}" value="{{.Value}}" {{ if eq .Value "unclaim_todo" }}
disabled>{{.Label}}</button> <button id="unclaimSubmit" class="btn btn-warning" name="intent" value="unclaim_todo"
{{- end}} disabled>Unclaim</button>
{{- with .Complete}} {{ else if eq .Value "complete_todo" -}}
<button id="completeSubmit" class="btn btn-success" type="{{.Type}}" name="{{.Name}}" value="{{.Value}}" <button id="completeSubmit" class="btn btn-success" name="intent" value="complete_todo"
disabled>{{.Label}}</button> disabled>Complete</button>
{{- end}} {{ end -}}
{{ end -}}
{{- end}} {{- end}}
</form> </form>
{{else}} {{else}}

View File

@ -27,6 +27,7 @@ func DefaultNavCollapse() NavCollapse {
func UserNavCollapse(username, reference string, accountAlert bool) NavCollapse { func UserNavCollapse(username, reference string, accountAlert bool) NavCollapse {
return NavCollapse{ return NavCollapse{
Links: []hmc.Link{{Href: "/", Label: "Home"}},
User: &NavUser{ User: &NavUser{
Label: fmt.Sprintf("Logged in as '%s'", username), Label: fmt.Sprintf("Logged in as '%s'", username),
Alert: accountAlert, Alert: accountAlert,