diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index e3e14c0..33bda61 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -10,6 +10,9 @@ "opener:default", "fs:default", "dialog:default", + { + "identifier": "core:window:allow-destroy" + }, { "identifier": "fs:scope", "allow": [ diff --git a/src/App.vue b/src/App.vue index ed73382..564e7ba 100644 --- a/src/App.vue +++ b/src/App.vue @@ -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);