Add saved components: reusable HTML boxes, placed as copies or linked
A component (models.Component, component.graphql) is a named HTML box. "+ New box" now lists components and places a copy, as it did with the hard-coded starters; the canvas's new Components button (ComponentPanel) can also place one linked. A linked box has Box.componentId, its row's html is nil, and the resolvers fill in the component's html before answering (fillLinked), so saving the html in the box editor saves the component and every linked box on every page changes. Only the html is shared: title, geometry, frame and visibility stay each box's own. The box editor gains "Save as component" (makes one from an html box and links it) and, on a linked box, a banner with Detach (gives the box its own copy). updateBox refuses html on a linked box. Deleting a component detaches its boxes first, so no page changes. Layouts store the link and the html; loading relinks only if the component still exists. The built-in starters in templates.js are no longer listed directly: "Import built-ins" in the panel creates them as components (skipping names already taken), so they can be edited and deleted like the rest. The html helpers there are unchanged. Everything is @admin. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -76,7 +76,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
|
||||
- `graph/*.resolvers.go` — resolver implementations (one per schema file, `follow-schema` layout)
|
||||
- `graph/generated.go` — auto-generated by gqlgen, do not edit
|
||||
- `graph/model/models_gen.go` — auto-generated GraphQL models, do not edit
|
||||
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing, Bookmark, Place, Box, Page, Background, Layout)
|
||||
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing, Bookmark, Place, Box, Page, Background, Layout, Component)
|
||||
- `graph/directives.go` — the `@admin` / `@signedIn` schema directives (see Key Patterns)
|
||||
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, the Python-service call helper (`python_call.go`), uploads (`uploads.go`: validation, naming, Garage bucket with disk fallback), DB seeding. There is no Claude client in Go any more
|
||||
|
||||
@@ -85,8 +85,8 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
|
||||
- `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`)
|
||||
- `src/api.js` — thin REST client for the `/api` JSON endpoints; failures become an `ApiError` carrying the backend's `error` message and the status
|
||||
- `src/uploads.js` — storing and showing uploaded files: `uploadFile(file)` → public `/uploads/...` URL, `ACCEPT` for file pickers, `kindOf`/`tagFor`/`isUploadUrl`/`mediaSize`. Every upload goes through it
|
||||
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, boxes, pages, layouts. `createCrudStore.js` is the factory behind places, boxes and pages; `createMirrorStore.js` is the one behind the home-page slices
|
||||
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines). Canvas pages are admin-arranged boxes (built-in widgets or sandboxed-iframe HTML) stored as the `Box` GraphQL type, drawn by `views/home3/BoxCanvas.vue` per page key: the landing page (`/`, key `index`) is one, and admin-created `Page`s (e.g. shrines, and `/stp`, the `Page` with slug `stp`) are served at `/<slug>` by the router's catch-all, `views/canvas/CanvasPage.vue`. A `Layout` is a saved, named copy of a page's boxes and background that can be loaded onto any canvas (the canvas's Layouts button, or the admin Pages tab). Boxes and pages can be admin-only, filtered server-side. Each canvas page key also has an optional `Background`, set from the canvas's Background button and painted by `DefaultLayout`. See "The /stp canvas" in `vue/README.md`
|
||||
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, boxes, pages, layouts, components. `createCrudStore.js` is the factory behind places, boxes and pages; `createMirrorStore.js` is the one behind the home-page slices
|
||||
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines). Canvas pages are admin-arranged boxes (built-in widgets or sandboxed-iframe HTML) stored as the `Box` GraphQL type, drawn by `views/home3/BoxCanvas.vue` per page key: the landing page (`/`, key `index`) is one, and admin-created `Page`s (e.g. shrines, and `/stp`, the `Page` with slug `stp`) are served at `/<slug>` by the router's catch-all, `views/canvas/CanvasPage.vue`. A `Layout` is a saved, named copy of a page's boxes and background that can be loaded onto any canvas (the canvas's Layouts button, or the admin Pages tab). A `Component` is a saved, named HTML box: "+ New box" places copies of it, and the canvas's Components button also places it *linked* (`Box.componentId`), so the box shows the component's HTML and editing it edits every linked box; the built-in starters in `templates.js` become components through that panel's "Import built-ins". Boxes and pages can be admin-only, filtered server-side. Each canvas page key also has an optional `Background`, set from the canvas's Background button and painted by `DefaultLayout`. See "The /stp canvas" in `vue/README.md`
|
||||
- `src/components/` — reusable UI components
|
||||
- `src/assets/styles.css` — design tokens (Tailwind `@theme`), base element styles, shared classes and transitions. `layouts/CVLayout.vue` re-points the colour tokens for the light CV theme. See "Styling" in `vue/README.md`.
|
||||
|
||||
|
||||
@@ -108,3 +108,11 @@ models:
|
||||
resolver: true
|
||||
hasBackground:
|
||||
resolver: true
|
||||
Component:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.Component
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
uses:
|
||||
resolver: true
|
||||
|
||||
@@ -7,6 +7,7 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
@@ -41,12 +42,31 @@ func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxI
|
||||
if input.AdminOnly != nil {
|
||||
box.AdminOnly = *input.AdminOnly
|
||||
}
|
||||
// A linked box takes its html from the component, so its own is
|
||||
// dropped rather than stored as a copy that would quietly go stale.
|
||||
if input.ComponentID != nil {
|
||||
id := uint(*input.ComponentID)
|
||||
exists, err := componentExists(r.Store.DB, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !exists {
|
||||
return nil, errors.New("there is no such component")
|
||||
}
|
||||
box.Kind = "html"
|
||||
box.Widget = nil
|
||||
box.HTML = nil
|
||||
box.ComponentID = &id
|
||||
}
|
||||
if err := validateBox(&box); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.Store.DB.Create(&box).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &box, nil
|
||||
}
|
||||
|
||||
@@ -64,6 +84,11 @@ func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.Up
|
||||
box.Widget = input.Widget
|
||||
}
|
||||
if input.HTML != nil {
|
||||
// A linked box's html is the component's; changing it here would
|
||||
// only fork a copy. The editor sends it to updateComponent instead.
|
||||
if box.ComponentID != nil {
|
||||
return nil, errors.New("that box is linked to a component: edit the component, or detach the box first")
|
||||
}
|
||||
box.HTML = input.HTML
|
||||
}
|
||||
if input.Title != nil {
|
||||
@@ -89,6 +114,9 @@ func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.Up
|
||||
if err := r.Store.DB.Save(&box).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &box, nil
|
||||
}
|
||||
|
||||
@@ -127,5 +155,8 @@ func (r *queryResolver) Boxes(ctx context.Context, page string) ([]*models.Box,
|
||||
if err := query.Order("z ASC, id ASC").Find(&boxes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := fillLinked(r.Store.DB, boxes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ptrs(boxes), nil
|
||||
}
|
||||
|
||||
@@ -33,12 +33,16 @@ func validateBox(box *models.Box) error {
|
||||
return errors.New("a widget box needs a widget name")
|
||||
}
|
||||
case "html":
|
||||
if box.HTML == nil {
|
||||
// A linked box's html lives on its component (fillLinked).
|
||||
if box.HTML == nil && box.ComponentID == nil {
|
||||
return errors.New("an html box needs html")
|
||||
}
|
||||
default:
|
||||
return errors.New(`box kind must be "widget" or "html"`)
|
||||
}
|
||||
if box.ComponentID != nil && box.Kind != "html" {
|
||||
return errors.New("only an html box can be linked to a component")
|
||||
}
|
||||
box.X = max(box.X, 0)
|
||||
box.Y = max(box.Y, 0)
|
||||
box.W = max(box.W, minBoxSize)
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
func TestValidateBox(t *testing.T) {
|
||||
str := func(s string) *string { return &s }
|
||||
one := uint(1)
|
||||
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
@@ -20,6 +21,8 @@ func TestValidateBox(t *testing.T) {
|
||||
{"html with html", models.Box{Page: "stp", Kind: "html", HTML: str("<p>hi</p>")}, false},
|
||||
{"html with empty html", models.Box{Page: "stp", Kind: "html", HTML: str("")}, false},
|
||||
{"html without html", models.Box{Page: "stp", Kind: "html"}, true},
|
||||
{"linked html without html", models.Box{Page: "stp", Kind: "html", ComponentID: &one}, false},
|
||||
{"linked widget", models.Box{Page: "stp", Kind: "widget", Widget: str("Chat"), ComponentID: &one}, true},
|
||||
{"no page", models.Box{Kind: "widget", Widget: str("Chat")}, true},
|
||||
{"bad page", models.Box{Page: "Shrines/GTO", Kind: "widget", Widget: str("Chat")}, true},
|
||||
{"unknown kind", models.Box{Page: "stp", Kind: "iframe", HTML: str("x")}, true},
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
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"
|
||||
)
|
||||
|
||||
// Uses is the resolver for the uses field.
|
||||
func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (int, error) {
|
||||
// One count per component, which is fine for an admin-only list of a
|
||||
// handful; soft-deleted boxes are excluded by GORM's default scope.
|
||||
var count int64
|
||||
if err := r.Store.DB.Model(&models.Box{}).Where("component_id = ?", obj.ID).Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(count), nil
|
||||
}
|
||||
|
||||
// CreateComponent is the resolver for the createComponent field.
|
||||
func (r *mutationResolver) CreateComponent(ctx context.Context, input model.CreateComponentInput) (*models.Component, error) {
|
||||
// Framed defaults to true and the size to 300x200, as for a new box.
|
||||
name, err := usableComponentName(r.Store.DB, input.Name, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := models.Component{Name: name, Title: input.Title, HTML: input.HTML, W: 300, H: 200, Framed: true}
|
||||
setInt(&c.W, input.W)
|
||||
setInt(&c.H, input.H)
|
||||
if input.Framed != nil {
|
||||
c.Framed = *input.Framed
|
||||
}
|
||||
if input.AdminOnly != nil {
|
||||
c.AdminOnly = *input.AdminOnly
|
||||
}
|
||||
c.W = max(c.W, minBoxSize)
|
||||
c.H = max(c.H, minBoxSize)
|
||||
if err := r.Store.DB.Create(&c).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// UpdateComponent is the resolver for the updateComponent field.
|
||||
func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input model.UpdateComponentInput) (*models.Component, error) {
|
||||
// Partial, like updateBox. Nothing to do for the linked boxes: they
|
||||
// read the html from here every time they are fetched.
|
||||
var c models.Component
|
||||
if err := r.Store.DB.First(&c, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.Name != nil {
|
||||
name, err := usableComponentName(r.Store.DB, *input.Name, c.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Name = name
|
||||
}
|
||||
if input.Title != nil {
|
||||
c.Title = input.Title
|
||||
}
|
||||
if input.HTML != nil {
|
||||
c.HTML = *input.HTML
|
||||
}
|
||||
setInt(&c.W, input.W)
|
||||
setInt(&c.H, input.H)
|
||||
if input.Framed != nil {
|
||||
c.Framed = *input.Framed
|
||||
}
|
||||
if input.AdminOnly != nil {
|
||||
c.AdminOnly = *input.AdminOnly
|
||||
}
|
||||
c.W = max(c.W, minBoxSize)
|
||||
c.H = max(c.H, minBoxSize)
|
||||
if err := r.Store.DB.Save(&c).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// DeleteComponent is the resolver for the deleteComponent field.
|
||||
func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models.Component, error) {
|
||||
// The linked boxes keep showing what they showed, as copies, so
|
||||
// deleting a component never changes a page. One transaction, so a
|
||||
// failure can't leave boxes linked to a deleted component.
|
||||
var c models.Component
|
||||
if err := r.Store.DB.First(&c, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
|
||||
if err := detachFrom(tx, &c); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Delete(&c).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// SaveBoxAsComponent is the resolver for the saveBoxAsComponent field.
|
||||
func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name string) (*models.Box, error) {
|
||||
// The box becomes the component's first linked instance, so carrying
|
||||
// on editing it edits the component. A box that is already linked
|
||||
// would make a component of a component's html; detach it first.
|
||||
var box models.Box
|
||||
if err := r.Store.DB.First(&box, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if box.Kind != "html" || box.HTML == nil {
|
||||
return nil, errors.New("only an html box can be saved as a component")
|
||||
}
|
||||
if box.ComponentID != nil {
|
||||
return nil, errors.New("that box is already linked to a component")
|
||||
}
|
||||
name, err := usableComponentName(r.Store.DB, name, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := models.Component{
|
||||
Name: name, Title: box.Title, HTML: *box.HTML,
|
||||
W: box.W, H: box.H, Framed: box.Framed, AdminOnly: box.AdminOnly,
|
||||
}
|
||||
err = r.Store.DB.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(&c).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
box.ComponentID = &c.ID
|
||||
box.HTML = nil
|
||||
return tx.Save(&box).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &box, nil
|
||||
}
|
||||
|
||||
// DetachBox is the resolver for the detachBox field.
|
||||
func (r *mutationResolver) DetachBox(ctx context.Context, id int) (*models.Box, error) {
|
||||
// The html is filled in from the component and then saved, which is
|
||||
// exactly the copy fillLinked otherwise never lets reach the row.
|
||||
var box models.Box
|
||||
if err := r.Store.DB.First(&box, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if box.ComponentID == nil {
|
||||
return nil, errors.New("that box isn't linked to a component")
|
||||
}
|
||||
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
box.ComponentID = nil
|
||||
if err := r.Store.DB.Save(&box).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &box, nil
|
||||
}
|
||||
|
||||
// Components is the resolver for the components field.
|
||||
func (r *queryResolver) Components(ctx context.Context) ([]*models.Component, error) {
|
||||
var components []models.Component
|
||||
if err := r.Store.DB.Order("name ASC").Find(&components).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ptrs(components), nil
|
||||
}
|
||||
|
||||
// Component returns ComponentResolver implementation.
|
||||
func (r *Resolver) Component() ComponentResolver { return &componentResolver{r} }
|
||||
|
||||
type componentResolver struct{ *Resolver }
|
||||
@@ -0,0 +1,112 @@
|
||||
package graph
|
||||
|
||||
// Hand-written helpers for component.resolvers.go, kept out of the resolver
|
||||
// file for the same reason as box_helpers.go.
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const maxComponentNameLen = 100
|
||||
|
||||
// cleanComponentName trims name and reports why it can't be a component's
|
||||
// name.
|
||||
func cleanComponentName(name string) (string, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return name, errors.New("a component needs a name")
|
||||
}
|
||||
if len(name) > maxComponentNameLen {
|
||||
return name, fmt.Errorf("a component name is at most %d characters", maxComponentNameLen)
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// componentNameTaken reports whether a live component other than exceptID
|
||||
// has this name. Checked up front, like layoutNameTaken, so the admin gets a
|
||||
// sentence rather than a constraint violation.
|
||||
func componentNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
|
||||
var count int64
|
||||
err := db.Model(&models.Component{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
// usableComponentName checks name and answers with a sentence if it can't be
|
||||
// used, so the resolvers that name a component share one set of messages.
|
||||
func usableComponentName(db *gorm.DB, name string, exceptID uint) (string, error) {
|
||||
name, err := cleanComponentName(name)
|
||||
if err != nil {
|
||||
return name, err
|
||||
}
|
||||
taken, err := componentNameTaken(db, name, exceptID)
|
||||
if err != nil {
|
||||
return name, err
|
||||
}
|
||||
if taken {
|
||||
return name, errors.New("there is already a component with that name")
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// fillLinked sets each linked box's in-memory HTML to its component's, with
|
||||
// one query for all of them. Only for boxes about to be returned or
|
||||
// snapshotted: a linked row's own HTML is nil, and saving a filled box would
|
||||
// freeze a copy of the component into it. A box whose component has gone
|
||||
// (deleted outside deleteComponent, which detaches first) is left with
|
||||
// empty HTML rather than failing the whole page.
|
||||
func fillLinked(db *gorm.DB, boxes []models.Box) error {
|
||||
var ids []uint
|
||||
for _, b := range boxes {
|
||||
if b.ComponentID != nil {
|
||||
ids = append(ids, *b.ComponentID)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
var components []models.Component
|
||||
if err := db.Where("id IN ?", ids).Find(&components).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
html := make(map[uint]string, len(components))
|
||||
for _, c := range components {
|
||||
html[c.ID] = c.HTML
|
||||
}
|
||||
for i := range boxes {
|
||||
if id := boxes[i].ComponentID; id != nil {
|
||||
h := html[*id]
|
||||
boxes[i].HTML = &h
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fillLinkedOne is fillLinked for a single box.
|
||||
func fillLinkedOne(db *gorm.DB, box *models.Box) error {
|
||||
boxes := []models.Box{*box}
|
||||
if err := fillLinked(db, boxes); err != nil {
|
||||
return err
|
||||
}
|
||||
*box = boxes[0]
|
||||
return nil
|
||||
}
|
||||
|
||||
// componentExists reports whether id is a live component, for linking a box
|
||||
// to it.
|
||||
func componentExists(db *gorm.DB, id uint) (bool, error) {
|
||||
var count int64
|
||||
err := db.Model(&models.Component{}).Where("id = ?", id).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
// detachFrom gives every box linked to component c its own copy of c's HTML
|
||||
// and unlinks it, inside tx.
|
||||
func detachFrom(tx *gorm.DB, c *models.Component) error {
|
||||
return tx.Model(&models.Box{}).Where("component_id = ?", c.ID).
|
||||
Updates(map[string]any{"html": c.HTML, "component_id": nil}).Error
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCleanComponentName(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, in, want string
|
||||
wantErr bool
|
||||
}{
|
||||
{"plain", "Clock", "Clock", false},
|
||||
{"trimmed", " Clock \n", "Clock", false},
|
||||
{"empty", "", "", true},
|
||||
{"only spaces", " ", "", true},
|
||||
{"at the limit", strings.Repeat("a", maxComponentNameLen), strings.Repeat("a", maxComponentNameLen), false},
|
||||
{"too long", strings.Repeat("a", maxComponentNameLen+1), "", true},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got, err := cleanComponentName(c.in)
|
||||
if (err != nil) != c.wantErr {
|
||||
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
|
||||
}
|
||||
if !c.wantErr && got != c.want {
|
||||
t.Fatalf("got %q, want %q", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -191,6 +191,7 @@ func TestGuardedQueriesArePinned(t *testing.T) {
|
||||
"user": "admin",
|
||||
"places": "signedIn",
|
||||
"layouts": "admin",
|
||||
"components": "admin",
|
||||
"permissionTypes": "signedIn",
|
||||
}
|
||||
got := map[string]string{}
|
||||
|
||||
+1298
-2
File diff suppressed because it is too large
Load Diff
@@ -126,6 +126,9 @@ func (r *mutationResolver) ApplyLayout(ctx context.Context, id int, page string,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := fillLinked(r.Store.DB, boxes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ptrs(boxes), nil
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,10 @@ type layoutBox struct {
|
||||
Framed bool `json:"framed"`
|
||||
HideOnMobile bool `json:"hideOnMobile"`
|
||||
AdminOnly bool `json:"adminOnly"`
|
||||
// ComponentID is the component a linked box was linked to. HTML is
|
||||
// stored too, so that a layout outlives the component: loading links the
|
||||
// box again if the component is still there and uses HTML if not.
|
||||
ComponentID *uint `json:"componentId,omitempty"`
|
||||
}
|
||||
|
||||
type layoutBackground struct {
|
||||
@@ -92,12 +96,16 @@ func snapshotPage(db *gorm.DB, page, name string) (layout models.Layout, empty b
|
||||
if err != nil {
|
||||
return layout, false, err
|
||||
}
|
||||
if err := fillLinked(db, boxes); 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,
|
||||
ComponentID: b.ComponentID,
|
||||
}
|
||||
}
|
||||
boxesJSON, err := json.Marshal(stored)
|
||||
@@ -200,6 +208,10 @@ func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool
|
||||
}
|
||||
}
|
||||
|
||||
live, err := liveComponents(tx, stored)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
boxes := make([]models.Box, len(stored))
|
||||
for i, b := range stored {
|
||||
boxes[i] = models.Box{
|
||||
@@ -207,6 +219,10 @@ func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool
|
||||
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 b.ComponentID != nil && live[*b.ComponentID] {
|
||||
boxes[i].ComponentID = b.ComponentID
|
||||
boxes[i].HTML = nil
|
||||
}
|
||||
if err := validateBox(&boxes[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -233,3 +249,26 @@ func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// liveComponents is the set of components the stored boxes were linked to
|
||||
// that still exist, so applyLayoutTo knows which boxes to link again.
|
||||
func liveComponents(db *gorm.DB, stored []layoutBox) (map[uint]bool, error) {
|
||||
var ids []uint
|
||||
for _, b := range stored {
|
||||
if b.ComponentID != nil {
|
||||
ids = append(ids, *b.ComponentID)
|
||||
}
|
||||
}
|
||||
live := map[uint]bool{}
|
||||
if len(ids) == 0 {
|
||||
return live, nil
|
||||
}
|
||||
var found []uint
|
||||
if err := db.Model(&models.Component{}).Where("id IN ?", ids).Pluck("id", &found).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, id := range found {
|
||||
live[id] = true
|
||||
}
|
||||
return live, nil
|
||||
}
|
||||
|
||||
@@ -44,6 +44,17 @@ type CreateBoxInput struct {
|
||||
Framed *bool `json:"framed,omitempty"`
|
||||
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
|
||||
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||
ComponentID *int `json:"componentId,omitempty"`
|
||||
}
|
||||
|
||||
type CreateComponentInput struct {
|
||||
Name string `json:"name"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
HTML string `json:"html"`
|
||||
W *int `json:"w,omitempty"`
|
||||
H *int `json:"h,omitempty"`
|
||||
Framed *bool `json:"framed,omitempty"`
|
||||
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||
}
|
||||
|
||||
type CreateFavoriteInput struct {
|
||||
@@ -160,6 +171,16 @@ type UpdateBoxInput struct {
|
||||
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateComponentInput struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
HTML *string `json:"html,omitempty"`
|
||||
W *int `json:"w,omitempty"`
|
||||
H *int `json:"h,omitempty"`
|
||||
Framed *bool `json:"framed,omitempty"`
|
||||
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateLayoutInput struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
# are px on a fixed 1400px-wide design canvas; see models.Box.
|
||||
#
|
||||
# kind is "widget" (a built-in Vue component named by `widget`) or "html"
|
||||
# (`html` rendered in a sandboxed iframe on the front end).
|
||||
# (`html` rendered in a sandboxed iframe on the front end). An html box with a
|
||||
# componentId is linked to that Component: its html is the component's, and
|
||||
# updateBox refuses to change it (component.graphql).
|
||||
|
||||
type Box {
|
||||
id: ID!
|
||||
@@ -24,6 +26,7 @@ type Box {
|
||||
framed: Boolean!
|
||||
hideOnMobile: Boolean!
|
||||
adminOnly: Boolean!
|
||||
componentId: ID
|
||||
}
|
||||
|
||||
input CreateBoxInput {
|
||||
@@ -40,6 +43,9 @@ input CreateBoxInput {
|
||||
framed: Boolean
|
||||
hideOnMobile: Boolean
|
||||
adminOnly: Boolean
|
||||
# Links the new box to this component; kind is then "html" and html is
|
||||
# ignored.
|
||||
componentId: ID
|
||||
}
|
||||
|
||||
input UpdateBoxInput {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Components: named HTML boxes that can be placed on any canvas page, either
|
||||
# as a copy (an ordinary box) or linked (a Box whose componentId is set).
|
||||
# Linked boxes share only the html — editing a component changes every box
|
||||
# linked to it — while title, geometry, frame and visibility stay each box's
|
||||
# own. title, w, h, framed and adminOnly here are what a newly placed box
|
||||
# starts with. See models.Component and graph/component_helpers.go.
|
||||
#
|
||||
# Admin only throughout, reads included, because a component may have been
|
||||
# saved from an adminOnly note. A linked box's html still reaches visitors
|
||||
# through the boxes query, which is the point.
|
||||
|
||||
type Component {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
name: String!
|
||||
title: String
|
||||
html: String!
|
||||
w: Int!
|
||||
h: Int!
|
||||
framed: Boolean!
|
||||
adminOnly: Boolean!
|
||||
# How many boxes are linked to it.
|
||||
uses: Int!
|
||||
}
|
||||
|
||||
input CreateComponentInput {
|
||||
name: String!
|
||||
title: String
|
||||
html: String!
|
||||
w: Int
|
||||
h: Int
|
||||
framed: Boolean
|
||||
adminOnly: Boolean
|
||||
}
|
||||
|
||||
input UpdateComponentInput {
|
||||
name: String
|
||||
title: String
|
||||
html: String
|
||||
w: Int
|
||||
h: Int
|
||||
framed: Boolean
|
||||
adminOnly: Boolean
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
# By name.
|
||||
components: [Component!]! @admin
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createComponent(input: CreateComponentInput!): Component! @admin
|
||||
# A new html changes every box linked to it.
|
||||
updateComponent(id: ID!, input: UpdateComponentInput!): Component! @admin
|
||||
# Detaches every linked box first, giving each its own copy of the html, so
|
||||
# no page changes.
|
||||
deleteComponent(id: ID!): Component! @admin
|
||||
# Makes html box `id` into a component named `name`, from its html, title,
|
||||
# size, frame and adminOnly, and links the box to it. Answers with the box.
|
||||
saveBoxAsComponent(id: ID!, name: String!): Box! @admin
|
||||
# Gives linked box `id` its own copy of the component's html and unlinks it.
|
||||
detachBox(id: ID!): Box! @admin
|
||||
}
|
||||
@@ -196,6 +196,12 @@ type Box struct {
|
||||
// AdminOnly boxes are never sent to anyone but an admin (the boxes
|
||||
// resolver filters them out), so they suit private notes.
|
||||
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
|
||||
// ComponentID links an html box to a Component, whose HTML it shows
|
||||
// instead of its own: the row's HTML is nil, and the resolvers fill it in
|
||||
// from the component before answering (graph/component_helpers.go). There
|
||||
// is deliberately no association field — with one, DB.Save(&box) would
|
||||
// write the component back too.
|
||||
ComponentID *uint `gorm:"index" json:"componentId"`
|
||||
}
|
||||
|
||||
// Page is an admin-created canvas page, served by the SPA's catch-all route
|
||||
@@ -254,3 +260,26 @@ type Layout struct {
|
||||
// Background is the page's background as JSON, or nil if it had none.
|
||||
Background *string `gorm:"type:text" json:"-"`
|
||||
}
|
||||
|
||||
// Component is a named HTML box that can be placed on any canvas page, either
|
||||
// as a copy (an ordinary box) or linked (a box with ComponentID set). Linked
|
||||
// boxes share only the HTML — editing it changes every one of them at once —
|
||||
// while title, geometry, frame and visibility stay each box's own, since
|
||||
// those are about where it sits on a page rather than what it is. Title, W,
|
||||
// H, Framed and AdminOnly are the defaults a newly placed box starts with.
|
||||
// Widgets are not components: a widget box is just a name, with nothing
|
||||
// worth sharing. The unique index is partial for the same reason as Page's.
|
||||
type Component 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_components_name,unique,where:deleted_at IS NULL" json:"name"`
|
||||
Title *string `json:"title"`
|
||||
HTML string `gorm:"type:text;not null" json:"html"`
|
||||
W int `gorm:"not null" json:"w"`
|
||||
H int `gorm:"not null" json:"h"`
|
||||
// No gorm default on Framed, for the same reason as Box.Framed.
|
||||
Framed bool `gorm:"not null" json:"framed"`
|
||||
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ func migrateDatabase(db *gorm.DB) error {
|
||||
&models.Page{},
|
||||
&models.Background{},
|
||||
&models.Layout{},
|
||||
&models.Component{},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
+16
-1
@@ -264,6 +264,21 @@ renders any page's boxes.
|
||||
page, load it on another. The copying happens on the server
|
||||
(`backend/graph/layout_helpers.go`); the browser only sees names and box
|
||||
counts. All of it is admin-only, since a layout keeps admin-only boxes.
|
||||
- **Components.** A **`Component`** (GraphQL type, `stores/components.js`) is
|
||||
a named HTML box. "+ New box" lists them and places a copy, an ordinary box.
|
||||
The "Components" button (`ComponentPanel.vue`) can also place one
|
||||
**linked**: the box has a `componentId`, the server answers with the
|
||||
component's html in its `html` (`fillLinked` in
|
||||
`backend/graph/component_helpers.go`), and saving the html in `BoxEditor`
|
||||
saves the component, so every linked box on every page changes. Only the
|
||||
html is shared; title, geometry, frame and visibility stay each box's own.
|
||||
"Save as component" in the editor makes a component from an html box and
|
||||
links it; "Detach" gives a linked box its own copy. Deleting a component
|
||||
detaches its boxes first, so no page changes. A layout keeps both the link
|
||||
and the html, and loading it links again only if the component still
|
||||
exists. The built-in starters in `templates.js` are not listed directly:
|
||||
"Import built-ins" in the panel makes them components, after which they can
|
||||
be edited or deleted like the rest. Admin-only throughout.
|
||||
- **Admin only.** A box or a page can be marked admin-only. The server never
|
||||
sends those to anyone else, so they are fit for private notes; admins see
|
||||
such boxes outlined, with a 🔒 in edit mode. The "Note" template starts
|
||||
@@ -301,7 +316,7 @@ renders any page's boxes.
|
||||
file through `@/uploads` (see "Uploading files") and puts an `<img>`/`<video>`
|
||||
tag for it at the cursor; "Choose upload" does the same with a file already
|
||||
stored, and "+ From uploads…" in the admin bar makes a box from one, as a
|
||||
drop would (`UploadPicker`). Starter HTML is in `templates.js`; links in a box
|
||||
drop would (`UploadPicker`). Built-in starter HTML is in `templates.js` (imported as components, above); links in a box
|
||||
need `target="_top"` or `_blank` (the Link templates set it), or they open
|
||||
inside the frame. A canvas given a `starter` has an import button in edit
|
||||
mode (it confirms first if the page isn't empty): only `/` has one, "Import
|
||||
|
||||
+28
-2
@@ -14,6 +14,11 @@
|
||||
* The list query returns boxes ordered by z, so a new box (given the top z)
|
||||
* belongs at the end. adminOnly boxes only come back for an admin — the
|
||||
* server filters them — so the canvas refetches when the session changes.
|
||||
*
|
||||
* A box with a `componentId` is linked to that component (stores/components.js):
|
||||
* the server answers with the component's html in `html`, and editing it goes
|
||||
* to the component. patchLinked() keeps every page already loaded in step when
|
||||
* a component changes, without refetching them.
|
||||
*/
|
||||
|
||||
import { createCrudStore } from "@/stores/createCrudStore";
|
||||
@@ -33,11 +38,15 @@ const BOX_FIELDS = `
|
||||
framed
|
||||
hideOnMobile
|
||||
adminOnly
|
||||
componentId
|
||||
`;
|
||||
|
||||
// The fields a duplicate copies. kind and widget/html are what make it the
|
||||
// same box; geometry is offset so the copy is visibly separate.
|
||||
const COPIED = ["page", "kind", "widget", "html", "title", "w", "h", "framed", "hideOnMobile", "adminOnly"];
|
||||
// same box — or componentId, which keeps a copy of a linked box linked;
|
||||
// geometry is offset so the copy is visibly separate.
|
||||
const COPIED = [
|
||||
"page", "kind", "widget", "html", "title", "w", "h", "framed", "hideOnMobile", "adminOnly", "componentId",
|
||||
];
|
||||
|
||||
const stores = new Map();
|
||||
|
||||
@@ -64,6 +73,11 @@ function defineFor(page) {
|
||||
const input = Object.fromEntries(COPIED.map((k) => [k, box[k]]));
|
||||
return create({ ...input, x: box.x + 20, y: box.y + 20, z: topZ() });
|
||||
},
|
||||
/** Swap in a box the server answered with from outside this store. */
|
||||
replaceLocal: (box) => {
|
||||
const idx = items.value.findIndex((b) => b.id === box.id);
|
||||
if (idx >= 0) items.value[idx] = box;
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -74,3 +88,15 @@ export function useBoxesStore(page) {
|
||||
if (!stores.has(page)) stores.set(page, defineFor(page));
|
||||
return stores.get(page)();
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply `patch` to every loaded box linked to component `componentId`, on
|
||||
* every page visited so far.
|
||||
*/
|
||||
export function patchLinked(componentId, patch) {
|
||||
for (const use of stores.values()) {
|
||||
for (const box of use().boxes) {
|
||||
if (box.componentId === componentId) Object.assign(box, patch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Saved components (the `Component` GraphQL type): named HTML boxes that can
|
||||
* be placed on any canvas page as a copy or linked — full CRUD, built on
|
||||
* createCrudStore(), plus the box-side actions.
|
||||
*
|
||||
* A linked box shows its component's html, so `update` is wrapped to push a
|
||||
* new html into every loaded page's boxes (stores/boxes.js patchLinked), and
|
||||
* `remove` unlinks them locally the way the server just did (each keeps the
|
||||
* html it showed). `uses` is kept roughly right locally (countUse) as this
|
||||
* tab places, detaches and deletes linked boxes, and the panel refetches the
|
||||
* list when it opens for the true figure.
|
||||
*
|
||||
* Admin only, so nothing fetches it until an admin opens the canvas's
|
||||
* Components panel or "+ New box" menu (views/home3/ComponentPanel.vue,
|
||||
* BoxCanvas.vue).
|
||||
*/
|
||||
|
||||
import { createCrudStore } from "@/stores/createCrudStore";
|
||||
import { gql } from "@/graphql";
|
||||
import { patchLinked, useBoxesStore } from "@/stores/boxes";
|
||||
import { TEMPLATES } from "@/views/home3/templates";
|
||||
|
||||
const COMPONENT_FIELDS = `
|
||||
id
|
||||
name
|
||||
title
|
||||
html
|
||||
w
|
||||
h
|
||||
framed
|
||||
adminOnly
|
||||
uses
|
||||
`;
|
||||
|
||||
// Matches BOX_FIELDS in stores/boxes.js, for the mutations that answer with
|
||||
// a box.
|
||||
const BOX_FIELDS = `
|
||||
id page kind widget html title x y w h z framed hideOnMobile adminOnly componentId
|
||||
`;
|
||||
|
||||
export const useComponentsStore = createCrudStore("components", {
|
||||
type: "Component",
|
||||
list: "components",
|
||||
fields: COMPONENT_FIELDS,
|
||||
// Created ones are put back in name order by sort() below.
|
||||
insert: "append",
|
||||
deleteReturns: "object",
|
||||
extend: ({ items, fetch, create, update, remove }) => {
|
||||
const sort = () => items.value.sort((a, b) => a.name.localeCompare(b.name));
|
||||
const countUse = (id, delta) => {
|
||||
const c = items.value.find((c) => c.id === id);
|
||||
if (c) c.uses = Math.max(0, c.uses + delta);
|
||||
};
|
||||
|
||||
return {
|
||||
countUse,
|
||||
|
||||
async create(input) {
|
||||
const created = await create(input);
|
||||
sort();
|
||||
return created;
|
||||
},
|
||||
|
||||
async update(id, input) {
|
||||
const updated = await update(id, input);
|
||||
if ("html" in input) patchLinked(id, { html: updated.html });
|
||||
sort();
|
||||
return updated;
|
||||
},
|
||||
|
||||
async remove(id) {
|
||||
await remove(id);
|
||||
patchLinked(id, { componentId: null });
|
||||
},
|
||||
|
||||
/**
|
||||
* Make html box `box` into a component named `name` and link it.
|
||||
* Throws on failure.
|
||||
*/
|
||||
async saveFromBox(box, name) {
|
||||
const data = await gql(
|
||||
`mutation SaveBoxAsComponent($id: ID!, $name: String!) {
|
||||
saveBoxAsComponent(id: $id, name: $name) { ${BOX_FIELDS} }
|
||||
}`,
|
||||
{ id: box.id, name },
|
||||
);
|
||||
useBoxesStore(box.page).replaceLocal(data.saveBoxAsComponent);
|
||||
await fetch();
|
||||
},
|
||||
|
||||
/** Give linked box `box` its own copy of the html. Throws on failure. */
|
||||
async detach(box) {
|
||||
const data = await gql(
|
||||
`mutation DetachBox($id: ID!) { detachBox(id: $id) { ${BOX_FIELDS} } }`,
|
||||
{ id: box.id },
|
||||
);
|
||||
useBoxesStore(box.page).replaceLocal(data.detachBox);
|
||||
countUse(box.componentId, -1);
|
||||
},
|
||||
|
||||
/**
|
||||
* Put `component` on page key `page` at `at` ({ x, y, z }): linked, or
|
||||
* as an ordinary box with a copy of its html. Answers with the new box.
|
||||
* Throws on failure.
|
||||
*/
|
||||
async place(component, page, at, linked) {
|
||||
const input = {
|
||||
kind: "html",
|
||||
title: component.title,
|
||||
w: component.w,
|
||||
h: component.h,
|
||||
framed: component.framed,
|
||||
adminOnly: component.adminOnly,
|
||||
...at,
|
||||
};
|
||||
if (linked) input.componentId = component.id;
|
||||
else input.html = component.html;
|
||||
const created = await useBoxesStore(page).create(input);
|
||||
if (linked) countUse(component.id, 1);
|
||||
return created;
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a component from each built-in starter in templates.js whose
|
||||
* name is free, and answer with how many were added. Deleted ones come
|
||||
* back; ones still there are left as they are. Throws on failure.
|
||||
*/
|
||||
async importBuiltins() {
|
||||
const taken = new Set(items.value.map((c) => c.name));
|
||||
let added = 0;
|
||||
for (const t of TEMPLATES) {
|
||||
if (taken.has(t.label)) continue;
|
||||
await create({
|
||||
name: t.label,
|
||||
title: t.title,
|
||||
html: t.html,
|
||||
w: t.size[0],
|
||||
h: t.size[1],
|
||||
framed: t.framed ?? true,
|
||||
adminOnly: t.adminOnly ?? false,
|
||||
});
|
||||
added++;
|
||||
}
|
||||
sort();
|
||||
return added;
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -30,14 +30,22 @@
|
||||
* The Layouts button saves the page as a named layout, or loads a saved one
|
||||
* onto it (LayoutPanel.vue, stores/layouts.js) — which is how a layout moves
|
||||
* from one page to another.
|
||||
*
|
||||
* "+ New box" offers the saved components (stores/components.js) as starters,
|
||||
* each placed as an ordinary box with a copy of its html, plus the widgets.
|
||||
* The Components button (ComponentPanel.vue) places them linked as well: a
|
||||
* linked box shows its component's html, so editing it in BoxEditor edits
|
||||
* every box linked to that component. Linked boxes are labelled with ⛓.
|
||||
*/
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { useMediaQuery } from "@vueuse/core";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useBoxesStore } from "@/stores/boxes";
|
||||
import { useBackgroundStore } from "@/stores/background";
|
||||
import { useComponentsStore } from "@/stores/components";
|
||||
import BackgroundEditor from "./BackgroundEditor.vue";
|
||||
import LayoutPanel from "./LayoutPanel.vue";
|
||||
import ComponentPanel from "./ComponentPanel.vue";
|
||||
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
|
||||
import UploadPicker from "@/components/util/UploadPicker.vue";
|
||||
import BoxFrame from "./BoxFrame.vue";
|
||||
@@ -46,7 +54,7 @@ import { panelWidth } from "./editorPrefs";
|
||||
import HtmlBox from "./HtmlBox.vue";
|
||||
import WidgetBox from "./WidgetBox.vue";
|
||||
import { WIDGETS } from "./widgetRegistry";
|
||||
import { TEMPLATES, imageHtml, videoHtml } from "./templates";
|
||||
import { imageHtml, videoHtml } from "./templates";
|
||||
import { isVideo, mediaSize, uploadFile } from "@/uploads";
|
||||
|
||||
const props = defineProps({
|
||||
@@ -72,8 +80,9 @@ store.fetch();
|
||||
const background = useBackgroundStore();
|
||||
background.show(props.page);
|
||||
onBeforeUnmount(() => background.hide(props.page));
|
||||
const backgroundOpen = ref(false);
|
||||
const layoutsOpen = ref(false);
|
||||
// Which of the left-hand panels is open: "background", "layouts",
|
||||
// "components" or null. They sit in the same place, so only one at a time.
|
||||
const panel = ref(null);
|
||||
const confirmation = ref(null);
|
||||
|
||||
const isMobile = useMediaQuery(MOBILE_QUERY);
|
||||
@@ -89,6 +98,12 @@ const editing = ref(false);
|
||||
const canEdit = computed(() => isAdmin.value && !isMobile.value);
|
||||
const inEditMode = computed(() => editing.value && canEdit.value);
|
||||
|
||||
// Admin only, so fetched on first entering edit mode, for "+ New box".
|
||||
const components = useComponentsStore();
|
||||
watch(inEditMode, (on) => {
|
||||
if (on && !components.loaded && !components.loading) components.fetch();
|
||||
});
|
||||
|
||||
const selectedId = ref(null);
|
||||
const selected = computed(() => store.boxes.find((b) => b.id === selectedId.value) ?? null);
|
||||
const preview = ref(null); // unsaved HTML for the selected box, from BoxEditor
|
||||
@@ -153,7 +168,10 @@ function onAction(box, action) {
|
||||
if (action === "front") run(() => store.bringToFront(box));
|
||||
else if (action === "back") run(() => store.sendToBack(box));
|
||||
else if (action === "duplicate") {
|
||||
run(async () => (selectedId.value = (await store.duplicate(box)).id));
|
||||
run(async () => {
|
||||
selectedId.value = (await store.duplicate(box)).id;
|
||||
if (box.componentId) components.countUse(box.componentId, 1);
|
||||
});
|
||||
} else if (action === "delete") {
|
||||
askConfirmation({
|
||||
title: "Delete box",
|
||||
@@ -162,7 +180,10 @@ function onAction(box, action) {
|
||||
}).then((confirmed) => {
|
||||
if (!confirmed) return;
|
||||
if (selectedId.value === box.id) selectedId.value = null;
|
||||
run(() => store.remove(box.id));
|
||||
run(async () => {
|
||||
await store.remove(box.id);
|
||||
if (box.componentId) components.countUse(box.componentId, -1);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -180,7 +201,8 @@ function finishConfirmation(confirmed) {
|
||||
}
|
||||
|
||||
function labelOf(box) {
|
||||
const name = box.title || (box.kind === "widget" ? box.widget : "HTML");
|
||||
let name = box.title || (box.kind === "widget" ? box.widget : "HTML");
|
||||
if (box.componentId) name = `⛓ ${name}`;
|
||||
return box.adminOnly ? `🔒 ${name}` : name;
|
||||
}
|
||||
|
||||
@@ -207,26 +229,31 @@ function addBox() {
|
||||
const choice = newChoice.value;
|
||||
newChoice.value = "";
|
||||
if (!choice) return;
|
||||
const [kind, key] = choice.split(":");
|
||||
const { x, y } = visibleOrigin();
|
||||
let input;
|
||||
if (kind === "widget") {
|
||||
const [w, h] = WIDGETS[key].size;
|
||||
input = { kind: "widget", widget: key, w, h };
|
||||
} else {
|
||||
const t = TEMPLATES[Number(key)];
|
||||
input = {
|
||||
kind: "html",
|
||||
html: t.html,
|
||||
title: t.title,
|
||||
w: t.size[0],
|
||||
h: t.size[1],
|
||||
framed: t.framed ?? true,
|
||||
adminOnly: t.adminOnly ?? false,
|
||||
};
|
||||
if (choice === "import") {
|
||||
run(() => components.importBuiltins());
|
||||
return;
|
||||
}
|
||||
const [kind, key] = choice.split(":");
|
||||
if (kind === "component") {
|
||||
const component = components.components.find((c) => c.id === key);
|
||||
if (component) placeComponent(component, false);
|
||||
return;
|
||||
}
|
||||
const { x, y } = visibleOrigin();
|
||||
const [w, h] = WIDGETS[key].size;
|
||||
run(async () => {
|
||||
const created = await store.create({ ...input, x, y, z: store.topZ() });
|
||||
const created = await store.create({ kind: "widget", widget: key, w, h, x, y, z: store.topZ() });
|
||||
selectedId.value = created.id;
|
||||
});
|
||||
}
|
||||
|
||||
// From "+ New box" (always a copy) or the Components panel (either). The
|
||||
// panel is closed, like selecting a box closes it, since the new box opens in
|
||||
// the editor and lands where the panel would cover it.
|
||||
function placeComponent(component, linked) {
|
||||
panel.value = null;
|
||||
run(async () => {
|
||||
const created = await components.place(component, props.page, { ...visibleOrigin(), z: store.topZ() }, linked);
|
||||
selectedId.value = created.id;
|
||||
});
|
||||
}
|
||||
@@ -323,27 +350,14 @@ async function placePicked(url) {
|
||||
// Leaving a box saves its unsaved HTML; BoxEditor does that itself as the
|
||||
// selection changes or it unmounts.
|
||||
function select(box) {
|
||||
backgroundOpen.value = false;
|
||||
layoutsOpen.value = false;
|
||||
panel.value = null;
|
||||
selectedId.value = box.id;
|
||||
}
|
||||
|
||||
// The background and layouts panels sit in the same place, so one closes the
|
||||
// other, and either closes the box editor.
|
||||
function toggleBackground() {
|
||||
backgroundOpen.value = !backgroundOpen.value;
|
||||
if (backgroundOpen.value) {
|
||||
layoutsOpen.value = false;
|
||||
selectedId.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
function toggleLayouts() {
|
||||
layoutsOpen.value = !layoutsOpen.value;
|
||||
if (layoutsOpen.value) {
|
||||
backgroundOpen.value = false;
|
||||
selectedId.value = null;
|
||||
}
|
||||
// Opening a panel closes the others and the box editor.
|
||||
function togglePanel(name) {
|
||||
panel.value = panel.value === name ? null : name;
|
||||
if (panel.value) selectedId.value = null;
|
||||
}
|
||||
|
||||
function toggleEdit() {
|
||||
@@ -362,17 +376,22 @@ function toggleEdit() {
|
||||
<button type="button" class="bar-btn" :class="{ on: editing }" @click="toggleEdit">
|
||||
{{ editing ? "Done" : "Edit layout" }}
|
||||
</button>
|
||||
<button type="button" class="bar-btn" :class="{ on: backgroundOpen }" @click="toggleBackground">
|
||||
<button type="button" class="bar-btn" :class="{ on: panel === 'background' }" @click="togglePanel('background')">
|
||||
Background
|
||||
</button>
|
||||
<button type="button" class="bar-btn" :class="{ on: layoutsOpen }" @click="toggleLayouts">
|
||||
<button type="button" class="bar-btn" :class="{ on: panel === 'layouts' }" @click="togglePanel('layouts')">
|
||||
Layouts
|
||||
</button>
|
||||
<button type="button" class="bar-btn" :class="{ on: panel === 'components' }" @click="togglePanel('components')">
|
||||
Components
|
||||
</button>
|
||||
<template v-if="inEditMode">
|
||||
<select v-model="newChoice" class="bar-btn" @change="addBox">
|
||||
<option value="" disabled>+ New box…</option>
|
||||
<optgroup label="HTML">
|
||||
<option v-for="(t, i) in TEMPLATES" :key="t.label" :value="`html:${i}`">{{ t.label }}</option>
|
||||
<option v-if="!components.loaded" value="" disabled>Loading…</option>
|
||||
<option v-else-if="!components.components.length" value="import">Import built-in templates</option>
|
||||
<option v-for="c in components.components" :key="c.id" :value="`component:${c.id}`">{{ c.name }}</option>
|
||||
</optgroup>
|
||||
<optgroup label="Widget">
|
||||
<option v-for="name in Object.keys(WIDGETS)" :key="name" :value="`widget:${name}`">{{ name }}</option>
|
||||
@@ -454,8 +473,9 @@ function toggleEdit() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BackgroundEditor v-if="backgroundOpen && canEdit" :page="page" @close="backgroundOpen = false" />
|
||||
<LayoutPanel v-if="layoutsOpen && canEdit" :page="page" @close="layoutsOpen = false" />
|
||||
<BackgroundEditor v-if="panel === 'background' && canEdit" :page="page" @close="panel = null" />
|
||||
<LayoutPanel v-if="panel === 'layouts' && canEdit" :page="page" @close="panel = null" />
|
||||
<ComponentPanel v-if="panel === 'components' && canEdit" @close="panel = null" @place="placeComponent" />
|
||||
|
||||
<BoxEditor
|
||||
v-if="inEditMode && selected"
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
* the panel. Saving every keystroke would push half-written markup to
|
||||
* every visitor; leaving is the point it is finished.
|
||||
*
|
||||
* A box linked to a component (stores/components.js) edits the component: its
|
||||
* html is saved there, and so changes on every box linked to it. Detach gives
|
||||
* the box its own copy — an unsaved draft is kept, and then saves to this box
|
||||
* alone. An unlinked html box can be saved as a new component, which links it.
|
||||
*
|
||||
* "Insert upload" uploads a file (@/uploads) and puts a tag for it at the
|
||||
* cursor — the way to add pictures to an existing box, e.g. a gallery.
|
||||
* "Choose upload" does the same with a file that is already uploaded.
|
||||
@@ -25,6 +30,7 @@
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useBoxesStore } from "@/stores/boxes";
|
||||
import { useComponentsStore } from "@/stores/components";
|
||||
import { ACCEPT, tagFor, uploadFile } from "@/uploads";
|
||||
import CodeEditor from "./CodeEditor.vue";
|
||||
import { FONT_SIZE, PANEL_WIDTH, fontSize, panelWidth, setPanelWidth, zoom } from "./editorPrefs";
|
||||
@@ -49,13 +55,26 @@ const draftHtml = ref(props.box.html ?? "");
|
||||
const saving = ref(false);
|
||||
const dirty = computed(() => props.box.kind === "html" && draftHtml.value !== (props.box.html ?? ""));
|
||||
|
||||
const components = useComponentsStore();
|
||||
if (!components.loaded && !components.loading) components.fetch();
|
||||
const component = computed(() =>
|
||||
props.box.componentId ? components.components.find((c) => c.id === props.box.componentId) ?? null : null,
|
||||
);
|
||||
const savingAs = ref(false); // the "Save as component" name field is showing
|
||||
const componentName = ref("");
|
||||
|
||||
// Where a box's html is saved: its component if it is linked, else itself.
|
||||
function storeHtml(box, html) {
|
||||
return box.componentId ? components.update(box.componentId, { html }) : store.update(box.id, { html });
|
||||
}
|
||||
|
||||
// Save the draft of box `id` if it differs from what is stored. Fire and
|
||||
// forget: it runs as the editor moves on or unmounts, with nothing left to
|
||||
// show progress in, so a failure is only reported through `error`.
|
||||
function flush(id) {
|
||||
const box = store.boxes.find((b) => b.id === id);
|
||||
if (!box || box.kind !== "html" || draftHtml.value === (box.html ?? "")) return;
|
||||
store.update(id, { html: draftHtml.value }).catch((err) => emit("error", err));
|
||||
storeHtml(box, draftHtml.value).catch((err) => emit("error", err));
|
||||
}
|
||||
|
||||
// Switching to another box: save the old one's draft, drop its preview, start
|
||||
@@ -66,6 +85,7 @@ watch(
|
||||
flush(oldId);
|
||||
emit("preview", null);
|
||||
draftHtml.value = props.box.html ?? "";
|
||||
savingAs.value = false;
|
||||
},
|
||||
);
|
||||
|
||||
@@ -94,7 +114,7 @@ async function saveHtml() {
|
||||
if (!dirty.value || saving.value) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
await store.update(props.box.id, { html: draftHtml.value });
|
||||
await storeHtml(props.box, draftHtml.value);
|
||||
emit("preview", null);
|
||||
} catch (err) {
|
||||
emit("error", err);
|
||||
@@ -103,6 +123,30 @@ async function saveHtml() {
|
||||
}
|
||||
}
|
||||
|
||||
// The draft is saved to the box first, so the component starts from what is
|
||||
// on screen.
|
||||
async function saveAsComponent() {
|
||||
const name = componentName.value.trim();
|
||||
if (!name) return;
|
||||
try {
|
||||
if (dirty.value) await store.update(props.box.id, { html: draftHtml.value });
|
||||
await components.saveFromBox(props.box, name);
|
||||
emit("preview", null);
|
||||
savingAs.value = false;
|
||||
componentName.value = "";
|
||||
} catch (err) {
|
||||
emit("error", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function detach() {
|
||||
try {
|
||||
await components.detach(props.box);
|
||||
} catch (err) {
|
||||
emit("error", err);
|
||||
}
|
||||
}
|
||||
|
||||
function saveNumber(field, event) {
|
||||
const value = Math.round(Number(event.target.value));
|
||||
if (!Number.isFinite(value) || value === props.box[field]) {
|
||||
@@ -208,6 +252,22 @@ function resizeByKey(event) {
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div v-if="box.componentId" class="linked">
|
||||
<span>
|
||||
Linked to <b>{{ component?.name ?? "a component" }}</b>
|
||||
<template v-if="component"> · {{ component.uses }} box{{ component.uses === 1 ? "" : "es" }}</template>
|
||||
— saving the html changes every linked box.
|
||||
</span>
|
||||
<button type="button" class="save small" title="Give this box its own copy of the html" @click="detach">
|
||||
Detach
|
||||
</button>
|
||||
</div>
|
||||
<form v-else-if="box.kind === 'html' && savingAs" class="linked" @submit.prevent="saveAsComponent">
|
||||
<input v-model="componentName" type="text" placeholder="Component name" required class="flex-1" />
|
||||
<button type="submit" class="save small">Save</button>
|
||||
<button type="button" class="save small" @click="savingAs = false">Cancel</button>
|
||||
</form>
|
||||
|
||||
<label v-if="box.kind === 'widget'" class="field">
|
||||
<span>Widget</span>
|
||||
<select :value="box.widget" @change="save({ widget: $event.target.value })">
|
||||
@@ -284,6 +344,15 @@ function resizeByKey(event) {
|
||||
>
|
||||
Choose upload
|
||||
</button>
|
||||
<button
|
||||
v-if="!box.componentId"
|
||||
type="button"
|
||||
class="save"
|
||||
title="Save this box as a reusable component, and link it"
|
||||
@click="savingAs = true"
|
||||
>
|
||||
Save as component
|
||||
</button>
|
||||
<button type="button" class="save" :disabled="!dirty || saving" @click="saveHtml">
|
||||
{{ saving ? "Saving…" : dirty ? "Save" : "Saved" }}
|
||||
</button>
|
||||
@@ -422,4 +491,24 @@ function resizeByKey(event) {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
.save.small {
|
||||
padding: 0.1rem 0.6rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.linked {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.4rem 0.5rem;
|
||||
font-size: 0.85rem;
|
||||
border: 1px dashed var(--color-primary);
|
||||
}
|
||||
.linked input {
|
||||
min-width: 0;
|
||||
padding: 3px 5px;
|
||||
color: var(--color-secondary);
|
||||
background: var(--color-surface-deep);
|
||||
border: 1px solid var(--color-quaternary);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
<script setup>
|
||||
/**
|
||||
* The admin's components panel, opened from BoxCanvas's "Components" button:
|
||||
* place a saved component on this page, linked or as a copy, and rename or
|
||||
* delete them (stores/components.js).
|
||||
*
|
||||
* Placing is BoxCanvas's job (it knows where the admin is looking), so this
|
||||
* only emits `place`. A component is made by "Save as component" in the box
|
||||
* editor, or by "Import built-ins", which turns the starters in templates.js
|
||||
* into components. Its html is edited through any box linked to it.
|
||||
*
|
||||
* The list is refetched on opening, because `uses` changes whenever a linked
|
||||
* box is placed or deleted, on any page.
|
||||
*/
|
||||
import { ref } from "vue";
|
||||
import { useComponentsStore } from "@/stores/components";
|
||||
import OverlayShell from "@/components/util/OverlayShell.vue";
|
||||
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
|
||||
|
||||
const emit = defineEmits(["close", "place"]);
|
||||
const open = ref(true);
|
||||
|
||||
const components = useComponentsStore();
|
||||
components.fetch();
|
||||
|
||||
const busy = ref(false);
|
||||
const error = ref("");
|
||||
const notice = ref("");
|
||||
const deleteTarget = ref(null);
|
||||
const renaming = ref(null); // id of the component whose name is being edited
|
||||
const renameDraft = ref("");
|
||||
|
||||
function close() {
|
||||
open.value = false;
|
||||
emit("close");
|
||||
}
|
||||
|
||||
async function act(action, failure) {
|
||||
error.value = "";
|
||||
notice.value = "";
|
||||
busy.value = true;
|
||||
try {
|
||||
await action();
|
||||
return true;
|
||||
} catch (err) {
|
||||
error.value = err?.message || failure;
|
||||
return false;
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startRename(component) {
|
||||
renaming.value = component.id;
|
||||
renameDraft.value = component.name;
|
||||
}
|
||||
|
||||
async function rename(component) {
|
||||
const ok = await act(
|
||||
() => components.update(component.id, { name: renameDraft.value.trim() }),
|
||||
"Failed to rename",
|
||||
);
|
||||
if (ok) renaming.value = null;
|
||||
}
|
||||
|
||||
function confirmDelete() {
|
||||
const component = deleteTarget.value;
|
||||
deleteTarget.value = null;
|
||||
act(() => components.remove(component.id), "Failed to delete");
|
||||
}
|
||||
|
||||
function importBuiltins() {
|
||||
act(async () => {
|
||||
const added = await components.importBuiltins();
|
||||
notice.value = added ? `Imported ${added}.` : "All the built-ins are already here.";
|
||||
}, "Failed to import");
|
||||
}
|
||||
|
||||
function describe(component) {
|
||||
const parts = [`${component.w}×${component.h}`];
|
||||
parts.push(component.uses ? `${component.uses} linked box${component.uses === 1 ? "" : "es"}` : "not linked anywhere");
|
||||
if (component.adminOnly) parts.push("admin only");
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
function deleteMessage(component) {
|
||||
const base = `Delete the component “${component.name}”?`;
|
||||
if (!component.uses) return base;
|
||||
return `${base} Boxes linked to it (${component.uses}) keep its html as their own copy, so no page changes.`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<OverlayShell v-model="open" title="Components" @close="close">
|
||||
<div class="component-panel bdr-2 bg-surface">
|
||||
<h3>Components</h3>
|
||||
<p class="hint">
|
||||
Linked boxes share the component's html: editing one edits them all. A copy is an ordinary box.
|
||||
Save a box as a component from the box editor.
|
||||
</p>
|
||||
|
||||
<p v-if="components.error" class="text-tertiary">Couldn't load the components.</p>
|
||||
<p v-else-if="components.loaded && !components.components.length" class="hint">
|
||||
No components yet. Import the built-in starters, or save a box from the box editor.
|
||||
</p>
|
||||
<ul v-else class="list">
|
||||
<li v-for="component in components.components" :key="component.id">
|
||||
<form v-if="renaming === component.id" class="row" @submit.prevent="rename(component)">
|
||||
<input v-model="renameDraft" type="text" required class="flex-1" />
|
||||
<button type="submit" class="bar-btn small" :disabled="busy">Save</button>
|
||||
<button type="button" class="bar-btn small" @click="renaming = null">Cancel</button>
|
||||
</form>
|
||||
<template v-else>
|
||||
<span class="name">{{ component.name }}</span>
|
||||
<span class="hint">{{ describe(component) }}</span>
|
||||
<span class="row">
|
||||
<button type="button" class="bar-btn small" @click="emit('place', component, true)">Place linked</button>
|
||||
<button type="button" class="bar-btn small" @click="emit('place', component, false)">Place copy</button>
|
||||
<button type="button" class="bar-btn small" @click="startRename(component)">Rename</button>
|
||||
<button type="button" class="bar-btn small danger" @click="deleteTarget = component">Delete</button>
|
||||
</span>
|
||||
</template>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="row">
|
||||
<button type="button" class="bar-btn" @click="close">Close</button>
|
||||
<button
|
||||
type="button"
|
||||
class="bar-btn"
|
||||
:disabled="busy || !components.loaded"
|
||||
title="Add the starters from templates.js that aren't here yet"
|
||||
@click="importBuiltins"
|
||||
>
|
||||
Import built-ins
|
||||
</button>
|
||||
<span v-if="busy" class="hint">Working…</span>
|
||||
<span v-else-if="notice" class="hint">{{ notice }}</span>
|
||||
</div>
|
||||
<p v-if="error" class="text-tertiary">{{ error }}</p>
|
||||
</div>
|
||||
</OverlayShell>
|
||||
|
||||
<ConfirmDialog
|
||||
v-if="deleteTarget"
|
||||
:model-value="true"
|
||||
title="Delete component"
|
||||
:message="deleteMessage(deleteTarget)"
|
||||
confirm-label="Delete"
|
||||
@confirm="confirmDelete"
|
||||
@cancel="deleteTarget = null"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.component-panel {
|
||||
position: fixed;
|
||||
top: 80px;
|
||||
left: 16px;
|
||||
z-index: 65;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
width: min(420px, calc(100vw - 32px));
|
||||
max-height: calc(100vh - 100px);
|
||||
overflow-y: auto;
|
||||
padding: 0.75rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
h3 {
|
||||
margin: 0;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.list li {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding-bottom: 0.5rem;
|
||||
border-bottom: 1px solid var(--color-quaternary);
|
||||
}
|
||||
.name {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--color-muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.bar-btn {
|
||||
padding: 0.25rem 0.75rem;
|
||||
color: var(--color-primary);
|
||||
background: var(--color-link-bg);
|
||||
border: 2px solid var(--color-quaternary);
|
||||
font-family: var(--font-heading);
|
||||
font-size: 1.1rem;
|
||||
letter-spacing: 0.025em;
|
||||
cursor: pointer;
|
||||
}
|
||||
.bar-btn:hover {
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
.bar-btn:disabled {
|
||||
opacity: 0.5;
|
||||
}
|
||||
.bar-btn.small {
|
||||
padding: 0.1rem 0.5rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.bar-btn.danger:hover {
|
||||
border-color: var(--color-tertiary);
|
||||
color: var(--color-tertiary);
|
||||
}
|
||||
</style>
|
||||
@@ -1,8 +1,16 @@
|
||||
/**
|
||||
* Starter HTML for the "New box" menu. Each runs inside the sandboxed iframe
|
||||
* (see HtmlBox.vue), so scripts work but can only reach APIs that allow
|
||||
* cross-origin requests from an opaque origin — i.e. that answer with
|
||||
* `Access-Control-Allow-Origin: *` and need no key. Open-Meteo is one.
|
||||
* The built-in starter HTML. The "+ New box" menu no longer reads TEMPLATES
|
||||
* directly: it lists saved components, and TEMPLATES is what the Components
|
||||
* panel's "Import built-ins" turns into components (stores/components.js), so
|
||||
* they can be edited and deleted like any other. Changing an entry here only
|
||||
* reaches a site whose admin imports it again (after deleting the old one).
|
||||
* The helpers at the bottom are still used directly, by dropped uploads and
|
||||
* the starter layouts.
|
||||
*
|
||||
* Each runs inside the sandboxed iframe (see HtmlBox.vue), so scripts work but
|
||||
* can only reach APIs that allow cross-origin requests from an opaque origin —
|
||||
* i.e. that answer with `Access-Control-Allow-Origin: *` and need no key.
|
||||
* Open-Meteo is one.
|
||||
*
|
||||
* The site's colour and font tokens are already defined in the frame
|
||||
* (frameStyles.js), so templates use var(--color-…) freely.
|
||||
@@ -158,8 +166,9 @@ const videoHtml = (src) => `<style>
|
||||
<video src="${src}" controls loop muted></video>`;
|
||||
|
||||
/**
|
||||
* Menu entries; `size` is [w, h] in canvas px. `adminOnly` sets the new
|
||||
* box's flag, which can be changed afterwards in the editor.
|
||||
* Built-in starters; `label` becomes the component's name and `size` ([w, h]
|
||||
* in canvas px) its default size. `adminOnly` sets a new box's flag, which can
|
||||
* be changed afterwards in the editor.
|
||||
*/
|
||||
export const TEMPLATES = [
|
||||
{ label: "Note (admin only)", title: "Note", html: NOTE, size: [260, 200], framed: false, adminOnly: true },
|
||||
|
||||
Reference in New Issue
Block a user