import { createElement, mergeOptions } from '../functions'; import type { MovableOptions, BoxRect, SnapTarget, SnapLine } from "../types"; type ResizeDir = 'n' | 's' | 'w' | 'e' | 'nw' | 'se' | 'ne' | 'sw'; type DragAction = ResizeDir | 'move'; const CURSOR_MAP: Record = { 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); } /** z-index 置为最前 */ function bringBoxToFront( box: HTMLElement, element: HTMLElement, parent: HTMLElement | null, dragSelector: string ): number | null { const scope = element === box && parent ? parent : element; const boxes = scope.querySelectorAll(dragSelector); let currZ = 0; let maxOtherZ = -Infinity; let hasOther = false; for (const el of boxes) { if (el !== box && el.offsetParent !== parent) { continue; } const z = parseInt(el.style.zIndex || getComputedStyle(el).zIndex) || 0; if (el === box) { currZ = z; } else { hasOther = true; if (z > maxOtherZ) { maxOtherZ = z; } } } if (!hasOther || currZ > maxOtherZ) { return null; } const nextZ = maxOtherZ + 1; box.style.zIndex = String(nextZ); return nextZ; } /** 获取 offsetParent 内容区域左上角在整个视图中的坐标 */ function getParentOrigin(parent: HTMLElement | null): { x: number; y: number } { if (!parent || parent === document.documentElement) { const rect = document.documentElement.getBoundingClientRect(); return { x: rect.left, y: rect.top }; } const rect = parent.getBoundingClientRect(); return { x: rect.left + parent.clientLeft - parent.scrollLeft, y: rect.top + parent.clientTop - parent.scrollTop }; } /** 采集容器和兄弟元素的吸附目标 */ function collectSnapTargets( box: HTMLElement, element: HTMLElement, parent: HTMLElement | null, dragSelector: string, toContainer: boolean, toSiblings: boolean ): { targetsX: SnapTarget[], targetsY: SnapTarget[] } { const targetsX: SnapTarget[] = []; const targetsY: SnapTarget[] = []; if (toContainer) { const cw = parent ? (parent === document.documentElement ? Math.max(document.documentElement.clientWidth, document.documentElement.scrollWidth) : parent.scrollWidth) : window.innerWidth; const ch = parent ? (parent === document.documentElement ? Math.max(document.documentElement.clientHeight, document.documentElement.scrollHeight) : parent.scrollHeight) : window.innerHeight; targetsX.push( { pos: 0, start: 0, end: ch }, { pos: cw / 2, start: 0, end: ch }, { pos: cw, start: 0, end: ch } ); targetsY.push( { pos: 0, start: 0, end: cw }, { pos: ch / 2, start: 0, end: cw }, { pos: ch, start: 0, end: cw } ); } if (toSiblings) { const scope = element === box && parent ? parent : element; const siblings = scope.querySelectorAll(dragSelector); for (const sibling of siblings) { if (sibling === box || sibling.offsetParent !== parent) { continue; } const sl = sibling.offsetLeft; const st = sibling.offsetTop; const sw = sibling.offsetWidth; const sh = sibling.offsetHeight; const sr = sl + sw; const sb = st + sh; targetsX.push( { pos: sl, start: st, end: sb }, { pos: sl + sw / 2, start: st, end: sb }, { pos: sr, start: st, end: sb } ); targetsY.push( { pos: st, start: sl, end: sr }, { pos: st + sh / 2, start: sl, end: sr }, { pos: sb, start: sl, end: sr } ); } } return { targetsX, targetsY }; } /** 计算移动时单轴最佳吸附位置,确保不小于 minPos */ function findBestSnapMove( rawPos: number, size: number, targets: SnapTarget[], threshold: number, minPos = 0 ): number { if (threshold <= 0 || targets.length === 0) { return Math.max(minPos, rawPos); } 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 p = t.pos - off; if (p < minPos) { continue; } const dist = Math.abs(t.pos - anchor); if (dist <= threshold && dist < bestDist) { bestDist = dist; bestPos = p; } } } return Math.max(minPos, bestPos); } /** 计算缩放时单边最佳吸附位置 */ function findBestSnapEdge( rawEdge: number, targets: SnapTarget[], threshold: number, minBound: number, maxBound: number ): number { if (threshold <= 0 || targets.length === 0) { return rawEdge; } let bestDist = threshold + 1; let bestEdge = rawEdge; for (const t of targets) { if (t.pos < minBound || t.pos > maxBound) { continue; } const dist = Math.abs(t.pos - rawEdge); if (dist <= threshold && dist < bestDist) { bestDist = dist; bestEdge = t.pos; } } return bestEdge; } /** 基于最终位置收集移动时所有命中的局部参考线 */ function collectMoveGuides( snappedPos: number, size: number, crossStart: number, crossEnd: number, targets: SnapTarget[] ): Array<{ pos: number, start: number, end: number }> { const anchors = [snappedPos, snappedPos + size / 2, snappedPos + size]; const merged = new Map(); for (const a of anchors) { for (const t of targets) { if (Math.abs(t.pos - a) < 0.01) { const prev = merged.get(t.pos); if (prev) { prev.start = Math.min(prev.start, t.start); prev.end = Math.max(prev.end, t.end); } else { merged.set(t.pos, { start: Math.min(crossStart, t.start), end: Math.max(crossEnd, t.end) }); } } } } const result: Array<{ pos: number; start: number; end: number }> = []; for (const [pos, range] of merged) { result.push({ pos, start: range.start, end: range.end }); } return result; } /** 基于最终边缘收集缩放时命中的局部参考线 */ function collectEdgeGuides( edgePos: number, crossStart: number, crossEnd: number, targets: SnapTarget[] ): Array<{ pos: number; start: number; end: number }> { const merged = new Map(); for (const t of targets) { if (Math.abs(t.pos - edgePos) < 0.01) { const prev = merged.get(t.pos); if (prev) { prev.start = Math.min(prev.start, t.start); prev.end = Math.max(prev.end, t.end); } else { merged.set(t.pos, { start: Math.min(crossStart, t.start), end: Math.max(crossEnd, t.end) }); } } } const result: Array<{ pos: number; start: number; end: number }> = []; for (const [pos, range] of merged) { result.push({ pos, start: range.start, end: range.end }); } return result; } 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(element: HTMLElement, opts: MovableOptions) { const snapPool: HTMLDivElement[] = []; const DEFAULT_OPTIONS = { minSize: 60, bringToFront: true, snapThreshold: 0, snapToContainer: true, snapToSiblings: true, hoverSelector: '.drag-hover', hoverIgnore: 'svg,use', dragSelector: '.drag-box', resizerSelector: '.resizer', rootDragClass: 'is-interacting' } satisfies Partial>; 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; scrollDirty: boolean; box: HTMLElement; offsetParent: HTMLElement | null; pointerId: number; action: DragAction; x: number; y: number; clientX: number; clientY: number; lastClientX: number; lastClientY: number; originX: number; originY: number; curOriginX: number; curOriginY: number; left: number; top: number; width: number; height: number; curLeft: number; curTop: number; curWidth: number; curHeight: number; targetsX: SnapTarget[]; targetsY: SnapTarget[]; prevCursor: string; } | null = null; function getAction(el: Element, target: Element): DragAction | null { if (opt.resizable) { const resizer = target.closest(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.onSnapped === 'function') { opt.onSnapped.call(opt.context, guides); } else { // default action const maxX = Math.max(element.clientWidth, element.scrollWidth) - 1; const maxY = Math.max(element.clientHeight, element.scrollHeight) - 1; for (let i = 0; i < guides.length; i++) { let line = snapPool[i]; if (!line) { line = createElement('div', 'snap-line'); element.appendChild(line); snapPool.push(line); } const { axis, pos, start, end } = guides[i]; const len = Math.max(0, Math.round(end - start)); if (axis === 'x') { const left = Math.max(0, Math.min(Math.round(pos), maxX)); const top = Math.round(start); line.className = 'snap-line line-x'; line.style.width = '1px'; line.style.height = `${len}px`; line.style.transform = `translate(${left}px, ${top}px)`; } else { const top = Math.max(0, Math.min(Math.round(pos), maxY)); const left = Math.round(start); line.className = 'snap-line line-y'; line.style.width = `${len}px`; line.style.height = '1px'; line.style.transform = `translate(${left}px, ${top}px)`; } line.style.display = 'block'; } for (let i = guides.length; i < snapPool.length; i++) { snapPool[i].style.display = 'none'; } } } } function applyFrame() { rafId = 0; if (!state) { return; } const { box, action, x, y, clientX, clientY, lastClientX, lastClientY, left, top, width, height, targetsX, targetsY } = state; if (!state.scrollDirty && clientX === lastClientX && clientY === lastClientY) { return; } state.lastClientX = clientX; state.lastClientY = clientY; if (state.scrollDirty) { const origin = getParentOrigin(state.offsetParent); state.curOriginX = origin.x; state.curOriginY = origin.y; state.scrollDirty = false; } const dx = (clientX - x) - (state.curOriginX - state.originX); const dy = (clientY - y) - (state.curOriginY - state.originY); const guides: SnapLine[] = []; if (action === 'move') { const newLeft = findBestSnapMove(left + dx, width, targetsX, opt.snapThreshold); const newTop = findBestSnapMove(top + dy, height, targetsY, opt.snapThreshold); if (newLeft !== state.curLeft) { box.style.left = `${newLeft}px`; state.curLeft = newLeft; state.moved = true; } if (newTop !== state.curTop) { box.style.top = `${newTop}px`; state.curTop = newTop; state.moved = true; } if (opt.snapThreshold > 0) { for (const g of collectMoveGuides(newLeft, width, newTop, newTop + height, targetsX)) { guides.push({ axis: 'x', ...g }); } for (const g of collectMoveGuides(newTop, height, newLeft, newLeft + width, targetsY)) { guides.push({ axis: 'y', ...g }); } } emitSnap(guides); return; } let newWidth = width, newHeight = height; let newLeft = left, newTop = top; let activeEdgeX: number | null = null; let activeEdgeY: number | null = null; if (action.includes('e')) { const rawRight = left + Math.max(opt.minSize, width + dx); const snappedRight = findBestSnapEdge(rawRight, targetsX, opt.snapThreshold, left + opt.minSize, Infinity); newWidth = snappedRight - left; activeEdgeX = snappedRight; } if (action.includes('w')) { const right = left + width; const maxLeft = Math.max(0, right - opt.minSize); const rawLeft = right - Math.max(opt.minSize, width - dx); const snappedLeft = findBestSnapEdge(rawLeft, targetsX, opt.snapThreshold, 0, maxLeft); newLeft = Math.min(maxLeft, Math.max(0, snappedLeft)); newWidth = right - newLeft; activeEdgeX = newLeft; } if (action.includes('s')) { const rawBottom = top + Math.max(opt.minSize, height + dy); const snappedBottom = findBestSnapEdge(rawBottom, targetsY, opt.snapThreshold, top + opt.minSize, Infinity); newHeight = snappedBottom - top; activeEdgeY = snappedBottom; } if (action.includes('n')) { const bottom = top + height; const maxTop = Math.max(0, bottom - opt.minSize); const rawTop = bottom - Math.max(opt.minSize, height - dy); const snappedTop = findBestSnapEdge(rawTop, targetsY, opt.snapThreshold, 0, maxTop); newTop = Math.min(maxTop, Math.max(0, snappedTop)); newHeight = bottom - newTop; activeEdgeY = newTop; } 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; } if (opt.snapThreshold > 0) { if (activeEdgeX !== null) { for (const g of collectEdgeGuides(activeEdgeX, newTop, newTop + newHeight, targetsX)) { guides.push({ axis: 'x', ...g }); } } if (activeEdgeY !== null) { for (const g of collectEdgeGuides(activeEdgeY, newLeft, newLeft + newWidth, targetsY)) { guides.push({ axis: 'y', ...g }); } } } 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 onScroll() { if (!state) { return; } state.scrollDirty = true; 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(opt.dragSelector); if (!box || !element.contains(box)) { return; } if (opt.hoverIgnore && e.target.closest(opt.hoverIgnore)) { return; } const offsetParent = box.offsetParent as HTMLElement | null; if (opt.bringToFront) { const z = bringBoxToFront(box, element, offsetParent, opt.dragSelector); if (z != null && typeof opt.onZIndexChanged === 'function') { opt.onZIndexChanged.call(opt.context, z, box); } } const action = getAction(box, e.target); if (!action) { return; } e.preventDefault(); try { box.setPointerCapture(e.pointerId); } catch { } const origin = getParentOrigin(offsetParent); 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, offsetParent, opt.dragSelector, opt.snapToContainer, opt.snapToSiblings) : { targetsX: [], targetsY: [] }; const root = document.documentElement; state = { moved: false, resized: false, hasGuides: false, scrollDirty: false, box, offsetParent, pointerId: e.pointerId, action, x: e.clientX, y: e.clientY, clientX: e.clientX, clientY: e.clientY, lastClientX: e.clientX, lastClientY: e.clientY, originX: origin.x, originY: origin.y, curOriginX: origin.x, curOriginY: origin.y, 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('scroll', onScroll, { signal, capture: true, passive: true }); 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(); }; }