feat: 添加i18n,美化界面

This commit is contained in:
2025-03-20 02:29:01 +08:00
parent 27d9bdf54e
commit c206add7eb
56 changed files with 2743 additions and 928 deletions

View File

@@ -0,0 +1,120 @@
import { EditorView, keymap } from '@codemirror/view';
import { javascript } from '@codemirror/lang-javascript';
import { markdown } from '@codemirror/lang-markdown';
import { html } from '@codemirror/lang-html';
import { css } from '@codemirror/lang-css';
import { json } from '@codemirror/lang-json';
import { yaml } from '@codemirror/lang-yaml';
import { history } from '@codemirror/history';
import { vscodeLight } from '@uiw/codemirror-theme-vscode';
import { formatKeymap } from './modules/keymap';
import { Compartment, EditorState, Extension } from '@codemirror/state';
import { defaultKeymap } from '@codemirror/commands';
import { autocompletion, Completion } from '@codemirror/autocomplete';
import { getFileType } from './utils/get-file-type';
type BaseEditorOpts = {
language?: string;
filename: string;
autoComplete?: {
props?: any;
open?: boolean;
overrideList?: Completion[];
};
};
export class BaseEditor {
editor?: EditorView;
onChangeCompartment?: Compartment;
language: string;
filename: string;
el?: HTMLElement;
autoComplete?: {
props?: any;
open?: boolean;
overrideList?: Completion[];
};
constructor(opts?: BaseEditorOpts) {
this.filename = opts?.filename || '';
this.language = opts?.language || 'typescript';
if (this.filename && !opts?.language) {
// 根据文件名自动判断语言
const fileType = getFileType(this.filename);
this.language = fileType || 'typescript';
}
this.autoComplete = opts?.autoComplete || { open: true, overrideList: [] };
this.onChangeCompartment = new Compartment(); // 创建一个用于 onChange 的独立扩展
}
onEditorChange(view: EditorView) {
console.log('onChange', view);
}
getFileType(filename: string) {
return getFileType(filename);
}
createEditor(el: HTMLElement) {
this.el = el;
const onChangeCompartment = this.onChangeCompartment!;
const language = this.language;
const extensions: Extension[] = [
vscodeLight,
formatKeymap,
keymap.of(defaultKeymap), //
// history(),
];
if (this.autoComplete?.open) {
extensions.push(
autocompletion({
activateOnTyping: true, // 输入时触发补全
closeOnBlur: true, // 失去焦点时关闭补全
activateOnTypingDelay: 2000, // 输入时触发补全
override: this.autoComplete?.overrideList || [],
...this.autoComplete?.props,
}),
);
}
if (language === 'typescript') {
extensions.push(javascript({ typescript: true }));
} else if (language === 'javascript') {
extensions.push(javascript());
} else if (language === 'markdown') {
extensions.push(markdown());
} else if (language === 'html') {
extensions.push(html());
} else if (language === 'css') {
extensions.push(css());
} else if (language === 'json') {
extensions.push(json());
} else if (language === 'yaml') {
extensions.push(yaml());
}
this.editor = new EditorView({
parent: el,
extensions: [
...extensions, //
onChangeCompartment.of([]),
],
});
}
resetEditor(el?: HTMLElement) {
this.editor?.destroy?.();
this.createEditor(el || (this.el as HTMLElement));
}
setLanguage(language: string, el?: HTMLElement) {
this.language = language;
this.editor?.destroy?.();
this.createEditor(el || (this.el as HTMLElement));
}
setContent(content: string) {
this.editor?.dispatch({
changes: { from: 0, to: this.editor?.state.doc.length, insert: content },
});
}
getContent() {
return this.editor?.state.doc.toString();
}
destroyEditor() {
this.editor?.destroy();
}
}
export default BaseEditor;

View File

@@ -0,0 +1,94 @@
import { CompletionResult, CompletionSource } from '@codemirror/autocomplete';
import { Transaction } from '@codemirror/state';
export async function fetchAICompletions(context) {
const userInput = context.matchBefore(/\w*/);
if (!userInput) return null;
const docText = context.state.doc.toString(); // 获取完整文档内容
const cursorPos = context.pos; // 获取光标位置
// 添加提示词
const promptText = `请根据以下代码和光标位置提供代码补全建议:
代码:
${docText}
光标位置:${cursorPos}
请提供适当的代码补全。`;
const aiResponse = await fetch('http://192.168.31.220:11434/api/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
prompt: promptText,
// 如果 Ollama 支持,可以传递其他参数,如模型名称
// model: 'your-model-name',
model: 'qwen2.5-coder:14b',
// model: 'qwen2.5:14b',
stream: false,
}),
});
const result = await aiResponse.json();
const data = result;
// 提取字段
const createdAt = new Date(data.created_at); // 转换为日期对象
const isDone = data.done;
const doneReason = data.done_reason;
const modelName = data.model;
const responseText = data.response;
const matchCodeBlock = responseText.match(/```javascript\n([\s\S]*?)\n```/);
let codeBlock = '';
if (matchCodeBlock) {
const codeBlock = matchCodeBlock[1]; // 提取代码块
console.log('补全代码:', codeBlock);
}
const suggestions = [
{
label: codeBlock,
type: 'text',
},
];
return {
from: userInput.from,
options: suggestions,
validFor: /^\w*$/,
};
}
// type AiCompletion = Readonly<CompletionSource>;
export const testAiCompletion = async (context: any): Promise<CompletionResult | null> => {
const userInput = context.matchBefore(/\w*/);
if (!userInput) return null;
const docText = context.state.doc.toString(); // 获取完整文档内容
const cursorPos = context.pos; // 获取光标位置
console.log('testAiCompletion', userInput, docText, cursorPos);
return {
from: userInput.from,
options: [
{
label: '123 测试 skflskdf ',
type: 'text',
apply: (state, completion, from, to) => {
console.log('apply', state, completion, from, to);
const newText = '123 测试 skflskdf ';
state.dispatch({
changes: { from, to, insert: newText },
});
},
info: '这是一个长文本上的反馈是冷酷的父母离开时的父母 这是一个长文本上的反馈是冷酷的父母离开时的父母 这是一个长文本上的反馈是冷酷的父母离开时的父母这是一个长文本上的反馈是冷酷的父母离开时的父母 这是一个长文本上的反馈是冷酷的父母离开时的父母这是一个长文本上的反馈是冷酷的父母离开时的父母 这是一个长文本上的反馈是冷酷的父母离开时的父母',
},
{
label: '456',
type: 'text',
},
],
validFor: /^\w*$/,
};
};

View File

@@ -0,0 +1,92 @@
import { EditorView, keymap } from '@codemirror/view';
import { defaultKeymap, indentSelection, indentWithTab, undo, history } from '@codemirror/commands';
import { indentUnit } from '@codemirror/language';
import prettier from 'prettier';
// import parserBabel from 'prettier/plugins/babel';
import parserEstree from 'prettier/plugins/estree';
// import parserHtml from 'prettier/plugins/html';
import parserTypescript from 'prettier/plugins/typescript';
import { autocompletion, CompletionContext } from '@codemirror/autocomplete';
// 格式化函数
// Function to format the code using Prettier
async function formatCode(view: EditorView) {
const editor = view;
const code = editor.state.doc.toString();
try {
const formattedCode = await prettier.format(code, {
parser: 'typescript',
plugins: [parserEstree, parserTypescript],
});
editor.dispatch({
changes: {
from: 0,
to: editor.state.doc.length,
insert: formattedCode.trim(),
},
});
} catch (error) {
console.error('Error formatting code:', error);
}
}
// export const TabFn = (view: EditorView) => {
// const { state } = view;
// const selection = state.selection.main;
// // 判断是否存在补全上下文
// if (state.field(autocompletion).active?.length) {
// // 插入当前选中的补全内容
// const active = state.field(autocompletion).active[0];
// const selected = active?.options[active.selected]?.label;
// if (selected) {
// view.dispatch({
// changes: { from: selection.from, to: selection.to, insert: selected },
// });
// return true;
// }
// }
// return false;
// };
// 自定义 Tab 键行为
function customIndentWithTab(view: EditorView) {
const { state, dispatch } = view;
const { from, to } = state.selection.main;
const _indentUnit = state.facet(indentUnit) as string;
// 计算插入的缩进
const indent = _indentUnit.repeat(1);
dispatch({
changes: { from, to, insert: indent },
selection: { anchor: from + indent.length },
});
return true; // 表示按键事件被处理
}
export const formatKeymap = keymap.of([
{
// bug, 必须小写
key: 'alt-shift-f', // 快捷键绑定
// mac: 'cmd-shift-f',
run: (view) => {
formatCode(view);
return true; // 表示按键事件被处理
},
},
{
key: 'Tab',
run: customIndentWithTab, // 使用自定义的缩进函数
},
{
key: 'Ctrl-z', // Windows 撤销快捷键
// key: 'Alt-z',
mac: 'Cmd-z', // Mac 撤销快捷键
run: (view) => {
console.log('undo', view);
return undo(view); // 表示按键事件被处理
},
},
...defaultKeymap, // 默认快捷键
]);
// console.log('formatKeymap', defaultKeymap);

View File

@@ -0,0 +1,31 @@
export const getExtension = (filename: string) => {
const extension = filename.split('.').pop();
if (!extension) return '';
return extension;
};
export const supportedExtensions = ['ts', 'js', 'md', 'json', 'yaml', 'yml', 'css', 'html'];
export function getFileType(filename: string) {
const extension = getExtension(filename);
if (!supportedExtensions.includes(extension)) return '';
switch (extension) {
case 'ts':
return 'typescript';
case 'js':
return 'javascript';
case 'md':
return 'markdown';
case 'json':
return 'json';
case 'yaml':
return 'yaml';
case 'yml':
return 'yaml';
case 'css':
return 'css';
case 'html':
return 'html';
default:
return '';
}
}