import {computed, createHooks, designComponent, getComponentCls, iMouseEvent, mergeAttrs, nextIndex, nextTick, onBeforeUnmount, Portal, PropType, reactive, useClasses, useModel, useRefs, useStyles, watch} from "@peryl/react-compose"; import {DialogAlign, DialogAnimations, DialogCloseType, DialogPositions} from "./utils/dialog.utils"; import {APPLICATION_SERVICE_CONTAINER_CLASS} from "../Application/utils/application.utils"; import {unit} from "@peryl/utils/unit"; import './dialog.scss'; import {i18n} from "../../i18n"; import {Icon} from "../Icon"; import {Button} from "../Button"; import {DialogMouse} from "./utils/dialog.mouse"; import {delay} from "@peryl/utils/delay"; import {throttle} from "@peryl/utils/throttle"; import {LoadingMask} from "../LoadingMask"; import {KeyboardService, KeyboardServiceOption} from "@peryl/utils/keyboard"; import {useDialogMovable} from "./useDialogMovable"; import {InnerTransition} from "../../utils/InnerTransition"; import {StyleProps, useStyle} from "../../uses/useStyle"; import {OpenController} from "../../utils/OpenController"; import {ClientZoom} from "../../utils/ClientZoom"; import {createTransitionHandler} from "../createTransitionHandler"; export const Dialog = designComponent({ name: '-dialog', provideRefer: true, inheritAttrs: false, props: { ...StyleProps, modelValue: { type: Boolean }, // model绑定是否打开对话框 open: { type: Boolean }, // model当前是否已经完全打开(完全关闭) title: { type: String }, // 弹框标题 loading: { type: Boolean as PropType, default: null }, // 开启弹框的loading状态 position: { type: String as PropType }, // 弹框位置,可选项:['center', 'top', 'bottom', 'left', 'right'] animation: { type: String as PropType }, // 弹框动画,可选项:['fade', 'scale', 'top', 'bottom', 'left', 'right'] externalClass: {}, // 额外的class类名 closeType: { type: String as PropType }, // 弹框关闭按钮样式类型 ['square', 'triangle'] height: { type: [String, Number] }, // 对话框高度 width: { type: [String, Number] }, // 对话框宽度 minHeight: { type: [String, Number] }, // 最小高度 minWidth: { type: [String, Number] }, // 最小宽度 maxHeight: { type: [String, Number] }, // 最大高度 maxWidth: { type: [String, Number] }, // 最大宽度 fullscreen: { type: Boolean }, // 全屏大小弹框 noContentPadding: { type: Boolean }, // 去掉内容默认内边距 noHead: { type: Boolean, }, // 去掉默认弹框标题 noFoot: { type: Boolean }, // 去掉底部内容 noMask: { type: Boolean }, // 去掉遮罩 noClose: { type: Boolean }, // 去掉关闭按钮 handleConfirm: { type: Function as PropType<(hide: () => void) => void | boolean | Promise> },// 处理确定动作,阻止关闭抛出异常或者返回Promise.reject handleCancel: { type: Function as PropType<(hide: () => void) => void | boolean | Promise> },// 处理取消动作,阻止关闭抛出异常或者返回Promise.reject headAlign: { type: String as PropType }, // 标题栏的内容对其方式 ['left', 'center', 'right'] contentAlign: { type: String as PropType }, // 标题栏的内容对其方式 ['left', 'center', 'right'] footAlign: { type: String as PropType }, // 操作栏按钮对其方式 ['left', 'center', 'right'] confirmButton: { type: Boolean }, // 是否显示确认按钮 cancelButton: { type: Boolean }, // 是否显示取消按钮 confirmButtonText: { type: String, }, // 确认按钮文本 cancelButtonText: { type: String, }, // 取消按钮文本 movable: { type: Boolean }, // 可以拖拽移动弹框 initialize: { type: Boolean }, // 是否立即初始化内容,默认第一次打开的时候才会初始化内容 destroyOnClose: { type: Boolean }, // 关闭的时候销毁内容实例 disableCancelOnClickMask: { type: Boolean }, // 禁用点击遮罩关闭弹框 disableConfirmOnEnter: { type: Boolean }, // 禁用点击enter的时候触发确定 disableCancelOnEsc: { type: Boolean }, // 禁用点击esc的时候触发取消 }, emits: { onUpdateModelValue: (val: boolean) => true, onUpdateOpen: (val: boolean) => true, onShow: () => true, onHide: () => true, onOpen: () => true, onClose: () => true, onConfirm: () => true, onCancel: () => true, }, slots: ['default', 'head', 'foot'], setup({ props, event, slots, attrs }) { const { styleComputed } = useStyle(); const { emit } = event; const model = useModel(() => props.modelValue, emit.onUpdateModelValue); const open = useModel(() => props.open, emit.onUpdateOpen); const { refs, onRef } = useRefs({ head: HTMLElement, content: HTMLDivElement, el: HTMLDivElement, }); const staticState = { isShow: false, }; const state = reactive({ loading: false, init: props.initialize, }); const isLoading = computed(() => state.loading || props.loading); const movable = computed(() => !!props.movable && wrapperAttrs.value.position === DialogPositions.center); const hooks = { beforeShow: createHooks<() => void>(), beforeHide: createHooks<() => void>(), onShow: createHooks<() => void>(), onHide: createHooks<() => void>(), onOpen: createHooks<() => void>(), onClose: createHooks<() => void>(), }; const wrapperAttrs = computed(() => { let position: typeof DialogPositions.TYPE = props.position || DialogPositions.center; let animation: typeof DialogAnimations.TYPE = props.animation || (position === DialogPositions.center ? DialogAnimations.scale : position); let width = props.width; let height = props.height; if (position === DialogPositions.top || position === DialogPositions.bottom) { width = '100%'; } if (position === DialogPositions.left || position === DialogPositions.right) { height = '100%'; } if (props.fullscreen) { width = '100%'; height = '100%'; position = DialogPositions.center; } return { position, animation, width, height }; }); useDialogMovable({ refs, movable }); const classes = useClasses(() => [ getComponentCls('dialog'), attrs.class, attrs.className, props.externalClass, `dialog-size-${styleComputed.value.size}`, `dialog-close-type-${props.closeType || DialogCloseType.square}`, `dialog-animation-${wrapperAttrs.value.animation}`, `dialog-position-${wrapperAttrs.value.position}`, `dialog-head-align-${props.headAlign || DialogAlign.left}`, `dialog-foot-align-${props.footAlign || (wrapperAttrs.value.position === DialogPositions.right ? DialogAlign.left : DialogAlign.right)}`, `dialog-content-align-${props.contentAlign || DialogAlign.left}`, { 'dialog-movable': movable.value, 'dialog-fullscreen': props.fullscreen, 'dialog-no-mask': props.noMask, 'dialog-no-content-padding': props.noContentPadding, } ]); const contentStyles = useStyles(style => { const { height, width } = wrapperAttrs.value; const { minWidth, minHeight, maxWidth, maxHeight } = props; !!height && (style.height = unit(height)); !!width && (style.width = unit(width)); !!minWidth && (style.minWidth = unit(minWidth)); !!minHeight && (style.minHeight = unit(minHeight)); !!maxWidth && (style.maxWidth = unit(maxWidth)); !!maxHeight && (style.maxHeight = unit(maxHeight)); }); const handler = { /** * 处理点击遮罩 * @author 韦胜健 * @date 2022.5.2 19:57 */ onClickWrapper: (e: iMouseEvent) => { if (e.target !== e.currentTarget) {return;} !props.disableCancelOnClickMask && methods.cancel(); }, /** * 处理点击关闭按钮 * @author 韦胜健 * @date 2022.5.2 19:57 */ onClickClose: () => { methods.cancel(); }, /** * 键盘事件 * @author 韦胜健 * @date 2022.5.2 20:56 */ keyboardEventOption: { "enter": () => { if (isLoading.value) return; if (!props.disableConfirmOnEnter) {methods.confirm();} }, "esc": () => { if (isLoading.value) return; if (!props.disableCancelOnEsc) {methods.cancel();} } } as KeyboardServiceOption, }; /** * 处理dialog content在transition完全结束之后的open.value的更新处理 * @author 韦胜健 * @date 2023/1/19 17:36 */ const handleTransition = createTransitionHandler({ getTransitionElement: () => refs.content, isOpen: open, isShow: { get value() {return staticState.isShow;}, set value(newVal) {staticState.isShow = newVal;} }, onOpen: () => hooks.onOpen.exec(undefined), onClose: () => hooks.onClose.exec(undefined), }); /** * 控制多次执行show的时候,只执行一次,避免派发多次onShow的情况 * @author 韦胜健 * @date 2023.1.21 15:58 */ const showing = (() => { let flag = false; return { flag: () => flag, start: () => flag = true, end: () => flag = false, }; })(); /** * 控制多次执行hide的时候,只执行一次,避免派发多次onHide的情况 * @author 韦胜健 * @date 2023.1.21 15:58 */ const hiding = (() => { let flag = false; return { flag: () => flag, start: () => flag = true, end: () => flag = false, }; })(); const methods = { show: async () => { if (staticState.isShow) {return;} if (showing.flag()) { return; } showing.start(); if (!state.init) { state.init = true; await delay(23); if (!refs.content) { await delay(23); } } else { await nextTick(); } await hooks.beforeShow.exec(undefined); if (!refs.el) { showing.end(); return; } refs.el!.style.zIndex = String(nextIndex()); refs.el!.setAttribute('data-show', ''); model.value = true; await hooks.onShow.exec(undefined); staticState.isShow = true; handleTransition(); showing.end(); }, hide: async () => { if (!staticState.isShow) {return;} if (!state.init) {return;} if (hiding.flag()) {return;} hiding.start(); await nextTick(); await hooks.beforeHide.exec(undefined); if (!refs.el) { hiding.end(); return; } refs.el!.removeAttribute('data-show'); model.value = false; await hooks.onHide.exec(undefined); staticState.isShow = false; handleTransition(); hiding.end(); }, confirm: throttle(async () => { if (isLoading.value) {return;} const timer = setTimeout(() => state.loading = true, 500); try { const flag = await props.handleConfirm?.(methods.hide); if (flag === false) { return; } emit.onConfirm(); await delay(68); await methods.hide(); } catch (e) { console.error(e); } finally { clearTimeout(timer); state.loading = false; } }, 300, { trailing: false }), cancel: throttle(async () => { if (isLoading.value) {return;} const timer = setTimeout(() => state.loading = true, 500); try { const flag = await props.handleCancel?.(methods.hide); if (flag === false) { return; } emit.onCancel(); await delay(68); await methods.hide(); } catch (e) { console.error(e); } finally { clearTimeout(timer); state.loading = false; } }, 300, { trailing: false }), }; onBeforeUnmount(() => { methods.confirm.dispose(); methods.cancel.dispose(); }); watch(() => model.value, async show => { await nextTick(); await (show ? methods.show() : methods.hide()); }, { immediate: true }); /** * scale跟随动画 * @author 韦胜健 * @date 2022.5.2 19:54 */ (() => { let durX = 0; let durY = 0; hooks.beforeShow.use(async () => { if (props.fullscreen) {return;} if (!(wrapperAttrs.value.animation === DialogAnimations.scale && wrapperAttrs.value.position === DialogPositions.center)) {return;} const { clientHeight, clientWidth } = ClientZoom.getClientSize(); durX = (DialogMouse.x - clientWidth / 2) * 0.75; durY = (DialogMouse.y - clientHeight / 2) * 0.75; const content = refs.content!; content.style.transition = 'none'; content.style.transform = `scale(0.7) translate3d(${durX}px,${durY}px,0)`; await delay(23); content.style.transition = ''; content.style.transform = ''; }); hooks.beforeHide.use(async () => { if (props.fullscreen) {return;} if (!(wrapperAttrs.value.animation === DialogAnimations.scale && wrapperAttrs.value.position === DialogPositions.center)) {return;} refs.content!.style.transform = `scale(0.7) translate3d(${durX}px,${durY}px,0)`; }); })(); /** * 键盘事件 * @author 韦胜健 * @date 2022.5.2 20:52 */ (() => { hooks.beforeShow.use(() => { KeyboardService.listen(handler.keyboardEventOption); KeyboardService.cancelActiveElement(); }); hooks.beforeHide.use(() => { KeyboardService.unbind(handler.keyboardEventOption); }); })(); /*关闭时销毁弹框内容*/ hooks.onClose.use(() => {!!props.destroyOnClose && (state.init = false);}); /*@formatter:off*/ hooks.onShow.use(() => {InnerTransition.disable(refs.content);emit.onShow()}); hooks.onHide.use(() => {InnerTransition.disable(refs.content);emit.onHide()}); hooks.onOpen.use(() => {InnerTransition.enable(refs.content);emit.onOpen()}); hooks.onClose.use(() => {InnerTransition.enable(refs.content);emit.onClose()}); /*@formatter:on*/ OpenController.provide(() => open.value); return { refer: { ...methods, model, openModel: open, hooks, event, }, render: () => { return ( !!state.init &&
{!props.noHead && (
{slots.head(props.title || i18n.$it('base.defaultTitle').d("提示"))} {!props.noClose && (
)}
)}
{slots.default()}
{!props.noFoot && (!!props.confirmButton || !!props.cancelButton || slots.foot.isExist()) && (
{slots.foot()} {(() => { const buttons = [ !!props.cancelButton && (
)} {isLoading.value && }
); } }; }, });