feat: drag

This commit is contained in:
tsanie committed 2026-11-24 08:27:04 +08:00
1 parent 05ce7035dd
commit 5c2c682baf
11 files changed
+806 -555

No files matched your search

+1 -506
View File
@@ -1,4 +1,4 @@
import type { MovableOptions, BoxRect, MarkRequired, SnapLine } from "./types";
import type { MarkRequired } from "./types";
export function createElement<K extends keyof HTMLElementTagNameMap>(
tagName: K,
@@ -46,508 +46,3 @@ export function mergeOptions<T extends object, D extends Partial<T>>(
}
return result as MarkRequired<T, Extract<keyof D, keyof T>>;
}
type ResizeDir = 'n' | 's' | 'w' | 'e' | 'nw' | 'se' | 'ne' | 'sw';
type DragAction = ResizeDir | 'move';
const CURSOR_MAP: Record<DragAction, string> = {
n: 'ns-resize', s: 'ns-resize',
w: 'ew-resize', e: 'ew-resize',
nw: 'nwse-resize', se: 'nwse-resize',
ne: 'nesw-resize', sw: 'nesw-resize',
move: 'move'
};
function isResizeDir(dir: string | undefined): dir is ResizeDir {
return typeof dir === 'string' && dir !== 'move' &&
Object.prototype.hasOwnProperty.call(CURSOR_MAP, dir);
}
function collectSnapTargets(
box: HTMLElement,
element: HTMLElement,
dragSelector: string,
toContainer: boolean,
toSiblings: boolean
): { targetsX: number[], targetsY: number[] } {
const setX = new Set<number>();
const setY = new Set<number>();
const parent = box.offsetParent as HTMLElement | null;
if (toContainer) {
const isRoot = !parent || parent === document.body || parent === document.documentElement;
const cw = isRoot ? document.documentElement.clientWidth : parent.clientWidth;
const ch = isRoot ? document.documentElement.clientHeight : parent.clientHeight;
setX.add(0).add(cw / 2).add(cw);
setY.add(0).add(ch / 2).add(ch);
}
if (toSiblings) {
const scope = element === box && parent ? parent : element;
const siblings = scope.querySelectorAll<HTMLElement>(dragSelector);
for (const sb of siblings) {
if (sb === box || sb.offsetParent !== parent) {
continue;
}
const sl = sb.offsetLeft;
const st = sb.offsetTop;
const sw = sb.offsetWidth;
const sh = sb.offsetHeight;
setX.add(sl).add(sl + sw / 2).add(sl + sw);
setY.add(st).add(st + sh / 2).add(st + sh);
}
}
return {
targetsX: Array.from(setX),
targetsY: Array.from(setY)
};
}
function snapAxisMove(
rawPos: number,
size: number,
targets: number[],
threshold: number
): { pos: number; guides: number[] } {
if (threshold <= 0 || targets.length === 0) {
return { pos: rawPos, guides: [] };
}
const offsets = [0, size / 2, size];
let bestDist = threshold + 1;
let bestPos = rawPos;
for (const off of offsets) {
const anchor = rawPos + off;
for (const t of targets) {
const dist = Math.abs(t - anchor);
if (dist <= threshold && dist < bestDist) {
bestDist = dist;
bestPos = t - off;
}
}
}
const guides = new Set<number>();
for (const off of offsets) {
const finalAnchor = bestPos + off;
for (const t of targets) {
if (Math.abs(t - finalAnchor) < 0.01) {
guides.add(t);
}
}
}
return { pos: bestPos, guides: Array.from(guides) };
}
function snapEdge(
rawEdge: number,
targets: number[],
threshold: number,
minBound: number,
maxBound: number
): { edge: number; guide: number | null } {
if (threshold <= 0 || targets.length === 0) {
return { edge: rawEdge, guide: null };
}
let bestDist = threshold + 1;
let bestEdge = rawEdge;
let bestGuide: number | null = null;
for (const target of targets) {
if (target < minBound || target > maxBound) {
continue;
}
const dist = Math.abs(target - rawEdge);
if (dist <= threshold && dist < bestDist) {
bestDist = dist;
bestEdge = target;
bestGuide = target;
}
}
return { edge: bestEdge, guide: bestGuide };
}
export function appendResizer(parent: ParentNode) {
parent.append(
createElement('layer', layer => {
layer.className = 'resizer';
layer.dataset.dir = 'e';
}),
createElement('layer', layer => {
layer.className = 'resizer';
layer.dataset.dir = 's';
}),
createElement('layer', layer => {
layer.className = 'resizer';
layer.dataset.dir = 'w';
}),
createElement('layer', layer => {
layer.className = 'resizer';
layer.dataset.dir = 'n';
}),
createElement('layer', layer => {
layer.className = 'resizer';
layer.dataset.dir = 'se';
}),
createElement('layer', layer => {
layer.className = 'resizer';
layer.dataset.dir = 'sw';
}),
createElement('layer', layer => {
layer.className = 'resizer';
layer.dataset.dir = 'nw';
}),
createElement('layer', layer => {
layer.className = 'resizer';
layer.dataset.dir = 'ne';
})
);
}
export function makeMovable<T = void>(element: HTMLElement, opts: MovableOptions<T>) {
const DEFAULT_OPTIONS = {
minSize: 60,
snapThreshold: 0,
snapToContainer: true,
snapToSiblings: true,
hoverSelector: '.drag-hover',
hoverIgnore: 'button,input,textarea,select,a,[contenteditable],svg,use',
dragSelector: '.drag-box',
resizerSelector: '.resizer',
rootDragClass: 'is-interacting'
} satisfies Partial<MovableOptions<T>>;
const opt = mergeOptions(DEFAULT_OPTIONS, opts);
const controller = new AbortController();
let dragController: AbortController | null = null;
let rafId = 0;
let state: {
moved: boolean;
resized: boolean;
hasGuides: boolean;
box: HTMLElement;
pointerId: number;
action: DragAction;
x: number;
y: number;
clientX: number;
clientY: number;
lastClientX: number;
lastClientY: number;
left: number;
top: number;
width: number;
height: number;
curLeft: number;
curTop: number;
curWidth: number;
curHeight: number;
targetsX: number[];
targetsY: number[];
prevCursor: string;
} | null = null;
function getAction(el: Element, target: Element): DragAction | null {
if (opt.hoverIgnore && target.closest(opt.hoverIgnore)) {
return null;
}
if (opt.resizable) {
const resizer = target.closest<HTMLElement>(opt.resizerSelector);
if (resizer && resizer.closest(opt.dragSelector) === el) {
const dir = resizer.dataset.dir;
if (isResizeDir(dir)) {
return dir;
}
}
}
if (opt.movable) {
const hover = target.closest(opt.hoverSelector);
if (hover && hover.closest(opt.dragSelector) === el) {
return 'move';
}
}
return null;
}
function emitSnap(guides: SnapLine[]) {
if (!state) {
return;
}
if (guides.length > 0 || state.hasGuides) {
state.hasGuides = guides.length > 0;
if (typeof opt.onSnap === 'function') {
opt.onSnap.call(opt.context, guides);
}
}
}
function applyFrame() {
rafId = 0;
if (!state) {
return;
}
const {
box, action, x, y, clientX, clientY,
lastClientX, lastClientY,
left, top, width, height,
targetsX, targetsY
} = state;
if (clientX === lastClientX && clientY === lastClientY) {
return;
}
state.lastClientX = clientX;
state.lastClientY = clientY;
const dx = clientX - x;
const dy = clientY - y;
const guides: SnapLine[] = [];
if (action === 'move') {
const snapX = snapAxisMove(left + dx, width, targetsX, opt.snapThreshold);
const snapY = snapAxisMove(top + dy, height, targetsY, opt.snapThreshold);
if (snapX.pos !== state.curLeft) {
box.style.left = `${snapX.pos}px`;
state.curLeft = snapX.pos;
state.moved = true;
}
if (snapY.pos !== state.curTop) {
box.style.top = `${snapY.pos}px`;
state.curTop = snapY.pos;
state.moved = true;
}
for (const pos of snapX.guides) {
guides.push({ axis: 'x', pos });
}
for (const pos of snapY.guides) {
guides.push({ axis: 'y', pos });
}
emitSnap(guides);
return;
}
let newWidth = width, newHeight = height,
newLeft = left, newTop = top;
if (action.includes('e')) {
const rawRight = left + Math.max(opt.minSize, width + dx);
const snap = snapEdge(rawRight, targetsX, opt.snapThreshold, left + opt.minSize, Infinity);
newWidth = snap.edge - left;
if (snap.guide != null) {
guides.push({ axis: 'x', pos: snap.guide });
}
}
if (action.includes('w')) {
const right = left + width;
const rawLeft = right - Math.max(opt.minSize, width - dx);
const snap = snapEdge(rawLeft, targetsX, opt.snapThreshold, -Infinity, right - opt.minSize);
newLeft = snap.edge;
newWidth = right - newLeft;
if (snap.guide != null) {
guides.push({ axis: 'x', pos: snap.guide });
}
}
if (action.includes('s')) {
const rawBottom = top + Math.max(opt.minSize, height + dy);
const snap = snapEdge(rawBottom, targetsY, opt.snapThreshold, top + opt.minSize, Infinity);
newHeight = snap.edge - top;
if (snap.guide != null) {
guides.push({ axis: 'y', pos: snap.guide });
}
}
if (action.includes('n')) {
const bottom = top + height;
const rawTop = bottom - Math.max(opt.minSize, height - dy);
const snap = snapEdge(rawTop, targetsY, opt.snapThreshold, -Infinity, bottom - opt.minSize);
newTop = snap.edge;
newHeight = bottom - newTop;
if (snap.guide != null) {
guides.push({ axis: 'y', pos: snap.guide });
}
}
if (newWidth !== state.curWidth) {
box.style.width = `${newWidth}px`;
state.curWidth = newWidth;
state.resized = true;
}
if (newHeight !== state.curHeight) {
box.style.height = `${newHeight}px`;
state.curHeight = newHeight;
state.resized = true;
}
if (newLeft !== state.curLeft) {
box.style.left = `${newLeft}px`;
state.curLeft = newLeft;
state.resized = true;
}
if (newTop !== state.curTop) {
box.style.top = `${newTop}px`;
state.curTop = newTop;
state.resized = true;
}
emitSnap(guides);
}
function onPointerMove(e: PointerEvent) {
if (!state || e.pointerId !== state.pointerId) {
return;
}
state.clientX = e.clientX;
state.clientY = e.clientY;
if (!rafId) {
rafId = requestAnimationFrame(applyFrame);
}
}
function finishDrag(e?: PointerEvent) {
if (!state || (e && e.pointerId !== state.pointerId)) {
return;
}
if (rafId) {
cancelAnimationFrame(rafId);
rafId = 0;
if (e) {
applyFrame();
}
}
dragController?.abort();
dragController = null;
emitSnap([]);
const {
box, pointerId, moved, resized,
curLeft, curTop, curWidth, curHeight,
prevCursor
} = state;
state = null;
if (box.hasPointerCapture(pointerId)) {
box.releasePointerCapture(pointerId);
}
const root = document.documentElement;
root.classList.remove(opt.rootDragClass);
root.style.cursor = prevCursor;
if (e && (moved || resized)) {
const rect: BoxRect = {
top: curTop,
left: curLeft,
width: curWidth,
height: curHeight
};
if (moved && typeof opt.onMoved === 'function') {
opt.onMoved.call(opt.context, rect);
}
if (resized && typeof opt.onResized === 'function') {
opt.onResized.call(opt.context, rect);
}
}
}
element.addEventListener('pointerdown', e => {
if (state) {
return;
}
if (e.pointerType === 'mouse' && e.button !== 0) {
return;
}
if (!(e.target instanceof Element)) {
return;
}
const box = e.target.closest<HTMLElement>(opt.dragSelector);
if (!box || !element.contains(box)) {
return;
}
const action = getAction(box, e.target);
if (!action) {
return;
}
e.preventDefault();
try {
box.setPointerCapture(e.pointerId);
} catch {
}
const left = box.offsetLeft;
const top = box.offsetTop;
const width = box.offsetWidth;
const height = box.offsetHeight;
const { targetsX, targetsY } = opt.snapThreshold > 0 ?
collectSnapTargets(box, element, opt.dragSelector, opt.snapToContainer, opt.snapToSiblings) :
{ targetsX: [], targetsY: [] };
const root = document.documentElement;
state = {
moved: false,
resized: false,
hasGuides: false,
box,
pointerId: e.pointerId,
action,
x: e.clientX,
y: e.clientY,
clientX: e.clientX,
clientY: e.clientY,
lastClientX: e.clientX,
lastClientY: e.clientY,
left,
top,
width,
height,
curLeft: left,
curTop: top,
curWidth: width,
curHeight: height,
targetsX,
targetsY,
prevCursor: root.style.cursor
};
root.classList.add(opt.rootDragClass);
root.style.cursor = CURSOR_MAP[action];
dragController = new AbortController();
const { signal } = dragController;
document.addEventListener('pointermove', onPointerMove, { signal });
document.addEventListener('pointerup', finishDrag, { signal });
document.addEventListener('pointercancel', finishDrag, { signal });
box.addEventListener('lostpointercapture', finishDrag, { signal });
if (typeof opt.onResizeStart === 'function') {
opt.onResizeStart.call(opt.context);
}
}, { signal: controller.signal });
return () => {
finishDrag();
controller.abort();
};
}