Snap canvas boxes to each other's edges and centres, with guides
Test and deploy / test (push) Successful in 1m31s
Test and deploy / deploy (push) Successful in 39s

Dragging a box snaps its edges and centre to other boxes' and to the
canvas's sides, centre and top within 6 screen px, and draws a guide
along each shared line; a resize snaps the dragged edge. The 5px grid
still applies elsewhere. An "Align" button in the edit bar turns it off
(kept per browser), and Ctrl/Cmd mid-drag skips it once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 22:53:27 +01:00
co-authored by Claude Opus 5.5
parent 7969859955
commit e764078aaf
6 changed files with 220 additions and 33 deletions
+44 -2
View File
@@ -17,7 +17,10 @@
* 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. Boxes
* changes save on release, and the selected box opens in BoxEditor. A dragged
* box snaps its edges and centre to other boxes' and to the canvas's sides
* and centre, drawing a guide along each line it shares (./alignment.js); the
* Align button turns that off, and Ctrl/⌘ while dragging skips it once. 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; "+ From
@@ -50,7 +53,8 @@ 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 { panelWidth } from "./editorPrefs";
import { panelWidth, snapping } from "./editorPrefs";
import { snapTargets } from "./alignment";
import HtmlBox from "./HtmlBox.vue";
import WidgetBox from "./WidgetBox.vue";
import { WIDGETS } from "./widgetRegistry";
@@ -131,6 +135,24 @@ const contentH = computed(() => Math.max(0, ...store.boxes.map((b) => b.y + b.h)
// drag to.
const canvasH = computed(() => Math.max(400, contentH.value + (inEditMode.value ? 400 : 40)));
// ---- Alignment -----------------------------------------------------------
// What a dragged box can line up with: every other box, and the canvas. Only
// the dragged box reports guides, so one list serves the whole canvas. One
// function for every BoxFrame, so redrawing the guides on each pointermove
// doesn't hand every frame a new prop and redraw it too.
const guides = ref([]);
function targetsFor(box) {
return snapping.value ? snapTargets(store.boxes.filter((b) => b.id !== box.id), CANVAS_W) : null;
}
// A guide is a 1-screen-px line, so its thickness undoes the canvas scale.
function guideStyle(g) {
const thickness = `${1 / scale.value}px`;
return g.axis === "x"
? { left: `${g.at}px`, top: `${g.from}px`, width: thickness, height: `${g.to - g.from}px` }
: { top: `${g.at}px`, left: `${g.from}px`, height: thickness, width: `${g.to - g.from}px` };
}
// ---- Mobile ordering -----------------------------------------------------
const stacked = computed(() =>
store.boxes.filter((b) => !b.hideOnMobile).sort((a, b) => a.y - b.y || a.x - b.x),
@@ -407,6 +429,16 @@ function toggleEdit() {
{{ importing ? "Importing…" : starterLabel }}
</button>
<button type="button" class="bar-btn" @click="picking = true">+ From uploads…</button>
<button
type="button"
class="bar-btn"
:class="{ on: snapping }"
:aria-pressed="snapping"
title="Snap dragged boxes to other boxes' edges and centres (hold Ctrl/⌘ to skip once)"
@click="snapping = !snapping"
>
Align: {{ snapping ? "on" : "off" }}
</button>
</template>
<span v-if="inEditMode" class="hint">
{{ uploading ? `Uploading ${uploading}…` : "Drop images or videos onto the canvas to add them" }}
@@ -458,7 +490,9 @@ function toggleEdit() {
:editing="inEditMode"
:selected="inEditMode && box.id === selectedId"
:label="labelOf(box)"
:targets="targetsFor"
@select="select(box)"
@guides="guides = $event"
@commit="commitGeometry(box, $event)"
@action="onAction(box, $event)"
>
@@ -469,6 +503,7 @@ function toggleEdit() {
:title="box.title"
/>
</BoxFrame>
<div v-for="g in guides" :key="`${g.axis}${g.at}`" class="guide" :style="guideStyle(g)" />
</div>
</div>
</div>
@@ -567,6 +602,13 @@ function toggleEdit() {
background-image: radial-gradient(var(--color-quaternary) 1px, transparent 1px);
background-size: 20px 20px;
}
/* Above every box, the lifted selected one (BoxFrame) included. */
.guide {
position: absolute;
z-index: 100001;
background: var(--color-tertiary);
pointer-events: none;
}
.canvas.drag-over {
outline: 3px dashed var(--color-primary);
}
+8 -2
View File
@@ -14,7 +14,10 @@
*
* 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.
* that never moves is a click (select only) and commits nothing. Drags snap
* to the lines `targets` returns (see ./alignment.js), and the guides for
* what the box currently lines up with are emitted as `guides` for the canvas
* to draw, since a guide runs outside this box.
*/
import { computed, toRef } from "vue";
import { useBoxInteraction } from "./useBoxInteraction";
@@ -25,15 +28,18 @@ const props = defineProps({
editing: { type: Boolean, default: false },
selected: { type: Boolean, default: false },
label: { type: String, default: "" },
// (box) => alignment.snapTargets(...) for that box, or null for the grid alone.
targets: { type: Function, default: null },
});
const emit = defineEmits(["select", "commit", "action"]);
const emit = defineEmits(["select", "commit", "action", "guides"]);
const HANDLES = ["n", "s", "e", "w", "ne", "nw", "se", "sw"];
const { draft, start } = useBoxInteraction({
box: toRef(props, "box"),
scale: toRef(props, "scale"),
targets: () => props.targets?.(props.box),
emit,
});
const geom = computed(() => draft.value ?? props.box);
+133
View File
@@ -0,0 +1,133 @@
/**
* Geometry for dragging and resizing a box, with smart guides.
*
* While a box is dragged, its left edge, centre and right edge (and top,
* middle and bottom) are compared with every other box's, and with the
* canvas's sides, centre and top. When one comes within SNAP_PX screen px of
* another it snaps onto it, and every line the box then shares is returned as
* a guide for BoxCanvas to draw. A resize does the same for the edges being
* dragged only. Away from all of them the 5px grid applies, as it always did.
*
* Everything here is canvas px. The threshold is in screen px because that is
* what the hand feels; the caller divides it by the canvas scale.
*/
export const GRID = 5;
export const MIN_SIZE = 40;
export const SNAP_PX = 6;
const grid = (n) => Math.round(n / GRID) * GRID;
// Start, centre and end of a span.
const thirds = (start, size) => [start, start + size / 2, start + size];
/**
* The lines a dragged box can snap to, per axis. Each carries the extent of
* what it came from on the other axis, so a guide can be drawn between the
* two boxes rather than across the whole canvas. Computed once per drag.
*/
export function snapTargets(others, canvasW) {
const x = thirds(0, canvasW).map((at) => ({ at, from: 0, to: 0 }));
// The canvas is as tall as its lowest box, so only its top is a fixed line.
const y = [{ at: 0, from: 0, to: canvasW }];
for (const b of others) {
for (const at of thirds(b.x, b.w)) x.push({ at, from: b.y, to: b.y + b.h });
for (const at of thirds(b.y, b.h)) y.push({ at, from: b.x, to: b.x + b.w });
}
return { x, y };
}
export const NO_TARGETS = { x: [], y: [] };
// Which of the box's edges a gesture moves: all four for a move, otherwise
// the ones named by the handle ("ne", "w", …). Spelled out because "move"
// itself contains an "e".
function edgesOf(mode) {
if (mode === "move") return { w: true, e: true, n: true, s: true };
return { w: mode.includes("w"), e: mode.includes("e"), n: mode.includes("n"), s: mode.includes("s") };
}
// The lines of `g` that the gesture is moving, per axis. A move carries the
// centres along too; a resize only moves the edge under the pointer.
function movingLines(g, mode) {
if (mode === "move") return { x: thirds(g.x, g.w), y: thirds(g.y, g.h) };
const edges = edgesOf(mode);
const x = [];
const y = [];
if (edges.w) x.push(g.x);
if (edges.e) x.push(g.x + g.w);
if (edges.n) y.push(g.y);
if (edges.s) y.push(g.y + g.h);
return { x, y };
}
// The smallest shift that puts one of the moving lines on a target, or null
// if none is within `threshold`.
function nearest(moving, targets, threshold) {
let best = null;
for (const m of moving) {
for (const t of targets) {
const d = t.at - m;
if (Math.abs(d) <= threshold && (best === null || Math.abs(d) < Math.abs(best))) best = d;
}
}
return best;
}
// One axis of the result. `lo` and `hi` say whether the gesture moves the
// box's start and end edge on this axis; `shift` is the snap from nearest(),
// or null to fall back to the grid.
function resolve(start, size, delta, lo, hi, shift) {
const fit = (n) => (shift === null ? grid(n) : Math.round(n + shift));
if (lo && hi) return [Math.max(0, fit(start + delta)), size];
if (hi) return [start, Math.max(MIN_SIZE, fit(size + delta))];
if (lo) {
const s = Math.max(0, Math.min(fit(start + delta), start + size - MIN_SIZE));
return [s, start + size - s];
}
return [start, size];
}
/**
* The geometry for a drag of (dx, dy) canvas px from `from`, in `mode`
* ("move" or a handle), snapped to `targets` within `threshold` canvas px.
* Pass NO_TARGETS for the grid alone.
*/
export function place(from, mode, dx, dy, targets, threshold) {
const edges = edgesOf(mode);
// Where the pointer alone would put the box, before any snapping.
const raw = { ...from };
if (edges.w) raw.x += dx;
if (edges.e !== edges.w) raw.w += edges.e ? dx : -dx;
if (edges.n) raw.y += dy;
if (edges.s !== edges.n) raw.h += edges.s ? dy : -dy;
const moving = movingLines(raw, mode);
const sx = nearest(moving.x, targets.x, threshold);
const sy = nearest(moving.y, targets.y, threshold);
const [x, w] = resolve(from.x, from.w, dx, edges.w, edges.e, sx);
const [y, h] = resolve(from.y, from.h, dy, edges.n, edges.s, sy);
return { x, y, w, h };
}
// Each target line that one of the moving lines now sits on, spanning both
// the box (from..to) and whatever the line came from. Lines from several
// boxes at the same place merge into one guide.
function matches(moving, targets, from, to) {
const found = new Map();
for (const t of targets) {
// Within a px, since centres of odd sizes fall on half px and the
// geometry is rounded.
if (!moving.some((m) => Math.abs(t.at - m) < 1)) continue;
const [lo, hi] = found.get(t.at) ?? [from, to];
found.set(t.at, [Math.min(lo, t.from), Math.max(hi, t.to)]);
}
return [...found].map(([at, [lo, hi]]) => ({ at, from: lo, to: hi }));
}
/** The guides to draw for box geometry `g` placed by place(). */
export function guidesFor(g, mode, targets) {
const moving = movingLines(g, mode);
return [
...matches(moving.x, targets.x, g.y, g.y + g.h).map((m) => ({ axis: "x", ...m })),
...matches(moving.y, targets.y, g.x, g.x + g.w).map((m) => ({ axis: "y", ...m })),
];
}
+5 -3
View File
@@ -2,7 +2,8 @@
* The box editor panel's size and its code's text size, shared between
* BoxEditor (which draws the panel and its controls) and BoxCanvas (which
* pads itself by the panel's width so the canvas rescales beside it rather
* than under it). They are one admin's preference for their own screen, so
* than under it), and whether dragged boxes snap to each other (BoxCanvas's
* Align button). They are one admin's preference for their own screen, so
* they live in localStorage, not the database.
*/
import { ref, watch } from "vue";
@@ -28,6 +29,7 @@ const valid = (n) => typeof n === "number" && Number.isFinite(n);
// so a width chosen on a wide monitor survives a visit from a narrow one.
export const panelWidth = ref(valid(saved.width) ? Math.max(PANEL_WIDTH.min, saved.width) : PANEL_WIDTH.default);
export const fontSize = ref(valid(saved.fontSize) ? clamp(saved.fontSize, FONT_SIZE.min, FONT_SIZE.max) : FONT_SIZE.default);
export const snapping = ref(saved.snapping !== false);
export function setPanelWidth(width) {
panelWidth.value = Math.round(clamp(width, PANEL_WIDTH.min, window.innerWidth));
@@ -38,9 +40,9 @@ export function zoom(delta) {
fontSize.value = delta === 0 ? FONT_SIZE.default : clamp(fontSize.value + delta, FONT_SIZE.min, FONT_SIZE.max);
}
watch([panelWidth, fontSize], ([width, size]) => {
watch([panelWidth, fontSize, snapping], ([width, size, snap]) => {
try {
localStorage.setItem(KEY, JSON.stringify({ width, fontSize: size }));
localStorage.setItem(KEY, JSON.stringify({ width, fontSize: size, snapping: snap }));
} catch {
/* storage unavailable: the preference just won't outlive the tab */
}
+23 -25
View File
@@ -1,22 +1,32 @@
import { onUnmounted, ref, toValue } from "vue";
import { NO_TARGETS, SNAP_PX, guidesFor, place } from "./alignment";
const SNAP = 5;
const MIN_SIZE = 40;
/** Owns pointer lifecycle and optimistic geometry while a box is manipulated. */
export function useBoxInteraction({ box, scale, emit }) {
/**
* Owns pointer lifecycle and optimistic geometry while a box is manipulated.
*
* `targets` returns what the box can line up with (alignment.snapTargets), or
* null when snapping is off; it is asked once per drag, since nothing else
* moves meanwhile. The guides for each position are emitted as `guides`, and
* an empty list on release. Holding Ctrl/⌘ places the box on the grid alone.
*/
export function useBoxInteraction({ box, scale, targets, emit }) {
const draft = ref(null);
let drag = null;
const snap = (n) => Math.round(n / SNAP) * SNAP;
function start(mode, event) {
if (event.button !== 0) return;
emit("select");
event.preventDefault();
event.target.setPointerCapture(event.pointerId);
const { x, y, w, h } = toValue(box);
drag = { mode, startX: event.clientX, startY: event.clientY, from: { x, y, w, h }, moved: false };
drag = {
mode,
startX: event.clientX,
startY: event.clientY,
from: { x, y, w, h },
targets: targets?.() ?? NO_TARGETS,
moved: false,
};
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", end);
window.addEventListener("pointercancel", end);
@@ -30,24 +40,11 @@ export function useBoxInteraction({ box, scale, emit }) {
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 {
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;
}
}
const free = event.ctrlKey || event.metaKey;
const lines = free ? NO_TARGETS : drag.targets;
const next = place(drag.from, drag.mode, dx, dy, lines, SNAP_PX / factor);
draft.value = next;
emit("guides", guidesFor(next, drag.mode, lines));
}
function end() {
@@ -55,6 +52,7 @@ export function useBoxInteraction({ box, scale, emit }) {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", end);
window.removeEventListener("pointercancel", end);
if (drag.moved) emit("guides", []);
if (drag.moved && draft.value) emit("commit", { ...draft.value });
drag = null;
draft.value = null;