Make /stp an admin-editable canvas of boxes
Test and deploy / test (push) Successful in 1m58s
Test and deploy / deploy (push) Successful in 1m18s

/stp is now views/home3/Home3.vue: boxes an admin creates, drags, resizes
and edits in the browser, saved to the database so every visitor sees the
same layout.

- backend: a Box GraphQL type (kind widget|html, x/y/w/h/z in px on a
  1400px design canvas, framed, hideOnMobile). Public `boxes` query;
  create/update/delete are @admin. Geometry is clamped rather than
  rejected. Framed has no gorm default, since GORM would turn an explicit
  false into true on insert.
- vue: widget boxes render the existing widgets from a registry; html
  boxes render in an iframe sandboxed with allow-scripts and no
  allow-same-origin, so admin script can't read cookies or call /api. The
  site tokens and fonts (inlined as data: URLs) are injected into each
  frame. The canvas scales to fit the window; phones get a single column
  in (y, x) order. Edit mode saves geometry on release and has a
  CodeMirror side panel (lazy-loaded) with a live HTML preview. Templates
  cover Clock, Weather (Open-Meteo) and Image/GIF. "Import current layout"
  recreates the old Home.vue grid on an empty canvas.
- Home.vue is kept with a STATUS: legacy header. Docs updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 18:15:03 +01:00
co-authored by Claude Opus 5.5
parent f66d9c52ee
commit e788e16898
26 changed files with 3113 additions and 8 deletions
+1 -1
View File
@@ -33,7 +33,7 @@ const router = createRouter({
{
path: "stp",
name: "home",
component: () => import("@/views/home/Home.vue"),
component: () => import("@/views/home3/Home3.vue"),
},
{
path: "admin/login",
+54
View File
@@ -0,0 +1,54 @@
/**
* Boxes on the /stp canvas (views/home3/) — full CRUD, built on
* createCrudStore().
*
* Not part of the homeData query: the canvas has to know which boxes exist
* before it can mount the widgets that then trigger homeData, and keeping the
* two apart means a failing Spotify/Steam upstream can't blank the layout.
*
* The list query returns boxes ordered by z, so a new box (given the top z)
* belongs at the end.
*/
import { createCrudStore } from "@/stores/createCrudStore";
const BOX_FIELDS = `
id
kind
widget
html
title
x
y
w
h
z
framed
hideOnMobile
`;
// 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 = ["kind", "widget", "html", "title", "w", "h", "framed", "hideOnMobile"];
export const useBoxesStore = createCrudStore("boxes", {
type: "Box",
list: "boxes",
fields: BOX_FIELDS,
insert: "append",
deleteReturns: "object",
extend: ({ items, create, update }) => {
const topZ = () => Math.max(0, ...items.value.map((b) => b.z)) + 1;
const bottomZ = () => Math.min(0, ...items.value.map((b) => b.z)) - 1;
return {
topZ,
bringToFront: (box) => update(box.id, { z: topZ() }),
sendToBack: (box) => update(box.id, { z: bottomZ() }),
duplicate: (box) => {
const input = Object.fromEntries(COPIED.map((k) => [k, box[k]]));
return create({ ...input, x: box.x + 20, y: box.y + 20, z: topZ() });
},
};
},
});
+5 -1
View File
@@ -1,6 +1,10 @@
<script setup>
/**
* Route `/stp` — the personal home page: an A4-shaped widget grid flanked by two
* STATUS: legacy — no route points here. `/stp` is now views/home3/Home3.vue,
* the admin-editable box canvas; views/home3/defaultLayout.js is this page's
* arrangement redrawn as boxes. Kept for reference.
*
* Was route `/stp` — the personal home page: an A4-shaped widget grid flanked by two
* sidebars.
*
* Layout is entirely CSS `grid-template-areas`: each child gets a `grid-area`
+223
View File
@@ -0,0 +1,223 @@
<script setup>
/**
* Side panel for the selected box in edit mode.
*
* Two save rhythms, matching how each kind of field is used:
* - Settings (title, geometry, frame, mobile, widget) save as soon as they
* change — on blur/Enter for numbers, on change for the rest — the same
* "instant" model as dragging.
* - HTML is a draft. Typing updates the box on the canvas live (through the
* `preview` event, so the parent can render the draft without touching the
* store) and is saved only by Save or Ctrl/Cmd+S. Saving every keystroke
* would push half-written markup to every visitor.
*/
import { computed, ref, watch } from "vue";
import { useBoxesStore } from "@/stores/boxes";
import CodeEditor from "./CodeEditor.vue";
import { WIDGETS } from "./widgetRegistry";
const props = defineProps({
box: { type: Object, required: true },
});
const emit = defineEmits(["preview", "close", "error"]);
const store = useBoxesStore();
const draftHtml = ref(props.box.html ?? "");
const saving = ref(false);
const dirty = computed(() => props.box.kind === "html" && draftHtml.value !== (props.box.html ?? ""));
// Switching to another box: drop this one's preview, start from the new
// box's saved html.
watch(
() => props.box.id,
() => {
emit("preview", null);
draftHtml.value = props.box.html ?? "";
},
);
let previewTimer = null;
watch(draftHtml, (html) => {
clearTimeout(previewTimer);
previewTimer = setTimeout(() => emit("preview", dirty.value ? html : null), 300);
});
async function save(patch) {
try {
await store.update(props.box.id, patch);
} catch (err) {
emit("error", err);
}
}
async function saveHtml() {
if (!dirty.value || saving.value) return;
saving.value = true;
try {
await store.update(props.box.id, { html: draftHtml.value });
emit("preview", null);
} catch (err) {
emit("error", err);
} finally {
saving.value = false;
}
}
function saveNumber(field, event) {
const value = Math.round(Number(event.target.value));
if (!Number.isFinite(value) || value === props.box[field]) {
event.target.value = props.box[field];
return;
}
save({ [field]: value });
}
function close() {
if (dirty.value && !confirm("Discard unsaved HTML changes?")) return;
emit("preview", null);
emit("close");
}
defineExpose({ close });
</script>
<template>
<aside class="box-editor" @keydown.esc="close">
<header class="flex items-center justify-between gap-2">
<h3 class="m-0">
{{ box.kind === "widget" ? `Widget · ${box.widget}` : "HTML box" }}
</h3>
<button type="button" class="close" title="Close" @click="close">✕</button>
</header>
<label class="field">
<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
type="number"
:value="box[field]"
@change="saveNumber(field, $event)"
@keydown.enter="$event.target.blur()"
/>
</label>
</div>
<div class="flex gap-4">
<label class="check">
<input type="checkbox" :checked="box.framed" @change="save({ framed: $event.target.checked })" />
Frame
</label>
<label class="check">
<input
type="checkbox"
:checked="box.hideOnMobile"
@change="save({ hideOnMobile: $event.target.checked })"
/>
Hide on mobile
</label>
</div>
<template v-if="box.kind === 'html'">
<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>
<button type="button" class="save" :disabled="!dirty || saving" @click="saveHtml">
{{ saving ? "Saving…" : dirty ? "Save" : "Saved" }}
</button>
</footer>
</template>
</aside>
</template>
<style scoped>
.box-editor {
position: fixed;
top: 0;
right: 0;
bottom: 0;
z-index: 60;
width: min(460px, 100vw);
display: flex;
flex-direction: column;
gap: 0.6rem;
padding: 0.75rem;
box-sizing: border-box;
background: var(--color-surface);
border-left: 2px solid var(--color-primary);
color: var(--color-secondary);
}
.close {
color: var(--color-primary);
background: var(--color-link-bg);
border: 1px solid var(--color-primary);
padding: 0 0.5rem;
cursor: pointer;
}
.field {
display: flex;
flex-direction: column;
gap: 2px;
font-size: 0.85rem;
color: var(--color-muted);
}
.field input,
.field select {
padding: 3px 5px;
color: var(--color-secondary);
background: var(--color-surface-deep);
border: 1px solid var(--color-quaternary);
min-width: 0;
}
.geometry {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 0.4rem;
}
.check {
white-space: nowrap;
display: flex;
align-items: center;
gap: 0.35rem;
font-size: 0.9rem;
}
.save {
flex: none;
padding: 0.3rem 1rem;
color: var(--color-primary);
background: var(--color-link-bg);
border: 2px solid var(--color-primary);
font-family: var(--font-heading);
font-size: 1.1rem;
cursor: pointer;
}
.save:disabled {
opacity: 0.5;
cursor: default;
}
</style>
+244
View File
@@ -0,0 +1,244 @@
<script setup>
/**
* One positioned box on the canvas, plus its edit-mode drag/resize overlay.
*
* Geometry is canvas px (see models.Box). The canvas is drawn with
* transform: scale(), so pointer deltas, which are screen px, are divided by
* `scale` before they are applied.
*
* In edit mode an overlay covers the whole box. That is what makes dragging
* work at all over an HTML box: pointer events that land on an iframe go to
* the iframe's document and never reach this one. It also means the box
* contents can't be clicked while editing, which is intended — leave edit mode
* to use them.
*
* While a drag is in progress the box draws from a local `draft`. On release
* the final geometry is emitted once as `commit`; the parent saves it. A press
* that never moves is a click (select only) and commits nothing.
*/
import { computed, ref } from "vue";
const props = defineProps({
box: { type: Object, required: true },
scale: { type: Number, default: 1 },
editing: { type: Boolean, default: false },
selected: { type: Boolean, default: false },
label: { type: String, default: "" },
});
const emit = defineEmits(["select", "commit", "action"]);
const SNAP = 5;
const MIN_SIZE = 40; // matches minBoxSize in backend/graph/box_helpers.go
const HANDLES = ["n", "s", "e", "w", "ne", "nw", "se", "sw"];
const draft = ref(null);
const geom = computed(() => draft.value ?? props.box);
const style = computed(() => ({
left: `${geom.value.x}px`,
top: `${geom.value.y}px`,
width: `${geom.value.w}px`,
height: `${geom.value.h}px`,
// The selected box is lifted above everything while editing: its resize
// handles sit just outside its edges, where an overlapping neighbour with a
// higher z would otherwise cover them and take the press.
zIndex: props.selected ? 100000 : props.box.z,
}));
const snap = (n) => Math.round(n / SNAP) * SNAP;
let drag = null;
function start(mode, event) {
if (event.button !== 0) return;
emit("select");
event.preventDefault();
event.target.setPointerCapture(event.pointerId);
const { x, y, w, h } = props.box;
drag = { mode, startX: event.clientX, startY: event.clientY, from: { x, y, w, h }, moved: false };
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", end);
window.addEventListener("pointercancel", end);
}
function move(event) {
const dx = (event.clientX - drag.startX) / props.scale;
const dy = (event.clientY - drag.startY) / props.scale;
// A few px of jitter on a click shouldn't count as a move.
if (!drag.moved && Math.hypot(dx, dy) < 3) return;
drag.moved = true;
const { x, y, w, h } = drag.from;
const next = { x, y, w, h };
if (drag.mode === "move") {
next.x = Math.max(0, snap(x + dx));
next.y = Math.max(0, snap(y + dy));
} else {
// Each handle moves the edges named in it. Moving the left or top edge
// changes position and size together, and is clamped so the opposite
// edge stays put once the box reaches its minimum size.
if (drag.mode.includes("e")) next.w = Math.max(MIN_SIZE, snap(w + dx));
if (drag.mode.includes("s")) next.h = Math.max(MIN_SIZE, snap(h + dy));
if (drag.mode.includes("w")) {
next.x = Math.max(0, Math.min(snap(x + dx), x + w - MIN_SIZE));
next.w = x + w - next.x;
}
if (drag.mode.includes("n")) {
next.y = Math.max(0, Math.min(snap(y + dy), y + h - MIN_SIZE));
next.h = y + h - next.y;
}
}
draft.value = next;
}
function end() {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", end);
window.removeEventListener("pointercancel", end);
if (drag?.moved && draft.value) emit("commit", { ...draft.value });
drag = null;
draft.value = null;
}
</script>
<template>
<div
class="box"
:class="{ framed: box.framed, editing, selected }"
:style="style"
>
<slot />
<div
v-if="editing"
class="overlay"
@pointerdown="start('move', $event)"
>
<span class="label">{{ label }}</span>
<div v-if="selected" class="toolbar" @pointerdown.stop>
<button type="button" title="Bring to front" @click="emit('action', 'front')">▲</button>
<button type="button" title="Send to back" @click="emit('action', 'back')">▼</button>
<button type="button" title="Duplicate" @click="emit('action', 'duplicate')">⧉</button>
<button type="button" title="Delete" @click="emit('action', 'delete')">✕</button>
</div>
<template v-if="selected">
<div
v-for="h in HANDLES"
:key="h"
class="handle"
:class="`h-${h}`"
@pointerdown.stop="start(h, $event)"
/>
</template>
</div>
</div>
</template>
<style scoped>
.box {
position: absolute;
box-sizing: border-box;
display: flex;
flex-direction: column;
min-height: 0;
}
.box.framed {
background-color: var(--color-surface);
border: 2px solid var(--color-quaternary);
}
.overlay {
position: absolute;
inset: 0;
cursor: move;
touch-action: none;
outline: 1px dashed var(--color-quaternary);
background: color-mix(in srgb, var(--color-surface-deep) 15%, transparent);
}
.box.selected .overlay {
outline: 2px solid var(--color-primary);
background: color-mix(in srgb, var(--color-primary) 6%, transparent);
}
.label {
position: absolute;
left: 0;
top: 0;
padding: 0 4px;
font-size: 12px;
color: var(--color-surface-deep);
background: var(--color-primary);
pointer-events: none;
opacity: 0.85;
}
.toolbar {
position: absolute;
right: 0;
top: -28px;
display: flex;
gap: 2px;
cursor: default;
}
.toolbar button {
width: 26px;
height: 24px;
font-size: 13px;
line-height: 1;
color: var(--color-primary);
background: var(--color-link-bg);
border: 1px solid var(--color-primary);
cursor: pointer;
}
.toolbar button:hover {
color: var(--color-tertiary);
border-color: var(--color-tertiary);
}
.handle {
position: absolute;
width: 10px;
height: 10px;
background: var(--color-primary);
border: 1px solid var(--color-surface-deep);
touch-action: none;
}
.h-n,
.h-s {
left: calc(50% - 5px);
cursor: ns-resize;
}
.h-e,
.h-w {
top: calc(50% - 5px);
cursor: ew-resize;
}
.h-n,
.h-ne,
.h-nw {
top: -5px;
}
.h-s,
.h-se,
.h-sw {
bottom: -5px;
}
.h-e,
.h-ne,
.h-se {
right: -5px;
}
.h-w,
.h-nw,
.h-sw {
left: -5px;
}
.h-ne,
.h-sw {
cursor: nesw-resize;
}
.h-nw,
.h-se {
cursor: nwse-resize;
}
</style>
+89
View File
@@ -0,0 +1,89 @@
<script setup>
/**
* CodeMirror 6 HTML editor with v-model, used by BoxEditor.
*
* CodeMirror is imported dynamically on mount, so the ~150 KB of editor code
* is only downloaded by an admin who opens a box for editing — never by a
* visitor to /stp.
*
* The document is owned by CodeMirror; `modelValue` is pushed in only when it
* differs from what the editor already holds, otherwise every keystroke would
* round-trip through the parent and reset the cursor.
*/
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
const props = defineProps({
modelValue: { type: String, default: "" },
});
const emit = defineEmits(["update:modelValue", "save"]);
const host = ref(null);
const failed = ref(false);
let view = null;
onMounted(async () => {
let mods;
try {
mods = await Promise.all([import("codemirror"), import("@codemirror/lang-html"), import("@codemirror/view")]);
} catch {
failed.value = true;
return;
}
const [{ basicSetup, EditorView }, { html }, { keymap }] = mods;
if (!host.value) return; // unmounted while loading
const theme = EditorView.theme(
{
"&": { height: "100%", fontSize: "13px", backgroundColor: "var(--color-surface-deep)", color: "var(--color-muted)" },
".cm-content": { caretColor: "var(--color-primary)" },
".cm-gutters": { backgroundColor: "var(--color-surface)", color: "var(--color-quaternary)", border: "none" },
".cm-activeLine, .cm-activeLineGutter": { backgroundColor: "var(--color-surface-tint)" },
"&.cm-focused .cm-selectionBackground, .cm-selectionBackground": { backgroundColor: "#24504a" },
".cm-scroller": { fontFamily: "ui-monospace, monospace" },
},
{ dark: true },
);
view = new EditorView({
parent: host.value,
doc: props.modelValue,
extensions: [
// Before basicSetup so Mod-s wins over the browser's "save page".
keymap.of([{ key: "Mod-s", preventDefault: true, run: () => (emit("save"), true) }]),
basicSetup,
html(),
theme,
EditorView.lineWrapping,
EditorView.updateListener.of((update) => {
if (update.docChanged) emit("update:modelValue", update.state.doc.toString());
}),
],
});
});
watch(
() => props.modelValue,
(value) => {
if (view && value !== view.state.doc.toString()) {
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } });
}
},
);
onBeforeUnmount(() => view?.destroy());
</script>
<template>
<div ref="host" class="code-editor">
<p v-if="failed" class="p-2 text-tertiary">Couldn't load the editor.</p>
</div>
</template>
<style scoped>
.code-editor {
height: 100%;
min-height: 0;
overflow: hidden;
border: 1px solid var(--color-quaternary);
}
</style>
+370
View File
@@ -0,0 +1,370 @@
<script setup>
/**
* Route `/stp` — the home page as a free-form canvas of boxes the admin
* arranges in the browser. Replaces views/home/Home.vue's fixed grid.
*
* Every box (stores/boxes.js, the `Box` GraphQL type) has a position, size and
* z-index in px on a fixed CANVAS_W-wide design canvas. The canvas is drawn at
* that width and shrunk with transform: scale() to fit narrower windows, so
* what the admin arranges is exactly what every desktop visitor sees, just
* smaller. The canvas is as tall as its lowest box.
*
* At phone width the canvas would be unreadably small, so the boxes are laid
* out in a single column instead: reading order is top-to-bottom then
* left-to-right by their canvas position, each keeps its height, and any box
* flagged hideOnMobile is skipped. There is no separate mobile layout to
* maintain, and no editing at that width.
*
* Admins get an Edit toggle. In edit mode boxes drag and resize (BoxFrame),
* changes save on release, and the selected box opens in BoxEditor.
*/
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import { useMediaQuery } from "@vueuse/core";
import { useAuthStore } from "@/stores/auth";
import { useBoxesStore } from "@/stores/boxes";
import { useHomeDataStore } from "@/stores/homeData";
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 } from "./templates";
import { defaultLayout } from "./defaultLayout";
const CANVAS_W = 1400;
const MOBILE_QUERY = "(max-width: 700px)";
const auth = useAuthStore();
const store = useBoxesStore();
// The widgets each start the shared home query when they mount, but a canvas
// of only HTML boxes would mount none — and that query is also what tells
// auth who is signed in on this page (see stores/auth.js), so without it the
// Edit button would never appear. Instantiating the store fires it.
useHomeDataStore();
store.fetch();
const isMobile = useMediaQuery(MOBILE_QUERY);
const isAdmin = computed(() => auth.loggedIn && !!auth.user.admin);
const editing = ref(false);
const canEdit = computed(() => isAdmin.value && !isMobile.value);
const inEditMode = computed(() => editing.value && canEdit.value);
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
const errorMsg = ref("");
const editor = ref(null);
// ---- Scaling -------------------------------------------------------------
const viewport = ref(null);
const availableW = ref(CANVAS_W);
let observer = null;
onMounted(() => {
observer = new ResizeObserver(([entry]) => (availableW.value = entry.contentRect.width));
if (viewport.value) observer.observe(viewport.value);
});
onBeforeUnmount(() => observer?.disconnect());
const scale = computed(() => Math.min(1, availableW.value / CANVAS_W));
const contentH = computed(() => Math.max(0, ...store.boxes.map((b) => b.y + b.h)));
// Spare room below the lowest box while editing, so there is somewhere to
// drag to.
const canvasH = computed(() => Math.max(400, contentH.value + (inEditMode.value ? 400 : 40)));
// ---- Mobile ordering -----------------------------------------------------
const stacked = computed(() =>
store.boxes.filter((b) => !b.hideOnMobile).sort((a, b) => a.y - b.y || a.x - b.x),
);
// ---- Saving --------------------------------------------------------------
function report(err) {
errorMsg.value = err?.message ?? String(err);
setTimeout(() => (errorMsg.value = ""), 6000);
}
// The new geometry is applied locally before the request so the box stays
// where it was dropped instead of snapping back until the server answers;
// on failure it is put back.
async function commitGeometry(box, geom) {
const before = { x: box.x, y: box.y, w: box.w, h: box.h };
Object.assign(box, geom);
try {
await store.update(box.id, geom);
} catch (err) {
Object.assign(box, before);
report(err);
}
}
async function run(action) {
try {
await action();
} catch (err) {
report(err);
}
}
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));
} else if (action === "delete") {
if (!confirm(`Delete “${labelOf(box)}”? This can't be undone from here.`)) return;
if (selectedId.value === box.id) selectedId.value = null;
run(() => store.remove(box.id));
}
}
function labelOf(box) {
return box.title || (box.kind === "widget" ? box.widget : "HTML");
}
// ---- Creating ------------------------------------------------------------
const canvasEl = ref(null);
// Top-left of the part of the canvas currently on screen, so a new box
// appears where the admin is looking rather than at the top of the page.
function visibleOrigin() {
const rect = canvasEl.value?.getBoundingClientRect();
const top = rect ? Math.max(0, -rect.top / scale.value) : 0;
const origin = { x: 40, y: Math.round(top / 5) * 5 + 40 };
// Cascade, so adding several boxes in a row doesn't stack them exactly on
// top of one another.
while (store.boxes.some((b) => b.x === origin.x && b.y === origin.y)) {
origin.x += 20;
origin.y += 20;
}
return origin;
}
const newChoice = ref("");
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 };
}
run(async () => {
const created = await store.create({ ...input, x, y, z: store.topZ() });
selectedId.value = created.id;
});
}
const importing = ref(false);
async function importDefault() {
importing.value = true;
try {
// Sequential, so the boxes come back in z order without a refetch.
for (const box of defaultLayout()) await store.create(box);
} catch (err) {
report(err);
} finally {
importing.value = false;
}
}
// ---- Selection -----------------------------------------------------------
function select(box) {
if (selectedId.value === box.id) return;
// Leaving a box with unsaved HTML goes through the editor's own confirm.
if (editor.value && selected.value) {
editor.value.close();
if (selectedId.value !== null) return; // they chose to keep editing
}
selectedId.value = box.id;
}
function toggleEdit() {
if (editing.value && selected.value) {
editor.value?.close();
if (selectedId.value !== null) return;
}
editing.value = !editing.value;
}
</script>
<template>
<main class="home3" :class="{ 'with-editor': inEditMode && selected }">
<div v-if="canEdit" class="admin-bar">
<button type="button" class="bar-btn" :class="{ on: editing }" @click="toggleEdit">
{{ editing ? "Done" : "Edit layout" }}
</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>
</optgroup>
<optgroup label="Widget">
<option v-for="name in Object.keys(WIDGETS)" :key="name" :value="`widget:${name}`">{{ name }}</option>
</optgroup>
</select>
<button
v-if="store.loaded && store.boxes.length === 0"
type="button"
class="bar-btn"
:disabled="importing"
@click="importDefault"
>
{{ importing ? "Importing…" : "Import current layout" }}
</button>
</template>
<span v-if="errorMsg" class="error">{{ errorMsg }}</span>
</div>
<p v-if="store.error" class="state">Couldn't load the page layout.</p>
<p v-else-if="store.loaded && store.boxes.length === 0 && !canEdit" class="state">Nothing here yet.</p>
<!-- Phone: one column, no editing -->
<div v-if="isMobile" class="stack">
<div
v-for="box in stacked"
:key="box.id"
class="stack-item"
:class="{ framed: box.framed }"
:style="{ height: `${box.h}px` }"
>
<WidgetBox v-if="box.kind === 'widget'" :name="box.widget" />
<HtmlBox v-else :html="box.html" :title="box.title" />
</div>
</div>
<!-- Desktop: the scaled canvas -->
<div v-else ref="viewport" class="viewport">
<div
class="canvas-size"
:style="{ width: `${CANVAS_W * scale}px`, height: `${canvasH * scale}px` }"
>
<div
ref="canvasEl"
class="canvas"
:class="{ editing: inEditMode }"
:style="{ width: `${CANVAS_W}px`, height: `${canvasH}px`, transform: `scale(${scale})` }"
@pointerdown.self="selectedId = null"
>
<BoxFrame
v-for="box in store.boxes"
:key="box.id"
:box="box"
:scale="scale"
:editing="inEditMode"
:selected="inEditMode && box.id === selectedId"
:label="labelOf(box)"
@select="select(box)"
@commit="commitGeometry(box, $event)"
@action="onAction(box, $event)"
>
<WidgetBox v-if="box.kind === 'widget'" :name="box.widget" />
<HtmlBox
v-else
:html="box.id === selectedId && preview !== null ? preview : box.html"
:title="box.title"
/>
</BoxFrame>
</div>
</div>
</div>
<BoxEditor
v-if="inEditMode && selected"
ref="editor"
:box="selected"
@preview="preview = $event"
@close="selectedId = null"
@error="report"
/>
</main>
</template>
<style scoped>
.home3 {
width: 100%;
min-height: 100%;
box-sizing: border-box;
padding: 10px 16px;
}
/* Leave room for the fixed editor panel so the canvas rescales beside it
instead of disappearing under it. */
.home3.with-editor {
padding-right: calc(min(460px, 100vw) + 16px);
}
.admin-bar {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0 auto 10px;
max-width: 1400px;
}
.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,
.bar-btn.on {
border-color: var(--color-primary);
}
.bar-btn:disabled {
opacity: 0.5;
}
.error {
color: var(--color-tertiary);
}
.state {
text-align: center;
color: var(--color-muted);
}
.viewport {
width: 100%;
}
.canvas-size {
position: relative;
margin: 0 auto;
}
.canvas {
position: absolute;
left: 0;
top: 0;
transform-origin: 0 0;
}
/* 20px dot grid while editing, to line things up by eye. */
.canvas.editing {
outline: 1px dashed var(--color-quaternary);
background-image: radial-gradient(var(--color-quaternary) 1px, transparent 1px);
background-size: 20px 20px;
}
.stack {
display: flex;
flex-direction: column;
gap: 5px;
}
.stack-item {
box-sizing: border-box;
width: 100%;
min-height: 0;
display: flex;
flex-direction: column;
}
.stack-item.framed {
background-color: var(--color-surface);
border: 2px solid var(--color-quaternary);
}
</style>
+54
View File
@@ -0,0 +1,54 @@
<script setup>
/**
* An admin-authored HTML box, rendered in a sandboxed iframe.
*
* The sandbox is the security boundary for the whole "write HTML in the
* browser" feature. `allow-scripts` without `allow-same-origin` gives the frame
* an opaque origin: its scripts run, but cannot read our cookies, call /api as
* the visitor, or reach into the parent page. NEVER add allow-same-origin —
* together with allow-scripts it lets the frame remove its own sandbox.
*
* The popup and top-navigation flags only let links work: target="_blank"
* opens a normal (unsandboxed) tab, and target="_top" can navigate the page on
* a real click.
*
* Nothing is rendered until the frame stylesheet (fonts inlined, see
* frameStyles.js) is ready, so boxes don't flash in fallback fonts.
*/
import { computed, ref } from "vue";
import { buildSrcdoc, frameCss } from "./frameStyles";
const props = defineProps({
html: { type: String, default: "" },
title: { type: String, default: "" },
});
const css = ref(null);
frameCss().then((value) => (css.value = value));
const srcdoc = computed(() =>
css.value === null ? null : buildSrcdoc(css.value, props.html),
);
</script>
<template>
<iframe
v-if="srcdoc !== null"
class="html-box"
:srcdoc="srcdoc"
:title="title || 'Custom box'"
sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation"
referrerpolicy="no-referrer"
loading="lazy"
/>
</template>
<style scoped>
.html-box {
display: block;
width: 100%;
height: 100%;
border: 0;
background: transparent;
}
</style>
+47
View File
@@ -0,0 +1,47 @@
<script setup>
/**
* A box showing one of the built-in Vue widgets from widgetRegistry.js.
*
* The widgets were written for Home.vue's grid cells and sidebars, and a few
* size their own root (Steam is 54mm tall). On the canvas the box decides the
* size, so the root is forced to fill it — hence the !important, which has to
* beat each widget's own scoped rule regardless of stylesheet order.
*/
import { computed } from "vue";
import { WIDGETS } from "./widgetRegistry";
const props = defineProps({
name: { type: String, required: true },
});
const entry = computed(() => WIDGETS[props.name]);
</script>
<template>
<div class="widget-host">
<component :is="entry.component" v-if="entry" />
<p v-else class="missing">Unknown widget “{{ name }}”</p>
</div>
</template>
<style scoped>
.widget-host {
width: 100%;
height: 100%;
min-height: 0;
overflow: hidden;
display: flex;
flex-direction: column;
}
.widget-host > :deep(*) {
width: 100% !important;
height: 100% !important;
max-height: none !important;
flex: 1 1 auto;
min-height: 0;
}
.missing {
margin: auto;
color: var(--color-tertiary);
}
</style>
+81
View File
@@ -0,0 +1,81 @@
/**
* The pre-Home3 /stp page (views/home/Home.vue) redrawn as boxes, for the
* one-off "Import current layout" button on an empty canvas.
*
* Home.vue was an A4 sheet (~800×1120px) holding a 10×10 CSS grid with 5px
* gaps, between two 240px sidebars. The grid areas below are copied from its
* grid-template-areas and turned into px here so they can be read against the
* original; the sidebars are stacked top to bottom.
*/
import { imageHtml } from "./templates";
const SHEET = { x: 300, y: 20, w: 800, h: 1120 };
const GAP = 5;
const CELL_W = (SHEET.w - 9 * GAP) / 10;
const CELL_H = (SHEET.h - 9 * GAP) / 10;
// [widget, column, row, column span, row span] — zero-based, as in Home.vue.
const GRID = [
["Intro", 0, 0, 6, 4],
["Listening", 6, 0, 4, 3],
["Stamps", 6, 3, 4, 1],
["Feed", 0, 4, 3, 4],
["Links", 3, 4, 2, 4],
["Collage", 5, 4, 5, 4],
["Consumption", 0, 8, 4, 2],
["Gym", 4, 8, 3, 2],
["Favorites", 7, 8, 3, 2],
];
// Collage and Gym were hidden on phones; keep that.
const HIDDEN_ON_MOBILE = new Set(["Collage", "Gym"]);
function gridBox([widget, col, row, cols, rows]) {
return {
kind: "widget",
widget,
x: Math.round(SHEET.x + col * (CELL_W + GAP)),
y: Math.round(SHEET.y + row * (CELL_H + GAP)),
w: Math.round(cols * CELL_W + (cols - 1) * GAP),
h: Math.round(rows * CELL_H + (rows - 1) * GAP),
hideOnMobile: HIDDEN_ON_MOBILE.has(widget),
};
}
// [widget or html box, height]; each column fills SHEET.h top to bottom.
function column(x, entries) {
let y = SHEET.y;
return entries.map(([box, h]) => {
const placed = { ...box, x, y, w: 240, h };
y += h + GAP;
return placed;
});
}
const widget = (name, extra = {}) => ({ kind: "widget", widget: name, ...extra });
export function defaultLayout() {
const left = column(50, [
[widget("Time", { hideOnMobile: true }), 90],
[widget("Timer", { hideOnMobile: true }), 130],
[widget("Radio", { hideOnMobile: true }), 160],
[widget("Commits"), 487],
[
{
kind: "html",
title: "Fire woman",
html: imageHtml("/img/memes/fire-woman.gif"),
framed: false,
hideOnMobile: true,
},
238,
],
]);
const right = column(1110, [
[widget("Steam"), 205],
[widget("Bookmarks"), 250],
[widget("Chat"), 410],
[widget("Miku", { framed: false, hideOnMobile: true }), 240],
]);
return [...GRID.map(gridBox), ...left, ...right].map((box, i) => ({ z: i + 1, ...box }));
}
+88
View File
@@ -0,0 +1,88 @@
/**
* The stylesheet injected at the top of every HTML box's iframe, so admin
* HTML looks like the rest of the site without restating the palette.
*
* Two things a sandboxed iframe cannot do for itself:
* - Inherit CSS. It is a separate document, so the design tokens are copied
* in as literal values, read from the live page so a re-themed layout
* (CVLayout re-points the tokens) would carry through.
* - Load our fonts. Without allow-same-origin its origin is opaque ("null"),
* which makes /fonts/*.woff2 a cross-origin font load that nginx and the
* Vite dev server would both refuse without CORS headers. Instead the page
* fetches the two files (28 KB) once, same-origin, and inlines them as
* data: URLs.
*/
const TOKENS = [
"--color-primary",
"--color-secondary",
"--color-tertiary",
"--color-quaternary",
"--color-muted",
"--color-surface",
"--color-surface-deep",
"--color-surface-tint",
"--color-link-bg",
];
const FONTS = [
["big_noodle_titling", "/fonts/big_noodle_titling.woff2"],
["CreatoDisplay", "/fonts/CreatoDisplay-Bold.woff2"],
];
async function toDataUrl(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`${url}: ${res.status}`);
const blob = await res.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
});
}
async function fontFaces() {
// A font that fails to load falls back to sans-serif rather than holding
// back every box on the page.
const faces = await Promise.all(
FONTS.map(async ([family, url]) => {
try {
const src = await toDataUrl(url);
return `@font-face{font-family:"${family}";src:url(${src}) format("woff2");font-display:swap}`;
} catch {
return "";
}
}),
);
return faces.join("\n");
}
function tokens() {
const style = getComputedStyle(document.documentElement);
const decls = TOKENS.map((t) => `${t}:${style.getPropertyValue(t).trim()};`);
return `:root{${decls.join("")}--font-heading:"big_noodle_titling",sans-serif;--font-body:"CreatoDisplay",sans-serif}`;
}
const BASE = `
html,body{margin:0;height:100%}
body{box-sizing:border-box;padding:8px;overflow:auto;background:transparent;
color:var(--color-secondary);font-family:var(--font-body);font-size:15px}
*,*::before,*::after{box-sizing:inherit}
h1,h2,h3,h4{font-family:var(--font-heading);color:var(--color-primary);margin:0 0 .25em;font-weight:normal;letter-spacing:.025em}
a{color:var(--color-primary)}
img{max-width:100%}
`;
let cached = null;
/** Resolves to the <style> body for an HTML box. Built once per page load. */
export function frameCss() {
cached ??= fontFaces().then((faces) => `${faces}\n${tokens()}\n${BASE}`);
return cached;
}
/** A complete srcdoc document wrapping `html` in the site styles. */
export function buildSrcdoc(css, html) {
return `<!doctype html><html><head><meta charset="utf-8"><style>${css}</style></head><body>${html}</body></html>`;
}
+96
View File
@@ -0,0 +1,96 @@
/**
* 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 site's colour and font tokens are already defined in the frame
* (frameStyles.js), so templates use var(--color-…) freely.
*/
const CLOCK = `<style>
body { display: grid; place-items: center; text-align: center; }
.time { font-family: var(--font-heading); color: var(--color-primary); font-size: 3rem; line-height: 1; }
.date { color: var(--color-tertiary); }
</style>
<div>
<div class="time" id="time"></div>
<div class="date" id="date"></div>
</div>
<script>
const zone = "Europe/London";
const time = new Intl.DateTimeFormat("en-GB", { timeZone: zone, hour: "2-digit", minute: "2-digit", second: "2-digit" });
const date = new Intl.DateTimeFormat("en-GB", { timeZone: zone, weekday: "long", day: "numeric", month: "long" });
function tick() {
const now = new Date();
document.getElementById("time").textContent = time.format(now);
document.getElementById("date").textContent = date.format(now);
}
tick();
setInterval(tick, 1000);
</script>`;
const WEATHER = `<style>
body { display: grid; place-items: center; text-align: center; }
.temp { font-family: var(--font-heading); color: var(--color-primary); font-size: 3rem; line-height: 1; }
.desc { color: var(--color-secondary); }
.meta { color: var(--color-tertiary); font-size: .8em; }
</style>
<div>
<h3>London</h3>
<div class="temp" id="temp">…</div>
<div class="desc" id="desc"></div>
<div class="meta" id="meta"></div>
</div>
<script>
// https://open-meteo.com/en/docs — free, keyless, CORS-open.
const URL_ = "https://api.open-meteo.com/v1/forecast"
+ "?latitude=51.5072&longitude=-0.1276"
+ "&current=temperature_2m,apparent_temperature,weather_code,wind_speed_10m"
+ "&wind_speed_unit=mph&timezone=Europe%2FLondon";
// WMO weather interpretation codes, as Open-Meteo documents them.
const CODES = {
0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
45: "Fog", 48: "Rime fog", 51: "Light drizzle", 53: "Drizzle", 55: "Heavy drizzle",
56: "Freezing drizzle", 57: "Freezing drizzle", 61: "Light rain", 63: "Rain",
65: "Heavy rain", 66: "Freezing rain", 67: "Freezing rain", 71: "Light snow",
73: "Snow", 75: "Heavy snow", 77: "Snow grains", 80: "Light showers",
81: "Showers", 82: "Violent showers", 85: "Snow showers", 86: "Snow showers",
95: "Thunderstorm", 96: "Thunderstorm, hail", 99: "Thunderstorm, hail",
};
async function load() {
try {
const res = await fetch(URL_);
const { current } = await res.json();
document.getElementById("temp").textContent = Math.round(current.temperature_2m) + "°C";
document.getElementById("desc").textContent = CODES[current.weather_code] ?? "";
document.getElementById("meta").textContent =
"feels " + Math.round(current.apparent_temperature) + "° · wind " + Math.round(current.wind_speed_10m) + " mph";
} catch (err) {
document.getElementById("desc").textContent = "Weather unavailable";
}
}
load();
setInterval(load, 10 * 60 * 1000);
</script>`;
const imageHtml = (src) => `<style>
body { padding: 0; overflow: hidden; }
img { display: block; width: 100%; height: 100%; object-fit: cover; }
</style>
<img src="${src}" alt="">`;
const EMPTY = `<h3>New box</h3>
<p>Edit me.</p>`;
/** Menu entries; `size` is [w, h] in canvas px. */
export const TEMPLATES = [
{ label: "Clock", title: "Clock", html: CLOCK, size: [240, 120] },
{ label: "Weather", title: "Weather", html: WEATHER, size: [240, 170] },
{ label: "Image / GIF", title: "Image", html: imageHtml("/img/memes/fire-woman.gif"), size: [240, 240], framed: false },
{ label: "Empty HTML", title: "HTML", html: EMPTY, size: [300, 200] },
];
export { imageHtml };
+31
View File
@@ -0,0 +1,31 @@
/**
* The built-in Vue widgets a "widget" box can show, by the name stored in
* Box.widget. Renaming a key orphans every box saved under the old name
* (WidgetBox shows a placeholder for it), so treat the keys as stored data.
*
* Each is an async component so a widget nobody has placed on the canvas
* never loads. `size` is what a newly added box of that kind starts at.
*/
import { defineAsyncComponent } from "vue";
const lazy = (load) => defineAsyncComponent(load);
export const WIDGETS = {
Intro: { component: lazy(() => import("@/views/home/Intro3.vue")), size: [480, 440] },
Listening: { component: lazy(() => import("@/views/home/Listening.vue")), size: [310, 330] },
Stamps: { component: lazy(() => import("@/views/home/Stamps.vue")), size: [310, 110] },
Feed: { component: lazy(() => import("@/views/home/Feed.vue")), size: [235, 440] },
Links: { component: lazy(() => import("@/views/home/Links.vue")), size: [155, 440] },
Collage: { component: lazy(() => import("@/views/home/Collage.vue")), size: [395, 440] },
Consumption: { component: lazy(() => import("@/views/home/Consumption.vue")), size: [315, 220] },
Favorites: { component: lazy(() => import("@/views/home/Favorites.vue")), size: [235, 220] },
Gym: { component: lazy(() => import("@/views/home/Gym2.vue")), size: [235, 220] },
Steam: { component: lazy(() => import("@/views/home/Steam.vue")), size: [240, 205] },
Bookmarks: { component: lazy(() => import("@/views/home/Bookmarks.vue")), size: [240, 250] },
Miku: { component: lazy(() => import("@/views/home/Miku.vue")), size: [240, 240] },
Time: { component: lazy(() => import("@/components/util/Time.vue")), size: [240, 90] },
Timer: { component: lazy(() => import("@/components/util/Timer.vue")), size: [240, 130] },
Radio: { component: lazy(() => import("@/components/util/Radio.vue")), size: [240, 160] },
Chat: { component: lazy(() => import("@/components/util/Chat.vue")), size: [240, 450] },
Commits: { component: lazy(() => import("@/components/util/CommitHistory.vue")), size: [240, 400] },
};