feat: 添加i18n,美化界面
This commit is contained in:
3
packages/codemirror/src/assets/style.css
Normal file
3
packages/codemirror/src/assets/style.css
Normal file
@@ -0,0 +1,3 @@
|
||||
.cm-editor {
|
||||
height: 100%;
|
||||
}
|
||||
120
packages/codemirror/src/editor/editor.ts
Normal file
120
packages/codemirror/src/editor/editor.ts
Normal 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;
|
||||
94
packages/codemirror/src/editor/modules/ai-completions.ts
Normal file
94
packages/codemirror/src/editor/modules/ai-completions.ts
Normal 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*$/,
|
||||
};
|
||||
};
|
||||
92
packages/codemirror/src/editor/modules/keymap.ts
Normal file
92
packages/codemirror/src/editor/modules/keymap.ts
Normal 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);
|
||||
31
packages/codemirror/src/editor/utils/get-file-type.ts
Normal file
31
packages/codemirror/src/editor/utils/get-file-type.ts
Normal 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 '';
|
||||
}
|
||||
}
|
||||
3
packages/codemirror/src/global.css
Normal file
3
packages/codemirror/src/global.css
Normal file
@@ -0,0 +1,3 @@
|
||||
@import 'tailwindcss';
|
||||
@import '@kevisual/center-components/theme/wind-theme.css';
|
||||
@import './style.css';
|
||||
4
packages/codemirror/src/main.ts
Normal file
4
packages/codemirror/src/main.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { render } from './pages/Bootstrap';
|
||||
import './styles.css';
|
||||
|
||||
render('#ai-root');
|
||||
40
packages/codemirror/src/pages/App.tsx
Normal file
40
packages/codemirror/src/pages/App.tsx
Normal file
@@ -0,0 +1,40 @@
|
||||
import { useMemo } from 'react';
|
||||
import { CustomThemeProvider } from '@kevisual/center-components/theme/index.tsx';
|
||||
import { ToastContainer } from 'react-toastify';
|
||||
import { FileEditor } from './file-editor/FileEditor';
|
||||
|
||||
export const InitProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
type AppProvider = {
|
||||
key: string;
|
||||
use: boolean;
|
||||
};
|
||||
export type AppProps = {
|
||||
providers?: AppProvider[];
|
||||
noProvider?: boolean;
|
||||
/**
|
||||
* 是否是单个应用
|
||||
* 默认是单个应用模块。
|
||||
*/
|
||||
isSingleApp?: boolean;
|
||||
};
|
||||
export const App = ({ providers, noProvider, isSingleApp = true }: AppProps) => {
|
||||
const children = useMemo(() => {
|
||||
return (
|
||||
<InitProvider>
|
||||
<FileEditor />
|
||||
</InitProvider>
|
||||
);
|
||||
}, []);
|
||||
if (noProvider) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
return (
|
||||
<CustomThemeProvider>
|
||||
{children}
|
||||
<ToastContainer />
|
||||
</CustomThemeProvider>
|
||||
);
|
||||
};
|
||||
88
packages/codemirror/src/pages/Bootstrap.tsx
Normal file
88
packages/codemirror/src/pages/Bootstrap.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { App, AppProps } from './App';
|
||||
import React from 'react';
|
||||
|
||||
export class ReactRenderer {
|
||||
component: any;
|
||||
element: HTMLElement;
|
||||
ref: React.RefObject<any>;
|
||||
props: any;
|
||||
root: any;
|
||||
constructor(component: any, { props, className }: any) {
|
||||
this.component = component;
|
||||
const el = document.createElement('div');
|
||||
this.element = el;
|
||||
this.ref = React.createRef();
|
||||
this.props = {
|
||||
...props,
|
||||
ref: this.ref,
|
||||
};
|
||||
el.className = className;
|
||||
this.root = createRoot(this.element);
|
||||
this.render();
|
||||
}
|
||||
|
||||
updateProps(props: any) {
|
||||
this.props = {
|
||||
...this.props,
|
||||
...props,
|
||||
};
|
||||
this.render();
|
||||
}
|
||||
|
||||
render() {
|
||||
this.root.render(React.createElement(this.component, this.props));
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.root.unmount();
|
||||
}
|
||||
}
|
||||
|
||||
export default ReactRenderer;
|
||||
export const randomId = () => {
|
||||
return Math.random().toString(36).substring(2, 15);
|
||||
};
|
||||
export const render = (el: HTMLElement | string, props?: AppProps) => {
|
||||
const root = typeof el === 'string' ? document.querySelector(el) : el;
|
||||
if (!root) {
|
||||
console.error('root not found');
|
||||
return;
|
||||
}
|
||||
const hasResourceApp = window.context?.codemirrorApp;
|
||||
if (hasResourceApp) {
|
||||
const render = hasResourceApp as ReactRenderer;
|
||||
render.updateProps({
|
||||
props: { t: randomId(), ...props },
|
||||
});
|
||||
root.innerHTML = '';
|
||||
root.appendChild(render.element);
|
||||
} else {
|
||||
const renderer = new ReactRenderer(App, {
|
||||
props: { ...props },
|
||||
className: 'codemirror-root w-full h-full',
|
||||
});
|
||||
if (window.context) {
|
||||
window.context.codemirrorApp = renderer;
|
||||
} else {
|
||||
window.context = {
|
||||
codemirrorApp: renderer,
|
||||
};
|
||||
}
|
||||
root.appendChild(renderer.element);
|
||||
}
|
||||
};
|
||||
|
||||
export const unmount = (el: HTMLElement | string) => {
|
||||
const root = typeof el === 'string' ? document.querySelector(el) : el;
|
||||
if (!root) {
|
||||
console.error('root not found');
|
||||
return;
|
||||
}
|
||||
const hasResourceApp = window.context?.codemirrorApp;
|
||||
if (hasResourceApp) {
|
||||
const render = hasResourceApp as ReactRenderer;
|
||||
render.destroy();
|
||||
window.context.codemirrorApp = null;
|
||||
}
|
||||
};
|
||||
17
packages/codemirror/src/pages/file-editor/FileEditor.tsx
Normal file
17
packages/codemirror/src/pages/file-editor/FileEditor.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { BaseEditor } from '../../editor/editor';
|
||||
|
||||
export const FileEditor = () => {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const editor = new BaseEditor();
|
||||
if (containerRef.current) {
|
||||
editor.createEditor(containerRef.current);
|
||||
}
|
||||
return () => {
|
||||
editor.destroyEditor();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return <div ref={containerRef} className='w-full h-full'></div>;
|
||||
};
|
||||
3
packages/codemirror/src/style.css
Normal file
3
packages/codemirror/src/style.css
Normal file
@@ -0,0 +1,3 @@
|
||||
.cm-editor {
|
||||
height: 100%;
|
||||
}
|
||||
Reference in New Issue
Block a user