Refactor frontend overlays
Test and deploy / test (push) Successful in 1m39s
Test and deploy / deploy (push) Successful in 26s

This commit is contained in:
2026-10-15 12:40:56 +01:00
parent ca3cd4db30
commit 3da49f4b24
13 changed files with 528 additions and 129 deletions
+65
View File
@@ -0,0 +1,65 @@
<script setup>
import OverlayShell from "./OverlayShell.vue";
const open = defineModel({ type: Boolean, default: false });
defineProps({
title: { type: String, default: "Are you sure?" },
message: { type: String, required: true },
confirmLabel: { type: String, default: "Confirm" },
});
const emit = defineEmits(["confirm", "cancel"]);
function cancel() {
open.value = false;
emit("cancel");
}
function confirm() {
open.value = false;
emit("confirm");
}
</script>
<template>
<OverlayShell v-model="open" :title="title" backdrop close-on-backdrop @close="cancel">
<div class="confirm bdr-1">
<h2>{{ title }}</h2>
<p>{{ message }}</p>
<div class="actions">
<button type="button" class="confirm-button" @click="confirm">{{ confirmLabel }}</button>
<button type="button" class="cancel-button" @click="cancel">Cancel</button>
</div>
</div>
</OverlayShell>
</template>
<style scoped>
.confirm {
box-sizing: border-box;
width: min(420px, calc(100vw - 24px));
padding: 16px;
color: var(--color-secondary);
background: var(--color-surface);
}
.confirm h2 {
margin-top: 0;
}
.actions {
display: flex;
gap: 0.5rem;
justify-content: flex-end;
}
.actions button {
padding: 0.35rem 0.75rem;
color: var(--color-primary);
background: var(--color-link-bg);
border: 1px solid var(--color-primary);
cursor: pointer;
}
.confirm-button {
color: var(--color-tertiary) !important;
border-color: var(--color-tertiary) !important;
}
</style>
+6 -42
View File
@@ -1,62 +1,26 @@
<script setup>
import { watch, onUnmounted } from "vue";
import OverlayShell from "./OverlayShell.vue";
// Popup modal: a dimmed backdrop over the page with the content floated on top.
// Closes on backdrop click or Escape. Used by the home widgets so their create
// forms pop up instead of replacing the widget's contents.
const open = defineModel({ type: Boolean, default: false });
const props = defineProps({
maxWidth: { type: String, default: "420px" },
});
function onKeydown(e) {
if (e.key === "Escape") open.value = false;
}
// The Escape listener is attached only while open, so several modals on one
// page can't all react to a single keypress. `immediate` covers a modal that
// mounts already open.
watch(
open,
(isOpen) => {
if (isOpen) {
window.addEventListener("keydown", onKeydown);
} else {
window.removeEventListener("keydown", onKeydown);
}
},
{ immediate: true },
);
onUnmounted(() => window.removeEventListener("keydown", onKeydown));
</script>
<template>
<!-- Teleported to <body> so the backdrop escapes any ancestor with
overflow/transform/z-index that would otherwise clip or trap it. -->
<Teleport to="body">
<div v-if="open" class="modal-backdrop" @click.self="open = false">
<div class="modal bdr-1" :style="{ maxWidth: props.maxWidth }">
<slot />
</div>
<OverlayShell v-model="open" title="Dialog" backdrop close-on-backdrop>
<div class="modal bdr-1" :style="{ maxWidth: props.maxWidth }">
<slot />
</div>
</Teleport>
</OverlayShell>
</template>
<style scoped>
.modal-backdrop {
position: fixed;
inset: 0;
background-color: rgba(0, 0, 0, 0.65);
display: flex;
align-items: center;
justify-content: center;
z-index: 50;
padding: 12px;
}
.modal {
box-sizing: border-box;
background-color: var(--color-surface);
padding: 16px;
width: 100%;
+132
View File
@@ -0,0 +1,132 @@
<script setup>
import { nextTick, onUnmounted, ref, watch } from "vue";
import { useOverlayStack } from "@/js/useOverlayStack";
const open = defineModel({ type: Boolean, default: false });
const emit = defineEmits(["close"]);
const props = defineProps({
role: { type: String, default: "dialog" },
title: { type: String, default: "" },
panelClass: { type: String, default: "" },
backdrop: { type: Boolean, default: false },
closeOnBackdrop: { type: Boolean, default: false },
});
const panel = ref(null);
let returnFocus = null;
let bodyLocks = 0;
let previousOverflow = "";
let bodyLocked = false;
function lockBody() {
if (!bodyLocks++) previousOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
bodyLocked = true;
}
function unlockBody() {
if (!bodyLocked) return;
bodyLocked = false;
if (--bodyLocks === 0) document.body.style.overflow = previousOverflow;
}
function close() {
open.value = false;
emit("close");
}
useOverlayStack(open, close);
function focusPanel() {
const target = panel.value?.querySelector("input, select, textarea, button, [tabindex]:not([tabindex='-1'])");
(target ?? panel.value)?.focus();
}
function trapFocus(event) {
if (event.key !== "Tab" || !panel.value) return;
const focusable = [...panel.value.querySelectorAll("input, select, textarea, button, [tabindex]:not([tabindex='-1'])")];
if (!focusable.length) {
event.preventDefault();
panel.value.focus();
return;
}
const first = focusable[0];
const last = focusable.at(-1);
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
watch(open, async (isOpen) => {
if (isOpen) {
lockBody();
returnFocus = document.activeElement;
await nextTick();
focusPanel();
} else if (returnFocus?.isConnected) {
unlockBody();
returnFocus.focus();
returnFocus = null;
} else {
unlockBody();
}
}, { immediate: true });
onUnmounted(() => {
unlockBody();
if (returnFocus?.isConnected) returnFocus.focus();
});
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="overlay-shell"
:class="{ 'has-backdrop': props.backdrop }"
@click.self="props.closeOnBackdrop && close()"
>
<section
ref="panel"
class="overlay-panel"
:class="props.panelClass"
:role="props.role"
:aria-modal="props.role === 'dialog' ? 'true' : undefined"
:aria-label="props.title || undefined"
tabindex="-1"
@keydown="trapFocus"
>
<slot />
</section>
</div>
</Teleport>
</template>
<style scoped>
.overlay-shell {
position: fixed;
inset: 0;
z-index: 60;
pointer-events: none;
}
.overlay-shell.has-backdrop {
display: flex;
align-items: center;
justify-content: center;
padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right))
max(12px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
background: rgb(0 0 0 / 65%);
pointer-events: auto;
}
.overlay-panel {
max-width: 100%;
max-height: 100%;
pointer-events: auto;
outline: none;
}
</style>
+42
View File
@@ -0,0 +1,42 @@
import { onUnmounted, watch } from "vue";
const entries = [];
let listening = false;
function onKeydown(event) {
if (event.key !== "Escape") return;
entries.at(-1)?.close();
}
function updateListener() {
if (entries.length && !listening) {
window.addEventListener("keydown", onKeydown);
listening = true;
} else if (!entries.length && listening) {
window.removeEventListener("keydown", onKeydown);
listening = false;
}
}
/** Registers one open overlay so Escape always closes only the topmost one. */
export function useOverlayStack(open, close) {
let entry = null;
function register() {
if (entry) return;
entry = { close };
entries.push(entry);
updateListener();
}
function unregister() {
if (!entry) return;
const index = entries.indexOf(entry);
if (index !== -1) entries.splice(index, 1);
entry = null;
updateListener();
}
watch(open, (isOpen) => (isOpen ? register() : unregister()), { immediate: true });
onUnmounted(unregister);
}
+17 -1
View File
@@ -19,12 +19,15 @@ import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { api } from "@/api";
import Button from "@/components/input/Button.vue";
import SecretReveal from "@/components/admin/SecretReveal.vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
import "./env.css";
const groups = ref([]);
const status = ref(null);
const error = ref("");
const loading = ref(true);
const applyConfirmationOpen = ref(false);
const applyConfirmation = ref({ title: "Apply changes", message: "", confirmLabel: "Apply" });
// Staged edits, none of which exist anywhere but this component until Apply.
// drafts: name -> text in the row's input
@@ -127,7 +130,12 @@ async function apply() {
`This recreates: ${affectedServices.value.join(", ")}. The site's API is unavailable for a few seconds.`,
...warnings,
];
if (!confirm(lines.join("\n"))) return;
applyConfirmation.value = { title: "Apply environment changes", message: lines.join("\n"), confirmLabel: "Apply" };
applyConfirmationOpen.value = true;
}
async function confirmApply() {
applyConfirmationOpen.value = false;
const body = { set: {}, generate: [] };
for (const { change } of changes.value) {
@@ -377,6 +385,14 @@ onUnmounted(stopPolling);
<Button class="px-2 env-apply" @click="apply">Apply</Button>
</div>
</footer>
<ConfirmDialog
v-if="applyConfirmationOpen"
v-model="applyConfirmationOpen"
:title="applyConfirmation.title"
:message="applyConfirmation.message"
:confirm-label="applyConfirmation.confirmLabel"
@confirm="confirmApply"
/>
</div>
</template>
+22 -1
View File
@@ -10,12 +10,23 @@
*/
import { usePagesStore } from "@/stores/pages";
import PageForm from "@/views/canvas/PageForm.vue";
import { ref } from "vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
const pages = usePagesStore();
pages.fetch();
const removeTarget = ref(null);
const confirmationOpen = ref(false);
async function remove(page) {
if (!confirm(`Delete the page “${page.title}” and everything on it?`)) return;
removeTarget.value = page;
confirmationOpen.value = true;
}
async function confirmRemove() {
const page = removeTarget.value;
removeTarget.value = null;
if (!page) return;
try {
await pages.remove(page.id);
} catch (err) {
@@ -61,5 +72,15 @@ async function remove(page) {
<h1>New page</h1>
<PageForm />
</section>
<ConfirmDialog
v-if="removeTarget"
v-model="confirmationOpen"
title="Delete page"
:message="`Delete the page “${removeTarget.title}” and everything on it?`"
confirm-label="Delete"
@confirm="confirmRemove"
@cancel="removeTarget = null"
/>
</div>
</template>
+16 -1
View File
@@ -19,6 +19,7 @@ import { PAGE_FIELDS, usePagesStore } from "@/stores/pages";
import BoxCanvas from "@/views/home3/BoxCanvas.vue";
import NotFound from "@/views/404/404.vue";
import PageForm from "./PageForm.vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
const route = useRoute();
const router = useRouter();
@@ -59,6 +60,7 @@ auth.ensureLoaded();
const settingsOpen = ref(false);
const draft = ref({ title: "", slug: "", adminOnly: false });
const settingsError = ref("");
const deleteConfirmationOpen = ref(false);
function openSettings() {
draft.value = { title: page.value.title, slug: page.value.slug, adminOnly: page.value.adminOnly };
@@ -83,7 +85,11 @@ async function saveSettings() {
}
async function deletePage() {
if (!confirm(`Delete the page “${page.value.title}” and everything on it?`)) return;
deleteConfirmationOpen.value = true;
}
async function confirmDeletePage() {
deleteConfirmationOpen.value = false;
try {
await pages.remove(page.value.id);
router.push("/");
@@ -126,6 +132,15 @@ async function deletePage() {
</section>
<NotFound />
</template>
<ConfirmDialog
v-if="deleteConfirmationOpen"
v-model="deleteConfirmationOpen"
title="Delete page"
:message="`Delete the page “${page.title}” and everything on it?`"
confirm-label="Delete"
@confirm="confirmDeletePage"
/>
</template>
<style scoped>
+21 -2
View File
@@ -6,13 +6,16 @@
* the `loggedIn` watcher covers someone who signs in while the page is open, and
* both check `!loaded && !loading` so the two paths can't fire two requests.
*/
import { computed, onMounted, watch } from "vue";
import { computed, onMounted, ref, watch } from "vue";
import { usePlacesStore } from "@/stores/places";
import { useAuthStore } from "@/stores/auth";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
const places = usePlacesStore();
const auth = useAuthStore();
const loggedIn = computed(() => auth.loggedIn);
const removeTarget = ref(null);
const confirmationOpen = ref(false);
// Two entry points, one fetch: onMounted covers an already-signed-in visitor,
// the watcher covers signing in with the page already open. The
@@ -36,7 +39,14 @@ async function toggleDone(place) {
async function remove(place) {
if (!loggedIn.value) return;
if (!confirm(`Delete "${place.title}"?`)) return;
removeTarget.value = place;
confirmationOpen.value = true;
}
async function confirmRemove() {
const place = removeTarget.value;
removeTarget.value = null;
if (!place) return;
try {
await places.remove(place.id);
} catch (err) {
@@ -98,6 +108,15 @@ async function remove(place) {
</tbody>
</table>
</div>
<ConfirmDialog
v-if="removeTarget"
v-model="confirmationOpen"
title="Delete place"
:message="`Delete ${removeTarget.title}?`"
confirm-label="Delete"
@confirm="confirmRemove"
@cancel="removeTarget = null"
/>
</template>
<style scoped>
+33 -11
View File
@@ -11,11 +11,14 @@
import { computed, onBeforeUnmount, ref, watch } from "vue";
import { FITS, useBackgroundStore } from "@/stores/background";
import { uploadFile, isImage } from "./upload";
import OverlayShell from "@/components/util/OverlayShell.vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
const props = defineProps({
page: { type: String, required: true },
});
const emit = defineEmits(["close"]);
const open = ref(true);
const bg = useBackgroundStore();
const saved = bg.byPage[props.page];
@@ -37,6 +40,7 @@ const swatch = computed(() => (HEX.test(draft.value.color) ? draft.value.color :
const busy = ref(false);
const error = ref("");
const dragOver = ref(false);
const confirmation = ref(false);
async function upload(file) {
if (!file) return;
@@ -60,6 +64,11 @@ function onDrop(event) {
upload(event.dataTransfer?.files?.[0]);
}
function close() {
open.value = false;
emit("close");
}
async function save() {
error.value = "";
busy.value = true;
@@ -76,7 +85,10 @@ async function save() {
}
async function resetToDefault() {
if (!confirm("Go back to the site's default background on this page?")) return;
confirmation.value = true;
}
async function confirmReset() {
error.value = "";
busy.value = true;
try {
@@ -91,14 +103,15 @@ async function resetToDefault() {
</script>
<template>
<form
class="bg-editor bdr-2 bg-surface"
:class="{ 'drag-over': dragOver }"
@submit.prevent="save"
@dragover.prevent="dragOver = true"
@dragleave.self="dragOver = false"
@drop.prevent="onDrop"
>
<OverlayShell v-model="open" title="Page background" @close="close">
<form
class="bg-editor bdr-2 bg-surface"
:class="{ 'drag-over': dragOver }"
@submit.prevent="save"
@dragover.prevent="dragOver = true"
@dragleave.self="dragOver = false"
@drop.prevent="onDrop"
>
<h3>Page background</h3>
<label>
@@ -135,13 +148,22 @@ async function resetToDefault() {
<div class="row">
<button type="submit" class="bar-btn" :disabled="busy">Save</button>
<button type="button" class="bar-btn" @click="emit('close')">Cancel</button>
<button type="button" class="bar-btn" @click="close">Cancel</button>
<button v-if="saved" type="button" class="bar-btn" :disabled="busy" @click="resetToDefault">
Theme default
</button>
</div>
<p v-if="error" class="text-tertiary">{{ error }}</p>
</form>
</form>
</OverlayShell>
<ConfirmDialog
v-if="confirmation"
v-model="confirmation"
title="Reset background"
message="Go back to the site's default background on this page?"
confirm-label="Reset"
@confirm="confirmReset"
/>
</template>
<style scoped>
+49 -5
View File
@@ -32,6 +32,7 @@ import { useAuthStore } from "@/stores/auth";
import { useBoxesStore } from "@/stores/boxes";
import { useBackgroundStore } from "@/stores/background";
import BackgroundEditor from "./BackgroundEditor.vue";
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
import BoxFrame from "./BoxFrame.vue";
import BoxEditor from "./BoxEditor.vue";
import HtmlBox from "./HtmlBox.vue";
@@ -64,6 +65,7 @@ const background = useBackgroundStore();
background.show(props.page);
onBeforeUnmount(() => background.hide(props.page));
const backgroundOpen = ref(false);
const confirmation = ref(null);
const isMobile = useMediaQuery(MOBILE_QUERY);
const isAdmin = computed(() => auth.loggedIn && !!auth.user.admin);
@@ -144,12 +146,30 @@ function onAction(box, action) {
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));
askConfirmation({
title: "Delete box",
message: `Delete “${labelOf(box)}”? This can't be undone from here.`,
confirmLabel: "Delete",
}).then((confirmed) => {
if (!confirmed) return;
if (selectedId.value === box.id) selectedId.value = null;
run(() => store.remove(box.id));
});
}
}
function askConfirmation(request) {
return new Promise((resolve) => {
confirmation.value = { ...request, open: true, resolve };
});
}
function finishConfirmation(confirmed) {
const request = confirmation.value;
confirmation.value = null;
request?.resolve(confirmed);
}
function labelOf(box) {
const name = box.title || (box.kind === "widget" ? box.widget : "HTML");
return box.adminOnly ? `🔒 ${name}` : name;
@@ -208,7 +228,14 @@ function addBox() {
const importing = ref(false);
async function importStarter() {
const count = store.boxes.length;
if (count && !confirm(`This page already has ${count} box${count === 1 ? "" : "es"}. Add the starter layout on top?`)) return;
if (count) {
const confirmed = await askConfirmation({
title: "Import starter layout",
message: `This page already has ${count} box${count === 1 ? "" : "es"}. Add the starter layout on top?`,
confirmLabel: "Import",
});
if (!confirmed) return;
}
importing.value = true;
try {
// Sequential, so the boxes come back in z order without a refetch.
@@ -273,11 +300,18 @@ async function onDrop(event) {
// Leaving a box saves its unsaved HTML; BoxEditor does that itself as the
// selection changes or it unmounts.
function select(box) {
backgroundOpen.value = false;
selectedId.value = box.id;
}
function toggleBackground() {
backgroundOpen.value = !backgroundOpen.value;
if (backgroundOpen.value) selectedId.value = null;
}
function toggleEdit() {
editing.value = !editing.value;
if (!editing.value) selectedId.value = null;
}
</script>
@@ -290,7 +324,7 @@ function toggleEdit() {
<button type="button" class="bar-btn" :class="{ on: editing }" @click="toggleEdit">
{{ editing ? "Done" : "Edit layout" }}
</button>
<button type="button" class="bar-btn" :class="{ on: backgroundOpen }" @click="backgroundOpen = !backgroundOpen">
<button type="button" class="bar-btn" :class="{ on: backgroundOpen }" @click="toggleBackground">
Background
</button>
<template v-if="inEditMode">
@@ -387,6 +421,16 @@ function toggleEdit() {
@close="selectedId = null"
@error="report"
/>
<ConfirmDialog
v-if="confirmation"
v-model="confirmation.open"
:title="confirmation.title"
:message="confirmation.message"
:confirm-label="confirmation.confirmLabel"
@confirm="finishConfirmation(true)"
@cancel="finishConfirmation(false)"
/>
</div>
</template>
+6 -4
View File
@@ -24,6 +24,7 @@ import { useBoxesStore } from "@/stores/boxes";
import { tagFor, uploadFile } from "./upload";
import CodeEditor from "./CodeEditor.vue";
import { WIDGETS } from "./widgetRegistry";
import OverlayShell from "@/components/util/OverlayShell.vue";
const props = defineProps({
box: { type: Object, required: true },
@@ -35,6 +36,7 @@ const store = useBoxesStore(props.box.page);
const codeEditor = ref(null);
const fileInput = ref(null);
const uploading = ref(false);
const open = ref(true);
const draftHtml = ref(props.box.html ?? "");
const saving = ref(false);
@@ -119,13 +121,14 @@ async function upload(event) {
}
function close() {
open.value = false;
emit("close");
}
</script>
<template>
<Teleport to="body">
<aside class="box-editor" @keydown.esc="close">
<OverlayShell v-model="open" title="Box editor" @close="close">
<aside class="box-editor">
<header class="flex items-center justify-between gap-2">
<h3 class="m-0">
{{ box.kind === "widget" ? `Widget · ${box.widget}` : "HTML box" }}
@@ -210,7 +213,7 @@ function close() {
</footer>
</template>
</aside>
</Teleport>
</OverlayShell>
</template>
<style scoped>
@@ -219,7 +222,6 @@ function close() {
top: 0;
right: 0;
bottom: 0;
z-index: 60;
width: min(460px, 100vw);
display: flex;
flex-direction: column;
+54 -62
View File
@@ -16,7 +16,8 @@
* 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";
import { computed, toRef } from "vue";
import { useBoxInteraction } from "./useBoxInteraction";
const props = defineProps({
box: { type: Object, required: true },
@@ -28,13 +29,52 @@ const props = defineProps({
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 { draft, start } = useBoxInteraction({
box: toRef(props, "box"),
scale: toRef(props, "scale"),
emit,
});
const geom = computed(() => draft.value ?? props.box);
function nudge(mode, event) {
if (!props.selected || !["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(event.key)) return;
event.preventDefault();
const step = event.shiftKey ? 10 : 5;
const next = { x: props.box.x, y: props.box.y, w: props.box.w, h: props.box.h };
if (mode === "move") {
if (event.key === "ArrowLeft") next.x -= step;
if (event.key === "ArrowRight") next.x += step;
if (event.key === "ArrowUp") next.y -= step;
if (event.key === "ArrowDown") next.y += step;
} else {
if (mode.includes("w") && event.key === "ArrowLeft") {
next.x -= step;
next.w += step;
}
if (mode.includes("w") && event.key === "ArrowRight") {
next.x += step;
next.w = Math.max(40, next.w - step);
}
if (mode.includes("e") && event.key === "ArrowRight") next.w += step;
if (mode.includes("e") && event.key === "ArrowLeft") next.w = Math.max(40, next.w - step);
if (mode.includes("n") && event.key === "ArrowUp") {
next.y -= step;
next.h += step;
}
if (mode.includes("n") && event.key === "ArrowDown") {
next.y += step;
next.h = Math.max(40, next.h - step);
}
if (mode.includes("s") && event.key === "ArrowDown") next.h += step;
if (mode.includes("s") && event.key === "ArrowUp") next.h = Math.max(40, next.h - step);
}
next.x = Math.max(0, next.x);
next.y = Math.max(0, next.y);
emit("commit", next);
}
const style = computed(() => ({
left: `${geom.value.x}px`,
top: `${geom.value.y}px`,
@@ -46,60 +86,6 @@ const style = computed(() => ({
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>
@@ -112,14 +98,16 @@ function end() {
<div
v-if="editing"
class="overlay"
:tabindex="selected ? 0 : -1"
@pointerdown="start('move', $event)"
@keydown="nudge('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>
<button type="button" title="Bring to front" aria-label="Bring to front" @click="emit('action', 'front')">▲</button>
<button type="button" title="Send to back" aria-label="Send to back" @click="emit('action', 'back')">▼</button>
<button type="button" title="Duplicate" aria-label="Duplicate" @click="emit('action', 'duplicate')">⧉</button>
<button type="button" title="Delete" aria-label="Delete" @click="emit('action', 'delete')">✕</button>
</div>
<template v-if="selected">
<div
@@ -127,7 +115,11 @@ function end() {
:key="h"
class="handle"
:class="`h-${h}`"
:tabindex="selected ? 0 : -1"
role="slider"
:aria-label="`Resize ${h}`"
@pointerdown.stop="start(h, $event)"
@keydown.stop="nudge(h, $event)"
/>
</template>
</div>
+65
View File
@@ -0,0 +1,65 @@
import { onUnmounted, ref, toValue } from "vue";
const SNAP = 5;
const MIN_SIZE = 40;
/** Owns pointer lifecycle and optimistic geometry while a box is manipulated. */
export function useBoxInteraction({ box, scale, 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 };
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", end);
window.addEventListener("pointercancel", end);
}
function move(event) {
if (!drag) return;
const factor = toValue(scale);
const dx = (event.clientX - drag.startX) / factor;
const dy = (event.clientY - drag.startY) / factor;
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;
}
}
draft.value = next;
}
function end() {
if (!drag) return;
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;
}
onUnmounted(end);
return { draft, start };
}