Add saved layouts, and make /stp an ordinary canvas page
A layout is a named copy of one canvas page's boxes and background (models.Layout, layout.graphql), saved from the canvas's new Layouts button and loaded onto any page from there or from the admin Pages tab. Loading onto a page with boxes asks whether to replace them or add on top; a replace first saves the page as a "<page> before <layout>" layout so it can be undone. Copies, not links: editing a page never changes a layout or another page. The copying is server-side in one transaction, and everything is @admin since a layout keeps admin-only boxes. /stp loses its static route and becomes a Page with slug "stp", created once at start-up (ensureStpPage), so it can be renamed, hidden or deleted like a shrine. Its boxes were already keyed "stp". Home3.vue is kept as legacy; its starter is now "Old /stp grid" in pageStarters.js. ConfirmDialog gains an optional second button. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -187,9 +187,10 @@ func TestSignedInMutationsArePinned(t *testing.T) {
|
||||
// `spotifyNeedsReauth` is false for non-admins.
|
||||
func TestGuardedQueriesArePinned(t *testing.T) {
|
||||
want := map[string]string{
|
||||
"users": "admin",
|
||||
"user": "admin",
|
||||
"places": "signedIn",
|
||||
"users": "admin",
|
||||
"user": "admin",
|
||||
"places": "signedIn",
|
||||
"layouts": "admin",
|
||||
}
|
||||
got := map[string]string{}
|
||||
for _, field := range schemaUnderTest().Query.Fields {
|
||||
|
||||
+943
-1
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,144 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// BoxCount is the resolver for the boxCount field.
|
||||
func (r *layoutResolver) BoxCount(ctx context.Context, obj *models.Layout) (int, error) {
|
||||
// Decoded rather than stored, so it can never disagree with the boxes.
|
||||
boxes, err := decodeLayoutBoxes(obj)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(boxes), nil
|
||||
}
|
||||
|
||||
// HasBackground is the resolver for the hasBackground field.
|
||||
func (r *layoutResolver) HasBackground(ctx context.Context, obj *models.Layout) (bool, error) {
|
||||
return obj.Background != nil, nil
|
||||
}
|
||||
|
||||
// CreateLayout is the resolver for the createLayout field.
|
||||
func (r *mutationResolver) CreateLayout(ctx context.Context, input model.CreateLayoutInput) (*models.Layout, error) {
|
||||
// A snapshot of the page as it is now, adminOnly boxes included —
|
||||
// which is why every layout field is @admin.
|
||||
name, err := cleanLayoutName(input.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !validPageKey(input.Page) {
|
||||
return nil, errors.New("a layout needs a valid page")
|
||||
}
|
||||
taken, err := layoutNameTaken(r.Store.DB, name, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if taken {
|
||||
return nil, errors.New("there is already a layout with that name")
|
||||
}
|
||||
layout, empty, err := snapshotPage(r.Store.DB, input.Page, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if empty {
|
||||
return nil, errors.New("that page has nothing on it to save")
|
||||
}
|
||||
if err := r.Store.DB.Create(&layout).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &layout, nil
|
||||
}
|
||||
|
||||
// UpdateLayout is the resolver for the updateLayout field.
|
||||
func (r *mutationResolver) UpdateLayout(ctx context.Context, id int, input model.UpdateLayoutInput) (*models.Layout, error) {
|
||||
// Only the name changes: a layout is a snapshot, and saving the page
|
||||
// again under a new name is how its content is refreshed.
|
||||
var layout models.Layout
|
||||
if err := r.Store.DB.First(&layout, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.Name != nil {
|
||||
name, err := cleanLayoutName(*input.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
taken, err := layoutNameTaken(r.Store.DB, name, layout.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if taken {
|
||||
return nil, errors.New("there is already a layout with that name")
|
||||
}
|
||||
layout.Name = name
|
||||
}
|
||||
if err := r.Store.DB.Save(&layout).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &layout, nil
|
||||
}
|
||||
|
||||
// DeleteLayout is the resolver for the deleteLayout field.
|
||||
func (r *mutationResolver) DeleteLayout(ctx context.Context, id int) (*models.Layout, error) {
|
||||
// Pages it was loaded onto keep their boxes: they were copies.
|
||||
var layout models.Layout
|
||||
if err := r.Store.DB.First(&layout, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.Store.DB.Delete(&layout).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &layout, nil
|
||||
}
|
||||
|
||||
// ApplyLayout is the resolver for the applyLayout field.
|
||||
func (r *mutationResolver) ApplyLayout(ctx context.Context, id int, page string, replace bool) ([]*models.Box, error) {
|
||||
// One transaction, so a replace that fails partway leaves the page as
|
||||
// it was rather than half emptied.
|
||||
var layout models.Layout
|
||||
if err := r.Store.DB.First(&layout, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
exists, err := canvasExists(r.Store.DB, page)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !exists {
|
||||
return nil, errors.New("there is no page at that address")
|
||||
}
|
||||
err = r.Store.DB.Transaction(func(tx *gorm.DB) error {
|
||||
return applyLayoutTo(tx, &layout, page, replace)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
boxes, err := pageBoxes(r.Store.DB, page)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ptrs(boxes), nil
|
||||
}
|
||||
|
||||
// Layouts is the resolver for the layouts field.
|
||||
func (r *queryResolver) Layouts(ctx context.Context) ([]*models.Layout, error) {
|
||||
var layouts []models.Layout
|
||||
if err := r.Store.DB.Order("created_at DESC").Find(&layouts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ptrs(layouts), nil
|
||||
}
|
||||
|
||||
// Layout returns LayoutResolver implementation.
|
||||
func (r *Resolver) Layout() LayoutResolver { return &layoutResolver{r} }
|
||||
|
||||
type layoutResolver struct{ *Resolver }
|
||||
@@ -0,0 +1,235 @@
|
||||
package graph
|
||||
|
||||
// Hand-written helpers for layout.resolvers.go, kept out of the resolver file
|
||||
// for the same reason as box_helpers.go.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const maxLayoutNameLen = 100
|
||||
|
||||
// layoutBox is one box as a layout stores it: what makes it look the way it
|
||||
// does, without the id and page that tie a row to one canvas. Changing these
|
||||
// field names would make older layouts load with the renamed fields empty.
|
||||
type layoutBox struct {
|
||||
Kind string `json:"kind"`
|
||||
Widget *string `json:"widget,omitempty"`
|
||||
HTML *string `json:"html,omitempty"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
X int `json:"x"`
|
||||
Y int `json:"y"`
|
||||
W int `json:"w"`
|
||||
H int `json:"h"`
|
||||
Z int `json:"z"`
|
||||
Framed bool `json:"framed"`
|
||||
HideOnMobile bool `json:"hideOnMobile"`
|
||||
AdminOnly bool `json:"adminOnly"`
|
||||
}
|
||||
|
||||
type layoutBackground struct {
|
||||
Color string `json:"color"`
|
||||
Image string `json:"image"`
|
||||
Fit string `json:"fit"`
|
||||
}
|
||||
|
||||
// cleanLayoutName trims name and reports why it can't be a layout's name.
|
||||
func cleanLayoutName(name string) (string, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return name, errors.New("a layout needs a name")
|
||||
}
|
||||
if len(name) > maxLayoutNameLen {
|
||||
return name, fmt.Errorf("a layout name is at most %d characters", maxLayoutNameLen)
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// layoutNameTaken reports whether a live layout other than exceptID has this
|
||||
// name. Checked up front, like slugTaken, so the admin gets a sentence rather
|
||||
// than a constraint violation.
|
||||
func layoutNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
|
||||
var count int64
|
||||
err := db.Model(&models.Layout{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
// canvasExists reports whether page is a canvas boxes can be put on: the
|
||||
// landing page, or a live Page. Loading a layout onto any other key would
|
||||
// leave its boxes where nothing shows them.
|
||||
func canvasExists(db *gorm.DB, page string) (bool, error) {
|
||||
if page == "index" {
|
||||
return true, nil
|
||||
}
|
||||
if !validPageKey(page) {
|
||||
return false, nil
|
||||
}
|
||||
var count int64
|
||||
err := db.Model(&models.Page{}).Where("slug = ?", page).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
// pageBoxes is every box on page, adminOnly ones included, in the order the
|
||||
// boxes query returns them. Only for admin-only callers.
|
||||
func pageBoxes(db *gorm.DB, page string) ([]models.Box, error) {
|
||||
var boxes []models.Box
|
||||
err := db.Where("page = ?", page).Order("z ASC, id ASC").Find(&boxes).Error
|
||||
return boxes, err
|
||||
}
|
||||
|
||||
// snapshotPage is an unsaved Layout holding page's boxes and background as
|
||||
// they are now. empty is true when there was nothing to keep.
|
||||
func snapshotPage(db *gorm.DB, page, name string) (layout models.Layout, empty bool, err error) {
|
||||
boxes, err := pageBoxes(db, page)
|
||||
if err != nil {
|
||||
return layout, false, err
|
||||
}
|
||||
stored := make([]layoutBox, len(boxes))
|
||||
for i, b := range boxes {
|
||||
stored[i] = layoutBox{
|
||||
Kind: b.Kind, Widget: b.Widget, HTML: b.HTML, Title: b.Title,
|
||||
X: b.X, Y: b.Y, W: b.W, H: b.H, Z: b.Z,
|
||||
Framed: b.Framed, HideOnMobile: b.HideOnMobile, AdminOnly: b.AdminOnly,
|
||||
}
|
||||
}
|
||||
boxesJSON, err := json.Marshal(stored)
|
||||
if err != nil {
|
||||
return layout, false, err
|
||||
}
|
||||
layout = models.Layout{Name: name, SourcePage: page, Boxes: string(boxesJSON)}
|
||||
|
||||
var bg models.Background
|
||||
err = db.Where("page = ?", page).First(&bg).Error
|
||||
switch {
|
||||
case err == nil:
|
||||
bgJSON, err := json.Marshal(layoutBackground{Color: bg.Color, Image: bg.Image, Fit: bg.Fit})
|
||||
if err != nil {
|
||||
return layout, false, err
|
||||
}
|
||||
s := string(bgJSON)
|
||||
layout.Background = &s
|
||||
case !errors.Is(err, gorm.ErrRecordNotFound):
|
||||
return layout, false, err
|
||||
}
|
||||
return layout, len(boxes) == 0 && layout.Background == nil, nil
|
||||
}
|
||||
|
||||
func decodeLayoutBoxes(layout *models.Layout) ([]layoutBox, error) {
|
||||
var boxes []layoutBox
|
||||
if err := json.Unmarshal([]byte(layout.Boxes), &boxes); err != nil {
|
||||
return nil, fmt.Errorf("layout %q is unreadable: %w", layout.Name, err)
|
||||
}
|
||||
return boxes, nil
|
||||
}
|
||||
|
||||
// pageLabel is how a page key reads in a generated layout name.
|
||||
func pageLabel(page string) string {
|
||||
if page == "index" {
|
||||
return "/"
|
||||
}
|
||||
return "/" + page
|
||||
}
|
||||
|
||||
// uniqueLayoutName is base, or base with " (2)", " (3)"… if that is taken.
|
||||
func uniqueLayoutName(db *gorm.DB, base string) (string, error) {
|
||||
name := base
|
||||
for n := 2; ; n++ {
|
||||
taken, err := layoutNameTaken(db, name, 0)
|
||||
if err != nil || !taken {
|
||||
return name, err
|
||||
}
|
||||
name = fmt.Sprintf("%s (%d)", base, n)
|
||||
}
|
||||
}
|
||||
|
||||
// applyLayoutTo copies layout onto page inside tx; see applyLayout in
|
||||
// layout.graphql for what replace does. The copies are new rows, so the page
|
||||
// owns them outright.
|
||||
func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool) error {
|
||||
stored, err := decodeLayoutBoxes(layout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Added on top, the copies keep their own stacking order but all sit
|
||||
// above what the page already has.
|
||||
zShift := 0
|
||||
if replace {
|
||||
// What is being replaced is kept first, so a replace can be undone by
|
||||
// loading that layout back. A page with nothing on it has nothing to
|
||||
// keep.
|
||||
name, err := uniqueLayoutName(tx, fmt.Sprintf("%s before %s, %s",
|
||||
pageLabel(page), layout.Name, time.Now().Format("2 Jan 2006 15:04")))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
backup, empty, err := snapshotPage(tx, page, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !empty {
|
||||
if err := tx.Create(&backup).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := tx.Where("page = ?", page).Delete(&models.Box{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("page = ?", page).Delete(&models.Background{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else if len(stored) > 0 {
|
||||
var top *int
|
||||
if err := tx.Model(&models.Box{}).Where("page = ?", page).Select("MAX(z)").Scan(&top).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if top != nil {
|
||||
lowest := stored[0].Z
|
||||
for _, b := range stored {
|
||||
lowest = min(lowest, b.Z)
|
||||
}
|
||||
zShift = *top + 1 - lowest
|
||||
}
|
||||
}
|
||||
|
||||
boxes := make([]models.Box, len(stored))
|
||||
for i, b := range stored {
|
||||
boxes[i] = models.Box{
|
||||
Page: page, Kind: b.Kind, Widget: b.Widget, HTML: b.HTML, Title: b.Title,
|
||||
X: b.X, Y: b.Y, W: b.W, H: b.H, Z: b.Z + zShift,
|
||||
Framed: b.Framed, HideOnMobile: b.HideOnMobile, AdminOnly: b.AdminOnly,
|
||||
}
|
||||
if err := validateBox(&boxes[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(boxes) > 0 {
|
||||
if err := tx.Create(&boxes).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Adding on top leaves the page's own background alone.
|
||||
if replace && layout.Background != nil {
|
||||
var saved layoutBackground
|
||||
if err := json.Unmarshal([]byte(*layout.Background), &saved); err != nil {
|
||||
return fmt.Errorf("layout %q is unreadable: %w", layout.Name, err)
|
||||
}
|
||||
bg, err := backgroundFrom(page, model.BackgroundInput{Color: saved.Color, Image: saved.Image, Fit: saved.Fit})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(&bg).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -52,6 +52,11 @@ type CreateFavoriteInput struct {
|
||||
Link *string `json:"link,omitempty"`
|
||||
}
|
||||
|
||||
type CreateLayoutInput struct {
|
||||
Name string `json:"name"`
|
||||
Page string `json:"page"`
|
||||
}
|
||||
|
||||
type CreatePageInput struct {
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
@@ -155,6 +160,10 @@ type UpdateBoxInput struct {
|
||||
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateLayoutInput struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
type UpdatePageInput struct {
|
||||
Slug *string `json:"slug,omitempty"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
|
||||
@@ -24,11 +24,11 @@ const maxSlugLen = 100
|
||||
// reservedFirstSegments are paths a page could never be reached at, because
|
||||
// nginx or one of the SPA's own routes answers them first (see
|
||||
// nginx/nginx_routes.conf.template and vue/src/router/index.js), plus the
|
||||
// built-in canvases' page keys, whose boxes a page of the same slug would
|
||||
// share. "shrines" is deliberately absent: /shrines and the shrine pages under
|
||||
// it are all canvas pages.
|
||||
// landing page's key "index", whose boxes a page of the same slug would
|
||||
// share. "shrines" and "stp" are deliberately absent: /shrines, the shrine
|
||||
// pages under it and the home page /stp are all canvas pages.
|
||||
var reservedFirstSegments = map[string]bool{
|
||||
"stp": true, "stp2": true, "index": true, "admin": true, "cv": true,
|
||||
"stp2": true, "index": true, "admin": true, "cv": true,
|
||||
"automata": true, "hotels": true, "api": true, "py": true, "radio": true,
|
||||
"gitea": true, "notes": true, "sb": true, "jobs": true, "tracker": true,
|
||||
"usaco": true, "uploads": true, "img": true, "fonts": true, "pdf": true,
|
||||
@@ -52,7 +52,7 @@ func validateSlug(slug string) error {
|
||||
}
|
||||
|
||||
// pageHiddenFrom reports whether the page with this key is an adminOnly page
|
||||
// and the caller is not an admin. A key with no Page row (a built-in canvas,
|
||||
// and the caller is not an admin. A key with no Page row (the landing page,
|
||||
// or a page that doesn't exist) is not hidden.
|
||||
func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error) {
|
||||
if IsAdminFromCtx(ctx) {
|
||||
|
||||
@@ -21,8 +21,9 @@ func TestValidateSlug(t *testing.T) {
|
||||
{"shrines/demoman", true}, // no longer an SPA route
|
||||
{"admin/pages", false}, // under an SPA route
|
||||
{"jobs/x", false}, // under an nginx route
|
||||
{"stp", false}, // a built-in canvas's key
|
||||
{"index", false}, // likewise
|
||||
{"stp", true}, // the home page is a canvas page too
|
||||
{"stp2", false}, // an SPA route
|
||||
{"index", false}, // the landing canvas's key
|
||||
{"stp-fan-page", true}, // only whole segments are reserved
|
||||
} {
|
||||
err := validateSlug(c.slug)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# The background behind a canvas page, keyed by the same page key as its
|
||||
# boxes ("index" for the landing page, "stp", or a Page's slug), so the
|
||||
# landing page and every shrine are set the same way. Edited from the
|
||||
# boxes ("index" for the landing page, or a Page's slug), so the landing
|
||||
# page and every other canvas page are set the same way. Edited from the
|
||||
# canvas's "Background" button; see models.Background.
|
||||
#
|
||||
# Anyone may read it, as part of the page, except that an adminOnly page's
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Boxes on a canvas page: the home page (/stp, page "stp"), the landing
|
||||
# page's overlay (page "index") or an admin-created Page (page = its slug).
|
||||
# Boxes on a canvas page: the landing page (page "index") or an
|
||||
# admin-created Page (page = its slug; the home page /stp is the Page "stp").
|
||||
# Anyone may read a page's layout — it is the page — but only an admin may
|
||||
# change it, and adminOnly boxes are only ever returned to an admin. x/y/w/h
|
||||
# are px on a fixed 1400px-wide design canvas; see models.Box.
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Saved layouts: a named copy of one canvas page's boxes and background,
|
||||
# which can be loaded onto any canvas page — the landing page ("index") or a
|
||||
# Page's slug. Loading copies: the new boxes belong to the target page, so
|
||||
# editing a page afterwards never changes the layout or another page. Moving
|
||||
# a layout is saving it on one page and loading it on another with
|
||||
# replace: true. See models.Layout and graph/layout_helpers.go.
|
||||
#
|
||||
# Admin only throughout, reads included, because a layout keeps a page's
|
||||
# adminOnly boxes along with the rest.
|
||||
|
||||
type Layout {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
name: String!
|
||||
# The page key it was saved from.
|
||||
sourcePage: String!
|
||||
boxCount: Int!
|
||||
hasBackground: Boolean!
|
||||
}
|
||||
|
||||
input CreateLayoutInput {
|
||||
name: String!
|
||||
# The page key to save, as it is now.
|
||||
page: String!
|
||||
}
|
||||
|
||||
input UpdateLayoutInput {
|
||||
name: String
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
# Newest first.
|
||||
layouts: [Layout!]! @admin
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createLayout(input: CreateLayoutInput!): Layout! @admin
|
||||
# Renames it; what a layout holds never changes after it is saved.
|
||||
updateLayout(id: ID!, input: UpdateLayoutInput!): Layout! @admin
|
||||
deleteLayout(id: ID!): Layout! @admin
|
||||
# Copies the layout onto `page` and answers with that page's boxes.
|
||||
# replace: false adds the copies on top of what is there, leaving the
|
||||
# background alone. replace: true first saves the page as a layout named
|
||||
# "<page> before <layout>, <time>", then swaps its boxes and background
|
||||
# for the layout's.
|
||||
applyLayout(id: ID!, page: String!, replace: Boolean!): [Box!]! @admin
|
||||
}
|
||||
Reference in New Issue
Block a user