import { computed, reactive } from 'vue';
|
import { cloneDeep } from 'lodash';
|
|
type UseDialogOptions = {
|
onConfirm?: (...args: any) => Promise<any>;
|
closeAfterConfirm?: boolean;
|
};
|
|
export function useDialog(options: UseDialogOptions = {}) {
|
const { onConfirm, closeAfterConfirm = true } = options;
|
|
const dialogState = reactive({
|
dialogVisible: false,
|
});
|
|
function onUpdateModelValue(value: boolean) {
|
dialogState.dialogVisible = value;
|
}
|
|
async function handleConfirm(...args: any) {
|
await onConfirm?.(...args);
|
if (closeAfterConfirm) {
|
dialogState.dialogVisible = false;
|
}
|
}
|
|
const dialogProps = computed(() => ({
|
modelValue: dialogState.dialogVisible,
|
['onUpdate:modelValue']: onUpdateModelValue,
|
onOnConfirm: handleConfirm,
|
}));
|
|
return {
|
dialogProps,
|
dialogState,
|
};
|
}
|
|
export type FormParams = {};
|
|
type UseFormDialogOptions<TFormParams extends FormParams> = UseDialogOptions & {
|
defaultFormParams: TFormParams;
|
};
|
|
export function useFormDialog<TFormParams extends FormParams>(
|
options: UseFormDialogOptions<TFormParams>
|
) {
|
const { onConfirm, closeAfterConfirm = true, defaultFormParams } = options;
|
const { dialogProps, dialogState } = useDialog({ onConfirm, closeAfterConfirm });
|
|
const editForm = reactive(cloneDeep(defaultFormParams));
|
|
function handleAdd(extraParams: Partial<TFormParams> = {}) {
|
Object.assign(editForm, cloneDeep(defaultFormParams), {
|
...extraParams,
|
});
|
dialogState.dialogVisible = true;
|
}
|
|
function handleEdit(data: Omit<TFormParams, 'title'>) {
|
Object.assign(editForm, cloneDeep(defaultFormParams), {
|
...data,
|
});
|
dialogState.dialogVisible = true;
|
}
|
|
function onUpdateForm(value: TFormParams) {
|
Object.assign(editForm, value);
|
}
|
|
const formDialogProps = computed(() => ({
|
...dialogProps.value,
|
form: editForm,
|
['onUpdate:form']: onUpdateForm,
|
}));
|
|
return {
|
dialogProps: formDialogProps,
|
dialogState,
|
editForm,
|
handleAdd,
|
handleEdit,
|
};
|
}
|