Add saved layouts, and make /stp an ordinary canvas page
Test and deploy / test (push) Successful in 1m51s
Test and deploy / deploy (push) Successful in 1m10s

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:
2026-10-23 20:33:07 +01:00
co-authored by Claude Opus 5.5
parent 8c535b1cc2
commit 2eacbc2e33
28 changed files with 1947 additions and 68 deletions
+10
View File
@@ -94,3 +94,13 @@ models:
fields:
deletedAt:
resolver: false
Layout:
model:
- adam-french.co.uk/backend/models.Layout
fields:
deletedAt:
resolver: false
boxCount:
resolver: true
hasBackground:
resolver: true
+4 -3
View File
@@ -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 {
File diff suppressed because it is too large Load Diff
+144
View File
@@ -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 }
+235
View File
@@ -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
}
+9
View File
@@ -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"`
+5 -5
View File
@@ -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) {
+3 -2
View File
@@ -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)
+2 -2
View File
@@ -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
+2 -2
View File
@@ -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.
+48
View File
@@ -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
}
+26 -4
View File
@@ -157,9 +157,9 @@ type Place struct {
}
// Box is one panel on a canvas page. Page names the canvas it belongs to:
// "stp" for the home page, "index" for the landing page's overlay, or a
// Page.Slug for an admin-created page — it is a key, not a foreign key, so the
// built-in canvases need no Page row. Its position and size are in px on a
// "index" for the landing page, or a Page.Slug for an admin-created page
// (the home page is the Page "stp") — it is a key, not a foreign key, so the
// built-in landing canvas needs no Page row. Its position and size are in px on a
// fixed 1400px-wide design canvas, which the page scales down on narrower
// screens — so the stored numbers mean the same thing for every visitor. Kind "widget" renders a built-in Vue component named by Widget;
// kind "html" renders HTML in a sandboxed iframe on the front end, which is
@@ -207,7 +207,7 @@ type Page struct {
}
// Background is the page background behind one canvas (Page is the same page
// key a Box has: "index" for the landing page, "stp", or a Page's slug), so
// key a Box has: "index" for the landing page, or a Page's slug), so
// built-in canvases and admin-created pages are set the same way. A page with
// no row shows the theme's halftone; deleting the row is "reset to default".
// The unique index is partial for the same reason as Page's.
@@ -224,3 +224,25 @@ type Background struct {
// Fit is how Image fills the window: "cover", "contain" or "tile".
Fit string `gorm:"not null;default:cover" json:"fit"`
}
// Layout is a named copy of one canvas page's boxes and background, saved so
// it can be loaded onto any page later (graph/layout_helpers.go). It is a
// snapshot, not a link: loading it creates new boxes that belong to the
// target page, so editing either page afterwards never touches the other or
// the layout. The content is JSON rather than child rows because nothing
// queries inside it — it is only ever written whole and read whole. The
// unique index is partial for the same reason as Page's.
type Layout struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
Name string `gorm:"not null;index:idx_layouts_name,unique,where:deleted_at IS NULL" json:"name"`
// SourcePage is the page key it was saved from, for the list only.
SourcePage string `gorm:"not null" json:"sourcePage"`
// Boxes is a JSON array of the boxes' content and geometry, without id
// or page.
Boxes string `gorm:"type:text;not null" json:"-"`
// Background is the page's background as JSON, or nil if it had none.
Background *string `gorm:"type:text" json:"-"`
}
+18 -1
View File
@@ -54,12 +54,29 @@ func migrateDatabase(db *gorm.DB) error {
&models.Box{},
&models.Page{},
&models.Background{},
&models.Layout{},
)
if err != nil {
return err
}
return nil
return ensureStpPage(db)
}
// ensureStpPage turns the home page (/stp) into an ordinary canvas Page once.
// It used to be a built-in canvas with its own route; its boxes and
// background were already keyed "stp", so a Page row with that slug is all
// it takes. Unscoped, so that deleting the page on purpose sticks rather than
// bringing it back on the next start.
func ensureStpPage(db *gorm.DB) error {
var count int64
if err := db.Unscoped().Model(&models.Page{}).Where("slug = ?", "stp").Count(&count).Error; err != nil {
return err
}
if count > 0 {
return nil
}
return db.Create(&models.Page{Slug: "stp", Title: "STP"}).Error
}
// InitDatabase connects to Postgres and runs the auto-migration.