Files
admin-vben5/apps/web-antd/src/utils/popup.ts

127 lines
3.2 KiB
TypeScript
Raw Normal View History

import type { ExtendedFormApi } from '@vben/common-ui';
import type { MaybePromise } from '@vben/types';
import { ref } from 'vue';
import { $t } from '@vben/locales';
import { Modal } from 'ant-design-vue';
import { isFunction } from 'lodash-es';
interface BeforeCloseDiffProps {
/**
*
* @returns Promise<string>
*/
initializedGetter: () => MaybePromise<string>;
/**
*
* @returns Promise<string>
*/
currentGetter: () => MaybePromise<string>;
/**
*
* @param init
* @param current
* @returns boolean
*/
compare?: (init: string, current: string) => boolean;
}
/**
2025-04-08 10:10:15 +08:00
* Drawer/Modal使用
* @param props props
* @returns hook
*/
export function useBeforeCloseDiff(props: BeforeCloseDiffProps) {
const { initializedGetter, currentGetter, compare } = props;
2025-04-08 10:10:15 +08:00
/**
* json
*/
const initialized = ref<string>('');
2025-04-08 10:10:15 +08:00
/**
* false直接关闭
*/
const isInitialized = ref(false);
2025-04-08 10:10:15 +08:00
/**
*
* @param data
*/
async function markInitialized(data?: string) {
initialized.value = data || (await initializedGetter());
isInitialized.value = true;
}
2025-04-08 10:10:15 +08:00
/**
* closed前调用
*/
function resetInitialized() {
initialized.value = '';
isInitialized.value = false;
}
2025-04-08 10:10:15 +08:00
/**
* useVbenForm/useVbenDrawer使用
* @returns
*/
async function onBeforeClose(): Promise<boolean> {
// 如果还未初始化,直接允许关闭
if (!isInitialized.value) {
return true;
}
try {
2025-04-08 10:10:15 +08:00
// 获取当前表单数据
const current = await currentGetter();
2025-04-08 10:10:15 +08:00
// 自定义比较的情况
if (isFunction(compare) && compare(initialized.value, current)) {
return true;
} else {
// 如果数据没有变化,直接允许关闭
if (current === initialized.value) {
return true;
}
}
// 数据有变化,显示确认对话框
return new Promise<boolean>((resolve) => {
Modal.confirm({
title: $t('pages.common.tip'),
content: $t('您有未保存的更改,确认要退出吗?'),
centered: true,
okButtonProps: { danger: true },
cancelText: $t('common.cancel'),
okText: $t('common.confirm'),
onOk: () => {
resolve(true);
isInitialized.value = false;
},
onCancel: () => resolve(false),
});
});
} catch (error) {
console.error('Failed to compare data:', error);
return true;
}
}
return {
onBeforeClose,
2025-04-08 10:10:15 +08:00
markInitialized,
resetInitialized,
};
}
/**
* useVbenForm使用的
* @param formApi
* @returns getter
*/
export function defaultFormValueGetter(formApi: ExtendedFormApi) {
return async () => {
const v = await formApi.getValues();
return JSON.stringify(v);
};
}