feat: 文件内容未保存时,阻塞窗口关闭事件

This commit is contained in:
Frankie Huang 2025-06-28 20:38:49 +08:00
parent 95d533f3bf
commit 1226991c7a
2 changed files with 24 additions and 5 deletions

View File

@ -10,6 +10,9 @@
"opener:default",
"fs:default",
"dialog:default",
{
"identifier": "core:window:allow-destroy"
},
{
"identifier": "fs:scope",
"allow": [

View File

@ -25,8 +25,9 @@ import LeftSidebar from './components/LeftSidebar.vue'
import MainEditor from './components/MainEditor.vue'
import { ref, watch, useTemplateRef, nextTick, onMounted, onUnmounted } from "vue";
import { invoke } from "@tauri-apps/api/core";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { readTextFile, writeTextFile, writeFile, exists } from '@tauri-apps/plugin-fs';
import { save } from '@tauri-apps/plugin-dialog';
import { save, confirm } from '@tauri-apps/plugin-dialog';
import { Message, Notice, Modal } from 'view-ui-plus'
import { GetSingleArticle, UpdateArticle } from '/src/utils/userHandler';
@ -89,12 +90,9 @@ watch(currentFilePath, async (newFilePath) => {
})
// 切换文件时,如果当前文件的变动未保存,允许用户取消切换动作,保存当前文件内容
const confirmSwitchingFile = () => {
// 判断当前文件内容是否被修改
const lastSaveTimeValue = lastSaveTime.get(currentFilePath.value);
const isUpdated = lastSaveTimeValue && lastUpdateTime.value > lastSaveTimeValue;
return new Promise((resolve) => {
// 如果当前文件内容未被修改,允许切换文件
if (!isUpdated) {
if (currentFileSaved()) {
resolve(true);
return;
}
@ -113,6 +111,12 @@ const confirmSwitchingFile = () => {
});
});
}
const currentFileSaved = () => {
// 判断当前文件内容是否被修改但未保存,如果已保存则返回 true
const lastSaveTimeValue = lastSaveTime.get(currentFilePath.value);
const isUpdated = lastSaveTimeValue && lastUpdateTime.value > lastSaveTimeValue;
return !isUpdated;
}
const getFileNameFromFilePath = (filePath) => {
const fullFileName = filePath.split('/').pop();
const splitResult = fullFileName.split(".");
@ -230,6 +234,18 @@ onMounted(async () => {
if (currentFilePath.value.length > 0) {
await readFileContent(currentFilePath.value);
}
// 监听窗口关闭事件。如果当前文件内容未保存,允许取消关闭事件
await getCurrentWindow().onCloseRequested(async (event) => {
if (currentFileSaved()) {
return; // 如果当前文件已保存,允许关闭窗口
}
const confirmed = await confirm('当前文件内容未保存,是否确认关闭窗口?');
if (!confirmed) {
// user did not confirm closing the window; let's prevent it
event.preventDefault();
}
});
});
onUnmounted(() => {
window.removeEventListener('resize', resizeHandler);