movable.ts, and fix popup issue.

This commit is contained in:
lchen committed 2026-11-24 10:57:36 +08:00
1 parent 5c2c682baf
commit 9028805363
7 files changed
+163 -36

No files matched your search

+10 -2
View File
@@ -33,6 +33,7 @@ export interface MovableOptions<T = void> {
movable: boolean; movable: boolean;
resizable: boolean; resizable: boolean;
minSize?: number; minSize?: number;
bringToFront?: boolean;
snapThreshold?: number; snapThreshold?: number;
snapToContainer?: boolean; snapToContainer?: boolean;
snapToSiblings?: boolean; snapToSiblings?: boolean;
@@ -45,7 +46,8 @@ export interface MovableOptions<T = void> {
onMoved?(this: T | undefined, rect: BoxRect): void; onMoved?(this: T | undefined, rect: BoxRect): void;
onResizeStart?(this: T | undefined): void; onResizeStart?(this: T | undefined): void;
onResized?(this: T | undefined, rect: BoxRect): void; onResized?(this: T | undefined, rect: BoxRect): void;
onSnap?(this: T | undefined, guides: SnapLine[]): void; onSnapped?(this: T | undefined, guides: SnapLine[]): void;
onZIndexChanged?(this: T | undefined, zIndex: number, box: HTMLElement): void;
} }
export type MarkRequired<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>; export type MarkRequired<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
@@ -90,7 +92,13 @@ export interface PopupButton {
key?: string; key?: string;
text: string; text: string;
isPrimary?: boolean; isPrimary?: boolean;
trigger?: (popup: Popup, button?: PopupButton) => boolean | Promise<boolean> | string | number; /**
* 按钮触发函数
* @param popup 操作的弹出框实例
* @param button 触发的按钮
* @returns 返回 false 则阻止窗口关闭
*/
trigger?: (this: PopupButton, popup: Popup) => boolean | string | number | Promise<boolean | string | number> | undefined;
} }
export interface PopupOptions { export interface PopupOptions {
+1 -1
View File
@@ -1,6 +1,6 @@
import './ui/css/variables/definition.scss'; import './ui/css/variables/definition.scss';
import './ui/css/common.scss'; import './ui/css/common.scss';
import { appendResizer, makeMovable } from "./drag"; import { appendResizer, makeMovable } from "./ui/movable";
import { createElement } from "./functions"; import { createElement } from "./functions";
import { createIcon, changeIcon, resolveIcon } from "./ui/icon"; import { createIcon, changeIcon, resolveIcon } from "./ui/icon";
import { createCheckbox, createRadiobox, resolveCheckbox } from "./ui/checkbox"; import { createCheckbox, createRadiobox, resolveCheckbox } from "./ui/checkbox";
+1 -1
View File
@@ -127,7 +127,7 @@
} }
.drag-box { .drag-box {
position: relative; position: absolute;
.drag-hover { .drag-hover {
cursor: move; cursor: move;
+117 -20
View File
@@ -1,5 +1,5 @@
import { createElement, mergeOptions } from './functions'; import { createElement, mergeOptions } from '../functions';
import type { MovableOptions, BoxRect, SnapTarget, SnapLine } from "./types"; import type { MovableOptions, BoxRect, SnapTarget, SnapLine } from "../types";
type ResizeDir = 'n' | 's' | 'w' | 'e' | 'nw' | 'se' | 'ne' | 'sw'; type ResizeDir = 'n' | 's' | 'w' | 'e' | 'nw' | 'se' | 'ne' | 'sw';
type DragAction = ResizeDir | 'move'; type DragAction = ResizeDir | 'move';
@@ -17,6 +17,45 @@ function isResizeDir(dir: string | undefined): dir is ResizeDir {
Object.prototype.hasOwnProperty.call(CURSOR_MAP, dir); 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<HTMLElement>(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 } { function getParentOrigin(parent: HTMLElement | null): { x: number; y: number } {
if (!parent || parent === document.documentElement) { if (!parent || parent === document.documentElement) {
const rect = document.documentElement.getBoundingClientRect(); const rect = document.documentElement.getBoundingClientRect();
@@ -29,6 +68,7 @@ function getParentOrigin(parent: HTMLElement | null): { x: number; y: number } {
}; };
} }
/** 采集容器和兄弟元素的吸附目标 */
function collectSnapTargets( function collectSnapTargets(
box: HTMLElement, box: HTMLElement,
element: HTMLElement, element: HTMLElement,
@@ -94,14 +134,16 @@ function collectSnapTargets(
return { targetsX, targetsY }; return { targetsX, targetsY };
} }
/** 计算移动时单轴最佳吸附位置,确保不小于 minPos */
function findBestSnapMove( function findBestSnapMove(
rawPos: number, rawPos: number,
size: number, size: number,
targets: SnapTarget[], targets: SnapTarget[],
threshold: number threshold: number,
minPos = 0
): number { ): number {
if (threshold <= 0 || targets.length === 0) { if (threshold <= 0 || targets.length === 0) {
return rawPos; return Math.max(minPos, rawPos);
} }
const offsets = [0, size / 2, size]; const offsets = [0, size / 2, size];
@@ -111,17 +153,22 @@ function findBestSnapMove(
for (const off of offsets) { for (const off of offsets) {
const anchor = rawPos + off; const anchor = rawPos + off;
for (const t of targets) { for (const t of targets) {
const p = t.pos - off;
if (p < minPos) {
continue;
}
const dist = Math.abs(t.pos - anchor); const dist = Math.abs(t.pos - anchor);
if (dist <= threshold && dist < bestDist) { if (dist <= threshold && dist < bestDist) {
bestDist = dist; bestDist = dist;
bestPos = t.pos - off; bestPos = p;
} }
} }
} }
return bestPos; return Math.max(minPos, bestPos);
} }
/** 计算缩放时单边最佳吸附位置 */
function findBestSnapEdge( function findBestSnapEdge(
rawEdge: number, rawEdge: number,
targets: SnapTarget[], targets: SnapTarget[],
@@ -150,6 +197,7 @@ function findBestSnapEdge(
return bestEdge; return bestEdge;
} }
/** 基于最终位置收集移动时所有命中的局部参考线 */
function collectMoveGuides( function collectMoveGuides(
snappedPos: number, snappedPos: number,
size: number, size: number,
@@ -184,6 +232,7 @@ function collectMoveGuides(
return result; return result;
} }
/** 基于最终边缘收集缩放时命中的局部参考线 */
function collectEdgeGuides( function collectEdgeGuides(
edgePos: number, edgePos: number,
crossStart: number, crossStart: number,
@@ -252,14 +301,16 @@ export function appendResizer(parent: ParentNode) {
} }
export function makeMovable<T = void>(element: HTMLElement, opts: MovableOptions<T>) { export function makeMovable<T = void>(element: HTMLElement, opts: MovableOptions<T>) {
const snapPool: HTMLDivElement[] = [];
const DEFAULT_OPTIONS = { const DEFAULT_OPTIONS = {
minSize: 60, minSize: 60,
bringToFront: true,
snapThreshold: 0, snapThreshold: 0,
snapToContainer: true, snapToContainer: true,
snapToSiblings: true, snapToSiblings: true,
hoverSelector: '.drag-hover', hoverSelector: '.drag-hover',
hoverIgnore: 'button,input,textarea,select,a,[contenteditable],svg,use', hoverIgnore: 'svg,use',
dragSelector: '.drag-box', dragSelector: '.drag-box',
resizerSelector: '.resizer', resizerSelector: '.resizer',
rootDragClass: 'is-interacting' rootDragClass: 'is-interacting'
@@ -304,10 +355,6 @@ export function makeMovable<T = void>(element: HTMLElement, opts: MovableOptions
} | null = null; } | null = null;
function getAction(el: Element, target: Element): DragAction | null { function getAction(el: Element, target: Element): DragAction | null {
if (opt.hoverIgnore && target.closest(opt.hoverIgnore)) {
return null;
}
if (opt.resizable) { if (opt.resizable) {
const resizer = target.closest<HTMLElement>(opt.resizerSelector); const resizer = target.closest<HTMLElement>(opt.resizerSelector);
if (resizer && resizer.closest(opt.dragSelector) === el) { if (resizer && resizer.closest(opt.dragSelector) === el) {
@@ -334,8 +381,45 @@ export function makeMovable<T = void>(element: HTMLElement, opts: MovableOptions
} }
if (guides.length > 0 || state.hasGuides) { if (guides.length > 0 || state.hasGuides) {
state.hasGuides = guides.length > 0; state.hasGuides = guides.length > 0;
if (typeof opt.onSnap === 'function') { if (typeof opt.onSnapped === 'function') {
opt.onSnap.call(opt.context, guides); 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';
}
} }
} }
} }
@@ -413,11 +497,12 @@ export function makeMovable<T = void>(element: HTMLElement, opts: MovableOptions
if (action.includes('w')) { if (action.includes('w')) {
const right = left + width; const right = left + width;
const maxLeft = Math.max(0, right - opt.minSize);
const rawLeft = right - Math.max(opt.minSize, width - dx); const rawLeft = right - Math.max(opt.minSize, width - dx);
const snappedLeft = findBestSnapEdge(rawLeft, targetsX, opt.snapThreshold, -Infinity, right - opt.minSize); const snappedLeft = findBestSnapEdge(rawLeft, targetsX, opt.snapThreshold, 0, maxLeft);
newLeft = snappedLeft; newLeft = Math.min(maxLeft, Math.max(0, snappedLeft));
newWidth = right - newLeft; newWidth = right - newLeft;
activeEdgeX = snappedLeft; activeEdgeX = newLeft;
} }
if (action.includes('s')) { if (action.includes('s')) {
@@ -429,11 +514,12 @@ export function makeMovable<T = void>(element: HTMLElement, opts: MovableOptions
if (action.includes('n')) { if (action.includes('n')) {
const bottom = top + height; const bottom = top + height;
const maxTop = Math.max(0, bottom - opt.minSize);
const rawTop = bottom - Math.max(opt.minSize, height - dy); const rawTop = bottom - Math.max(opt.minSize, height - dy);
const snappedTop = findBestSnapEdge(rawTop, targetsY, opt.snapThreshold, -Infinity, bottom - opt.minSize); const snappedTop = findBestSnapEdge(rawTop, targetsY, opt.snapThreshold, 0, maxTop);
newTop = snappedTop; newTop = Math.min(maxTop, Math.max(0, snappedTop));
newHeight = bottom - newTop; newHeight = bottom - newTop;
activeEdgeY = snappedTop; activeEdgeY = newTop;
} }
if (newWidth !== state.curWidth) { if (newWidth !== state.curWidth) {
@@ -560,6 +646,18 @@ export function makeMovable<T = void>(element: HTMLElement, opts: MovableOptions
return; 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); const action = getAction(box, e.target);
if (!action) { if (!action) {
return; return;
@@ -572,7 +670,6 @@ export function makeMovable<T = void>(element: HTMLElement, opts: MovableOptions
} catch { } catch {
} }
const offsetParent = box.offsetParent as HTMLElement | null;
const origin = getParentOrigin(offsetParent); const origin = getParentOrigin(offsetParent);
const left = box.offsetLeft; const left = box.offsetLeft;
const top = box.offsetTop; const top = box.offsetTop;
+31 -10
View File
@@ -2,7 +2,7 @@ import "./css/popup.scss";
import { r as lang } from "../utility/lgres"; import { r as lang } from "../utility/lgres";
import { nullOrEmpty } from "../utility/strings"; import { nullOrEmpty } from "../utility/strings";
import { global } from "../utility"; import { global } from "../utility";
import { appendResizer, makeMovable } from "../drag"; import { appendResizer, makeMovable } from "./movable";
import { createElement, mergeOptions } from "../functions"; import { createElement, mergeOptions } from "../functions";
import { createIcon, changeIcon } from "./icon"; import { createIcon, changeIcon } from "./icon";
import { requestAnimationFrame } from "../ui"; import { requestAnimationFrame } from "../ui";
@@ -56,7 +56,10 @@ export class Popup {
option: DEFAULT_OPTIONS, option: DEFAULT_OPTIONS,
/** @type {PopupRectParam | undefined} */ /** @type {PopupRectParam | undefined} */
bounds: undefined, bounds: undefined,
cursor: undefined cursor: undefined,
/** @type {(() => void) | undefined} */
movableDisposer: undefined,
__resolved: false
}; };
/** /**
@@ -170,6 +173,9 @@ export class Popup {
const option = this._var.option; const option = this._var.option;
const mask = this._var.mask; const mask = this._var.mask;
const doClose = () => { const doClose = () => {
if (typeof this._var.movableDisposer === 'function') {
this._var.movableDisposer();
}
if (option.persistent) { if (option.persistent) {
if (mask != null) { if (mask != null) {
mask.style.display = 'none'; mask.style.display = 'none';
@@ -334,16 +340,31 @@ export class Popup {
} }
button.innerText = b.text; button.innerText = b.text;
button.addEventListener('click', () => { button.addEventListener('click', () => {
if (this._var.__resolved) {
return;
}
this._var.__resolved = true;
if (typeof b.trigger === 'function') { if (typeof b.trigger === 'function') {
const result = b.trigger(this); const result = b.trigger(this);
if (typeof result === 'boolean' || typeof result === 'string' || typeof result === 'number') { if (typeof result === 'boolean' || typeof result === 'string' || typeof result === 'number') {
if (result !== false) {
this.close(result); this.close(result);
} else {
this._var.__resolved = false;
}
} else if (typeof result?.then === 'function') { } else if (typeof result?.then === 'function') {
result.then(r => { result.then(r => {
if (r !== false) { if (r !== false) {
this.close(r); this.close(r);
} else {
this._var.__resolved = false;
} }
}).catch(reason => console.warn(reason)); }).catch(reason => {
this._var.__resolved = false;
console.warn(reason);
});
} else {
this.close();
} }
} else { } else {
this.close(b.key ?? i); this.close(b.key ?? i);
@@ -376,7 +397,7 @@ export class Popup {
} }
if (option.movable || option.resizable) { if (option.movable || option.resizable) {
const parent = !option.mask ? document.body : mask; const parent = !option.mask ? document.body : mask;
makeMovable(parent, { this._var.movableDisposer = makeMovable(parent, {
movable: option.movable, movable: option.movable,
resizable: option.resizable, resizable: option.resizable,
context: this, context: this,
@@ -539,10 +560,10 @@ export function showAlert(title, message, iconType = 'info', parent = document.b
/** /**
* @param {string | HTMLElement} title * @param {string | HTMLElement} title
* @param {boolean} multiline * @param {boolean} [multiline]
* @param {string} message * @param {string} [message]
* @param {InputOptions} options * @param {InputOptions} [options]
* @param {PopupButton[]} buttons * @param {PopupButton[]} [buttons]
* @param {HTMLElement} parent * @param {HTMLElement} parent
* @returns {Promise<any>} * @returns {Promise<any>}
*/ */
@@ -612,7 +633,7 @@ export function showInput(title, multiline, message, options, buttons, parent =
* *
* @param {string | HTMLElement} title * @param {string | HTMLElement} title
* @param {string | HTMLElement} content * @param {string | HTMLElement} content
* @param {PopupButton[]} buttons * @param {PopupButton[]} [buttons]
* @param {keyof iconTypes} iconType * @param {keyof iconTypes} iconType
* @param {HTMLElement} parent * @param {HTMLElement} parent
* @returns * @returns
@@ -637,7 +658,7 @@ export function showConfirm(title, content, buttons, iconType = 'question', pare
isPrimary: b.isPrimary, isPrimary: b.isPrimary,
trigger: p => { trigger: p => {
if (typeof b.trigger === 'function') { if (typeof b.trigger === 'function') {
return b.trigger(p, b); return b.trigger(p);
} }
return b.key ?? i; return b.key ?? i;
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@soft-qr/ui-lib", "name": "@soft-qr/ui-lib",
"version": "1.1.7", "version": "1.1.8",
"publishConfig": { "publishConfig": {
"registry": "https://git.soft.qr/api/packages/soft-qr/npm/" "registry": "https://git.soft.qr/api/packages/soft-qr/npm/"
}, },
+2 -1
View File
@@ -21,6 +21,7 @@
"lib/ui.js", "lib/ui.js",
"lib/ui", "lib/ui",
"lib/utility.js", "lib/utility.js",
"lib/utility" "lib/utility",
"sample/*.ts"
] ]
} }