diff --git a/lib/drag.ts b/lib/drag.ts new file mode 100644 index 0000000..80c4c0a --- /dev/null +++ b/lib/drag.ts @@ -0,0 +1,638 @@ +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); +} + +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 }; +} + +function findBestSnapMove( + rawPos: number, + size: number, + targets: SnapTarget[], + threshold: number +): number { + if (threshold <= 0 || targets.length === 0) { + return 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 dist = Math.abs(t.pos - anchor); + if (dist <= threshold && dist < bestDist) { + bestDist = dist; + bestPos = t.pos - off; + } + } + } + + return 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 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>; + + 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.hoverIgnore && target.closest(opt.hoverIgnore)) { + return 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.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 (!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 rawLeft = right - Math.max(opt.minSize, width - dx); + const snappedLeft = findBestSnapEdge(rawLeft, targetsX, opt.snapThreshold, -Infinity, right - opt.minSize); + newLeft = snappedLeft; + newWidth = right - newLeft; + activeEdgeX = snappedLeft; + } + + 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 rawTop = bottom - Math.max(opt.minSize, height - dy); + const snappedTop = findBestSnapEdge(rawTop, targetsY, opt.snapThreshold, -Infinity, bottom - opt.minSize); + newTop = snappedTop; + newHeight = bottom - newTop; + activeEdgeY = snappedTop; + } + + 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; + } + + const action = getAction(box, e.target); + if (!action) { + return; + } + + e.preventDefault(); + + try { + box.setPointerCapture(e.pointerId); + } catch { + } + + const offsetParent = box.offsetParent as HTMLElement | null; + 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(); + }; +} diff --git a/lib/functions.ts b/lib/functions.ts index 12123b9..199fd7c 100644 --- a/lib/functions.ts +++ b/lib/functions.ts @@ -1,4 +1,4 @@ -import type { MovableOptions, BoxRect, MarkRequired, SnapLine } from "./types"; +import type { MarkRequired } from "./types"; export function createElement( tagName: K, @@ -46,508 +46,3 @@ export function mergeOptions>( } return result as MarkRequired>; } - -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); -} - -function collectSnapTargets( - box: HTMLElement, - element: HTMLElement, - dragSelector: string, - toContainer: boolean, - toSiblings: boolean -): { targetsX: number[], targetsY: number[] } { - const setX = new Set(); - const setY = new Set(); - 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(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(); - 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(element: HTMLElement, opts: MovableOptions) { - - 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>; - - 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(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(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(); - }; -} diff --git a/lib/types.d.ts b/lib/types.d.ts index 7b4d1b9..8aad5c5 100644 --- a/lib/types.d.ts +++ b/lib/types.d.ts @@ -19,9 +19,14 @@ export interface RectLike { export type BoxRect = Required>; -export interface SnapLine { - axis: 'x' | 'y'; +export interface SnapTarget { pos: number; + start: number; + end: number; +} + +export type SnapLine = SnapTarget & { + axis: 'x' | 'y'; } export interface MovableOptions { @@ -153,12 +158,12 @@ export interface PopupOptions { resolve?: (this: Popup, result: { result: any, popup: Popup }) => void; } -export interface InputOptions { +export interface InputOptionsBase { tabIndex?: number; default?: string; placeholder?: string; - [key: string]: string; } +export type InputOptions = InputOptionsBase & Record; /** * 复选框选项 diff --git a/lib/ui.js b/lib/ui.js index c244560..8410223 100644 --- a/lib/ui.js +++ b/lib/ui.js @@ -1,6 +1,7 @@ import './ui/css/variables/definition.scss'; import './ui/css/common.scss'; -import { appendResizer, createElement, makeMovable } from "./functions"; +import { appendResizer, makeMovable } from "./drag"; +import { createElement } from "./functions"; import { createIcon, changeIcon, resolveIcon } from "./ui/icon"; import { createCheckbox, createRadiobox, resolveCheckbox } from "./ui/checkbox"; import { setTooltip, resolveTooltip } from "./ui/tooltip"; diff --git a/lib/ui/css/common.scss b/lib/ui/css/common.scss index a205178..9eb1458 100644 --- a/lib/ui/css/common.scss +++ b/lib/ui/css/common.scss @@ -200,23 +200,17 @@ .snap-line { position: absolute; + top: 0; + left: 0; pointer-events: none; z-index: 9999; display: none; &.line-x { - top: 0; - bottom: 0; - left: 0; - width: 1px; border-left: 1px dashed var(--red-color); } &.line-y { - left: 0; - right: 0; - top: 0; - height: 1px; border-top: 1px dashed var(--red-color); } } diff --git a/lib/ui/popup.js b/lib/ui/popup.js index 18bb615..272fa20 100644 --- a/lib/ui/popup.js +++ b/lib/ui/popup.js @@ -2,7 +2,8 @@ import "./css/popup.scss"; import { r as lang } from "../utility/lgres"; import { nullOrEmpty } from "../utility/strings"; import { global } from "../utility"; -import { appendResizer, createElement, makeMovable, mergeOptions } from "../functions"; +import { appendResizer, makeMovable } from "../drag"; +import { createElement, mergeOptions } from "../functions"; import { createIcon, changeIcon } from "./icon"; import { requestAnimationFrame } from "../ui"; @@ -241,7 +242,7 @@ export class Popup { } else { } - let tabIndex = Math.max.apply(null, [...document.querySelectorAll('[tabindex]')].map(e => e.tabIndex ?? 0)); + let tabIndex = Math.max.apply(null, /** @type {HTMLElement[]} */ ([...document.querySelectorAll('[tabindex]')]).map(e => e.tabIndex ?? 0)); if (tabIndex < 0) { tabIndex = 0; } @@ -316,7 +317,7 @@ export class Popup { )) ); if (Array.isArray(option.buttons) && option.buttons.length > 0) { - tabIndex = Math.max.apply(null, [...container.querySelectorAll('[tabindex]')].map(e => e.tabIndex ?? 0)); + tabIndex = Math.max.apply(null, /** @type {HTMLElement[]} */ ([...container.querySelectorAll('[tabindex]')]).map(e => e.tabIndex ?? 0)); container.appendChild( createElement('div', 'ui-popup-footer', ...option.buttons.map((b, i) => { const button = createElement('button', 'ui-popup-button'); @@ -351,7 +352,7 @@ export class Popup { return button; })) ); - const tabs = [...container.querySelectorAll('[tabindex]')].map(e => e.tabIndex ?? 0); + const tabs = /** @type {HTMLElement[]} */ ([...container.querySelectorAll('[tabindex]')]).map(e => e.tabIndex ?? 0); const tabMin = Math.min.apply(null, tabs); const tabMax = Math.max.apply(null, tabs); /** @type {HTMLElement | null} */ @@ -475,7 +476,7 @@ export function resolvePopup(wrapper, callback, removable, zIndex) { if (!wrapper.classList.contains('dialog')) { return null; } - const title = wrapper.querySelector('.dialog-title>.title')?.innerText; + const title = /** @type {HTMLElement | null} */ (wrapper.querySelector('.dialog-title>.title'))?.innerText ?? ''; /** @type {HTMLElement | null} */ const content = wrapper.querySelector('.dialog-title+div'); const buttons = /** @type {HTMLInputElement[]} */ ([...wrapper.querySelectorAll('.dialog-func>input[type="button"]')].reverse()).map(b => ({ @@ -485,12 +486,13 @@ export function resolvePopup(wrapper, callback, removable, zIndex) { // @ts-ignore trigger: b.onclick == null ? undefined : ((/** @type {IPopup} */ popup) => (b.onclick?.call(popup, null), false)) })); + const z = parseInt(global.getComputedStyle(wrapper).zIndex); const popup = new Popup({ title, content: content ?? '', persistent: !removable, resolve: typeof callback === 'function' ? (result => callback(result)) : undefined, - zIndex: wrapper.zIndex ?? zIndex, + zIndex: z == null || isNaN(z) ? zIndex : z, buttons }); popup.show(document.body, true); @@ -546,7 +548,11 @@ export function showAlert(title, message, iconType = 'info', parent = document.b */ export function showInput(title, multiline, message, options, buttons, parent = document.body) { const r = typeof global.GetTextByKey === 'function' ? global.GetTextByKey : lang; - const opts = mergeOptions({}, options); + const opts = mergeOptions({ + tabIndex: undefined, + default: undefined, + placeholder: undefined + }, options); return new Promise(resolve => { const input = multiline ? createElement('textarea', text => { @@ -574,12 +580,13 @@ export function showInput(title, multiline, message, options, buttons, parent = } break; default: + // @ts-ignore input[key] = opts[key]; break; } } if (isNaN(opts.tabIndex)) { - let tabIndex = Math.max.apply(null, [...document.querySelectorAll('[tabindex]')].map(e => e.tabIndex ?? 0)); + let tabIndex = Math.max.apply(null, /** @type {HTMLElement[]} */ ([...document.querySelectorAll('[tabindex]')]).map(e => e.tabIndex ?? 0)); if (tabIndex < 0) { tabIndex = 0; } diff --git a/sample/index.html b/sample/index.html index 94dfba1..8ba024c 100644 --- a/sample/index.html +++ b/sample/index.html @@ -6,12 +6,44 @@ UI Lib - - - - - + + +