ratings

package
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

Package ratings - star ratings of content: a voter's vote for a content item, its average and count on the item's page (the node_rating block) and in Views (the module's sorts, filters and field). Which types are rated, the scale and whether a vote may change are the module's settings; who may vote - the "rate content" permission, and guests when the settings let them.

Index

Constants

View Source
const (
	MinScale     = 3
	MaxScale     = 10
	DefaultScale = 5
)

The scale a site may set (Settings.Scale).

Variables

View Source
var (
	// ErrNotRated - the node's type isn't rated, or the node can't be seen.
	ErrNotRated = errors.New("this content is not rated")
	// ErrScore - not a score of the scale.
	ErrScore = errors.New("not a score of the scale")
	// ErrFinal - the voter has voted and votes can't change.
	ErrFinal = errors.New("a vote can't be changed")
	// ErrWithdraw - votes can't be taken back.
	ErrWithdraw = errors.New("a vote can't be taken back")
)

The errors of voting (Service.Vote/Withdraw).

View Source
var Assets embed.FS

Assets - the module's templates/ and static/, built into the binary (modules.Assets, paths.SetModuleAssets): a site runs without the module's source directory.

Functions

func RegisterAdminRoutes

func RegisterAdminRoutes(r modulekit.Mux, c *Controller, admin func(http.Handler) http.Handler)

RegisterAdminRoutes registers the settings page (administrators).

func RegisterHooks

func RegisterHooks(s *Service, logger *slog.Logger)

RegisterHooks adds the module's section of the content type form and its data of node pages (wiring, at startup).

func RegisterRoutes

func RegisterRoutes(r modulekit.Mux, store *sessions.CookieStore, c *Controller, voteRL *ratelimit.RateLimiter)

RegisterRoutes registers the widget of a content page and its votes (any visitor, the votes rate limited per client IP).

func ValidScale

func ValidScale(n int) bool

ValidScale - whether n is a scale the site may set.

func Weighted

func Weighted(s Stats, siteShare float64, minVotes int) float64

Weighted - the share a top list ranks by: the node's average pulled to the site's (siteShare) while it has fewer votes than minVotes - two fives don't outrank forty votes of 4.8. A Bayesian average: (v·R + m·C) / (v + m).

func Wire

func Wire(d modulekit.Deps) modulekit.Parts

Wire - the module's service, its hooks (the content type form, node pages), its criteria in Views, the settings page and the votes (modulekit).

Types

type Controller

type Controller struct {
	*modulekit.BaseController
	// contains filtered or unexported fields
}

Controller - the module's settings page and the rating widget of a content page: its fragment and the votes.

func NewController

func NewController(deps modulekit.BaseDeps, ratings *Service, nodes nodeLoader, types typeLabels) *Controller

NewController creates the controller.

func (*Controller) SettingsPage

func (c *Controller) SettingsPage(w http.ResponseWriter, r *http.Request)

SettingsPage handles GET/POST /admin/config/ratings: the scale, whether a vote can change and be taken back, the rated content types.

func (*Controller) Vote

func (c *Controller) Vote(w http.ResponseWriter, r *http.Request)

Vote handles POST /node/{id}/rating: the visitor's score ("score") or taking theirs back ("withdraw"). A script gets the new widget as JSON ({"html"}, or {"error"} with a status); a form is sent back to the node's page.

func (*Controller) Widget

func (c *Controller) Widget(w http.ResponseWriter, r *http.Request)

Widget handles GET /node/{id}/rating: the widget of the node's page with the visitor's own vote, which the node_rating block loads (the page may be cached).

type Repository

type Repository struct {
	// contains filtered or unexported fields
}

Repository - the module's tables: its settings, the rated types, the votes (a type's count joins the core's nodes). A built-in module, tested with the engine, may read the core's tables in its SQL; a module of its own repository goes through the SDK's services instead (docs/modules/sdk.md): the core's columns aren't its API.

func NewRepository

func NewRepository(db *sql.DB) *Repository

NewRepository creates the repository on db.

func (*Repository) DeleteVote

func (r *Repository) DeleteVote(ctx context.Context, nid int, v Voter) error

DeleteVote takes voter's vote for nid back.

func (*Repository) RatedTypes

func (r *Repository) RatedTypes(ctx context.Context) ([]string, error)

RatedTypes - the machine names of the rated content types.

func (*Repository) SaveSettings

func (r *Repository) SaveSettings(ctx context.Context, s Settings) error

SaveSettings writes the module's settings (its row made if missing).

func (*Repository) SaveVote

func (r *Repository) SaveVote(ctx context.Context, nid int, v Voter, vote Vote) error

SaveVote sets voter's vote for nid, replacing theirs.

func (*Repository) SetTypeRated

func (r *Repository) SetTypeRated(ctx context.Context, contentType string, on bool) error

SetTypeRated switches rating content of contentType on or off (its votes stay).

func (*Repository) Settings

func (r *Repository) Settings(ctx context.Context) (Settings, error)

Settings - the module's settings (the defaults without the row).

func (*Repository) SiteShare

func (r *Repository) SiteShare(ctx context.Context) (float64, error)

SiteShare - the average share of every vote on the site (0 - none).

func (*Repository) Stats

func (r *Repository) Stats(ctx context.Context, ids []int) (map[int]Stats, error)

Stats - the votes of each node among ids that has any.

func (*Repository) TypeTotals

func (r *Repository) TypeTotals(ctx context.Context, contentType string) (votes, nodes int, err error)

TypeTotals - the votes of contentType's nodes and how many nodes have them.

func (*Repository) VoteOf

func (r *Repository) VoteOf(ctx context.Context, nid int, v Voter) (Vote, bool, error)

VoteOf - voter's vote for nid; false - none.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service - voting and what a page shows of a node's rating.

func NewService

func NewService(repo *Repository) *Service

NewService creates the service on repo.

func (*Service) Averages

func (s *Service) Averages(ctx context.Context, ids []int) (map[int]float64, error)

Averages - the average on the scale of each node among ids that has votes.

func (*Service) Counts

func (s *Service) Counts(ctx context.Context, ids []int) (map[int]float64, error)

Counts - the votes of every node among ids (0 - none).

func (*Service) MayRate

func (s *Service) MayRate(ctx context.Context, guest, userAllowed bool) (bool, error)

MayRate - whether the visitor may rate: a user with the permission (userAllowed), a guest when guests may.

func (*Service) Rated

func (s *Service) Rated(ctx context.Context, nodeType string) (bool, error)

Rated - whether content of nodeType is rated.

func (*Service) RatedTypes

func (s *Service) RatedTypes(ctx context.Context) ([]string, error)

RatedTypes - the machine names of the rated content types.

func (*Service) SaveSettings

func (s *Service) SaveSettings(ctx context.Context, st Settings) error

SaveSettings writes the module's settings (a scale out of range - the default).

func (*Service) SetRatedTypes

func (s *Service) SetRatedTypes(ctx context.Context, all []string, on []string) error

SetRatedTypes rates exactly the types of on among all (the others of all switched off).

func (*Service) SetTypeRated

func (s *Service) SetTypeRated(ctx context.Context, contentType string, on bool) error

SetTypeRated switches rating of one content type on or off (its votes stay).

func (*Service) Settings

func (s *Service) Settings(ctx context.Context) (Settings, error)

Settings - the module's settings.

func (*Service) Summaries

func (s *Service) Summaries(ctx context.Context, ids []int, look string) (map[int]Summary, error)

Summaries - the summary of each node among ids that has votes.

func (*Service) TypeTotals

func (s *Service) TypeTotals(ctx context.Context, contentType string) (votes, nodes int, err error)

TypeTotals - the votes of contentType's content and how many items have them.

func (*Service) Vote

func (s *Service) Vote(ctx context.Context, node modulekit.Node, v Voter, score int) error

Vote gives voter's score (1 to the scale) to node, replacing their vote while votes may change (the same score again is no change).

func (*Service) WeightedAverages

func (s *Service) WeightedAverages(ctx context.Context, ids []int, minVotes int) (map[int]float64, error)

WeightedAverages - the weighted rating on the scale (Weighted) of each node among ids that has votes; minVotes - the votes a node needs to count fully.

func (*Service) WidgetFor

func (s *Service) WidgetFor(ctx context.Context, node modulekit.Node, v Voter, allowed, logIn bool) (Widget, bool, error)

WidgetFor - node's widget for the visitor (v, may rate: allowed; logIn - a guest who may not, offered to log in); false - its type isn't rated.

func (*Service) Withdraw

func (s *Service) Withdraw(ctx context.Context, node modulekit.Node, v Voter) error

Withdraw takes voter's vote for node back, while votes may be taken back.

type Settings

type Settings struct {
	// Scale - the stars of a vote. Votes keep the scale they were given
	// on: changing it keeps each vote's share (4 of 5 is 8 of 10).
	Scale int
	// AllowGuests - guests may rate (each by their session), besides the
	// users with the "rate content" permission.
	AllowGuests   bool
	AllowChange   bool
	AllowWithdraw bool
}

Settings - the module's settings.

func DefaultSettings

func DefaultSettings() Settings

DefaultSettings - the settings of a new install.

type Stats

type Stats struct {
	Count int
	Share float64
}

Stats - a node's votes: how many, and their average as a share of the scale (0 to 1), so the site's scale may change.

func (Stats) Average

func (s Stats) Average(scale int) float64

Average - the average on scale.

type Summary

type Summary struct {
	Scale   int
	Count   int
	Average string
	Fill    float64
	// Look - what the field shows (lookFull, lookAverage, lookCount).
	Look string
}

Summary - the average and count of a node, as a View's field shows them.

type Vote

type Vote struct {
	Score int
	Scale int
}

Vote - a voter's vote: score stars of the scale it was given on.

func (Vote) On

func (v Vote) On(scale int) int

On - the vote on scale, rounded to a whole star (at least 1).

type Voter

type Voter struct {
	UserID int
	Guest  string
}

Voter - who votes: a user, or a guest by their key (Guest; the hash of their browser's cookie).

func (Voter) Known

func (v Voter) Known() bool

Known - whether the voter can be told apart (a user, or a guest with a key).

type Widget

type Widget struct {
	NodeID int
	// NodeURL - the node's address (the log in link's destination).
	NodeURL string
	Scale   int
	Count   int
	// Average - the average on the scale, formatted ("4.6"); Fill - the
	// share of the stars filled, in percent.
	Average string
	Fill    float64
	// Stars - 1 to Scale, the vote buttons.
	Stars []int
	// Mine - the visitor's vote on the scale (0 - none).
	Mine int
	// CanVote - the visitor may rate (and hasn't voted, or may change
	// it); CanWithdraw - may take theirs back; LogIn - a guest who may
	// not rate, offered to log in.
	CanVote     bool
	CanWithdraw bool
	LogIn       bool
}

Widget - what the node_rating block shows: the average and the count, the visitor's own vote and what they may do.

Directories

Path Synopsis
ent
Package ent - the ratings module's own ent schema (schema/), its generated client (generated/, go generate) and migration files (migrations/<dialect>/, scripts/migrations_gen.sh writes them), apart from the core's: the module's set of migrations (Schema).
Package ent - the ratings module's own ent schema (schema/), its generated client (generated/, go generate) and migration files (migrations/<dialect>/, scripts/migrations_gen.sh writes them), apart from the core's: the module's set of migrations (Schema).
Package manifest declares the ratings module (its registry entry).
Package manifest declares the ratings module (its registry entry).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL