feat: drag
This commit is contained in:
1 parent
05ce7035dd
commit
5c2c682baf
11 files changed
+806
-555
No files matched your search
+638
@@ -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<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 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<HTMLElement>(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<number, { start: number; end: number }>();
|
||||
|
||||
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<number, { start: number; end: number }>();
|
||||
|
||||
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<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;
|
||||
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<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 (!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<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 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();
|
||||
};
|
||||
}
|
||||
+1
-506
@@ -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();
|
||||
};
|
||||
}
|
||||
Vendored
+9
-4
@@ -19,9 +19,14 @@ export interface RectLike {
|
||||
|
||||
export type BoxRect = Required<Omit<RectLike, 'zIndex'>>;
|
||||
|
||||
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<T = void> {
|
||||
@@ -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<string, any>;
|
||||
|
||||
/**
|
||||
* 复选框选项
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+15
-8
@@ -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;
|
||||
}
|
||||
|
||||
+38
-6
@@ -6,12 +6,44 @@
|
||||
<!-- <link rel="icon" type="image/svg+xml" href="/vite.svg" /> -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>UI Lib</title>
|
||||
<link href="dist/ui.min.css" rel="stylesheet" />
|
||||
<script src="amrnb.js"></script>
|
||||
<script type="module" src="main.js"></script>
|
||||
<script src="dist/ui.min.js"></script>
|
||||
<script src="dist/utility.min.js"></script>
|
||||
<!-- <script src="amrnb.js"></script> -->
|
||||
<script type="module" src="main.ts"></script>
|
||||
<link rel="stylesheet" href="../lib/ui/css/common.scss" />
|
||||
<style type="text/css">
|
||||
:root {
|
||||
--red-color: red;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.drag-box {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.box-inner {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid #ccc;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
.drag-hover {
|
||||
background-color: #ccc;
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.wrapper {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
#container>.ui-grid {
|
||||
width: 1000px;
|
||||
height: 400px;
|
||||
@@ -20,7 +52,7 @@
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div style="display: flex; flex-direction: column; align-items: flex-start">
|
||||
<div class="wrapper">
|
||||
<div id="container"></div>
|
||||
<!--<button id="setItem">set item</button>
|
||||
<button id="addItem">add item</button>
|
||||
|
||||
@@ -1,18 +1,97 @@
|
||||
// import './style.scss'
|
||||
// import javascriptLogo from './javascript.svg'
|
||||
// import { get } from './lib/utility'
|
||||
// import { createPicture, createAudio, createVideo, createPdf } from './lib/ui/media'
|
||||
// import './lib/element/style.scss'
|
||||
// import ScheduleItem from './lib/element/schedule'
|
||||
// import { createElement } from './lib/functions';
|
||||
// import Grid from './lib/ui/grid/grid';
|
||||
// import { get } from '../lib/utility'
|
||||
// import { createPicture, createAudio, createVideo, createPdf } from '../lib/ui/media'
|
||||
// import '../lib/element/style.scss'
|
||||
// import ScheduleItem from '../lib/element/schedule'
|
||||
|
||||
import '../lib/global.d.ts';
|
||||
|
||||
import { createElement } from '../lib/functions';
|
||||
import { Grid } from '../lib/ui/grid/grid';
|
||||
import { toDateValue } from '../lib/ui/date';
|
||||
import { showConfirm } from '../lib/ui/popup';
|
||||
import { init } from '../lib/utility';
|
||||
import { appendResizer, makeMovable } from '../lib/drag';
|
||||
|
||||
// document.querySelector('#js-logo').src = javascriptLogo
|
||||
|
||||
window.consts = {
|
||||
path: '/',
|
||||
resver: 20231218
|
||||
}
|
||||
resver: 20231218,
|
||||
prefix: ''
|
||||
};
|
||||
|
||||
const snapPool: HTMLDivElement[] = [];
|
||||
|
||||
window.addEventListener('DOMContentLoaded', () => {
|
||||
const container = document.body.querySelector<HTMLElement>('.wrapper');
|
||||
if (container == null) {
|
||||
return;
|
||||
}
|
||||
container.replaceChildren();
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const p = createElement('div', 'drag-box',
|
||||
createElement('div', 'box-inner',
|
||||
createElement('div', div => {
|
||||
div.className = 'drag-hover';
|
||||
div.innerText = `Window #${i}`;
|
||||
})
|
||||
)
|
||||
);
|
||||
p.style.cssText += `
|
||||
left: ${Math.round(Math.random() * 800)}px;
|
||||
top: ${Math.round(Math.random() * 800)}px;
|
||||
width: ${Math.round(Math.random() * 300) + 200}px;
|
||||
height: ${Math.round(Math.random() * 300) + 200}px;
|
||||
`;
|
||||
appendResizer(p);
|
||||
container.append(p);
|
||||
}
|
||||
|
||||
makeMovable(container, {
|
||||
movable: true,
|
||||
resizable: true,
|
||||
snapThreshold: 5,
|
||||
onSnap(guides) {
|
||||
const maxX = Math.max(container.clientWidth, container.scrollWidth) - 1;
|
||||
const maxY = Math.max(container.clientHeight, container.scrollHeight) - 1;
|
||||
|
||||
for (let i = 0; i < guides.length; i++) {
|
||||
let line = snapPool[i];
|
||||
if (!line) {
|
||||
line = document.createElement('div');
|
||||
container.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';
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// const DateSelector = window['lib-ui'].DateSelector;
|
||||
// const formatDate = window['lib-ui'].formatDate;
|
||||
@@ -26,11 +105,7 @@ window.consts = {
|
||||
// });
|
||||
// });
|
||||
|
||||
const Grid = window['lib-ui'].Grid;
|
||||
const createElement = window['lib-ui'].createElement;
|
||||
const toDateValue = window['lib-ui'].toDateValue;
|
||||
const showConfirm = window['lib-ui'].showConfirm;
|
||||
|
||||
/*/
|
||||
window.addEventListener('load', () => {
|
||||
const grid = new Grid('#container');
|
||||
grid.columns = [
|
||||
@@ -235,7 +310,7 @@ window.addEventListener('load', () => {
|
||||
// }, 1000);
|
||||
|
||||
window.grid = grid;
|
||||
});
|
||||
});//*/
|
||||
|
||||
/*
|
||||
window.addEventListener('load', () => {
|
||||
@@ -1 +0,0 @@
|
||||
@keyframes loading-spinner{0%{transform:rotate(0deg)}100%{transform:rotate(359deg)}}:root{--color: #201f1e;--secondary-color: #777;--bg-color: #fff;--border-color: #b9b9b9;--focus-border-color: #666;--shadow-color: rgba(0 0 0 /11%);--disabled-color: #aaa;--disabled-bg-color: #e9e9e9;--disabled-border-color: #d9d9d9;--red-color: red;--title-color: #fff;--title-bg-color: rgb(68, 114, 196);--hover-bg-color: #eee;--link-color: #1890ff;--secondary-link-color: #1d9ac0;--primary-color: rgb(123, 28, 33);--loading-bg-color: hsla(0, 0%, 100%, .4);--loading-fore-color: rgba(0, 0, 0, .2);--border-radius: 2px;--text-indent: 4px;--line-height: 24px;--font-size: .8125rem;--font-smaller-size: .75rem;--font-larger-size: .875rem;--font-family: "Franklin Gothic Book", "San Francisco", "Segoe UI", "Open Sans", "Helvetica Neue", Arial, "PingFang SC", "Microsoft YaHei UI", sans-serif}.ui-text,.ui-input[type]{font-size:var(--font-size);font-family:var(--font-family);border:1px solid var(--border-color);border-radius:var(--border-radius);transition:border-color .12s ease}.ui-text:focus,.ui-text:focus-visible,.ui-input[type]:focus,.ui-input[type]:focus-visible{outline:none}.ui-text:focus,.ui-text:hover,.ui-input[type]:focus,.ui-input[type]:hover{border-color:var(--focus-border-color)}.ui-text:disabled,.ui-input[type]:disabled{border-color:var(--disabled-border-color);color:var(--disabled-color);background-color:var(--disabled-bg-color)}.ui-input{text-indent:var(--text-indent);line-height:var(--line-height)}.ui-check-image-wrapper>input[type=checkbox]{display:none}.ui-check-image-wrapper>input[type=checkbox]:checked~.checked{display:inline}.ui-check-image-wrapper>input[type=checkbox]:checked~.unchecked{display:none}.ui-check-image-wrapper>.checked{display:none}.ui-check-image-wrapper>.unchecked{display:inline}.ui-check-wrapper{display:inline-flex;align-items:center;padding:0 8px;height:36px}.ui-check-wrapper .ui-check-inner{position:relative;display:inline-block;padding:0;width:14px;height:14px;background-color:#fff;-webkit-user-select:none;-moz-user-select:none;user-select:none;cursor:pointer;border:1px solid var(--border-color);border-radius:var(--border-radius);transition:border-color .12s ease}.ui-check-wrapper .ui-check-inner:focus,.ui-check-wrapper .ui-check-inner:focus-visible{outline:none}.ui-check-wrapper .ui-check-inner:focus,.ui-check-wrapper .ui-check-inner:hover{border-color:var(--focus-border-color)}.ui-check-wrapper .ui-check-inner:disabled{border-color:var(--disabled-border-color);color:var(--disabled-color);background-color:var(--disabled-bg-color)}.ui-check-wrapper .ui-check-inner>svg{position:absolute;top:0;left:0;width:100%;height:100%;fill:#fff;transform:scale(0);opacity:0;transition:all .08s cubic-bezier(0.78, 0.14, 0.15, 0.86)}.ui-check-wrapper.ui-radio-wrapper .ui-check-inner{box-sizing:border-box;border-radius:8px;width:16px;height:16px}.ui-check-wrapper>input[type=checkbox],.ui-check-wrapper>input[type=radio]{display:none}.ui-check-wrapper>input[type=checkbox]:checked+.ui-check-inner,.ui-check-wrapper>input[type=radio]:checked+.ui-check-inner{border-color:var(--link-color);background-color:var(--link-color)}.ui-check-wrapper>input[type=checkbox]:checked+.ui-check-inner>svg,.ui-check-wrapper>input[type=radio]:checked+.ui-check-inner>svg{transform:scale(1);opacity:1}.ui-check-wrapper>input[type=checkbox]:disabled:checked+.ui-check-inner,.ui-check-wrapper>input[type=radio]:disabled:checked+.ui-check-inner{border-color:var(--disabled-border-color);background-color:var(--disabled-border-color)}.ui-check-wrapper>input[type=checkbox]:disabled+.ui-check-inner,.ui-check-wrapper>input[type=radio]:disabled+.ui-check-inner{border-color:var(--disabled-border-color);background-color:var(--disabled-bg-color);cursor:default}.ui-check-wrapper>input[type=checkbox]:disabled~span,.ui-check-wrapper>input[type=radio]:disabled~span{color:var(--disabled-border-color);cursor:default}.ui-check-wrapper .ui-check-inner{flex:0 0 auto}.ui-check-wrapper .ui-check-inner+*{flex:1 1 auto;font-weight:400;font-size:var(--font-size);padding-left:8px;padding-right:6px;align-self:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;cursor:pointer;color:var(--color)}.ui-drop-wrapper{display:inline-block;border:none;border-radius:unset;-webkit-user-select:none;-moz-user-select:none;user-select:none;position:relative;font-size:var(--font-size);font-family:var(--font-family)}.ui-drop-wrapper>.ui-drop-header{background-color:var(--bg-color);display:flex;height:26px;border:1px solid var(--border-color);border-radius:var(--border-radius);transition:border-color .12s ease}.ui-drop-wrapper>.ui-drop-header:focus,.ui-drop-wrapper>.ui-drop-header:focus-visible{outline:none}.ui-drop-wrapper>.ui-drop-header:focus,.ui-drop-wrapper>.ui-drop-header:hover{border-color:var(--focus-border-color)}.ui-drop-wrapper>.ui-drop-header:disabled{border-color:var(--disabled-border-color);color:var(--disabled-color);background-color:var(--disabled-bg-color)}.ui-dLine truncated
|
||||
+7
-7
@@ -1,10 +1,10 @@
|
||||
@import './lib/ui/css/variables/definition.scss';
|
||||
@import './lib/ui/css/common.scss';
|
||||
@import './lib/ui/css/checkbox.scss';
|
||||
@import './lib/ui/css/dropdown.scss';
|
||||
@import './lib/ui/css/grid.scss';
|
||||
@import './lib/ui/css/popup.scss';
|
||||
@import './lib/ui/css/tooltip.scss';
|
||||
@import '../lib/ui/css/variables/definition.scss';
|
||||
@import '../lib/ui/css/common.scss';
|
||||
@import '../lib/ui/css/checkbox.scss';
|
||||
@import '../lib/ui/css/dropdown.scss';
|
||||
@import '../lib/ui/css/grid.scss';
|
||||
@import '../lib/ui/css/popup.scss';
|
||||
@import '../lib/ui/css/tooltip.scss';
|
||||
|
||||
:root {
|
||||
font-family: var(--serif-font-family);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
root: 'sample'
|
||||
})
|
||||
Reference in new issue
Block a user