Web polls #12

Merged
noah merged 2 commits from polls into main 2022-12-21 03:19:24 +00:00
17 changed files with 16701 additions and 13 deletions

View File

@ -98,6 +98,26 @@ const (
ThreadViewDebounceCooldown = 1 * time.Hour
)
// Poll settings
var (
// Max number of responses to accept for a poll (how many form
// values the app will read in). NOTE: also enforced in frontend
// UX in new_post.html, update there if you change this.
PollMaxAnswers = 100
// Poll color CSS classes (Bulma). Plugged in to templates like:
// <progress class="$CLASS">
// Values will wrap around for long polls.
PollProgressBarClasses = []string{
"progress is-success",
"progress is-link",
"progress is-warning",
"progress is-danger",
"progress is-primary",
"progress is-info",
}
)
// Variables set by main.go to make them readily available.
var (
RuntimeVersion string

View File

@ -9,6 +9,7 @@ import (
"path/filepath"
"strconv"
"code.nonshy.com/nonshy/website/pkg/config"
"code.nonshy.com/nonshy/website/pkg/log"
"code.nonshy.com/nonshy/website/pkg/markdown"
"code.nonshy.com/nonshy/website/pkg/models"
@ -45,6 +46,12 @@ func NewPost() http.HandlerFunc {
// well (pinned, explicit, noreply)
isOriginalComment bool
// Polls
pollOptions = []string{}
pollExpires = 3
pollMultipleChoice = r.FormValue("poll_multiple_choice") == "true"
isPoll bool
// Attached photo object.
commentPhoto *models.CommentPhoto
)
@ -171,6 +178,29 @@ func NewPost() http.HandlerFunc {
// Submitting the form.
if r.Method == http.MethodPost {
// Polls: parse form parameters into a neat list of answers.
pollExpires, _ = strconv.Atoi(r.FormValue("poll_expires"))
var distinctPollChoices = map[string]interface{}{}
for i := 0; i < config.PollMaxAnswers; i++ {
if value := r.FormValue(fmt.Sprintf("answer%d", i)); value != "" {
pollOptions = append(pollOptions, value)
isPoll = len(pollOptions) >= 2
// Make sure every option is distinct!
if _, ok := distinctPollChoices[value]; ok {
session.FlashError(w, r, "Your poll options must all be unique! Duplicate option '%s' seen in your post!", value)
intent = "preview" // do not continue to submit
}
distinctPollChoices[value] = nil
}
}
// If only one poll option, warn about it.
if len(pollOptions) == 1 {
session.FlashError(w, r, "Your poll should have at least two choices.")
intent = "preview" // do not continue to submit
}
// Is a photo coming along?
if forum.PermitPhotos {
// Removing or replacing?
@ -356,6 +386,22 @@ func NewPost() http.HandlerFunc {
}
}
// Are we attaching a poll to this new thread?
if isPoll {
log.Info("It's a Poll! Options: %+v", pollOptions)
poll := models.CreatePoll(pollOptions, pollExpires)
poll.MultipleChoice = pollMultipleChoice
if err := poll.Save(); err != nil {
session.FlashError(w, r, "Error creating poll: %s", err)
}
// Attach it to this thread.
thread.PollID = &poll.ID
if err := thread.Save(); err != nil {
log.Error("Couldn't save PollID onto thread! %s", err)
}
}
// Subscribe the current user to responses on this thread.
if _, err := models.SubscribeTo(currentUser, "threads", thread.ID); err != nil {
log.Error("Couldn't subscribe user %d to forum thread %d: %s", currentUser.ID, thread.ID, err)
@ -381,6 +427,9 @@ func NewPost() http.HandlerFunc {
"IsExplicit": isExplicit,
"IsNoReply": isNoReply,
// Polls
"PollOptions": pollOptions,
// Attached photo.
"CommentPhoto": commentPhoto,
}

View File

@ -0,0 +1,91 @@
package poll
import (
"fmt"
"net/http"
"strconv"
"code.nonshy.com/nonshy/website/pkg/models"
"code.nonshy.com/nonshy/website/pkg/session"
"code.nonshy.com/nonshy/website/pkg/templates"
)
// Vote controller for polls.
func Vote() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
// Form parameters
pollID uint64
fromThreadID uint64
answers = r.Form["answer"] // a slice in case of MultipleChoice
nextURL string
)
// Parse integer params.
if value, err := strconv.Atoi(r.FormValue("poll_id")); err != nil {
session.FlashError(w, r, "Invalid poll ID")
templates.Redirect(w, "/")
return
} else {
pollID = uint64(value)
}
// Currently polls only exist in forum threads, require the thread ID.
if value, err := strconv.Atoi(r.FormValue("from_thread_id")); err != nil {
session.FlashError(w, r, "Invalid thread ID")
templates.Redirect(w, "/")
return
} else {
fromThreadID = uint64(value)
nextURL = fmt.Sprintf("/forum/thread/%d", fromThreadID)
}
// POST request only.
if r.Method != http.MethodPost {
session.FlashError(w, r, "POST requests only.")
templates.Redirect(w, nextURL)
return
}
// An answer is required.
if len(answers) == 0 || len(answers) == 1 && answers[0] == "" {
session.FlashError(w, r, "An answer to this poll is required for voting.")
templates.Redirect(w, nextURL)
return
}
// Get the current user.
user, err := session.CurrentUser(r)
if err != nil {
session.FlashError(w, r, "Unexpected error: couldn't get CurrentUser")
templates.Redirect(w, nextURL)
return
}
// Look up the poll.
poll, err := models.GetPoll(pollID)
if err != nil {
session.FlashError(w, r, "Poll not found.")
templates.Redirect(w, nextURL)
return
}
// Is it accepting responses?
result := poll.Result(user)
if !result.AcceptingVotes {
session.FlashError(w, r, "This poll is not accepting your vote at this time.")
templates.Redirect(w, nextURL)
return
}
// Cast the vote!
if err := poll.CastVote(user, answers); err != nil {
session.FlashError(w, r, "Couldn't cast the vote: %s", err)
templates.Redirect(w, nextURL)
return
}
session.Flash(w, r, "Your vote has been recorded!")
templates.Redirect(w, nextURL)
})
}

View File

@ -35,7 +35,7 @@ func PaginateRecentPosts(user *User, categories []string, pager *Pagination) ([]
// Hide explicit forum if user hasn't opted into it.
if !user.Explicit && !user.IsAdmin {
wheres = append(wheres, "explicit = false")
wheres = append(wheres, "forums.explicit = false")
}
// Get the page of recent forum comment IDs of all time.

View File

@ -24,4 +24,6 @@ func AutoMigrate() {
DB.AutoMigrate(&Notification{})
DB.AutoMigrate(&Subscription{})
DB.AutoMigrate(&CommentPhoto{})
DB.AutoMigrate(&Poll{})
DB.AutoMigrate(&PollVote{})
}

135
pkg/models/poll.go Normal file
View File

@ -0,0 +1,135 @@
package models
import (
"fmt"
"strings"
"time"
"code.nonshy.com/nonshy/website/pkg/config"
)
// Poll table for user surveys posted in the forums.
type Poll struct {
ID uint64 `gorm:"primaryKey"`
// Poll options
Choices string // line-separated choices
MultipleChoice bool // User can vote multiple choices
CustomAnswers bool // Users can contribute a custom response
Expires bool // if it stops accepting new votes
ExpiresAt time.Time // when it stops accepting new votes
CreatedAt time.Time
UpdatedAt time.Time
}
// CreatePoll initializes a poll.
//
// expires is in days (0 = doesn't expire)
func CreatePoll(choices []string, expires int) *Poll {
return &Poll{
Choices: strings.Join(choices, "\n"),
Expires: expires > 0,
ExpiresAt: time.Now().Add(time.Duration(expires) * 24 * time.Hour),
}
}
// GetPoll by ID.
func GetPoll(id uint64) (*Poll, error) {
m := &Poll{}
result := DB.First(&m, id)
return m, result.Error
}
// Options returns a conveniently formatted listing of the options.
func (p *Poll) Options() []string {
return strings.Split(p.Choices, "\n")
}
// IsExpired returns if the poll has ended.
func (p *Poll) IsExpired() bool {
return p.Expires && time.Now().After(p.ExpiresAt)
}
// InputType returns "radio" or "checkbox" for multiple choice polls.
func (p *Poll) InputType() string {
if p.MultipleChoice {
return "checkbox"
}
return "radio"
}
// Result returns metadata about a poll's status and results, for frontend assist.
func (p *Poll) Result(currentUser *User) PollResult {
var (
result = PollResult{
AcceptingVotes: true,
CurrentUserVote: []string{},
Results: map[string]int{},
ResultsPercent: map[string]float64{},
ResultsClass: map[string]string{},
}
votes = p.GetAllVotes()
distinctAnswers int
)
// Populate the CSS classes.
for i, answer := range p.Options() {
result.ResultsClass[answer] = config.PollProgressBarClasses[i%len(config.PollProgressBarClasses)]
}
result.TotalVotes = len(votes)
for _, res := range votes {
if res.UserID == currentUser.ID {
result.CurrentUserVote = append(result.CurrentUserVote, res.Answer)
result.AcceptingVotes = false
}
if _, ok := result.Results[res.Answer]; !ok {
distinctAnswers++
result.Results[res.Answer] = 0
result.ResultsPercent[res.Answer] = 0
}
result.Results[res.Answer]++
}
// Compute the percent splits.
if result.TotalVotes > 0 {
for answer, count := range result.Results {
result.ResultsPercent[answer] = float64(count) / float64(result.TotalVotes)
}
}
// Expired polls don't accept answers.
if p.IsExpired() {
result.AcceptingVotes = false
}
return result
}
// Save Poll.
func (p *Poll) Save() error {
result := DB.Save(p)
return result.Error
}
// PollResult holds metadata about the poll result for frontend display.
type PollResult struct {
AcceptingVotes bool // user voted or it expired
CurrentUserVote []string // current user's selection, if any
Results map[string]int // answers and their %
ResultsPercent map[string]float64
ResultsClass map[string]string // progress bar classes
TotalVotes int
}
func (pr PollResult) GetPercent(answer string) string {
value := pr.ResultsPercent[answer]
return fmt.Sprintf("%.1f", value*100)
}
func (pr PollResult) GetClass(answer string) string {
return pr.ResultsClass[answer]
}

68
pkg/models/poll_votes.go Normal file
View File

@ -0,0 +1,68 @@
package models
import (
"errors"
"time"
"code.nonshy.com/nonshy/website/pkg/log"
)
// PollVote table records answers to polls.
type PollVote struct {
ID uint64 `gorm:"primaryKey"`
PollID uint64 `gorm:"index"`
Poll Poll
UserID uint64 `gorm:"index"`
Answer string
CreatedAt time.Time
UpdatedAt time.Time
}
// CastVote on a poll. Multiple answers OK for multiple choice polls.
func (p *Poll) CastVote(user *User, answers []string) error {
if len(answers) > 1 && !p.MultipleChoice {
return errors.New("multiple answers not accepted for this poll")
}
// If this user has already voted, remove their vote.
result := DB.Where(
"poll_id = ? AND user_id = ?",
p.ID, user.ID,
).Delete(&PollVote{})
if result.Error != nil {
return result.Error
}
// Insert their votes.
var err error
for _, answer := range answers {
vote := &PollVote{
PollID: p.ID,
UserID: user.ID,
Answer: answer,
}
err = vote.Save()
}
return err
}
// GetAllVotes for a poll.
func (p *Poll) GetAllVotes() []*PollVote {
var pv = []*PollVote{}
result := DB.Where(
"poll_id = ?", p.ID,
).Find(&pv)
if result.Error != nil {
log.Error("Poll(%d).GetAllVotes(): %s", p.ID, result.Error)
}
return pv
}
// Save Poll.
func (v *PollVote) Save() error {
result := DB.Save(v)
return result.Error
}

View File

@ -23,6 +23,8 @@ type Thread struct {
Title string
CommentID uint64 `gorm:"index"`
Comment Comment // first comment of the thread
PollID *uint64 `gorm:"poll_id"`
Poll Poll // if the thread has a poll attachment
Views uint64
CreatedAt time.Time
UpdatedAt time.Time
@ -30,7 +32,7 @@ type Thread struct {
// Preload related tables for the forum (classmethod).
func (f *Thread) Preload() *gorm.DB {
return DB.Preload("Forum").Preload("Comment.User.ProfilePhoto")
return DB.Preload("Forum").Preload("Comment.User.ProfilePhoto").Preload("Poll")
}
// GetThread by ID.

View File

@ -15,6 +15,7 @@ import (
"code.nonshy.com/nonshy/website/pkg/controller/inbox"
"code.nonshy.com/nonshy/website/pkg/controller/index"
"code.nonshy.com/nonshy/website/pkg/controller/photo"
"code.nonshy.com/nonshy/website/pkg/controller/poll"
"code.nonshy.com/nonshy/website/pkg/middleware"
)
@ -67,6 +68,7 @@ func New() http.Handler {
mux.Handle("/forum/thread/", middleware.CertRequired(forum.Thread()))
mux.Handle("/forum/newest", middleware.CertRequired(forum.Newest()))
mux.Handle("/f/", middleware.CertRequired(forum.Forum()))
mux.Handle("/poll/vote", middleware.CertRequired(poll.Vote()))
// Admin endpoints.
mux.Handle("/admin", middleware.AdminRequired(admin.Dashboard()))

View File

@ -1,6 +1,7 @@
package templates
import (
"encoding/json"
"fmt"
"html/template"
"net/http"
@ -28,6 +29,7 @@ func TemplateFuncs(r *http.Request) template.FuncMap {
"ComputeAge": utility.Age,
"Split": strings.Split,
"ToMarkdown": ToMarkdown,
"ToJSON": ToJSON,
"PhotoURL": photo.URLPath,
"Now": time.Now,
"PrettyTitle": func() template.HTML {
@ -77,6 +79,15 @@ func ToMarkdown(input string) template.HTML {
return template.HTML(markdown.Render(input))
}
// ToJSON will stringify any json-serializable object.
func ToJSON(v any) template.JS {
bin, err := json.Marshal(v)
if err != nil {
return template.JS(err.Error())
}
return template.JS(string(bin))
}
// Pluralize text based on a quantity number. Provide up to 2 labels for the
// singular and plural cases, or the defaults are "", "s"
func Pluralize[V Number](count V, labels ...string) string {

View File

@ -8,6 +8,11 @@ import (
// FormatDurationCoarse returns a pretty printed duration with coarse granularity.
func FormatDurationCoarse(duration time.Duration) string {
// Negative durations (e.g. future dates) should work too.
if duration < 0 {
duration *= -1
}
var result = func(text string, v int64) string {
if v == 1 {
text = strings.TrimSuffix(text, "s")

16081
web/static/js/vue-3.2.45.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,5 @@
{{define "title"}}Untitled{{end}}
{{define "scripts"}}{{end}}
{{define "base"}}
<!DOCTYPE html>
<html lang="en">
@ -306,6 +307,8 @@
<script type="text/javascript" src="/static/js/bulma.js?build={{.BuildHash}}"></script>
<script type="text/javascript" src="/static/js/likes.js?build={{.BuildHash}}"></script>
<script type="text/javascript" src="/static/js/vue-3.2.45.js"></script>
{{template "scripts" .}}
</body>
</html>

View File

@ -105,6 +105,13 @@
</span>
{{end}}
{{if .PollID}}
<span class="tag is-info is-light mr-2">
<span class="icon"><i class="fa fa-poll"></i></span>
<span>Poll</span>
</span>
{{end}}
{{if .Explicit}}
<span class="tag is-danger is-light mr-2">
<span class="icon"><i class="fa fa-fire"></i></span>

View File

@ -8,7 +8,7 @@
{{end}}
{{end}}
{{define "content"}}
<div class="container">
<div class="container" id="app">
<section class="hero is-info is-bold">
<div class="hero-body">
<div class="container">
@ -81,6 +81,80 @@
</p>
</div>
{{if and (not .EditCommentID) (not .Thread)}}
<div class="field block">
<label for="message" class="label">Poll <span class="tag is-success">NEW!</span></label>
<div v-if="pollVisible">
<!-- MultipleChoice option -->
<div class="mb-2">
<label class="checkbox">
<input type="checkbox"
name="poll_multiple_choice"
value="true">
<small class="ml-2">Allow multiple selections per vote</small>
</label>
</div>
<!-- Answer rows -->
<div v-for="(answer, i) in answers"
v-bind:key="i"
class="columns mb-0 is-mobile">
<div class="column pr-0">
<input type="text"
class="input"
v-model="answer.value"
:name="'answer'+i"
:placeholder="`Option ${i+1}`">
</div>
<div class="column pl-2 is-narrow">
<button type="button"
class="button is-danger is-outlined"
@click="removeOption(i)">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
<!-- Add option -->
<div v-if="answers.length < answersLimit">
<button type="button"
class="button is-small is-success is-outlined"
@click="addOption()">
<i class="fa fa-plus mr-3"></i>
Add another option
</button>
</div>
<!-- Settings -->
<div class="columns mt-2 mb-0 is-mobile">
<div class="column is-narrow">
<small>Poll expires:</small>
</div>
<div class="column">
<div class="select is-small is-fullwidth">
<select v-model="expires"
name="poll_expires">
<option :value="0">Never</option>
<option :value="1">1 Day</option>
<option :value="2">2 Days</option>
<option :value="3">3 Days</option>
<option :value="4">4 Days</option>
<option :value="5">5 Days</option>
<option :value="6">6 Days</option>
<option :value="7">7 Days</option>
</select>
</div>
</div>
</div>
</div>
<div v-else>
<button type="button"
class="button is-success is-small"
@click="pollVisible = true">Make this a poll</button>
</div>
</div>
{{end}}
<!-- Photo attachment widget -->
{{if .Forum.PermitPhotos}}
<!-- Intent: upload, remove, or replace -->
@ -133,6 +207,8 @@
</div>
{{end}}
<hr>
{{if or (not .Thread) .EditThreadSettings}}
<div class="field block">
{{if or .CurrentUser.IsAdmin (and .Forum (eq .Forum.OwnerID .CurrentUser.ID))}}
@ -277,4 +353,64 @@
{{end}}
</div>
{{end}}
{{define "scripts"}}
<script type="text/javascript">
const { createApp } = Vue;
// Some help from backend..
const pollOptions = {{ ToJSON .PollOptions }};
const app = createApp({
delimiters: ['[[', ']]'],
data() {
return {
pollVisible: pollOptions.length > 0,
answers: [
{value: ""},
{value: ""},
],
expires: 3, // days
answersLimit: 100,
}
},
mounted() {
// Set the posted poll options.
if (pollOptions.length > 0) {
this.answers = [];
for (let row of pollOptions) {
this.answers.push({value: row});
}
}
},
methods: {
addOption() {
console.log(this.answers);
if (this.answers.length < this.answersLimit) {
this.answers.push({value: ""});
}
},
removeOption(idx) {
if (this.answers.length <= 2) {
if (!window.confirm("A poll needs at least two options. Remove the poll?")) {
return;
}
this.removePoll();
return;
}
this.answers.splice(idx, 1);
},
removePoll() {
this.answers = [
{value: ""},
{value: ""},
],
this.pollVisible = false;
}
},
});
app.mount("#app");
</script>
{{end}}

View File

@ -81,6 +81,10 @@
<sup class="has-text-success fa fa-thumbtack is-size-6 ml-1"></sup>
{{end}}
{{if .Thread.PollID}}
<sup class="has-text-info fa fa-poll is-size-6 ml-1"></sup>
{{end}}
{{if .Thread.Explicit}}
<sup class="has-text-danger fa fa-fire is-size-6 ml-1"></sup>
{{end}}

View File

@ -119,17 +119,17 @@
{{$Root := .}}
<div class="block p-2">
{{range .Comments}}
{{range $i, $c := .Comments}}
<div class="box has-background-link-light">
<div class="columns">
<div class="column is-2 has-text-centered">
<div>
<a href="/u/{{.User.Username}}">
{{template "avatar-96x96" .User}}
<a href="/u/{{$c.User.Username}}">
{{template "avatar-96x96" $c.User}}
</a>
</div>
<a href="/u/{{.User.Username}}">{{.User.Username}}</a>
{{if .User.IsAdmin}}
<a href="/u/{{$c.User.Username}}">{{$c.User.Username}}</a>
{{if $c.User.IsAdmin}}
<div class="is-size-7 mt-1">
<span class="tag is-danger is-light">
<span class="icon"><i class="fa fa-gavel"></i></span>
@ -139,18 +139,90 @@
{{end}}
</div>
<div class="column content">
{{ToMarkdown .Message}}
{{ToMarkdown $c.Message}}
{{if .IsEdited}}
{{if $c.IsEdited}}
<div class="mt-4">
<em title="{{.UpdatedAt.Format "2006-01-02 15:04:05"}}">
<small>Edited {{SincePrettyCoarse .UpdatedAt}} ago</small>
<em title="{{$c.UpdatedAt.Format "2006-01-02 15:04:05"}}">
<small>Edited {{SincePrettyCoarse $c.UpdatedAt}} ago</small>
</em>
</div>
{{end}}
<!-- Poll attachment? -->
{{if and (eq $i 0) $Root.Thread.PollID}}
<h2>Poll</h2>
<!-- Get the results -->
{{$Poll := $Root.Thread.Poll}}
{{$PollResult := $Poll.Result $Root.CurrentUser}}
<form name="ballot" action="/poll/vote" method="POST">
{{InputCSRF}}
<input type="hidden" name="poll_id" value="{{$Root.Thread.PollID}}">
<input type="hidden" name="from_thread_id" value="{{$Root.Thread.ID}}">
<!-- Poll is open? -->
{{if $PollResult.AcceptingVotes}}
{{range $Poll.Options}}
<div class="control">
<label class="{{$Poll.InputType}} box nonshy-fullwidth p-3 mb-3">
<input type="{{$Poll.InputType}}"
name="answer"
value="{{.}}">
{{.}}
</label>
</div>
{{end}}
{{if $Poll.MultipleChoice}}
<div class="mt-2 mb-4">
<strong>Multiple choice:</strong> select all the answers you want before casting your vote!
</div>
{{end}}
<div class="mb-4">
{{if and ($Poll.Expires) (not $Poll.IsExpired)}}
Poll expires in about <span title="{{$Poll.ExpiresAt.Format "2006-01-02 15:04:05"}}">{{SincePrettyCoarse $Root.Thread.Poll.ExpiresAt}}</span>.
Vote or wait to see the responses.
{{else}}
Poll doesn't expire. Vote to see the responses.
{{end}}
</div>
<button type="submit"
class="button is-primary is-outline">
Submit response
</button>
{{else}}
{{range $Poll.Options}}
<div class="columns mb-0">
<div class="column is-one-quarter">
{{.}}
</div>
<div class="column">
<progress class="{{$PollResult.GetClass .}}" value="{{$PollResult.GetPercent .}}" max="100">{{$PollResult.GetPercent .}}%</progress>
</div>
<div class="column is-1">
{{$PollResult.GetPercent .}}%
</div>
</div>
{{end}}
<em>
{{$PollResult.TotalVotes}} vote{{Pluralize $PollResult.TotalVotes}}.
{{if $Poll.IsExpired}}
Poll ended <span title="{{$Poll.ExpiresAt.Format "2006-01-02 15:04:05"}}">{{SincePrettyCoarse $Root.Thread.Poll.ExpiresAt}} ago</span>.
{{end}}
</em>
{{end}}
</form>
{{end}}
<!-- Photo attachments? -->
{{$Photos := $Root.PhotoMap.Get .ID}}
{{$Photos := $Root.PhotoMap.Get $c.ID}}
{{if $Photos}}
{{range $Photos}}
{{if not .ExpiredAt.IsZero}}