Fix the landing notes editor, drop-to-upload pictures, retire Demoman

The box editor rendered inside the landing page's overlay canvas, which
is pointer-events: none so the page underneath stays clickable; the
panel inherited it and ignored every click and keystroke. It is now
teleported to <body>.

Image and video files dropped onto a canvas in edit mode are uploaded
and each becomes an unframed box at the drop point, sized to its aspect
ratio. The upload code moves to home3/upload.js, shared with the
editor's "Insert upload".

The hand-written Demoman shrine is unrouted (and its slug unreserved)
so it can be remade as a canvas page. /shrines lists only canvas pages
and keeps the admin-only create form behind a "+ New shrine" button.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 23:47:15 +01:00
co-authored by Claude Opus 5.5
parent bb5fd2bef9
commit 30e1fb31d8
10 changed files with 248 additions and 134 deletions
+1 -2
View File
@@ -36,8 +36,7 @@ var reservedFirstSegments = map[string]bool{
// reservedSlugs are individual paths the SPA routes itself. // reservedSlugs are individual paths the SPA routes itself.
var reservedSlugs = map[string]bool{ var reservedSlugs = map[string]bool{
"shrines": true, "shrines": true,
"shrines/demoman": true,
} }
func validPageKey(key string) bool { func validPageKey(key string) bool {
+1 -1
View File
@@ -18,7 +18,7 @@ func TestValidateSlug(t *testing.T) {
{"shrines/gto-", false}, // trailing hyphen {"shrines/gto-", false}, // trailing hyphen
{"shrines/../admin", false}, // dots {"shrines/../admin", false}, // dots
{"shrines", false}, // the SPA's own index {"shrines", false}, // the SPA's own index
{"shrines/demoman", false}, // an existing SPA route {"shrines/demoman", true}, // no longer an SPA route
{"admin/pages", false}, // under an SPA route {"admin/pages", false}, // under an SPA route
{"jobs/x", false}, // under an nginx route {"jobs/x", false}, // under an nginx route
{"stp", false}, // a built-in canvas's key {"stp", false}, // a built-in canvas's key
+6 -3
View File
@@ -68,7 +68,7 @@ Two layout shells, defined in `src/router/index.js`:
| `/` | DefaultLayout | Landing page (statically imported — it's the first paint), with a canvas overlay for pinned notes (page key `index`) | | `/` | DefaultLayout | Landing page (statically imported — it's the first paint), with a canvas overlay for pinned notes (page key `index`) |
| `/stp` | DefaultLayout | The personal home page: an admin-editable canvas of boxes (`views/home3/`, see "The /stp canvas" below) | | `/stp` | DefaultLayout | The personal home page: an admin-editable canvas of boxes (`views/home3/`, see "The /stp canvas" below) |
| `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin` | | `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin` |
| `/automata`, `/hotels`, `/shrines`, `/shrines/demoman` | DefaultLayout | Every other shrine is a canvas page | | `/automata`, `/hotels`, `/shrines` | DefaultLayout | Each shrine under `/shrines/` is a canvas page |
| `/cv` | CVLayout | Light print theme. Its Jobs button goes to `/jobs/`, the separate job tracker app (`adamf/job-tracker`); nginx redirects the old `/cv/jobs` and `/cv/leads` there | | `/cv` | CVLayout | Light print theme. Its Jobs button goes to `/jobs/`, the separate job tracker app (`adamf/job-tracker`); nginx redirects the old `/cv/jobs` and `/cv/leads` there |
| `/stp2` | (none) | Bare full-bleed mock, deliberately outside both layouts | | `/stp2` | (none) | Bare full-bleed mock, deliberately outside both layouts |
| `:pathMatch(.*)*` | DefaultLayout | `views/canvas/CanvasPage.vue`: an admin-created canvas page if one exists at the path, else the 404 (with a "create a page here" form for admins) | | `:pathMatch(.*)*` | DefaultLayout | `views/canvas/CanvasPage.vue`: an admin-created canvas page if one exists at the path, else the 404 (with a "create a page here" form for admins) |
@@ -243,7 +243,10 @@ renders any page's boxes.
saves on pointer release, and the box is moved locally first and put back if saves on pointer release, and the box is moved locally first and put back if
the save fails. `BoxEditor.vue` is the side panel. Settings save on change; the save fails. `BoxEditor.vue` is the side panel. Settings save on change;
HTML is a draft that previews live and saves with Save or Ctrl/Cmd+S. HTML is a draft that previews live and saves with Save or Ctrl/Cmd+S.
CodeMirror is loaded only when that panel opens. "Insert upload" stores a CodeMirror is loaded only when that panel opens; the panel is teleported to
`<body>` so the landing overlay's `pointer-events: none` doesn't reach it.
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 the chat's public upload endpoint and puts an `<img>`/`<video>` file through the chat's public upload endpoint and puts an `<img>`/`<video>`
tag for it at the cursor. Starter HTML is in `templates.js`. On `/stp`, tag for it at the cursor. Starter HTML is in `templates.js`. On `/stp`,
"Import current layout" (shown only on an empty canvas) recreates the old "Import current layout" (shown only on an empty canvas) recreates the old
@@ -295,7 +298,7 @@ in its header comment; the summary:
| File | Status | | File | Status |
| --- | --- | | --- | --- |
| `views/home3/Home3.vue` | live (`/stp`) — the box canvas; its widget boxes use **Intro3** and **Gym2** | | `views/home3/Home3.vue` | live (`/stp`) — the box canvas; its widget boxes use **Intro3** and **Gym2** |
| `views/home/shrines/{GTO,Evangelion,Skipskipbenben}.vue` | `<Wip />` placeholders, unrouted; those shrines are canvas pages now | | `views/home/shrines/{Demoman,GTO,Evangelion,Skipskipbenben}.vue` | the old hand-written shrines (Demoman a video wall, the rest `<Wip />`), unrouted; shrines are canvas pages now |
| `views/home/Home.vue` | legacy fixed grid that `/stp` used to be; no route. Its widgets are still live through `home3/widgetRegistry.js` | | `views/home/Home.vue` | legacy fixed grid that `/stp` used to be; no route. Its widgets are still live through `home3/widgetRegistry.js` |
| `views/home/Intro.vue` | superseded by `Intro2.vue`; not imported | | `views/home/Intro.vue` | superseded by `Intro2.vue`; not imported |
| `views/home/Gym.vue` | superseded by `Gym2.vue`; not imported | | `views/home/Gym.vue` | superseded by `Gym2.vue`; not imported |
+3 -8
View File
@@ -65,14 +65,9 @@ const router = createRouter({
name: "shrine links", name: "shrine links",
component: () => import("@/views/home/shrines/Shrines.vue"), component: () => import("@/views/home/shrines/Shrines.vue"),
}, },
// The GTO, Evangelion and Skipskipbenben shrines were <Wip /> // Individual shrines are canvas pages, made from /shrines and
// placeholders; they are canvas pages now, made from /shrines // served by the catch-all below. The old hand-written ones
// and served by the catch-all below. // (views/home/shrines/) are unrouted.
{
path: "shrines/demoman",
name: "demoman shrine",
component: () => import("@/views/home/shrines/Demoman.vue"),
},
// Anything else is an admin-created canvas page if one exists // Anything else is an admin-created canvas page if one exists
// at that address (the Page GraphQL type), else the 404. // at that address (the Page GraphQL type), else the 404.
{ {
+5 -1
View File
@@ -1,6 +1,10 @@
<script setup> <script setup>
/** /**
* Route `/shrines/demoman` — a wall of TF2 Demoman clips via <VideoTable>. * STATUS: no route points here — removed so /shrines/demoman can be made
* again as a canvas page (views/canvas/CanvasPage.vue). The clips are still
* in public/img/demoman/.
*
* Was route `/shrines/demoman` — a wall of TF2 Demoman clips via <VideoTable>.
*/ */
import VideoTable from "@/components/util/VideoTable.vue"; import VideoTable from "@/components/util/VideoTable.vue";
import Link from "@/components/text/Link.vue"; import Link from "@/components/text/Link.vue";
+20 -15
View File
@@ -1,11 +1,12 @@
<script setup> <script setup>
/** /**
* Route `/shrines` — index of the shrine pages. Demoman is a hand-written * Route `/shrines` — index of the shrine pages: every canvas page
* view; every other shrine is a canvas page (views/canvas/) whose address * (views/canvas/) whose address starts with "shrines/", from the pages query.
* starts with "shrines/", listed from the pages query. Admins get a form to * Admins — and only admins; the server refuses createPage to anyone else
* start a new one from the Shrine layout. * anyway — get a button that opens a form to start one from the Shrine
* layout.
*/ */
import { computed } from "vue"; import { computed, ref } from "vue";
import RouterTable from "@/components/util/RouterTable.vue"; import RouterTable from "@/components/util/RouterTable.vue";
import { useAuthStore } from "@/stores/auth"; import { useAuthStore } from "@/stores/auth";
import { usePagesStore } from "@/stores/pages"; import { usePagesStore } from "@/stores/pages";
@@ -17,14 +18,13 @@ auth.ensureLoaded();
pages.fetch(); pages.fetch();
const isAdmin = computed(() => auth.loggedIn && !!auth.user.admin); const isAdmin = computed(() => auth.loggedIn && !!auth.user.admin);
const creating = ref(false);
const shrine_links = computed(() => const shrine_links = computed(() =>
[ pages.pages
{ name: "Demoman", link: "/shrines/demoman" }, .filter((p) => p.slug.startsWith("shrines/"))
...pages.pages .map((p) => ({ name: p.adminOnly ? `${p.title} 🔒` : p.title, link: `/${p.slug}` }))
.filter((p) => p.slug.startsWith("shrines/")) .sort((a, b) => a.name.localeCompare(b.name)),
.map((p) => ({ name: p.adminOnly ? `${p.title} 🔒` : p.title, link: `/${p.slug}` })),
].sort((a, b) => a.name.localeCompare(b.name)),
); );
</script> </script>
@@ -34,10 +34,15 @@ const shrine_links = computed(() =>
class="page-a4 bdr-1 flex flex-col relative overflow-scroll gap-1" class="page-a4 bdr-1 flex flex-col relative overflow-scroll gap-1"
> >
<RouterTable :linkArr="shrine_links" /> <RouterTable :linkArr="shrine_links" />
<section v-if="isAdmin" class="mt-4"> <p v-if="pages.loaded && !shrine_links.length" class="text-muted text-center">
<h3>New shrine</h3> No shrines yet.
<PageForm prefix="shrines/" starter="shrine" /> </p>
</section> <template v-if="isAdmin">
<button type="button" class="bdr-2 bg-surface mt-4 cursor-pointer" @click="creating = !creating">
{{ creating ? "Cancel" : "+ New shrine" }}
</button>
<PageForm v-if="creating" prefix="shrines/" starter="shrine" />
</template>
</div> </div>
</main> </main>
</template> </template>
+67 -3
View File
@@ -19,7 +19,8 @@
* Admins get an Edit toggle. In edit mode boxes drag and resize (BoxFrame), * Admins get an Edit toggle. In edit mode boxes drag and resize (BoxFrame),
* changes save on release, and the selected box opens in BoxEditor. Boxes * changes save on release, and the selected box opens in BoxEditor. Boxes
* marked adminOnly are never sent to anyone else (the server filters them); * marked adminOnly are never sent to anyone else (the server filters them);
* admins see them outlined. * 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.
* *
* `overlay` lays the canvas over whatever the parent already renders instead * `overlay` lays the canvas over whatever the parent already renders instead
* of taking space of its own — the landing page uses it to pin notes over its * of taking space of its own — the landing page uses it to pin notes over its
@@ -38,7 +39,8 @@ import BoxEditor from "./BoxEditor.vue";
import HtmlBox from "./HtmlBox.vue"; import HtmlBox from "./HtmlBox.vue";
import WidgetBox from "./WidgetBox.vue"; import WidgetBox from "./WidgetBox.vue";
import { WIDGETS } from "./widgetRegistry"; import { WIDGETS } from "./widgetRegistry";
import { TEMPLATES } from "./templates"; import { TEMPLATES, imageHtml, videoHtml } from "./templates";
import { mediaSize, uploadFile } from "./upload";
const props = defineProps({ const props = defineProps({
page: { type: String, required: true }, page: { type: String, required: true },
@@ -218,6 +220,55 @@ async function importStarter() {
} }
} }
// ---- Dropping files -----------------------------------------------------
const DROP_MAX = 400; // longest side of a dropped picture's box, canvas px
const dragOver = ref(false);
const uploading = ref(0);
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().
async function onDrop(event) {
dragOver.value = false;
const files = [...(event.dataTransfer?.files ?? [])].filter(isMedia);
if (!files.length) return;
const rect = canvasEl.value.getBoundingClientRect();
const snap = (n) => Math.max(0, Math.round(n / 5) * 5);
let x = snap((event.clientX - rect.left) / scale.value);
let y = snap((event.clientY - rect.top) / scale.value);
uploading.value += files.length;
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;
x += 20;
y += 20;
} catch (err) {
report(err);
} finally {
uploading.value--;
}
}
}
// ---- Selection ----------------------------------------------------------- // ---- Selection -----------------------------------------------------------
function select(box) { function select(box) {
if (selectedId.value === box.id) return; if (selectedId.value === box.id) return;
@@ -271,6 +322,9 @@ function toggleEdit() {
{{ importing ? "Importing…" : starterLabel }} {{ importing ? "Importing…" : starterLabel }}
</button> </button>
</template> </template>
<span v-if="inEditMode" class="hint">
{{ uploading ? `Uploading ${uploading}…` : "Drop images or videos onto the canvas to add them" }}
</span>
<slot name="admin-bar" :editing="inEditMode" /> <slot name="admin-bar" :editing="inEditMode" />
<span v-if="errorMsg" class="error">{{ errorMsg }}</span> <span v-if="errorMsg" class="error">{{ errorMsg }}</span>
</div> </div>
@@ -303,9 +357,12 @@ function toggleEdit() {
<div <div
ref="canvasEl" ref="canvasEl"
class="canvas" class="canvas"
:class="{ editing: inEditMode }" :class="{ editing: inEditMode, 'drag-over': dragOver }"
:style="{ width: `${CANVAS_W}px`, height: `${canvasH}px`, transform: `scale(${scale})` }" :style="{ width: `${CANVAS_W}px`, height: `${canvasH}px`, transform: `scale(${scale})` }"
@pointerdown.self="selectedId = null" @pointerdown.self="selectedId = null"
@dragover.prevent="dragOver = inEditMode"
@dragleave.self="dragOver = false"
@drop.prevent="inEditMode && onDrop($event)"
> >
<BoxFrame <BoxFrame
v-for="box in store.boxes" v-for="box in store.boxes"
@@ -405,6 +462,10 @@ function toggleEdit() {
.error { .error {
color: var(--color-tertiary); color: var(--color-tertiary);
} }
.hint {
color: var(--color-muted);
font-size: 0.85rem;
}
.state { .state {
text-align: center; text-align: center;
color: var(--color-muted); color: var(--color-muted);
@@ -429,6 +490,9 @@ function toggleEdit() {
background-image: radial-gradient(var(--color-quaternary) 1px, transparent 1px); background-image: radial-gradient(var(--color-quaternary) 1px, transparent 1px);
background-size: 20px 20px; background-size: 20px 20px;
} }
.canvas.drag-over {
outline: 3px dashed var(--color-primary);
}
.stack { .stack {
display: flex; display: flex;
+88 -97
View File
@@ -11,15 +11,16 @@
* store) and is saved only by Save or Ctrl/Cmd+S. Saving every keystroke * store) and is saved only by Save or Ctrl/Cmd+S. Saving every keystroke
* would push half-written markup to every visitor. * would push half-written markup to every visitor.
* *
* "Insert upload" stores a file through the chat's upload endpoint (public, * "Insert upload" uploads a file (upload.js) and puts a tag for it at the
* unguessable URLs under /uploads/) and puts a tag for it at the cursor — * cursor — the way to add pictures to an existing box, e.g. a gallery.
* the quick way to fill a shrine with images. It is never the private upload *
* directory: that one is behind a cookie check, and the sandboxed frame * The panel is teleported to <body>. On the landing page the canvas is an
* loads as an opaque origin, so its requests may not carry the cookie. * overlay with pointer-events: none, which a panel rendered inside it would
* inherit — it would show but ignore every click and keystroke.
*/ */
import { computed, ref, watch } from "vue"; import { computed, ref, watch } from "vue";
import { useBoxesStore } from "@/stores/boxes"; import { useBoxesStore } from "@/stores/boxes";
import { api } from "@/api"; import { tagFor, uploadFile } from "./upload";
import CodeEditor from "./CodeEditor.vue"; import CodeEditor from "./CodeEditor.vue";
import { WIDGETS } from "./widgetRegistry"; import { WIDGETS } from "./widgetRegistry";
@@ -84,25 +85,13 @@ function saveNumber(field, event) {
save({ [field]: value }); save({ [field]: value });
} }
// The markup an upload is inserted as, by file type. Anything else (a PDF,
// a text file) becomes a link.
function tagFor(url) {
if (/\.(jpe?g|png|gif|webp)$/i.test(url)) return `<img src="${url}" alt="">`;
if (/\.(mp4|webm)$/i.test(url)) return `<video src="${url}" controls loop muted></video>`;
if (/\.(mp3|ogg)$/i.test(url)) return `<audio src="${url}" controls></audio>`;
return `<a href="${url}" target="_blank">${url.split("/").pop()}</a>`;
}
async function upload(event) { async function upload(event) {
const file = event.target.files?.[0]; const file = event.target.files?.[0];
event.target.value = ""; event.target.value = "";
if (!file) return; if (!file) return;
uploading.value = true; uploading.value = true;
try { try {
const body = new FormData(); const tag = tagFor(await uploadFile(file));
body.append("file", file);
const { url } = await api.post("/messages/upload", body, { fallback: "Upload failed" });
const tag = tagFor(url);
if (!codeEditor.value?.insert(tag)) draftHtml.value += `\n${tag}`; if (!codeEditor.value?.insert(tag)) draftHtml.value += `\n${tag}`;
} catch (err) { } catch (err) {
emit("error", err); emit("error", err);
@@ -121,91 +110,93 @@ defineExpose({ close });
</script> </script>
<template> <template>
<aside class="box-editor" @keydown.esc="close"> <Teleport to="body">
<header class="flex items-center justify-between gap-2"> <aside class="box-editor" @keydown.esc="close">
<h3 class="m-0"> <header class="flex items-center justify-between gap-2">
{{ box.kind === "widget" ? `Widget · ${box.widget}` : "HTML box" }} <h3 class="m-0">
</h3> {{ box.kind === "widget" ? `Widget · ${box.widget}` : "HTML box" }}
<button type="button" class="close" title="Close" @click="close">✕</button> </h3>
</header> <button type="button" class="close" title="Close" @click="close">✕</button>
</header>
<label class="field"> <label class="field">
<span>Title</span> <span>Title</span>
<input
type="text"
:value="box.title ?? ''"
placeholder="(label in edit mode)"
@change="save({ title: $event.target.value })"
/>
</label>
<label v-if="box.kind === 'widget'" class="field">
<span>Widget</span>
<select :value="box.widget" @change="save({ widget: $event.target.value })">
<option v-for="name in Object.keys(WIDGETS)" :key="name" :value="name">{{ name }}</option>
</select>
</label>
<div class="geometry">
<label v-for="field in ['x', 'y', 'w', 'h', 'z']" :key="field" class="field">
<span>{{ field }}</span>
<input <input
type="number" type="text"
:value="box[field]" :value="box.title ?? ''"
@change="saveNumber(field, $event)" placeholder="(label in edit mode)"
@keydown.enter="$event.target.blur()" @change="save({ title: $event.target.value })"
/> />
</label> </label>
</div>
<div class="flex flex-wrap gap-x-4 gap-y-1"> <label v-if="box.kind === 'widget'" class="field">
<label class="check"> <span>Widget</span>
<input type="checkbox" :checked="box.framed" @change="save({ framed: $event.target.checked })" /> <select :value="box.widget" @change="save({ widget: $event.target.value })">
Frame <option v-for="name in Object.keys(WIDGETS)" :key="name" :value="name">{{ name }}</option>
</select>
</label> </label>
<label class="check">
<input
type="checkbox"
:checked="box.hideOnMobile"
@change="save({ hideOnMobile: $event.target.checked })"
/>
Hide on mobile
</label>
<label class="check" title="Only signed-in admins are sent this box">
<input type="checkbox" :checked="box.adminOnly" @change="save({ adminOnly: $event.target.checked })" />
Admin only
</label>
</div>
<template v-if="box.kind === 'html'"> <div class="geometry">
<CodeEditor ref="codeEditor" v-model="draftHtml" class="flex-1" @save="saveHtml" /> <label v-for="field in ['x', 'y', 'w', 'h', 'z']" :key="field" class="field">
<footer class="flex items-center justify-between gap-2"> <span>{{ field }}</span>
<small class="text-muted"> <input
Runs sandboxed: scripts work, cookies and /api don't. fetch() only reaches type="number"
keyless CORS-open APIs. Ctrl+S saves. :value="box[field]"
</small> @change="saveNumber(field, $event)"
<input @keydown.enter="$event.target.blur()"
ref="fileInput" />
type="file" </label>
accept="image/*,video/mp4,video/webm,audio/mpeg,audio/ogg" </div>
hidden
@change="upload" <div class="flex flex-wrap gap-x-4 gap-y-1">
/> <label class="check">
<button <input type="checkbox" :checked="box.framed" @change="save({ framed: $event.target.checked })" />
type="button" Frame
class="save" </label>
:disabled="uploading" <label class="check">
title="Upload a file and insert it at the cursor" <input
@click="fileInput.click()" type="checkbox"
> :checked="box.hideOnMobile"
{{ uploading ? "Uploading…" : "Insert upload" }} @change="save({ hideOnMobile: $event.target.checked })"
</button> />
<button type="button" class="save" :disabled="!dirty || saving" @click="saveHtml"> Hide on mobile
{{ saving ? "Saving…" : dirty ? "Save" : "Saved" }} </label>
</button> <label class="check" title="Only signed-in admins are sent this box">
</footer> <input type="checkbox" :checked="box.adminOnly" @change="save({ adminOnly: $event.target.checked })" />
</template> Admin only
</aside> </label>
</div>
<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">
<small class="text-muted">
Runs sandboxed: scripts work, cookies and /api don't. fetch() only reaches
keyless CORS-open APIs. Ctrl+S saves.
</small>
<input
ref="fileInput"
type="file"
accept="image/*,video/mp4,video/webm,audio/mpeg,audio/ogg"
hidden
@change="upload"
/>
<button
type="button"
class="save"
:disabled="uploading"
title="Upload a file and insert it at the cursor"
@click="fileInput.click()"
>
{{ uploading ? "Uploading…" : "Insert upload" }}
</button>
<button type="button" class="save" :disabled="!dirty || saving" @click="saveHtml">
{{ saving ? "Saving…" : dirty ? "Save" : "Saved" }}
</button>
</footer>
</template>
</aside>
</Teleport>
</template> </template>
<style scoped> <style scoped>
+4 -4
View File
@@ -131,11 +131,11 @@ const galleryHtml = (srcs) => `<style>
${srcs.map((src) => ` <img src="${src}" alt="">`).join("\n")} ${srcs.map((src) => ` <img src="${src}" alt="">`).join("\n")}
</div>`; </div>`;
const VIDEO = `<style> const videoHtml = (src) => `<style>
body { padding: 0; overflow: hidden; background: #000; } body { padding: 0; overflow: hidden; background: #000; }
video { display: block; width: 100%; height: 100%; object-fit: contain; } video { display: block; width: 100%; height: 100%; object-fit: contain; }
</style> </style>
<video src="/img/demoman/1760582395316219.webm" controls loop muted></video>`; <video src="${src}" controls loop muted></video>`;
/** /**
* Menu entries; `size` is [w, h] in canvas px. `adminOnly` sets the new * Menu entries; `size` is [w, h] in canvas px. `adminOnly` sets the new
@@ -147,10 +147,10 @@ export const TEMPLATES = [
{ label: "Text", title: "Text", html: TEXT, size: [400, 260] }, { label: "Text", title: "Text", html: TEXT, size: [400, 260] },
{ label: "Image / GIF", title: "Image", html: imageHtml("/img/memes/fire-woman.gif"), size: [240, 240], framed: false }, { label: "Image / GIF", title: "Image", html: imageHtml("/img/memes/fire-woman.gif"), size: [240, 240], framed: false },
{ label: "Image gallery", title: "Gallery", html: galleryHtml(["/img/memes/fire-woman.gif", "/img/memes/epic.jpeg"]), size: [460, 320] }, { label: "Image gallery", title: "Gallery", html: galleryHtml(["/img/memes/fire-woman.gif", "/img/memes/epic.jpeg"]), size: [460, 320] },
{ label: "Video", title: "Video", html: VIDEO, size: [400, 260], framed: false }, { label: "Video", title: "Video", html: videoHtml("/img/demoman/1760582395316219.webm"), size: [400, 260], framed: false },
{ label: "Clock", title: "Clock", html: CLOCK, size: [240, 120] }, { label: "Clock", title: "Clock", html: CLOCK, size: [240, 120] },
{ label: "Weather", title: "Weather", html: WEATHER, size: [240, 170] }, { label: "Weather", title: "Weather", html: WEATHER, size: [240, 170] },
{ label: "Empty HTML", title: "HTML", html: EMPTY, size: [300, 200] }, { label: "Empty HTML", title: "HTML", html: EMPTY, size: [300, 200] },
]; ];
export { imageHtml, galleryHtml }; export { imageHtml, galleryHtml, videoHtml };
+53
View File
@@ -0,0 +1,53 @@
/**
* Uploading a file for use in a box: stores it through the chat's upload
* endpoint (public, unguessable URLs under /uploads/) and says what markup
* shows it. Used by BoxEditor's "Insert upload" and by dropping files onto
* the canvas in edit mode.
*
* Never the private upload directory: that one is behind a cookie check, and
* a box's sandboxed frame loads as an opaque origin, so its requests may not
* carry the cookie.
*/
import { api } from "@/api";
/** Upload one file; resolves to its URL. Throws an ApiError on failure. */
export async function uploadFile(file) {
const body = new FormData();
body.append("file", file);
const { url } = await api.post("/messages/upload", body, { fallback: `Upload of ${file.name} failed` });
return url;
}
export const isImage = (url) => /\.(jpe?g|png|gif|webp)$/i.test(url);
export const isVideo = (url) => /\.(mp4|webm)$/i.test(url);
/** The markup an uploaded file is shown with, by type. Anything else (a PDF,
* a text file) becomes a link. */
export function tagFor(url) {
if (isImage(url)) return `<img src="${url}" alt="">`;
if (isVideo(url)) return `<video src="${url}" controls loop muted></video>`;
if (/\.(mp3|ogg)$/i.test(url)) return `<audio src="${url}" controls></audio>`;
return `<a href="${url}" target="_blank">${url.split("/").pop()}</a>`;
}
/** Natural size of an image or video file, or null if it can't be read. */
export function mediaSize(file) {
return new Promise((resolve) => {
const src = URL.createObjectURL(file);
const done = (size) => {
URL.revokeObjectURL(src);
resolve(size);
};
if (file.type.startsWith("video/")) {
const v = document.createElement("video");
v.onloadedmetadata = () => done({ w: v.videoWidth, h: v.videoHeight });
v.onerror = () => done(null);
v.src = src;
} else {
const img = new Image();
img.onload = () => done({ w: img.naturalWidth, h: img.naturalHeight });
img.onerror = () => done(null);
img.src = src;
}
});
}