diff --git a/lib/types.d.ts b/lib/types.d.ts index 8aad5c5..a57fde4 100644 --- a/lib/types.d.ts +++ b/lib/types.d.ts @@ -33,6 +33,7 @@ export interface MovableOptions { movable: boolean; resizable: boolean; minSize?: number; + bringToFront?: boolean; snapThreshold?: number; snapToContainer?: boolean; snapToSiblings?: boolean; @@ -45,7 +46,8 @@ export interface MovableOptions { onMoved?(this: T | undefined, rect: BoxRect): void; onResizeStart?(this: T | undefined): 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 = Omit & Required>; @@ -90,7 +92,13 @@ export interface PopupButton { key?: string; text: string; isPrimary?: boolean; - trigger?: (popup: Popup, button?: PopupButton) => boolean | Promise | string | number; + /** + * 按钮触发函数 + * @param popup 操作的弹出框实例 + * @param button 触发的按钮 + * @returns 返回 false 则阻止窗口关闭 + */ + trigger?: (this: PopupButton, popup: Popup) => boolean | string | number | Promise | undefined; } export interface PopupOptions { diff --git a/lib/ui.js b/lib/ui.js index 8410223..ec586a2 100644 --- a/lib/ui.js +++ b/lib/ui.js @@ -1,6 +1,6 @@ import './ui/css/variables/definition.scss'; import './ui/css/common.scss'; -import { appendResizer, makeMovable } from "./drag"; +import { appendResizer, makeMovable } from "./ui/movable"; import { createElement } from "./functions"; import { createIcon, changeIcon, resolveIcon } from "./ui/icon"; import { createCheckbox, createRadiobox, resolveCheckbox } from "./ui/checkbox"; diff --git a/lib/ui/css/common.scss b/lib/ui/css/common.scss index 9eb1458..722e337 100644 --- a/lib/ui/css/common.scss +++ b/lib/ui/css/common.scss @@ -127,7 +127,7 @@ } .drag-box { - position: relative; + position: absolute; .drag-hover { cursor: move; diff --git a/lib/drag.ts b/lib/ui/movable.ts similarity index 81% rename from lib/drag.ts rename to lib/ui/movable.ts index 80c4c0a..7cf3a2d 100644 --- a/lib/drag.ts +++ b/lib/ui/movable.ts @@ -1,5 +1,5 @@ -import { createElement, mergeOptions } from './functions'; -import type { MovableOptions, BoxRect, SnapTarget, SnapLine } from "./types"; +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'; @@ -17,6 +17,45 @@ function isResizeDir(dir: string | undefined): dir is ResizeDir { Object.prototype.hasOwnProperty.call(CURSOR_MAP, dir); } +/** z-index 置为最前 */ +function bringBoxToFront( + box: HTMLElement, + element: HTMLElement, + parent: HTMLElement | null, + dragSelector: string +): number | null { + const scope = element === box && parent ? parent : element; + const boxes = scope.querySelectorAll(dragSelector); + + let currZ = 0; + let maxOtherZ = -Infinity; + let hasOther = false; + + for (const el of boxes) { + if (el !== box && el.offsetParent !== parent) { + continue; + } + const z = parseInt(el.style.zIndex || getComputedStyle(el).zIndex) || 0; + if (el === box) { + currZ = z; + } else { + hasOther = true; + if (z > maxOtherZ) { + maxOtherZ = z; + } + } + } + + if (!hasOther || currZ > maxOtherZ) { + return null; + } + + const nextZ = maxOtherZ + 1; + box.style.zIndex = String(nextZ); + return nextZ; +} + +/** 获取 offsetParent 内容区域左上角在整个视图中的坐标 */ function getParentOrigin(parent: HTMLElement | null): { x: number; y: number } { if (!parent || parent === document.documentElement) { const rect = document.documentElement.getBoundingClientRect(); @@ -29,6 +68,7 @@ function getParentOrigin(parent: HTMLElement | null): { x: number; y: number } { }; } +/** 采集容器和兄弟元素的吸附目标 */ function collectSnapTargets( box: HTMLElement, element: HTMLElement, @@ -94,14 +134,16 @@ function collectSnapTargets( return { targetsX, targetsY }; } +/** 计算移动时单轴最佳吸附位置,确保不小于 minPos */ function findBestSnapMove( rawPos: number, size: number, targets: SnapTarget[], - threshold: number + threshold: number, + minPos = 0 ): number { if (threshold <= 0 || targets.length === 0) { - return rawPos; + return Math.max(minPos, rawPos); } const offsets = [0, size / 2, size]; @@ -111,17 +153,22 @@ function findBestSnapMove( for (const off of offsets) { const anchor = rawPos + off; for (const t of targets) { + const p = t.pos - off; + if (p < minPos) { + continue; + } const dist = Math.abs(t.pos - anchor); if (dist <= threshold && dist < bestDist) { bestDist = dist; - bestPos = t.pos - off; + bestPos = p; } } } - return bestPos; + return Math.max(minPos, bestPos); } +/** 计算缩放时单边最佳吸附位置 */ function findBestSnapEdge( rawEdge: number, targets: SnapTarget[], @@ -150,6 +197,7 @@ function findBestSnapEdge( return bestEdge; } +/** 基于最终位置收集移动时所有命中的局部参考线 */ function collectMoveGuides( snappedPos: number, size: number, @@ -184,6 +232,7 @@ function collectMoveGuides( return result; } +/** 基于最终边缘收集缩放时命中的局部参考线 */ function collectEdgeGuides( edgePos: number, crossStart: number, @@ -252,14 +301,16 @@ export function appendResizer(parent: ParentNode) { } export function makeMovable(element: HTMLElement, opts: MovableOptions) { + const snapPool: HTMLDivElement[] = []; const DEFAULT_OPTIONS = { minSize: 60, + bringToFront: true, snapThreshold: 0, snapToContainer: true, snapToSiblings: true, hoverSelector: '.drag-hover', - hoverIgnore: 'button,input,textarea,select,a,[contenteditable],svg,use', + hoverIgnore: 'svg,use', dragSelector: '.drag-box', resizerSelector: '.resizer', rootDragClass: 'is-interacting' @@ -304,10 +355,6 @@ export function makeMovable(element: HTMLElement, opts: MovableOptions } | 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) { @@ -334,8 +381,45 @@ export function makeMovable(element: HTMLElement, opts: MovableOptions } if (guides.length > 0 || state.hasGuides) { state.hasGuides = guides.length > 0; - if (typeof opt.onSnap === 'function') { - opt.onSnap.call(opt.context, guides); + if (typeof opt.onSnapped === 'function') { + opt.onSnapped.call(opt.context, guides); + } else { + // default action + const maxX = Math.max(element.clientWidth, element.scrollWidth) - 1; + const maxY = Math.max(element.clientHeight, element.scrollHeight) - 1; + + for (let i = 0; i < guides.length; i++) { + let line = snapPool[i]; + if (!line) { + line = createElement('div', 'snap-line'); + element.appendChild(line); + snapPool.push(line); + } + + const { axis, pos, start, end } = guides[i]; + const len = Math.max(0, Math.round(end - start)); + + if (axis === 'x') { + const left = Math.max(0, Math.min(Math.round(pos), maxX)); + const top = Math.round(start); + line.className = 'snap-line line-x'; + line.style.width = '1px'; + line.style.height = `${len}px`; + line.style.transform = `translate(${left}px, ${top}px)`; + } else { + const top = Math.max(0, Math.min(Math.round(pos), maxY)); + const left = Math.round(start); + line.className = 'snap-line line-y'; + line.style.width = `${len}px`; + line.style.height = '1px'; + line.style.transform = `translate(${left}px, ${top}px)`; + } + line.style.display = 'block'; + } + + for (let i = guides.length; i < snapPool.length; i++) { + snapPool[i].style.display = 'none'; + } } } } @@ -413,11 +497,12 @@ export function makeMovable(element: HTMLElement, opts: MovableOptions if (action.includes('w')) { const right = left + width; + const maxLeft = Math.max(0, right - opt.minSize); const rawLeft = right - Math.max(opt.minSize, width - dx); - const snappedLeft = findBestSnapEdge(rawLeft, targetsX, opt.snapThreshold, -Infinity, right - opt.minSize); - newLeft = snappedLeft; + const snappedLeft = findBestSnapEdge(rawLeft, targetsX, opt.snapThreshold, 0, maxLeft); + newLeft = Math.min(maxLeft, Math.max(0, snappedLeft)); newWidth = right - newLeft; - activeEdgeX = snappedLeft; + activeEdgeX = newLeft; } if (action.includes('s')) { @@ -429,11 +514,12 @@ export function makeMovable(element: HTMLElement, opts: MovableOptions if (action.includes('n')) { const bottom = top + height; + const maxTop = Math.max(0, bottom - opt.minSize); const rawTop = bottom - Math.max(opt.minSize, height - dy); - const snappedTop = findBestSnapEdge(rawTop, targetsY, opt.snapThreshold, -Infinity, bottom - opt.minSize); - newTop = snappedTop; + const snappedTop = findBestSnapEdge(rawTop, targetsY, opt.snapThreshold, 0, maxTop); + newTop = Math.min(maxTop, Math.max(0, snappedTop)); newHeight = bottom - newTop; - activeEdgeY = snappedTop; + activeEdgeY = newTop; } if (newWidth !== state.curWidth) { @@ -560,6 +646,18 @@ export function makeMovable(element: HTMLElement, opts: MovableOptions return; } + if (opt.hoverIgnore && e.target.closest(opt.hoverIgnore)) { + return; + } + + const offsetParent = box.offsetParent as HTMLElement | null; + if (opt.bringToFront) { + const z = bringBoxToFront(box, element, offsetParent, opt.dragSelector); + if (z != null && typeof opt.onZIndexChanged === 'function') { + opt.onZIndexChanged.call(opt.context, z, box); + } + } + const action = getAction(box, e.target); if (!action) { return; @@ -572,7 +670,6 @@ export function makeMovable(element: HTMLElement, opts: MovableOptions } catch { } - const offsetParent = box.offsetParent as HTMLElement | null; const origin = getParentOrigin(offsetParent); const left = box.offsetLeft; const top = box.offsetTop; diff --git a/lib/ui/popup.js b/lib/ui/popup.js index 272fa20..8d853b4 100644 --- a/lib/ui/popup.js +++ b/lib/ui/popup.js @@ -2,7 +2,7 @@ import "./css/popup.scss"; import { r as lang } from "../utility/lgres"; import { nullOrEmpty } from "../utility/strings"; import { global } from "../utility"; -import { appendResizer, makeMovable } from "../drag"; +import { appendResizer, makeMovable } from "./movable"; import { createElement, mergeOptions } from "../functions"; import { createIcon, changeIcon } from "./icon"; import { requestAnimationFrame } from "../ui"; @@ -56,7 +56,10 @@ export class Popup { option: DEFAULT_OPTIONS, /** @type {PopupRectParam | 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 mask = this._var.mask; const doClose = () => { + if (typeof this._var.movableDisposer === 'function') { + this._var.movableDisposer(); + } if (option.persistent) { if (mask != null) { mask.style.display = 'none'; @@ -242,7 +248,7 @@ export class Popup { } else { } - let tabIndex = Math.max.apply(null, /** @type {HTMLElement[]} */ ([...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; } @@ -317,7 +323,7 @@ export class Popup { )) ); if (Array.isArray(option.buttons) && option.buttons.length > 0) { - tabIndex = Math.max.apply(null, /** @type {HTMLElement[]} */ ([...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'); @@ -334,16 +340,31 @@ export class Popup { } button.innerText = b.text; button.addEventListener('click', () => { + if (this._var.__resolved) { + return; + } + this._var.__resolved = true; if (typeof b.trigger === 'function') { const result = b.trigger(this); if (typeof result === 'boolean' || typeof result === 'string' || typeof result === 'number') { - this.close(result); + if (result !== false) { + this.close(result); + } else { + this._var.__resolved = false; + } } else if (typeof result?.then === 'function') { result.then(r => { if (r !== false) { 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 { this.close(b.key ?? i); @@ -376,7 +397,7 @@ export class Popup { } if (option.movable || option.resizable) { const parent = !option.mask ? document.body : mask; - makeMovable(parent, { + this._var.movableDisposer = makeMovable(parent, { movable: option.movable, resizable: option.resizable, context: this, @@ -539,10 +560,10 @@ export function showAlert(title, message, iconType = 'info', parent = document.b /** * @param {string | HTMLElement} title - * @param {boolean} multiline - * @param {string} message - * @param {InputOptions} options - * @param {PopupButton[]} buttons + * @param {boolean} [multiline] + * @param {string} [message] + * @param {InputOptions} [options] + * @param {PopupButton[]} [buttons] * @param {HTMLElement} parent * @returns {Promise} */ @@ -586,7 +607,7 @@ export function showInput(title, multiline, message, options, buttons, parent = } } if (isNaN(opts.tabIndex)) { - let tabIndex = Math.max.apply(null, /** @type {HTMLElement[]} */ ([...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; } @@ -612,7 +633,7 @@ export function showInput(title, multiline, message, options, buttons, parent = * * @param {string | HTMLElement} title * @param {string | HTMLElement} content - * @param {PopupButton[]} buttons + * @param {PopupButton[]} [buttons] * @param {keyof iconTypes} iconType * @param {HTMLElement} parent * @returns @@ -637,7 +658,7 @@ export function showConfirm(title, content, buttons, iconType = 'question', pare isPrimary: b.isPrimary, trigger: p => { if (typeof b.trigger === 'function') { - return b.trigger(p, b); + return b.trigger(p); } return b.key ?? i; } diff --git a/package.json b/package.json index ca55e67..c0026a6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@soft-qr/ui-lib", - "version": "1.1.7", + "version": "1.1.8", "publishConfig": { "registry": "https://git.soft.qr/api/packages/soft-qr/npm/" }, diff --git a/tsconfig.json b/tsconfig.json index 44979da..fb10c5f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -21,6 +21,7 @@ "lib/ui.js", "lib/ui", "lib/utility.js", - "lib/utility" + "lib/utility", + "sample/*.ts" ] } \ No newline at end of file