Let the canvas panels choose from files already uploaded
Test and deploy / deploy (push) Has been cancelled
Test and deploy / test (push) Successful in 2m4s

The Background panel, the Box editor and the canvas admin bar could only
take a new upload, so reusing a picture meant uploading it again or
pasting its URL. Each now has a picker (UploadPicker.vue): a grid of the
public uploads, newest first, filterable by name.

It lists through a new admin-only GET /api/uploads (Uploads.List), the
union of the Garage bucket and the disk fallback, since nginx serves
from both; a bucket that can't list falls back to the disk's files.
Admin-only because upload URLs are public but unguessable, and a public
listing would give every one away. Private files and anything off the
UploadTypes allow-list are never listed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 19:59:03 +01:00
co-authored by Claude Opus 5.5
parent 1ddaff0690
commit 3fa456a063
12 changed files with 498 additions and 40 deletions
+1 -1
View File
@@ -63,7 +63,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
**Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`.
**Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). nginx serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7.
**Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. `GET /api/uploads` (admin only, `Uploads.List`, `listUploads()`) lists what is stored, bucket and disk merged, for `components/util/UploadPicker.vue`, the "choose an existing upload" modal used by the canvas's Background panel, Box editor and admin bar. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). nginx serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7.
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/nginx/payloads.log` via `nginx/payload_log.conf`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. nginx runs one worker per CPU and has a healthcheck (`/nginx-health` on :80); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea's commit-pinned history views and archives are admin-gated in nginx because a crawler swarm hammers them; the branch views stay public.
+5 -1
View File
@@ -173,6 +173,7 @@ for the things GraphQL cannot do:
| `/auth/*` | cookie handling and the status-code-only admin probe |
| `/spotify/callback` | OAuth providers redirect a *browser* here |
| `/uploads`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
| `/uploads` (GET, admin) | lists the stored files, next to the endpoint that stores them |
| `/notes/*path` | streams a file download, not JSON |
| `/ws` | WebSocket upgrade |
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
@@ -235,7 +236,10 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
to disk alone when `S3_ENDPOINT` is unset; private ones always to disk
(nginx cannot gate a bucket). nginx serves `/uploads/` from the bucket
first and disk second, so either store's files work at the same URL. A new
handler that takes a file calls `store.Uploads.Save`.
handler that takes a file calls `store.Uploads.Save`. `Uploads.List` (behind
admin-only `GET /uploads`, for the canvas's upload picker) returns the union
of bucket and disk, allow-listed types only, newest first; it is admin-only
because listing would give away every unguessable URL.
- **notes.go** — path-traversal-safe file lookup for the notes directory.
- **seed.go** — dev-only test data. Creates an admin with the password
`password`, so it must never run in production (`SEED_DB=true` is set only
+19
View File
@@ -49,6 +49,25 @@ func (store *Store) Upload(ctx *gin.Context) {
}
}
// ListUploads backs GET /uploads (admin): every public upload, newest first,
// for the upload picker on the canvas pages (vue/src/components/util/
// UploadPicker.vue). It answers {"files": [{name, url, size, modified}]}.
//
// Admin-only because the listing is the one thing that turns unguessable
// upload URLs into known ones; see services.Uploads.List.
func (store *Store) ListUploads(ctx *gin.Context) {
files, err := store.Uploads.List(ctx.Request.Context())
if err != nil {
log.Printf("[upload] listing failed: %v", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list uploads"})
return
}
if files == nil {
files = []services.StoredFile{} // [] rather than null for the frontend
}
ctx.JSON(http.StatusOK, gin.H{"files": files})
}
// requestIsAdmin reports whether the caller's access token carries admin=true.
//
// This route sits in the `protected` group, which runs AuthMiddlewear but not
+1
View File
@@ -190,6 +190,7 @@ func main() {
// the handler checks the cookies itself to decide admin privileges.
r.GET("/ws", store.ConnectWebSocket)
protected.POST("/uploads", store.Upload)
admin.GET("/uploads", store.ListUploads)
// NOTES
admin.GET("/notes/*path", store.GetNoteFile)
+124 -3
View File
@@ -4,13 +4,16 @@ import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
@@ -184,13 +187,51 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
return prefix + name, nil
}
// StoredFile is one public upload, as listed for the admin's upload picker.
type StoredFile struct {
Name string `json:"name"`
URL string `json:"url"`
Size int64 `json:"size"`
Modified time.Time `json:"modified"`
}
// List returns every public upload, newest first. Private files are never
// listed: they live in their own store, which this doesn't touch.
//
// The caller must be an admin. An upload's URL is public but unguessable, and
// that is the only thing keeping a file nobody linked to from being found; a
// listing anyone could read would hand every one of them out.
//
// Only names with an extension on the allow-list are returned, so anything
// else that ends up in the bucket or the directory (by hand, through
// garage-webui) never reaches a page through the picker.
func (u *Uploads) List(ctx context.Context) ([]StoredFile, error) {
files, err := u.public.List(ctx)
if err != nil {
return nil, err
}
out := files[:0]
for _, f := range files {
if _, ok := UploadTypes[strings.ToLower(filepath.Ext(f.Name))]; ok {
f.URL = publicURLPrefix + f.Name
out = append(out, f)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Modified.After(out[j].Modified) })
return out, nil
}
// ---- Stores ----------------------------------------------------------------
// FileStore stores one file under key. r is a ReadSeeker because the S3
// client must hash the body before sending it over plain HTTP, and because
// FallbackFileStore rewinds it to retry; a multipart.File satisfies it.
// FileStore stores one file under key, and lists what it holds. r is a
// ReadSeeker because the S3 client must hash the body before sending it over
// plain HTTP, and because FallbackFileStore rewinds it to retry; a
// multipart.File satisfies it.
//
// List returns top-level files only, with URL unset (Uploads.List fills it).
type FileStore interface {
Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error
List(ctx context.Context) ([]StoredFile, error)
}
// DiskFileStore writes files into Dir, creating it if needed.
@@ -212,6 +253,31 @@ func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _
return out.Close()
}
// List skips subdirectories, which is what keeps the private/ directory
// (inside the public one on the volume) out of the listing. A directory that
// doesn't exist yet just holds nothing.
func (d DiskFileStore) List(_ context.Context) ([]StoredFile, error) {
entries, err := os.ReadDir(d.Dir)
if errors.Is(err, fs.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var files []StoredFile
for _, e := range entries {
if !e.Type().IsRegular() {
continue
}
info, err := e.Info()
if err != nil {
continue // deleted between ReadDir and here
}
files = append(files, StoredFile{Name: e.Name(), Size: info.Size(), Modified: info.ModTime()})
}
return files, nil
}
// S3FileStore writes files into one bucket of an S3-compatible server.
type S3FileStore struct {
client *s3.Client
@@ -266,6 +332,31 @@ func (s *S3FileStore) Put(ctx context.Context, key, contentType string, r io.Rea
return nil
}
// List pages through the whole bucket. Keys containing "/" are skipped: they
// are not uploads (Save never makes one) but something put under a prefix by
// hand, and nginx's /uploads/<name> only ever serves a top-level name anyway.
func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
defer cancel()
var files []StoredFile
pages := s3.NewListObjectsV2Paginator(s.client, &s3.ListObjectsV2Input{Bucket: aws.String(s.bucket)})
for pages.HasMorePages() {
page, err := pages.NextPage(ctx)
if err != nil {
return nil, fmt.Errorf("s3 list %s: %w", s.bucket, err)
}
for _, obj := range page.Contents {
key := aws.ToString(obj.Key)
if key == "" || strings.Contains(key, "/") {
continue
}
files = append(files, StoredFile{Name: key, Size: aws.ToInt64(obj.Size), Modified: aws.ToTime(obj.LastModified)})
}
}
return files, nil
}
// FallbackFileStore tries Primary and, if that fails, logs it and writes to
// Fallback instead. The upload still succeeds and its URL still works (nginx
// looks in both places), so a Garage outage costs a log line rather than
@@ -286,3 +377,33 @@ func (f FallbackFileStore) Put(ctx context.Context, key, contentType string, r i
}
return f.Fallback.Put(ctx, key, contentType, r, size)
}
// List is the union of both stores, since nginx serves from both: the
// fallback holds whatever was written while the primary was down (and, on
// the live volume, the pre-Garage copies). A name in both is listed once,
// with the primary's details. A primary that can't list is logged and the
// fallback's files are returned alone, as for Put.
func (f FallbackFileStore) List(ctx context.Context) ([]StoredFile, error) {
primary, err := f.Primary.List(ctx)
if err != nil {
log.Printf("[upload] primary store failed to list, listing fallback only: %v", err)
primary = nil
}
fallback, fbErr := f.Fallback.List(ctx)
if fbErr != nil {
if err != nil {
return nil, fmt.Errorf("listing both stores: %v; %w", err, fbErr)
}
log.Printf("[upload] fallback store failed to list: %v", fbErr)
}
seen := make(map[string]bool, len(primary))
for _, file := range primary {
seen[file.Name] = true
}
for _, file := range fallback {
if !seen[file.Name] {
primary = append(primary, file)
}
}
return primary, nil
}
+98 -1
View File
@@ -14,6 +14,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
)
// Covered here: the type table (the upload trust boundary's data), Save's
@@ -21,7 +22,7 @@ import (
// fallback — including against a real S3 client talking to a server that
// refuses the write, since "Garage said no" is the case it exists for.
//
// Not covered: a successful PutObject against Garage. That needs the garage
// Not covered: a successful PutObject or ListObjectsV2 against Garage. That needs the garage
// container; it is checked by hand in the stack (DEPLOYMENT.md, "Garage").
// fileHeader builds the *multipart.FileHeader a handler would get from
@@ -59,6 +60,17 @@ func (r *recordingStore) Put(_ context.Context, key, contentType string, rd io.R
return nil
}
func (r *recordingStore) List(context.Context) ([]StoredFile, error) { return nil, nil }
// listStore lists a fixed set of files, or fails.
type listStore struct {
files []StoredFile
err error
}
func (l listStore) Put(context.Context, string, string, io.ReadSeeker, int64) error { return nil }
func (l listStore) List(context.Context) ([]StoredFile, error) { return l.files, l.err }
func TestUploadTypes(t *testing.T) {
t.Run("nothing executable or markup is allowed", func(t *testing.T) {
// Served from our own origin with no login, so anything a browser
@@ -209,3 +221,88 @@ func TestFallbackWhenBucketRefuses(t *testing.T) {
t.Fatalf("fallback file has %d bytes (%v), want %d", len(got), err, len(img))
}
}
func TestDiskFileStoreList(t *testing.T) {
if files, err := (DiskFileStore{Dir: filepath.Join(t.TempDir(), "missing")}).List(context.Background()); err != nil || len(files) != 0 {
t.Fatalf("missing dir: got %v, %v; want nothing and no error", files, err)
}
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "a.png"), []byte("abc"), 0644)
os.MkdirAll(filepath.Join(dir, "private"), 0755)
os.WriteFile(filepath.Join(dir, "private", "secret.png"), []byte("x"), 0644)
files, err := (DiskFileStore{Dir: dir}).List(context.Background())
if err != nil {
t.Fatal(err)
}
if len(files) != 1 || files[0].Name != "a.png" || files[0].Size != 3 {
t.Fatalf("got %+v, want just a.png (3 bytes): private/ must not be listed", files)
}
}
func TestFallbackFileStoreList(t *testing.T) {
ctx := context.Background()
bucket := listStore{files: []StoredFile{{Name: "a.png", Size: 1}, {Name: "b.png"}}}
disk := listStore{files: []StoredFile{{Name: "a.png", Size: 2}, {Name: "c.png"}}}
files, err := FallbackFileStore{Primary: bucket, Fallback: disk}.List(ctx)
if err != nil {
t.Fatal(err)
}
names := map[string]int64{}
for _, f := range files {
names[f.Name] = f.Size
}
if len(files) != 3 || names["a.png"] != 1 || len(names) != 3 {
t.Errorf("got %+v, want a (from the bucket), b and c once each", files)
}
t.Run("bucket down", func(t *testing.T) {
files, err := FallbackFileStore{Primary: listStore{err: errors.New("down")}, Fallback: disk}.List(ctx)
if err != nil || len(files) != 2 {
t.Errorf("got %+v, %v; want the disk's two files", files, err)
}
})
t.Run("both down", func(t *testing.T) {
_, err := FallbackFileStore{Primary: listStore{err: errors.New("down")}, Fallback: listStore{err: errors.New("gone")}}.List(ctx)
if err == nil {
t.Error("want an error when neither store can list")
}
})
}
func TestFallbackListWhenBucketRefuses(t *testing.T) {
// The real S3 client against a server that refuses: the listing still
// comes back, from disk.
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
}))
defer srv.Close()
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "on-disk.png"), pngBytes(), 0644)
u := NewUploads(S3Config{Endpoint: srv.URL, Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}, dir, filepath.Join(dir, "private"))
files, err := u.List(context.Background())
if err != nil || len(files) != 1 || files[0].URL != "/uploads/on-disk.png" {
t.Fatalf("got %+v, %v; want the one disk file", files, err)
}
}
func TestUploadsList(t *testing.T) {
now := time.Now()
u := &Uploads{public: listStore{files: []StoredFile{
{Name: "old.png", Modified: now.Add(-time.Hour)},
{Name: "page.html", Modified: now},
{Name: "new.JPG", Modified: now.Add(-time.Minute)},
{Name: "noext", Modified: now},
}}}
files, err := u.List(context.Background())
if err != nil {
t.Fatal(err)
}
if len(files) != 2 || files[0].URL != "/uploads/new.JPG" || files[1].URL != "/uploads/old.png" {
t.Fatalf("got %+v, want new.JPG then old.png, nothing off the allow-list", files)
}
}
+9 -3
View File
@@ -160,7 +160,10 @@ the allowed types, the 10MB limit and the file name, and stores the file in
Garage. A refused file rejects with an `ApiError` whose message can be shown
as-is. `kindOf(url)` says image/video/audio/file, `tagFor(url)` gives the
markup for a box, `isUploadUrl(url)` checks a URL from someone else before
rendering it, and `mediaSize(file)` reads an image or video's dimensions.
rendering it, and `mediaSize(file)` reads an image or video's dimensions
(from a `File` or a stored URL). `listUploads()` (admin only) lists every
public upload, newest first; `components/util/UploadPicker.vue` is the modal
that shows them as a grid to choose from.
`{ private: true }` (admin only) is for private chat attachments; never use
it for anything shown in a canvas box, whose sandboxed frame has no cookie.
@@ -239,7 +242,8 @@ renders any page's boxes.
GraphQL, `stores/background.js`): a colour, an image, and whether the image
fills the window, fits inside it or tiles. Admins set it with the
"Background" button next to "Edit layout" (`BackgroundEditor.vue`), which
previews live and takes an uploaded or dropped image. `DefaultLayout` paints
previews live and takes an uploaded, dropped or already-uploaded image
(`UploadPicker`). `DefaultLayout` paints
it behind the whole window, navbar included, while that canvas is mounted,
and falls back to the halftone. Renaming or deleting a page carries its
background along; an admin-only page's background is hidden with it.
@@ -275,7 +279,9 @@ renders any page's boxes.
Image and video files dropped onto the canvas in edit mode are uploaded and
each becomes an unframed box at the drop point. "Insert upload" stores a
file through `@/uploads` (see "Uploading files") and puts an `<img>`/`<video>`
tag for it at the cursor. Starter HTML is in `templates.js`; links in a box
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
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): on `/stp`, "Import current
+147
View File
@@ -0,0 +1,147 @@
<script setup>
/**
* Choose a file that is already uploaded, instead of uploading it again: a
* modal grid of every public upload (listUploads in @/uploads), newest first.
* Admin only, because the listing is. Used by the canvas's Background panel,
* Box editor and "+ From uploads" button.
*
* <UploadPicker v-if="picking" v-model="picking" :kinds="['image']" @pick="use" />
*
* `kinds` filters by kindOf(url). The bucket holds hundreds of megabytes, so
* thumbnails load lazily and videos fetch only their metadata.
*/
import { computed, ref } from "vue";
import { kindOf, listUploads } from "@/uploads";
import OverlayShell from "./OverlayShell.vue";
const open = defineModel({ type: Boolean, default: false });
const props = defineProps({
kinds: { type: Array, default: () => ["image"] },
title: { type: String, default: "Choose an upload" },
});
const emit = defineEmits(["pick", "close"]);
const files = ref([]);
const loading = ref(true);
const error = ref("");
const filter = ref("");
listUploads()
.then((all) => (files.value = all.filter((f) => props.kinds.includes(kindOf(f.url)))))
.catch((err) => (error.value = err?.message || "Couldn't list uploads"))
.finally(() => (loading.value = false));
const shown = computed(() => {
const q = filter.value.trim().toLowerCase();
return q ? files.value.filter((f) => f.name.toLowerCase().includes(q)) : files.value;
});
function describe(f) {
const kb = f.size / 1024;
const size = kb < 1024 ? `${Math.round(kb)} KB` : `${(kb / 1024).toFixed(1)} MB`;
return `${f.name} · ${size} · ${new Date(f.modified).toLocaleString()}`;
}
function close() {
open.value = false;
emit("close");
}
function pick(f) {
emit("pick", f.url);
close();
}
</script>
<template>
<OverlayShell v-model="open" :title="title" backdrop close-on-backdrop @close="close">
<div class="picker bdr-2 bg-surface">
<header class="flex items-center gap-2">
<h3 class="m-0 flex-1">{{ title }}</h3>
<input v-model="filter" type="search" placeholder="Filter by name" class="filter" />
<button type="button" class="close" title="Close" @click="close">✕</button>
</header>
<p v-if="loading" class="state">Loading…</p>
<p v-else-if="error" class="state text-tertiary">{{ error }}</p>
<p v-else-if="!shown.length" class="state">
{{ files.length ? "Nothing matches." : "No uploads yet." }}
</p>
<div v-else class="grid">
<button v-for="f in shown" :key="f.name" type="button" class="tile" :title="describe(f)" @click="pick(f)">
<img v-if="kindOf(f.url) === 'image'" :src="f.url" alt="" loading="lazy" />
<video v-else-if="kindOf(f.url) === 'video'" :src="f.url" preload="metadata" muted></video>
<span v-else class="name">{{ f.name }}</span>
</button>
</div>
</div>
</OverlayShell>
</template>
<style scoped>
.picker {
box-sizing: border-box;
display: flex;
flex-direction: column;
gap: 0.6rem;
width: min(760px, calc(100vw - 24px));
height: min(600px, calc(100vh - 24px));
padding: 0.75rem;
color: var(--color-secondary);
}
.filter {
min-width: 0;
width: 12rem;
padding: 3px 5px;
color: var(--color-secondary);
background: var(--color-surface-deep);
border: 1px solid var(--color-quaternary);
}
.close {
color: var(--color-primary);
background: var(--color-link-bg);
border: 1px solid var(--color-primary);
padding: 0 0.5rem;
cursor: pointer;
}
.state {
color: var(--color-muted);
}
.grid {
flex: 1;
overflow-y: auto;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
grid-auto-rows: 120px;
gap: 0.5rem;
}
.tile {
display: flex;
align-items: center;
justify-content: center;
padding: 0;
overflow: hidden;
background: var(--color-surface-deep);
border: 2px solid var(--color-quaternary);
cursor: pointer;
}
.tile:hover,
.tile:focus-visible {
border-color: var(--color-primary);
}
.tile img,
.tile video {
width: 100%;
height: 100%;
object-fit: cover;
pointer-events: none;
}
.name {
padding: 0.25rem;
font-size: 0.75rem;
word-break: break-all;
color: var(--color-muted);
}
</style>
+22 -4
View File
@@ -18,6 +18,10 @@
*
* A refused file (wrong type, too large) rejects with an ApiError whose
* `message` is the backend's sentence, ready to show the user.
*
* listUploads() lists what is already stored, for reusing a file instead of
* uploading it again (components/util/UploadPicker.vue). It is admin-only:
* the listing is what would turn every unguessable URL into a known one.
*/
import { api } from "@/api";
@@ -50,6 +54,16 @@ export async function uploadFile(file, { private: isPrivate = false } = {}) {
return url;
}
/**
* Every public upload, newest first. Admin only.
*
* @returns {Promise<Array<{name: string, url: string, size: number, modified: string}>>}
*/
export async function listUploads() {
const { files } = await api.get("/uploads", { fallback: "Couldn't list uploads" });
return files;
}
/** What a stored file is, from its URL: "image", "video", "audio" or "file". */
export function kindOf(url) {
if (/\.(jpe?g|png|gif|webp)$/i.test(url)) return "image";
@@ -86,15 +100,19 @@ export function tagFor(url) {
}
}
/** Natural size of an image or video File, or null if it can't be read. */
/**
* Natural size of an image or video — a File, or the URL of one already
* stored — or null if it can't be read.
*/
export function mediaSize(file) {
return new Promise((resolve) => {
const src = URL.createObjectURL(file);
const isFile = typeof file !== "string";
const src = isFile ? URL.createObjectURL(file) : file;
const done = (size) => {
URL.revokeObjectURL(src);
if (isFile) URL.revokeObjectURL(src);
resolve(size);
};
if (file.type.startsWith("video/")) {
if (isFile ? file.type.startsWith("video/") : isVideo(file)) {
const v = document.createElement("video");
v.onloadedmetadata = () => done({ w: v.videoWidth, h: v.videoHeight });
v.onerror = () => done(null);
+9 -4
View File
@@ -1,8 +1,9 @@
<script setup>
/**
* The admin's background panel for one canvas page, opened from BoxCanvas's
* "Background" button: a colour, an image (uploaded, dropped on the panel or
* given as a URL) and how the image fills the window.
* "Background" button: a colour, an image (uploaded, dropped on the panel,
* chosen from what is already uploaded, or given as a URL) and how the image
* fills the window.
*
* Every change previews live through the background store; Cancel (or
* closing) puts the saved one back. Saving with neither colour nor image is
@@ -13,6 +14,7 @@ import { FITS, useBackgroundStore } from "@/stores/background";
import { ACCEPT, uploadFile, isImage } from "@/uploads";
import OverlayShell from "@/components/util/OverlayShell.vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
import UploadPicker from "@/components/util/UploadPicker.vue";
const props = defineProps({
page: { type: String, required: true },
@@ -41,6 +43,7 @@ const busy = ref(false);
const error = ref("");
const dragOver = ref(false);
const confirmation = ref(false);
const picking = ref(false);
async function upload(file) {
if (!file) return;
@@ -130,13 +133,14 @@ async function confirmReset() {
<button v-if="draft.image" type="button" class="bar-btn small" @click="draft.image = ''">✕</button>
</span>
</label>
<span class="row">
<span class="row flex-wrap">
<label class="bar-btn upload">
{{ busy ? "Working…" : "Upload image…" }}
<input type="file" :accept="ACCEPT.images" hidden :disabled="busy" @change="upload($event.target.files[0])" />
</label>
<span class="hint">or drop one on this panel</span>
<button type="button" class="bar-btn" :disabled="busy" @click="picking = true">Choose from uploads…</button>
</span>
<span class="hint">or drop one on this panel</span>
<img v-if="draft.image && isImage(draft.image)" :src="draft.image" alt="" class="thumb" />
<label v-if="draft.image">
@@ -164,6 +168,7 @@ async function confirmReset() {
confirm-label="Reset"
@confirm="confirmReset"
/>
<UploadPicker v-if="picking" v-model="picking" @pick="draft.image = $event" />
</template>
<style scoped>
+39 -20
View File
@@ -20,7 +20,8 @@
* changes save on release, and the selected box opens in BoxEditor. Boxes
* marked adminOnly are never sent to anyone else (the server filters them);
* admins see them outlined. Image and video files dropped onto the canvas in
* edit mode are uploaded and each becomes a box where it was dropped.
* edit mode are uploaded and each becomes a box where it was dropped; "+ From
* uploads" does the same with a file that is already uploaded.
*
* The canvas also owns its page's background (stores/background.js), which
* DefaultLayout paints behind the whole window while the canvas is mounted;
@@ -33,13 +34,14 @@ import { useBoxesStore } from "@/stores/boxes";
import { useBackgroundStore } from "@/stores/background";
import BackgroundEditor from "./BackgroundEditor.vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
import UploadPicker from "@/components/util/UploadPicker.vue";
import BoxFrame from "./BoxFrame.vue";
import BoxEditor from "./BoxEditor.vue";
import HtmlBox from "./HtmlBox.vue";
import WidgetBox from "./WidgetBox.vue";
import { WIDGETS } from "./widgetRegistry";
import { TEMPLATES, imageHtml, videoHtml } from "./templates";
import { mediaSize, uploadFile } from "@/uploads";
import { isVideo, mediaSize, uploadFile } from "@/uploads";
const props = defineProps({
page: { type: String, required: true },
@@ -256,8 +258,26 @@ function isMedia(file) {
return file.type.startsWith("image/") || file.type.startsWith("video/");
}
// Each file is uploaded and placed at the drop point, sized to its own
// aspect ratio so nothing is cropped, then cascaded like visibleOrigin().
// A box showing one stored image or video at (x, y), sized to the file's own
// aspect ratio so nothing is cropped. Selected once made.
async function placeMedia(url, size, title, x, y) {
const fit = size ? Math.min(1, DROP_MAX / Math.max(size.w, size.h)) : 1;
const created = await store.create({
kind: "html",
title,
html: isVideo(url) ? videoHtml(url) : imageHtml(url),
framed: false,
x,
y,
w: size ? Math.max(40, Math.round(size.w * fit)) : 300,
h: size ? Math.max(40, Math.round(size.h * fit)) : 300,
z: store.topZ(),
});
selectedId.value = created.id;
}
// Each file is uploaded and placed at the drop point, then cascaded like
// visibleOrigin().
async function onDrop(event) {
dragOver.value = false;
const files = [...(event.dataTransfer?.files ?? [])].filter(isMedia);
@@ -270,22 +290,7 @@ async function onDrop(event) {
for (const file of files) {
try {
const [url, size] = await Promise.all([uploadFile(file), mediaSize(file)]);
const fit = size ? Math.min(1, DROP_MAX / Math.max(size.w, size.h)) : 1;
const w = size ? Math.max(40, Math.round(size.w * fit)) : 300;
const h = size ? Math.max(40, Math.round(size.h * fit)) : 300;
const video = file.type.startsWith("video/");
const created = await store.create({
kind: "html",
title: file.name,
html: video ? videoHtml(url) : imageHtml(url),
framed: false,
x,
y,
w,
h,
z: store.topZ(),
});
selectedId.value = created.id;
await placeMedia(url, size, file.name, x, y);
x += 20;
y += 20;
} catch (err) {
@@ -296,6 +301,17 @@ async function onDrop(event) {
}
}
// A file picked from what is already uploaded goes where a new box would.
const picking = ref(false);
async function placePicked(url) {
const { x, y } = visibleOrigin();
try {
await placeMedia(url, await mediaSize(url), url.split("/").pop(), x, y);
} catch (err) {
report(err);
}
}
// ---- Selection -----------------------------------------------------------
// Leaving a box saves its unsaved HTML; BoxEditor does that itself as the
// selection changes or it unmounts.
@@ -346,6 +362,7 @@ function toggleEdit() {
>
{{ importing ? "Importing…" : starterLabel }}
</button>
<button type="button" class="bar-btn" @click="picking = true">+ From uploads…</button>
</template>
<span v-if="inEditMode" class="hint">
{{ uploading ? `Uploading ${uploading}…` : "Drop images or videos onto the canvas to add them" }}
@@ -422,6 +439,8 @@ function toggleEdit() {
@error="report"
/>
<UploadPicker v-if="picking" v-model="picking" :kinds="['image', 'video']" @pick="placePicked" />
<ConfirmDialog
v-if="confirmation"
v-model="confirmation.open"
+24 -3
View File
@@ -15,6 +15,7 @@
*
* "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.
*
* The panel is teleported to <body>, so it is fixed to the window whatever
* transform or stacking context the page puts around the canvas.
@@ -25,6 +26,7 @@ import { ACCEPT, tagFor, uploadFile } from "@/uploads";
import CodeEditor from "./CodeEditor.vue";
import { WIDGETS } from "./widgetRegistry";
import OverlayShell from "@/components/util/OverlayShell.vue";
import UploadPicker from "@/components/util/UploadPicker.vue";
const props = defineProps({
box: { type: Object, required: true },
@@ -36,6 +38,7 @@ const store = useBoxesStore(props.box.page);
const codeEditor = ref(null);
const fileInput = ref(null);
const uploading = ref(false);
const picking = ref(false);
const open = ref(true);
const draftHtml = ref(props.box.html ?? "");
@@ -105,14 +108,18 @@ function saveNumber(field, event) {
save({ [field]: value });
}
function insertFile(url) {
const tag = tagFor(url);
if (!codeEditor.value?.insert(tag)) draftHtml.value += `\n${tag}`;
}
async function upload(event) {
const file = event.target.files?.[0];
event.target.value = "";
if (!file) return;
uploading.value = true;
try {
const tag = tagFor(await uploadFile(file));
if (!codeEditor.value?.insert(tag)) draftHtml.value += `\n${tag}`;
insertFile(await uploadFile(file));
} catch (err) {
emit("error", err);
} finally {
@@ -186,7 +193,7 @@ function close() {
<template v-if="box.kind === 'html'">
<CodeEditor ref="codeEditor" v-model="draftHtml" class="flex-1" @save="saveHtml" />
<footer class="flex items-center justify-between gap-2">
<footer class="flex flex-wrap items-center justify-between gap-2">
<small class="text-muted">
Runs sandboxed: scripts work, cookies and /api don't. fetch() only reaches
keyless CORS-open APIs. Ctrl+S saves; so does leaving the box.
@@ -207,6 +214,14 @@ function close() {
>
{{ uploading ? "Uploading…" : "Insert upload" }}
</button>
<button
type="button"
class="save"
title="Insert a file that is already uploaded"
@click="picking = true"
>
Choose upload
</button>
<button type="button" class="save" :disabled="!dirty || saving" @click="saveHtml">
{{ saving ? "Saving…" : dirty ? "Save" : "Saved" }}
</button>
@@ -214,6 +229,12 @@ function close() {
</template>
</aside>
</OverlayShell>
<UploadPicker
v-if="picking"
v-model="picking"
:kinds="['image', 'video', 'audio']"
@pick="insertFile"
/>
</template>
<style scoped>