diff --git a/vue/README.md b/vue/README.md
index 7c8f709..2200641 100644
--- a/vue/README.md
+++ b/vue/README.md
@@ -302,7 +302,13 @@ renders any page's boxes.
`/fonts/` without CORS headers.
- **Editing.** Admins get an "Edit layout" toggle at desktop width. Geometry
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. Dragging snaps a box's edges and centre to other boxes'
+ edges and centres and to the canvas's sides, centre and top, within 6 screen
+ px, and draws a pink guide along each line it then shares; a resize snaps
+ the dragged edge the same way. Elsewhere the 5px grid applies. The pure
+ geometry is `alignment.js`; the admin bar's "Align" button turns it off (kept
+ per browser by `editorPrefs.js`), and holding Ctrl/⌘ mid-drag skips it.
+ `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, or
automatically on leaving the box (selecting another, clicking empty canvas,
Done, ✕).
diff --git a/vue/src/views/home3/BoxCanvas.vue b/vue/src/views/home3/BoxCanvas.vue
index 59f1ef8..47d1d74 100644
--- a/vue/src/views/home3/BoxCanvas.vue
+++ b/vue/src/views/home3/BoxCanvas.vue
@@ -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 }}
+
{{ 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"
/>
+
@@ -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);
}
diff --git a/vue/src/views/home3/BoxFrame.vue b/vue/src/views/home3/BoxFrame.vue
index 95d1427..b3c2729 100644
--- a/vue/src/views/home3/BoxFrame.vue
+++ b/vue/src/views/home3/BoxFrame.vue
@@ -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);
diff --git a/vue/src/views/home3/alignment.js b/vue/src/views/home3/alignment.js
new file mode 100644
index 0000000..6be98fc
--- /dev/null
+++ b/vue/src/views/home3/alignment.js
@@ -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 })),
+ ];
+}
diff --git a/vue/src/views/home3/editorPrefs.js b/vue/src/views/home3/editorPrefs.js
index 04f9e16..b85c472 100644
--- a/vue/src/views/home3/editorPrefs.js
+++ b/vue/src/views/home3/editorPrefs.js
@@ -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 */
}
diff --git a/vue/src/views/home3/useBoxInteraction.js b/vue/src/views/home3/useBoxInteraction.js
index 3479dbc..79af611 100644
--- a/vue/src/views/home3/useBoxInteraction.js
+++ b/vue/src/views/home3/useBoxInteraction.js
@@ -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;