🎨 Optimize code

This commit is contained in:
2026-01-02 00:03:50 +08:00
parent 76f6c30b9d
commit 009274e4ad
14 changed files with 590 additions and 487 deletions

View File

@@ -1,43 +1,24 @@
import {defineStore} from 'pinia';
import {computed, ref} from 'vue';
import {ref} from 'vue';
import {DocumentService} from '@/../bindings/voidraft/internal/services';
import {OpenDocumentWindow} from '@/../bindings/voidraft/internal/services/windowservice';
import {Document} from '@/../bindings/voidraft/internal/models/ent/models';
import type {EditorViewState} from '@/stores/editorStore';
import type {TimerManager} from '@/common/utils/timerUtils';
import {createTimerManager} from '@/common/utils/timerUtils';
export const useDocumentStore = defineStore('document', () => {
// === 核心状态 ===
const documents = ref<Record<number, Document>>({});
const currentDocumentId = ref<number | null>(null);
const currentDocument = ref<Document | null>(null);
// === 编辑器状态持久化 ===
const documentStates = ref<Record<number, EditorViewState>>({});
// 自动保存定时器
const autoSaveTimers = ref<Map<number, TimerManager>>(new Map());
// === UI状态 ===
const showDocumentSelector = ref(false);
const selectorError = ref<{ docId: number; message: string } | null>(null);
const isLoading = ref(false);
// === 计算属性 ===
const documentList = computed(() =>
Object.values(documents.value).sort((a, b) => {
const timeA = a.updated_at ? new Date(a.updated_at).getTime() : 0;
const timeB = b.updated_at ? new Date(b.updated_at).getTime() : 0;
return timeB - timeA;
})
);
const setDocuments = (docs: Document[]) => {
documents.value = {};
docs.forEach(doc => {
if (doc.id !== undefined) {
documents.value[doc.id] = doc;
}
});
};
// === 错误处理 ===
const setError = (docId: number, message: string) => {
selectorError.value = {docId, message};
@@ -65,6 +46,39 @@ export const useDocumentStore = defineStore('document', () => {
};
// 获取文档列表
const getDocumentList = async (): Promise<Document[]> => {
try {
isLoading.value = true;
const docs = await DocumentService.ListAllDocumentsMeta();
return docs?.filter((doc): doc is Document => doc !== null) || [];
} catch (_error) {
return [];
} finally {
isLoading.value = false;
}
};
// 获取单个文档
const getDocument = async (docId: number): Promise<Document | null> => {
try {
return await DocumentService.GetDocumentByID(docId);
} catch (error) {
console.error('Failed to get document:', error);
return null;
}
};
// 保存文档内容
const saveDocument = async (docId: number, content: string): Promise<Document | null> => {
try {
await DocumentService.UpdateDocumentContent(docId, content);
return await DocumentService.GetDocumentByID(docId);
} catch (error) {
console.error('Failed to save document:', error);
throw error;
}
};
// 在新窗口中打开文档
const openDocumentInNewWindow = async (docId: number): Promise<boolean> => {
@@ -81,36 +95,16 @@ export const useDocumentStore = defineStore('document', () => {
const createNewDocument = async (title: string): Promise<Document | null> => {
try {
const doc = await DocumentService.CreateDocument(title);
if (doc && doc.id !== undefined) {
documents.value[doc.id] = doc;
return doc;
}
return null;
return doc || null;
} catch (error) {
console.error('Failed to create document:', error);
return null;
}
};
// 获取文档列表
const getDocumentMetaList = async () => {
try {
isLoading.value = true;
const docs = await DocumentService.ListAllDocumentsMeta();
if (docs) {
setDocuments(docs.filter((doc): doc is Document => doc !== null));
}
} catch (error) {
console.error('Failed to update documents:', error);
} finally {
isLoading.value = false;
}
};
// 打开文档 - 只负责文档数据管理
// 打开文档
const openDocument = async (docId: number): Promise<boolean> => {
try {
// 获取完整文档数据
const doc = await DocumentService.GetDocumentByID(docId);
if (!doc) {
throw new Error(`Document ${docId} not found`);
@@ -118,7 +112,6 @@ export const useDocumentStore = defineStore('document', () => {
currentDocumentId.value = docId;
currentDocument.value = doc;
return true;
} catch (error) {
console.error('Failed to open document:', error);
@@ -126,18 +119,12 @@ export const useDocumentStore = defineStore('document', () => {
}
};
// 更新文档元数据 - 只负责文档数据管理
const updateDocumentMetadata = async (docId: number, title: string): Promise<boolean> => {
// 更新文档标题
const updateDocumentTitle = async (docId: number, title: string): Promise<boolean> => {
try {
await DocumentService.UpdateDocumentTitle(docId, title);
// 更新本地状态
const doc = documents.value[docId];
if (doc) {
doc.title = title;
doc.updated_at = new Date().toISOString();
}
// 更新当前文档状态
if (currentDocument.value?.id === docId) {
currentDocument.value.title = title;
currentDocument.value.updated_at = new Date().toISOString();
@@ -145,24 +132,28 @@ export const useDocumentStore = defineStore('document', () => {
return true;
} catch (error) {
console.error('Failed to update document metadata:', error);
console.error('Failed to update document title:', error);
return false;
}
};
// 删除文档 - 只负责文档数据管理
// 删除文档
const deleteDocument = async (docId: number): Promise<boolean> => {
try {
await DocumentService.DeleteDocument(docId);
// 更新本地状态
delete documents.value[docId];
// 清理定时器
const timer = autoSaveTimers.value.get(docId);
if (timer) {
timer.clear();
autoSaveTimers.value.delete(docId);
}
// 如果删除的是当前文档,切换到第一个可用文档
if (currentDocumentId.value === docId) {
const availableDocs = Object.values(documents.value);
if (availableDocs.length > 0 && availableDocs[0].id !== undefined) {
await openDocument(availableDocs[0].id);
const docs = await getDocumentList();
if (docs.length > 0 && docs[0].id !== undefined) {
await openDocument(docs[0].id);
} else {
currentDocumentId.value = null;
currentDocument.value = null;
@@ -175,23 +166,46 @@ export const useDocumentStore = defineStore('document', () => {
return false;
}
};
// 调度自动保存
const scheduleAutoSave = (docId: number, saveCallback: () => Promise<void>, delay: number = 2000) => {
let timer = autoSaveTimers.value.get(docId);
if (!timer) {
timer = createTimerManager();
autoSaveTimers.value.set(docId, timer);
}
timer.set(async () => {
try {
await saveCallback();
} catch (error) {
console.error(`auto save for document ${docId} failed:`, error);
}
}, delay);
};
// 取消自动保存
const cancelAutoSave = (docId: number) => {
const timer = autoSaveTimers.value.get(docId);
if (timer) {
timer.clear();
}
};
// === 初始化 ===
// 初始化文档
const initDocument = async (urlDocumentId?: number): Promise<void> => {
try {
await getDocumentMetaList();
const docs = await getDocumentList();
// 优先使用URL参数中的文档ID
if (urlDocumentId && documents.value[urlDocumentId]) {
if (urlDocumentId) {
await openDocument(urlDocumentId);
} else if (currentDocumentId.value && documents.value[currentDocumentId.value]) {
// 如果URL中没有指定文档ID使用持久化的文档ID
} else if (currentDocumentId.value) {
// 使用持久化的文档ID
await openDocument(currentDocumentId.value);
} else {
// 否则打开第一个文档
if (documentList.value[0].id) {
await openDocument(documentList.value[0].id);
}
} else if (docs.length > 0 && docs[0].id !== undefined) {
// 打开第一个文档
await openDocument(docs[0].id);
}
} catch (error) {
console.error('Failed to initialize document store:', error);
@@ -200,32 +214,38 @@ export const useDocumentStore = defineStore('document', () => {
return {
// 状态
documents,
documentList,
currentDocumentId,
currentDocument,
documentStates,
showDocumentSelector,
selectorError,
isLoading,
// 方法
getDocumentMetaList,
getDocumentList,
getDocument,
saveDocument,
createNewDocument,
updateDocumentTitle,
deleteDocument,
openDocument,
openDocumentInNewWindow,
createNewDocument,
updateDocumentMetadata,
deleteDocument,
// 自动保存
scheduleAutoSave,
cancelAutoSave,
// UI 控制
openDocumentSelector,
closeDocumentSelector,
setError,
clearError,
// 初始化
initDocument,
};
}, {
persist: {
key: 'voidraft-document',
storage: localStorage,
pick: ['currentDocumentId', 'documents', 'documentStates']
pick: ['currentDocumentId']
}
});