Add extension management service

This commit is contained in:
2025-06-24 14:16:53 +08:00
parent ea025e3f5d
commit f3bcb87828
31 changed files with 1682 additions and 176 deletions

View File

@@ -2,7 +2,7 @@
import {onBeforeUnmount, onMounted, ref} from 'vue';
import {useEditorStore} from '@/stores/editorStore';
import {useConfigStore} from '@/stores/configStore';
import {createWheelZoomHandler} from './extensions';
import {createWheelZoomHandler} from './basic/wheelZoomExtension';
import Toolbar from '@/components/toolbar/Toolbar.vue';
const editorStore = useEditorStore();

View File

@@ -1,5 +1,5 @@
import { EditorView, ViewPlugin, ViewUpdate } from '@codemirror/view';
import { DocumentService } from '../../../../bindings/voidraft/internal/services';
import { DocumentService } from '@/../bindings/voidraft/internal/services';
import { useDebounceFn } from '@vueuse/core';
// 定义自动保存配置选项

View File

@@ -21,16 +21,6 @@ import {
import {history} from '@codemirror/commands';
import {highlightSelectionMatches} from '@codemirror/search';
import {autocompletion, closeBrackets, closeBracketsKeymap} from '@codemirror/autocomplete';
import {searchVisibilityField, vscodeSearch} from './vscodeSearch';
import {hyperLink} from './hyperlink';
import {color} from './colorSelector';
import {createTextHighlighter} from './textHighlightExtension';
import {minimap} from './minimap';
import {createCodeBlockExtension} from './codeblock/index';
import {foldingOnIndent} from './foldExtension'
import rainbowBrackets from "./rainbowBrackets";
import {createCodeBlastExtension} from './codeblast';
// 基本编辑器设置
export const createBasicSetup = (): Extension[] => {
return [
@@ -63,30 +53,6 @@ export const createBasicSetup = (): Extension[] => {
// 自动完成
autocompletion(),
vscodeSearch,
searchVisibilityField,
foldingOnIndent,
rainbowBrackets(),
createCodeBlastExtension({
effect: 1,
shake: true,
maxParticles: 300,
shakeIntensity: 3
}),
hyperLink,
color,
...createTextHighlighter('hl'),
minimap({
displayText: 'characters',
showOverlay: 'always',
autohide: false,
}),
createCodeBlockExtension({
showBackground: true,
enableAutoDetection: true,
}),
// 键盘映射
keymap.of([
...closeBracketsKeymap,

View File

@@ -81,14 +81,6 @@ export function createFontExtension(config: Partial<FontConfig> = {}): Extension
return EditorView.theme(styles);
}
// 创建响应式字体大小扩展
export function createResponsiveFontExtension(baseFontSize: number = 14): Extension {
return fontCompartment.of(createFontExtension({
fontSize: baseFontSize,
lineHeight: 1.5
}));
}
// 从后端配置创建字体扩展
export function createFontExtensionFromBackend(backendConfig: {
fontFamily?: string;

View File

@@ -1,10 +0,0 @@
// 统一导出所有扩展
export * from './tabExtension';
export * from './wheelZoomExtension';
export * from './statsExtension';
export * from './autoSaveExtension';
export * from './fontExtension';
export * from './themeExtension';
export * from './codeblast';
export * from './codeblock';
export * from './keymap';

View File

@@ -70,7 +70,7 @@ const rainbowBracketsPlugin = ViewPlugin.fromClass(RainbowBracketsView, {
decorations: (v) => v.decorations,
});
export default function rainbowBrackets() {
export default function rainbowBracketsExtension() {
return [
rainbowBracketsPlugin,
EditorView.baseTheme({

View File

@@ -7,7 +7,7 @@ import {
searchToggleRegex,
searchToggleWholeWord,
showSearchVisibilityCommand
} from '../vscodeSearch/commands'
} from '../extensions/vscodeSearch/commands'
import {
addNewBlockAfterCurrent,
addNewBlockAfterLast,
@@ -20,14 +20,39 @@ import {
moveCurrentBlockUp,
selectNextBlock,
selectPreviousBlock
} from '../codeblock/commands'
import { selectAll } from '../codeblock/selectAll'
import { deleteLineCommand } from '../codeblock/deleteLine'
import { moveLineUp, moveLineDown } from '../codeblock/moveLines'
import { transposeChars } from '@/views/editor/extensions'
import { copyCommand, cutCommand, pasteCommand } from '../codeblock/copyPaste'
import { undo, redo, undoSelection, redoSelection, cursorSyntaxLeft, cursorSyntaxRight, selectSyntaxLeft, selectSyntaxRight, copyLineUp, copyLineDown, insertBlankLine, selectLine, selectParentSyntax, indentLess, indentMore, indentSelection, cursorMatchingBracket, toggleComment, toggleBlockComment, insertNewlineAndIndent, deleteCharBackward, deleteCharForward, deleteGroupBackward, deleteGroupForward } from '@codemirror/commands'
import { foldCode, unfoldCode, foldAll, unfoldAll } from '@codemirror/language'
} from '../extensions/codeblock/commands'
import {selectAll} from '../extensions/codeblock/selectAll'
import {deleteLineCommand} from '../extensions/codeblock/deleteLine'
import {moveLineDown, moveLineUp} from '../extensions/codeblock/moveLines'
import {transposeChars} from '../extensions/codeblock'
import {copyCommand, cutCommand, pasteCommand} from '../extensions/codeblock/copyPaste'
import {
copyLineDown,
copyLineUp,
cursorMatchingBracket,
cursorSyntaxLeft,
cursorSyntaxRight,
deleteCharBackward,
deleteCharForward,
deleteGroupBackward,
deleteGroupForward,
indentLess,
indentMore,
indentSelection,
insertBlankLine,
insertNewlineAndIndent,
redo,
redoSelection,
selectLine,
selectParentSyntax,
selectSyntaxLeft,
selectSyntaxRight,
toggleBlockComment,
toggleComment,
undo,
undoSelection
} from '@codemirror/commands'
import {foldAll, foldCode, unfoldAll, unfoldCode} from '@codemirror/language'
import i18n from '@/i18n'
// 默认编辑器选项

View File

@@ -0,0 +1,264 @@
import { Compartment, Extension, StateEffect } from '@codemirror/state'
import { EditorView } from '@codemirror/view'
import { ExtensionID, Extension as ExtensionConfig } from '@/../bindings/voidraft/internal/models/models'
/**
* 扩展工厂接口
* 每个扩展需要实现此接口来创建和配置扩展
*/
export interface ExtensionFactory {
/**
* 创建扩展实例
* @param config 扩展配置
* @returns CodeMirror扩展
*/
create(config: any): Extension
/**
* 获取默认配置
* @returns 默认配置对象
*/
getDefaultConfig(): any
/**
* 验证配置
* @param config 配置对象
* @returns 是否有效
*/
validateConfig?(config: any): boolean
}
/**
* 扩展区间信息
*/
interface ExtensionCompartment {
id: ExtensionID
compartment: Compartment
factory: ExtensionFactory
currentConfig?: any
enabled: boolean
}
/**
* 扩展管理器
* 负责管理所有动态扩展的注册、启用、禁用和配置更新
*/
export class ExtensionManager {
private view: EditorView | null = null
private compartments = new Map<ExtensionID, ExtensionCompartment>()
private extensionFactories = new Map<ExtensionID, ExtensionFactory>()
/**
* 注册扩展工厂
* @param id 扩展ID
* @param factory 扩展工厂
*/
registerExtension(id: ExtensionID, factory: ExtensionFactory): void {
this.extensionFactories.set(id, factory)
this.compartments.set(id, {
id,
compartment: new Compartment(),
factory,
currentConfig: factory.getDefaultConfig(),
enabled: false
})
}
/**
* 获取所有注册的扩展ID列表
*/
getRegisteredExtensions(): ExtensionID[] {
return Array.from(this.extensionFactories.keys())
}
/**
* 检查扩展是否已注册
* @param id 扩展ID
*/
isExtensionRegistered(id: ExtensionID): boolean {
return this.extensionFactories.has(id)
}
/**
* 根据后端配置获取初始扩展数组
* @param extensionConfigs 后端扩展配置列表
* @returns CodeMirror扩展数组
*/
getInitialExtensions(extensionConfigs: ExtensionConfig[]): Extension[] {
const extensions: Extension[] = []
for (const config of extensionConfigs) {
const compartmentInfo = this.compartments.get(config.id)
if (!compartmentInfo) {
console.warn(`Extension ${config.id} is not registered`)
continue
}
// 验证配置
if (compartmentInfo.factory.validateConfig &&
!compartmentInfo.factory.validateConfig(config.config)) {
console.warn(`Invalid config for extension ${config.id}`)
continue
}
try {
const extension = config.enabled
? compartmentInfo.factory.create(config.config)
: [] // 空扩展表示禁用
extensions.push(compartmentInfo.compartment.of(extension))
// 更新状态
compartmentInfo.currentConfig = config.config
compartmentInfo.enabled = config.enabled
} catch (error) {
console.error(`Failed to create extension ${config.id}:`, error)
}
}
return extensions
}
/**
* 设置编辑器视图
* @param view 编辑器视图实例
*/
setView(view: EditorView): void {
this.view = view
}
/**
* 动态更新单个扩展
* @param id 扩展ID
* @param enabled 是否启用
* @param config 扩展配置
*/
updateExtension(id: ExtensionID, enabled: boolean, config: any = {}): void {
if (!this.view) {
console.warn('Editor view not set')
return
}
const compartmentInfo = this.compartments.get(id)
if (!compartmentInfo) {
console.warn(`Extension ${id} is not registered`)
return
}
try {
// 验证配置
if (compartmentInfo.factory.validateConfig &&
!compartmentInfo.factory.validateConfig(config)) {
console.warn(`Invalid config for extension ${id}`)
return
}
const extension = enabled
? compartmentInfo.factory.create(config)
: []
this.view.dispatch({
effects: compartmentInfo.compartment.reconfigure(extension)
})
// 更新状态
compartmentInfo.currentConfig = config
compartmentInfo.enabled = enabled
} catch (error) {
console.error(`Failed to update extension ${id}:`, error)
}
}
/**
* 批量更新扩展
* @param updates 更新配置数组
*/
updateExtensions(updates: Array<{
id: ExtensionID
enabled: boolean
config: any
}>): void {
if (!this.view) {
console.warn('Editor view not set')
return
}
const effects: StateEffect<any>[] = []
for (const update of updates) {
const compartmentInfo = this.compartments.get(update.id)
if (!compartmentInfo) {
console.warn(`Extension ${update.id} is not registered`)
continue
}
try {
// 验证配置
if (compartmentInfo.factory.validateConfig &&
!compartmentInfo.factory.validateConfig(update.config)) {
console.warn(`Invalid config for extension ${update.id}`)
continue
}
const extension = update.enabled
? compartmentInfo.factory.create(update.config)
: []
effects.push(compartmentInfo.compartment.reconfigure(extension))
// 更新状态
compartmentInfo.currentConfig = update.config
compartmentInfo.enabled = update.enabled
} catch (error) {
console.error(`Failed to update extension ${update.id}:`, error)
}
}
if (effects.length > 0) {
this.view.dispatch({ effects })
}
}
/**
* 获取扩展当前状态
* @param id 扩展ID
*/
getExtensionState(id: ExtensionID): {
enabled: boolean
config: any
} | null {
const compartmentInfo = this.compartments.get(id)
if (!compartmentInfo) {
return null
}
return {
enabled: compartmentInfo.enabled,
config: compartmentInfo.currentConfig
}
}
/**
* 重置扩展到默认配置
* @param id 扩展ID
*/
resetExtensionToDefault(id: ExtensionID): void {
const compartmentInfo = this.compartments.get(id)
if (!compartmentInfo) {
console.warn(`Extension ${id} is not registered`)
return
}
const defaultConfig = compartmentInfo.factory.getDefaultConfig()
this.updateExtension(id, true, defaultConfig)
}
/**
* 销毁管理器
*/
destroy(): void {
this.view = null
this.compartments.clear()
this.extensionFactories.clear()
}
}

View File

@@ -0,0 +1,296 @@
import {ExtensionFactory, ExtensionManager} from './ExtensionManager'
import {ExtensionID} from '@/../bindings/voidraft/internal/models/models'
// 导入现有扩展的创建函数
import rainbowBracketsExtension from '../extensions/rainbowBracket/rainbowBracketsExtension'
import {createTextHighlighter} from '../extensions/textHighlight/textHighlightExtension'
import {createCodeBlastExtension} from '../extensions/codeblast'
import {color} from '../extensions/colorSelector'
import {hyperLink} from '../extensions/hyperlink'
import {minimap} from '../extensions/minimap'
import {vscodeSearch} from '../extensions/vscodeSearch'
import {createCodeBlockExtension} from '../extensions/codeblock'
import {foldingOnIndent} from '../extensions/fold/foldExtension'
/**
* 彩虹括号扩展工厂
*/
export const rainbowBracketsFactory: ExtensionFactory = {
create(config: any) {
return rainbowBracketsExtension()
},
getDefaultConfig() {
return {}
},
validateConfig(config: any) {
return typeof config === 'object'
}
}
/**
* 文本高亮扩展工厂
*/
export const textHighlightFactory: ExtensionFactory = {
create(config: any) {
return createTextHighlighter('default')
},
getDefaultConfig() {
return {
highlightClass: 'hl'
}
},
validateConfig(config: any) {
return typeof config === 'object' &&
(!config.highlightClass || typeof config.highlightClass === 'string')
}
}
/**
* 小地图扩展工厂
*/
export const minimapFactory: ExtensionFactory = {
create(config: any) {
const options = {
displayText: config.displayText || 'characters',
showOverlay: config.showOverlay || 'always',
autohide: config.autohide || false
}
return minimap(options)
},
getDefaultConfig() {
return {
displayText: 'characters',
showOverlay: 'always',
autohide: false
}
},
validateConfig(config: any) {
return typeof config === 'object' &&
(!config.displayText || typeof config.displayText === 'string') &&
(!config.showOverlay || typeof config.showOverlay === 'string') &&
(!config.autohide || typeof config.autohide === 'boolean')
}
}
/**
* 代码爆炸效果扩展工厂
*/
export const codeBlastFactory: ExtensionFactory = {
create(config: any) {
const options = {
effect: config.effect || 1,
shake: config.shake !== false,
maxParticles: config.maxParticles || 300,
shakeIntensity: config.shakeIntensity || 3
}
return createCodeBlastExtension(options)
},
getDefaultConfig() {
return {
effect: 1,
shake: true,
maxParticles: 300,
shakeIntensity: 3
}
},
validateConfig(config: any) {
return typeof config === 'object' &&
(!config.effect || [1, 2].includes(config.effect)) &&
(!config.shake || typeof config.shake === 'boolean') &&
(!config.maxParticles || typeof config.maxParticles === 'number') &&
(!config.shakeIntensity || typeof config.shakeIntensity === 'number')
}
}
/**
* 超链接扩展工厂
*/
export const hyperlinkFactory: ExtensionFactory = {
create(config: any) {
return hyperLink
},
getDefaultConfig() {
return {}
},
validateConfig(config: any) {
return typeof config === 'object'
}
}
/**
* 颜色选择器扩展工厂
*/
export const colorSelectorFactory: ExtensionFactory = {
create(config: any) {
return color
},
getDefaultConfig() {
return {}
},
validateConfig(config: any) {
return typeof config === 'object'
}
}
/**
* 搜索扩展工厂
*/
export const searchFactory: ExtensionFactory = {
create(config: any) {
return vscodeSearch
},
getDefaultConfig() {
return {}
},
validateConfig(config: any) {
return typeof config === 'object'
}
}
/**
* 代码块扩展工厂
*/
export const codeBlockFactory: ExtensionFactory = {
create(config: any) {
const options = {
showBackground: config.showBackground !== false,
enableAutoDetection: config.enableAutoDetection !== false
}
return createCodeBlockExtension(options)
},
getDefaultConfig() {
return {
showBackground: true,
enableAutoDetection: true
}
},
validateConfig(config: any) {
return typeof config === 'object' &&
(!config.showBackground || typeof config.showBackground === 'boolean') &&
(!config.enableAutoDetection || typeof config.enableAutoDetection === 'boolean')
}
}
export const foldFactory: ExtensionFactory = {
create(config: any) {
return foldingOnIndent;
},
getDefaultConfig(): any {
return {}
},
validateConfig(config: any): boolean {
return typeof config === 'object'
}
}
/**
* 所有扩展的统一配置
* 排除$zero值以避免TypeScript类型错误
*/
const EXTENSION_CONFIGS = {
// 编辑增强扩展
[ExtensionID.ExtensionRainbowBrackets]: {
factory: rainbowBracketsFactory,
displayName: '彩虹括号',
description: '用不同颜色显示嵌套括号'
},
[ExtensionID.ExtensionHyperlink]: {
factory: hyperlinkFactory,
displayName: '超链接',
description: '识别并可点击超链接'
},
[ExtensionID.ExtensionColorSelector]: {
factory: colorSelectorFactory,
displayName: '颜色选择器',
description: '颜色值的可视化和选择'
},
// UI增强扩展
[ExtensionID.ExtensionMinimap]: {
factory: minimapFactory,
displayName: '小地图',
description: '显示小地图视图'
},
[ExtensionID.ExtensionCodeBlast]: {
factory: codeBlastFactory,
displayName: '爆炸效果',
description: '编写时的动画效果'
},
// 工具扩展
[ExtensionID.ExtensionSearch]: {
factory: searchFactory,
displayName: '搜索功能',
description: '文本搜索和替换功能'
},
[ExtensionID.ExtensionCodeBlock]: {
factory: codeBlockFactory,
displayName: '代码块',
description: '代码块语法高亮和格式化'
},
[ExtensionID.ExtensionFold]: {
factory: foldFactory,
displayName: '折叠',
description: '折叠'
},
[ExtensionID.ExtensionTextHighlight]:{
factory: textHighlightFactory,
displayName: '文本高亮',
description: '文本高亮'
}
}
/**
* 注册所有扩展工厂到管理器
* @param manager 扩展管理器实例
*/
export function registerAllExtensions(manager: ExtensionManager): void {
Object.entries(EXTENSION_CONFIGS).forEach(([id, config]) => {
manager.registerExtension(id as ExtensionID, config.factory)
})
}
/**
* 获取扩展工厂的显示名称
* @param id 扩展ID
* @returns 显示名称
*/
export function getExtensionDisplayName(id: ExtensionID): string {
if (id === ExtensionID.$zero) return ''
return EXTENSION_CONFIGS[id as Exclude<ExtensionID, ExtensionID.$zero>]?.displayName || id
}
/**
* 获取扩展工厂的描述
* @param id 扩展ID
* @returns 描述
*/
export function getExtensionDescription(id: ExtensionID): string {
if (id === ExtensionID.$zero) return ''
return EXTENSION_CONFIGS[id as Exclude<ExtensionID, ExtensionID.$zero>]?.description || '未知扩展'
}
/**
* 获取扩展的完整信息
* @param id 扩展ID
* @returns 扩展信息对象
*/
export function getExtensionInfo(id: ExtensionID): { displayName: string; description: string } | null {
if (id === ExtensionID.$zero) return null
const config = EXTENSION_CONFIGS[id as Exclude<ExtensionID, ExtensionID.$zero>]
if (!config) return null
return {
displayName: config.displayName,
description: config.description
}
}
/**
* 获取所有可用扩展的ID列表
* @returns 扩展ID数组
*/
export function getAllExtensionIds(): ExtensionID[] {
return Object.keys(EXTENSION_CONFIGS) as ExtensionID[]
}

View File

@@ -0,0 +1,51 @@
import {Extension} from '@codemirror/state'
import {useExtensionStore} from '@/stores/extensionStore'
import {ExtensionManager} from './ExtensionManager'
import {registerAllExtensions} from './factories'
/**
* 全局扩展管理器实例
*/
const extensionManager = new ExtensionManager()
/**
* 异步创建动态扩展
* 确保扩展配置已加载
*/
export const createDynamicExtensions = async (): Promise<Extension[]> => {
const extensionStore = useExtensionStore()
// 注册所有扩展工厂
registerAllExtensions(extensionManager)
// 确保扩展配置已加载
if (extensionStore.extensions.length === 0) {
await extensionStore.loadExtensions()
}
// 获取启用的扩展配置
const enabledExtensions = extensionStore.enabledExtensions
return extensionManager.getInitialExtensions(enabledExtensions)
}
/**
* 获取扩展管理器实例
* @returns 扩展管理器
*/
export const getExtensionManager = (): ExtensionManager => {
return extensionManager
}
/**
* 设置编辑器视图到扩展管理器
* @param view 编辑器视图
*/
export const setExtensionManagerView = (view: any): void => {
extensionManager.setView(view)
}
// 导出相关模块
export {ExtensionManager} from './ExtensionManager'
export {registerAllExtensions, getExtensionDisplayName, getExtensionDescription} from './factories'
export type {ExtensionFactory} from './ExtensionManager'

View File

@@ -4,7 +4,7 @@ import { onMounted, computed } from 'vue';
import SettingSection from '../components/SettingSection.vue';
import { useKeybindingStore } from '@/stores/keybindingStore';
import { useSystemStore } from '@/stores/systemStore';
import { getCommandDescription } from '@/views/editor/extensions/keymap/commandRegistry';
import { getCommandDescription } from '@/views/editor/keymap/commandRegistry';
import {KeyBindingCommand} from "@/../bindings/voidraft/internal/models";
const { t } = useI18n();