🚧 Optimize

This commit is contained in:
2025-09-30 00:28:15 +08:00
parent 4d6a4ff79f
commit cf8bf688bf
36 changed files with 1520 additions and 3896 deletions

View File

@@ -1,13 +1,13 @@
import {defineStore} from 'pinia';
import {computed, nextTick, ref, watch} from 'vue';
import {nextTick, ref, watch} from 'vue';
import {EditorView} from '@codemirror/view';
import {EditorState, Extension} from '@codemirror/state';
import {useConfigStore} from './configStore';
import {useDocumentStore} from './documentStore';
import {useThemeStore} from './themeStore';
import {useEditorCacheStore} from './editorCacheStore';
import {ExtensionID, SystemThemeType} from '@/../bindings/voidraft/internal/models/models';
import {DocumentService, ExtensionService} from '@/../bindings/voidraft/internal/services';
import {ensureSyntaxTree} from "@codemirror/language";
import {createBasicSetup} from '@/views/editor/basic/basicSetup';
import {createThemeExtension, updateEditorTheme} from '@/views/editor/basic/themeExtension';
import {getTabExtensions, updateTabConfig} from '@/views/editor/basic/tabExtension';
@@ -15,15 +15,11 @@ import {createFontExtensionFromBackend, updateFontConfig} from '@/views/editor/b
import {createStatsUpdateExtension} from '@/views/editor/basic/statsExtension';
import {createContentChangePlugin} from '@/views/editor/basic/contentChangeExtension';
import {createDynamicKeymapExtension, updateKeymapExtension} from '@/views/editor/keymap';
import {
createDynamicExtensions,
getExtensionManager,
removeExtensionManagerView,
setExtensionManagerView
} from '@/views/editor/manager';
import {createDynamicExtensions, getExtensionManager, setExtensionManagerView, removeExtensionManagerView} from '@/views/editor/manager';
import {useExtensionStore} from './extensionStore';
import createCodeBlockExtension from "@/views/editor/extensions/codeblock";
import {AsyncOperationManager} from '@/common/async';
const NUM_EDITOR_INSTANCES = 5; // 最多缓存5个编辑器实例
export interface DocumentStats {
lines: number;
@@ -31,48 +27,136 @@ export interface DocumentStats {
selectedCharacters: number;
}
interface EditorInstance {
view: EditorView;
documentId: number;
content: string;
isDirty: boolean;
lastModified: Date;
autoSaveTimer: number | null;
syntaxTreeCache: {
lastDocLength: number;
lastContentHash: string;
lastParsed: Date;
} | null;
}
export const useEditorStore = defineStore('editor', () => {
// === 依赖store ===
const configStore = useConfigStore();
const documentStore = useDocumentStore();
const themeStore = useThemeStore();
const extensionStore = useExtensionStore();
const editorCacheStore = useEditorCacheStore();
// === 核心状态 ===
const editorCache = ref<{
lru: number[];
instances: Record<number, EditorInstance>;
containerElement: HTMLElement | null;
}>({
lru: [],
instances: {},
containerElement: null
});
const currentEditor = ref<EditorView | null>(null);
const documentStats = ref<DocumentStats>({
lines: 0,
characters: 0,
selectedCharacters: 0
});
// 编辑器加载状态
const isLoading = ref(false);
// 异步操作管理器
const operationManager = new AsyncOperationManager({
debug: false,
autoCleanup: true
});
// 异步操作竞态条件控制
const operationSequence = ref(0);
const pendingOperations = ref(new Map<number, AbortController>());
const currentLoadingDocumentId = ref<number | null>(null);
// 自动保存设置
// 自动保存设置 - 从配置动态获取
const getAutoSaveDelay = () => configStore.config.editing.autoSaveDelay;
// 生成新的操作序列号
const getNextOperationId = () => ++operationSequence.value;
// 取消之前的操作
const cancelPreviousOperations = (excludeId?: number) => {
pendingOperations.value.forEach((controller, id) => {
if (id !== excludeId) {
controller.abort();
pendingOperations.value.delete(id);
}
});
};
// 检查操作是否仍然有效
const isOperationValid = (operationId: number, documentId: number) => {
return (
pendingOperations.value.has(operationId) &&
!pendingOperations.value.get(operationId)?.signal.aborted &&
currentLoadingDocumentId.value === documentId
);
};
// === 私有方法 ===
// 生成内容哈希
const generateContentHash = (content: string): string => {
let hash = 0;
for (let i = 0; i < content.length; i++) {
const char = content.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash.toString();
};
// 缓存化的语法树确保方法
const ensureSyntaxTreeCached = (view: EditorView, documentId: number): void => {
const instance = editorCache.value.instances[documentId];
if (!instance) return;
const docLength = view.state.doc.length;
const content = view.state.doc.toString();
const contentHash = generateContentHash(content);
const now = new Date();
// 检查是否需要重新构建语法树
const cache = instance.syntaxTreeCache;
const shouldRebuild = !cache ||
cache.lastDocLength !== docLength ||
cache.lastContentHash !== contentHash ||
(now.getTime() - cache.lastParsed.getTime()) > 30000; // 30秒过期
if (shouldRebuild) {
try {
ensureSyntaxTree(view.state, docLength, 5000);
// 更新缓存
instance.syntaxTreeCache = {
lastDocLength: docLength,
lastContentHash: contentHash,
lastParsed: now
};
} catch (error) {
console.warn('Failed to ensure syntax tree:', error);
}
}
};
// 创建编辑器实例
const createEditorInstance = async (
content: string,
signal: AbortSignal,
content: string,
operationId: number,
documentId: number
): Promise<EditorView> => {
if (!editorCacheStore.getContainer()) {
if (!editorCache.value.containerElement) {
throw new Error('Editor container not set');
}
// 检查操作是否被取消
if (signal.aborted) {
// 检查操作是否仍然有效
if (!isOperationValid(operationId, documentId)) {
throw new Error('Operation cancelled');
}
@@ -111,24 +195,24 @@ export const useEditorStore = defineStore('editor', () => {
enableAutoDetection: true
});
// 再次检查操作是否被取消
if (signal.aborted) {
// 再次检查操作有效性
if (!isOperationValid(operationId, documentId)) {
throw new Error('Operation cancelled');
}
// 快捷键扩展
const keymapExtension = await createDynamicKeymapExtension();
// 检查操作是否被取消
if (signal.aborted) {
// 检查操作有效性
if (!isOperationValid(operationId, documentId)) {
throw new Error('Operation cancelled');
}
// 动态扩展传递文档ID以便扩展管理器可以预初始化
const dynamicExtensions = await createDynamicExtensions(documentId);
// 最终检查操作是否被取消
if (signal.aborted) {
// 最终检查操作有效性
if (!isOperationValid(operationId, documentId)) {
throw new Error('Operation cancelled');
}
@@ -166,43 +250,91 @@ export const useEditorStore = defineStore('editor', () => {
return view;
};
// 添加编辑器到缓存
const addEditorToCache = (documentId: number, view: EditorView, content: string) => {
// 如果缓存已满,移除最少使用的编辑器
if (editorCache.value.lru.length >= NUM_EDITOR_INSTANCES) {
const oldestId = editorCache.value.lru.shift();
if (oldestId && editorCache.value.instances[oldestId]) {
const oldInstance = editorCache.value.instances[oldestId];
// 清除自动保存定时器
if (oldInstance.autoSaveTimer) {
clearTimeout(oldInstance.autoSaveTimer);
}
// 移除DOM元素
if (oldInstance.view.dom.parentElement) {
oldInstance.view.dom.remove();
}
oldInstance.view.destroy();
delete editorCache.value.instances[oldestId];
}
}
// 添加新的编辑器实例
editorCache.value.instances[documentId] = {
view,
documentId,
content,
isDirty: false,
lastModified: new Date(),
autoSaveTimer: null,
syntaxTreeCache: null
};
// 添加到LRU列表
editorCache.value.lru.push(documentId);
// 初始化语法树缓存
ensureSyntaxTreeCached(view, documentId);
};
// 更新LRU
const updateLRU = (documentId: number) => {
const lru = editorCache.value.lru;
const index = lru.indexOf(documentId);
if (index > -1) {
lru.splice(index, 1);
}
lru.push(documentId);
};
// 获取或创建编辑器
const getOrCreateEditor = async (
documentId: number,
content: string,
signal: AbortSignal
documentId: number,
content: string,
operationId: number
): Promise<EditorView> => {
// 检查缓存
const cached = editorCacheStore.getEditor(documentId);
const cached = editorCache.value.instances[documentId];
if (cached) {
updateLRU(documentId);
return cached.view;
}
// 检查操作是否被取消
if (signal.aborted) {
// 检查操作是否仍然有效
if (!isOperationValid(operationId, documentId)) {
throw new Error('Operation cancelled');
}
// 创建新的编辑器实例
const view = await createEditorInstance(content, signal, documentId);
// 最终检查操作是否被取消
if (signal.aborted) {
const view = await createEditorInstance(content, operationId, documentId);
// 最终检查操作有效性
if (!isOperationValid(operationId, documentId)) {
// 如果操作已取消,清理创建的实例
view.destroy();
throw new Error('Operation cancelled');
}
// 添加到缓存
editorCacheStore.addEditor(documentId, view, content);
addEditorToCache(documentId, view, content);
return view;
};
// 显示编辑器
const showEditor = (documentId: number) => {
const instance = editorCacheStore.getEditor(documentId);
if (!instance || !editorCacheStore.getContainer()) return;
const instance = editorCache.value.instances[documentId];
if (!instance || !editorCache.value.containerElement) return;
try {
// 移除当前编辑器DOM
@@ -211,19 +343,18 @@ export const useEditorStore = defineStore('editor', () => {
}
// 确保容器为空
const container = editorCacheStore.getContainer();
if (container) {
container.innerHTML = '';
// 将目标编辑器DOM添加到容器
container.appendChild(instance.view.dom);
}
editorCache.value.containerElement.innerHTML = '';
// 将目标编辑器DOM添加到容器
editorCache.value.containerElement.appendChild(instance.view.dom);
currentEditor.value = instance.view;
// 设置扩展管理器视图
setExtensionManagerView(instance.view, documentId);
// 更新LRU
updateLRU(documentId);
// 重新测量和聚焦编辑器
nextTick(() => {
// 将光标定位到文档末尾并滚动到该位置
@@ -232,12 +363,12 @@ export const useEditorStore = defineStore('editor', () => {
selection: {anchor: docLength, head: docLength},
scrollIntoView: true
});
// 滚动到文档底部
// 滚动到文档底部(将光标位置滚动到可见区域)
instance.view.focus();
// 使用缓存的语法树确保方法
editorCacheStore.ensureSyntaxTreeCached(instance.view, documentId);
ensureSyntaxTreeCached(instance.view, documentId);
});
} catch (error) {
console.error('Error showing editor:', error);
@@ -246,19 +377,20 @@ export const useEditorStore = defineStore('editor', () => {
// 保存编辑器内容
const saveEditorContent = async (documentId: number): Promise<boolean> => {
const instance = editorCacheStore.getEditor(documentId);
if (!instance || !instance.state.isDirty) return true;
const instance = editorCache.value.instances[documentId];
if (!instance || !instance.isDirty) return true;
try {
const content = instance.view.state.doc.toString();
const lastModified = instance.state.lastModified;
const lastModified = instance.lastModified;
await DocumentService.UpdateDocumentContent(documentId, content);
// 检查在保存期间内容是否又被修改了
if (instance.state.lastModified === lastModified) {
editorCacheStore.updateEditorContent(documentId, content);
// isDirty 已在 updateEditorContent 中设置为 false
if (instance.lastModified === lastModified) {
instance.content = content;
instance.isDirty = false;
instance.lastModified = new Date();
}
// 如果内容在保存期间被修改了,保持 isDirty 状态
@@ -271,23 +403,31 @@ export const useEditorStore = defineStore('editor', () => {
// 内容变化处理
const onContentChange = (documentId: number) => {
const instance = editorCacheStore.getEditor(documentId);
const instance = editorCache.value.instances[documentId];
if (!instance) return;
editorCacheStore.markEditorDirty(documentId);
instance.isDirty = true;
instance.lastModified = new Date();
// 清理语法树缓存,下次访问时重新构建
instance.syntaxTreeCache = null;
// 清除之前的定时器并设置新的自动保存定时器
const timer = setTimeout(() => {
// 清除之前的定时器
if (instance.autoSaveTimer) {
clearTimeout(instance.autoSaveTimer);
}
// 设置新的自动保存定时器
instance.autoSaveTimer = window.setTimeout(() => {
saveEditorContent(documentId);
}, getAutoSaveDelay());
editorCacheStore.setAutoSaveTimer(documentId, timer as unknown as number);
};
// === 公共API ===
// 设置编辑器容器
const setEditorContainer = (container: HTMLElement | null) => {
editorCacheStore.setContainer(container);
editorCache.value.containerElement = container;
// 如果设置容器时已有当前文档,立即加载编辑器
if (container && documentStore.currentDocument) {
@@ -299,6 +439,9 @@ export const useEditorStore = defineStore('editor', () => {
const loadEditor = async (documentId: number, content: string) => {
// 设置加载状态
isLoading.value = true;
// 生成新的操作ID
const operationId = getNextOperationId();
const abortController = new AbortController();
try {
// 验证参数
@@ -306,69 +449,72 @@ export const useEditorStore = defineStore('editor', () => {
throw new Error('Invalid parameters for loadEditor');
}
// 使用异步操作管理器执行加载操作
const result = await operationManager.executeOperation(
documentId,
async (signal) => {
// 保存当前编辑器内容
if (currentEditor.value) {
const currentDocId = documentStore.currentDocumentId;
if (currentDocId && currentDocId !== documentId) {
await saveEditorContent(currentDocId);
// 取消之前的操作并设置当前操作
cancelPreviousOperations();
currentLoadingDocumentId.value = documentId;
pendingOperations.value.set(operationId, abortController);
// 检查操作是否被取消
if (signal.aborted) {
throw new Error('Operation cancelled');
}
}
// 保存当前编辑器内容
if (currentEditor.value) {
const currentDocId = documentStore.currentDocumentId;
if (currentDocId && currentDocId !== documentId) {
await saveEditorContent(currentDocId);
// 检查操作是否仍然有效
if (!isOperationValid(operationId, documentId)) {
return;
}
// 获取或创建编辑器
const view = await getOrCreateEditor(documentId, content, signal);
// 检查操作是否被取消
if (signal.aborted) {
throw new Error('Operation cancelled');
}
// 更新内容
const instance = editorCacheStore.getEditor(documentId);
if (instance && instance.state.content !== content) {
// 确保编辑器视图有效
if (view && view.state && view.dispatch) {
view.dispatch({
changes: {
from: 0,
to: view.state.doc.length,
insert: content
}
});
editorCacheStore.updateEditorContent(documentId, content);
}
}
// 最终检查操作是否被取消
if (signal.aborted) {
throw new Error('Operation cancelled');
}
// 显示编辑器
showEditor(documentId);
return view;
},
'loadEditor'
);
if (!result.success) {
if (result.error?.message !== 'Operation cancelled') {
console.error('Failed to load editor:', result.error);
}
}
// 获取或创建编辑器
const view = await getOrCreateEditor(documentId, content, operationId);
// 检查操作是否仍然有效
if (!isOperationValid(operationId, documentId)) {
return;
}
// 更新内容(如果需要)
const instance = editorCache.value.instances[documentId];
if (instance && instance.content !== content) {
// 确保编辑器视图有效
if (view && view.state && view.dispatch) {
view.dispatch({
changes: {
from: 0,
to: view.state.doc.length,
insert: content
}
});
instance.content = content;
instance.isDirty = false;
// 清理语法树缓存,因为内容已更新
instance.syntaxTreeCache = null;
}
}
// 最终检查操作有效性
if (!isOperationValid(operationId, documentId)) {
return;
}
// 显示编辑器
showEditor(documentId);
} catch (error) {
console.error('Failed to load editor:', error);
if (error instanceof Error && error.message === 'Operation cancelled') {
console.log(`Editor loading cancelled for document ${documentId}`);
} else {
console.error('Failed to load editor:', error);
}
} finally {
// 清理操作记录
pendingOperations.value.delete(operationId);
if (currentLoadingDocumentId.value === documentId) {
currentLoadingDocumentId.value = null;
}
// 延迟一段时间后再取消加载状态
setTimeout(() => {
isLoading.value = false;
@@ -378,20 +524,49 @@ export const useEditorStore = defineStore('editor', () => {
// 移除编辑器
const removeEditor = (documentId: number) => {
// 取消该文档的所有操作
operationManager.cancelResourceOperations(documentId);
const instance = editorCache.value.instances[documentId];
if (instance) {
try {
// 如果正在加载这个文档,取消操作
if (currentLoadingDocumentId.value === documentId) {
cancelPreviousOperations();
currentLoadingDocumentId.value = null;
}
// 从扩展管理器中移除视图
removeExtensionManagerView(documentId);
// 清除自动保存定时器
if (instance.autoSaveTimer) {
clearTimeout(instance.autoSaveTimer);
instance.autoSaveTimer = null;
}
// 清除当前编辑器引用
const instance = editorCacheStore.getEditor(documentId);
if (instance && currentEditor.value === instance.view) {
currentEditor.value = null;
// 从扩展管理器中移除视图
removeExtensionManagerView(documentId);
// 移除DOM元素
if (instance.view && instance.view.dom && instance.view.dom.parentElement) {
instance.view.dom.remove();
}
// 销毁编辑器
if (instance.view && instance.view.destroy) {
instance.view.destroy();
}
// 清理引用
if (currentEditor.value === instance.view) {
currentEditor.value = null;
}
delete editorCache.value.instances[documentId];
const lruIndex = editorCache.value.lru.indexOf(documentId);
if (lruIndex > -1) {
editorCache.value.lru.splice(lruIndex, 1);
}
} catch (error) {
console.error('Error removing editor:', error);
}
}
// 从缓存中移除编辑器
editorCacheStore.removeEditor(documentId);
};
// 更新文档统计
@@ -401,7 +576,7 @@ export const useEditorStore = defineStore('editor', () => {
// 应用字体设置
const applyFontSettings = () => {
editorCacheStore.allEditors.forEach(instance => {
Object.values(editorCache.value.instances).forEach(instance => {
updateFontConfig(instance.view, {
fontFamily: configStore.config.editing.fontFamily,
fontSize: configStore.config.editing.fontSize,
@@ -413,7 +588,7 @@ export const useEditorStore = defineStore('editor', () => {
// 应用主题设置
const applyThemeSettings = () => {
editorCacheStore.allEditors.forEach(instance => {
Object.values(editorCache.value.instances).forEach(instance => {
updateEditorTheme(instance.view,
themeStore.currentTheme || SystemThemeType.SystemThemeAuto
);
@@ -422,7 +597,7 @@ export const useEditorStore = defineStore('editor', () => {
// 应用Tab设置
const applyTabSettings = () => {
editorCacheStore.allEditors.forEach(instance => {
Object.values(editorCache.value.instances).forEach(instance => {
updateTabConfig(
instance.view,
configStore.config.editing.tabSize,
@@ -436,21 +611,37 @@ export const useEditorStore = defineStore('editor', () => {
const applyKeymapSettings = async () => {
// 确保所有编辑器实例的快捷键都更新
await Promise.all(
editorCacheStore.allEditors.map(instance =>
Object.values(editorCache.value.instances).map(instance =>
updateKeymapExtension(instance.view)
)
);
};
// 清所有编辑器
// 清所有编辑器
const clearAllEditors = () => {
// 取消所有挂起的操作
operationManager.cancelAllOperations();
cancelPreviousOperations();
currentLoadingDocumentId.value = null;
Object.values(editorCache.value.instances).forEach(instance => {
// 清除自动保存定时器
if (instance.autoSaveTimer) {
clearTimeout(instance.autoSaveTimer);
}
// 从扩展管理器移除
removeExtensionManagerView(instance.documentId);
// 移除DOM元素
if (instance.view.dom.parentElement) {
instance.view.dom.remove();
}
// 销毁编辑器
instance.view.destroy();
});
// 清理所有编辑器
editorCacheStore.clearAll();
// 清除当前编辑器引用
editorCache.value.instances = {};
editorCache.value.lru = [];
currentEditor.value = null;
};
@@ -479,37 +670,9 @@ export const useEditorStore = defineStore('editor', () => {
await applyKeymapSettings();
};
// === 配置监听相关的 computed 属性 ===
// 字体相关配置的 computed 属性
const fontSettings = computed(() => ({
fontSize: configStore.config.editing.fontSize,
fontFamily: configStore.config.editing.fontFamily,
lineHeight: configStore.config.editing.lineHeight,
fontWeight: configStore.config.editing.fontWeight
}));
// Tab相关配置的 computed 属性
const tabSettings = computed(() => ({
tabSize: configStore.config.editing.tabSize,
enableTabIndent: configStore.config.editing.enableTabIndent,
tabType: configStore.config.editing.tabType
}));
// === 配置监听器 ===
// 监听字体配置变化
watch(fontSettings, applyFontSettings, { deep: true });
// 监听Tab配置变化
watch(tabSettings, applyTabSettings, { deep: true });
// 监听主题变化
watch(() => themeStore.currentTheme, applyThemeSettings);
// 监听文档切换
watch(() => documentStore.currentDocument, (newDoc) => {
if (newDoc && editorCacheStore.getContainer()) {
if (newDoc && editorCache.value.containerElement) {
// 使用 nextTick 确保DOM更新完成后再加载编辑器
nextTick(() => {
loadEditor(newDoc.id, newDoc.content);
@@ -517,6 +680,15 @@ export const useEditorStore = defineStore('editor', () => {
}
});
// 监听配置变化
watch(() => configStore.config.editing.fontSize, applyFontSettings);
watch(() => configStore.config.editing.fontFamily, applyFontSettings);
watch(() => configStore.config.editing.lineHeight, applyFontSettings);
watch(() => configStore.config.editing.fontWeight, applyFontSettings);
watch(() => configStore.config.editing.tabSize, applyTabSettings);
watch(() => configStore.config.editing.enableTabIndent, applyTabSettings);
watch(() => configStore.config.editing.tabType, applyTabSettings);
return {
// 状态
currentEditor,