chore: code-editor

This commit is contained in:
xiaojunnuo
2025-04-07 23:52:21 +08:00
parent 2e0c067cd2
commit 9475f2e56c
12 changed files with 551 additions and 98 deletions

View File

@@ -0,0 +1,37 @@
export async function importJsYaml() {
return await import("js-yaml");
}
export async function importYamlContribution() {
await import("monaco-editor/esm/vs/basic-languages/yaml/yaml.contribution");
}
export async function importJsonContribution() {
await import("monaco-editor/esm/vs/language/json/monaco.contribution");
}
export async function importJavascriptContribution() {
await import("monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution");
}
export async function importMonacoYaml() {
return await import("monaco-yaml");
}
export async function importWorks() {
const editorWorker = await import("monaco-editor/esm/vs/editor/editor.worker?worker");
const jsonWorker = await import("monaco-editor/esm/vs/language/json/json.worker?worker");
const cssWorker = await import("monaco-editor/esm/vs/language/css/css.worker?worker");
const htmlWorker = await import("monaco-editor/esm/vs/language/html/html.worker?worker");
const tsWorker = await import("monaco-editor/esm/vs/language/typescript/ts.worker?worker");
const yamlWorker = await import("./yaml.worker?worker");
return {
editorWorker,
jsonWorker,
cssWorker,
htmlWorker,
tsWorker,
yamlWorker,
};
}

View File

@@ -0,0 +1,48 @@
// const editorWorker = await import("monaco-editor/esm/vs/editor/editor.worker?worker");
// const jsonWorker = await import("monaco-editor/esm/vs/language/json/json.worker?worker");
// const cssWorker = await import("monaco-editor/esm/vs/language/css/css.worker?worker");
// const htmlWorker = await import("monaco-editor/esm/vs/language/html/html.worker?worker");
// const tsWorker = await import("monaco-editor/esm/vs/language/typescript/ts.worker?worker");
// const yamlWorker = await import("monaco-yaml/yaml.worker.js?worker");
import editorWorker from "monaco-editor/esm/vs/editor/editor.worker?worker";
import jsonWorker from "monaco-editor/esm/vs/language/json/json.worker?worker";
import cssWorker from "monaco-editor/esm/vs/language/css/css.worker?worker";
import htmlWorker from "monaco-editor/esm/vs/language/html/html.worker?worker";
import tsWorker from "monaco-editor/esm/vs/language/typescript/ts.worker?worker";
import yamlWorker from "./yaml.worker?worker";
const WorkerBucket: any = {};
/**
* 注册自定义worker
* @param name
* @param worker
*/
export function registerWorker(name: string, worker: any) {
WorkerBucket[name] = worker;
}
//@ts-ignore
window.MonacoEnvironment = {
//@ts-ignore
getWorker(_, label) {
debugger;
const custom = WorkerBucket[label];
if (custom) {
return new custom();
}
if (label === "json") {
return new jsonWorker();
} else if (label === "css" || label === "scss" || label === "less") {
return new cssWorker();
} else if (label === "html" || label === "handlebars" || label === "razor") {
return new htmlWorker();
} else if (label === "typescript" || label === "javascript") {
return new tsWorker();
} else if (label === "yaml" || label === "yml") {
//@ts-ignore
return new yamlWorker();
}
return new editorWorker();
},
};

View File

@@ -0,0 +1,247 @@
<template>
<div ref="monacoRef" class="fs-editor-code"></div>
</template>
<script lang="ts" setup>
import * as monaco from "monaco-editor";
// import * as monaco from "monaco-editor/esm/vs/editor/editor.api";
import { onMounted, onUnmounted, ref, watch } from "vue";
import { cloneDeep, debounce as lodashDebounce } from "lodash-es";
import { initWorkers } from "./workers";
import { importJavascriptContribution, importJsonContribution, importMonacoYaml, importYamlContribution } from "./async-import";
/**
* config:
* value: '', // 编辑器初始文本
* language: 'javascript', // 语言
* theme: 'vs', // 主题
* readOnly: false, // 是否只读
* minimap: { enabled: false }, // 是否启用小地图
* fontSize: 14, // 字体大小
* tabSize: 2, // tab缩进长度
* automaticLayout: true, // 自动布局
* lineNumbers: 'off', // 是否启用行号
* contextmenu: true, // 是否启用上下文菜单
* folding: true, // 是否启用代码折叠
* foldingStrategy: 'auto', // 代码折叠策略
* wordWrap: 'on', // 自动换行设置
* wrappingIndent: 'indent', // 换行缩进
* formatOnPaste: true, // 粘贴时是否自动格式化
* formatOnType: true, // 输入时是否自动格式化
* dragAndDrop: true, // 是否允许拖放
* cursorStyle: 'line', // 光标样式
* cursorBlinking: 'blink', // 光标闪烁方式
* scrollbar: {
* vertical: 'auto', // 垂直滚动条的显示方式
* horizontal: 'auto', // 水平滚动条的显示方式
* verticalScrollbarSize: 2, // 垂直滚动条的宽
* horizontalScrollbarSize: 2, // 水平滚动条的高度
* }
*/
const props = defineProps<{
language?: string;
modelValue?: string;
config?: any;
schema?: any;
debounce?: number;
init?: any;
readonly?: boolean;
disabled?: boolean;
id?: string;
}>();
export type EditorCodeCtx = {
// monaco对象
monaco: any;
//语言
language: string;
//配置
config: any;
//editor实例对象
instance?: any;
schema?: any;
};
const monacoRef = ref();
let instanceRef: any = null;
function disposeEditor() {
// if (instanceRef.value) {
// instanceRef.value.dispose(); //使用完成销毁实例
// }
}
onUnmounted(() => {
disposeEditor();
});
const emits = defineEmits(["update:modelValue", "change", "ready"]);
const emitValue = lodashDebounce((value: any) => {
emits("update:modelValue", value);
}, props.debounce || 500);
// watch(
// () => {
// return props.modelValue;
// },
// (value: string) => {
// if (instanceRef.value && value !== instanceRef.value.getValue()) {
// // instanceRef.value.setValue(value);
// }
// }
// );
async function createEditor(ctx: EditorCodeCtx) {
disposeEditor();
const instance = monaco.editor.create(monacoRef.value, {
automaticLayout: true,
value: props.modelValue,
language: ctx.language,
theme: "vs-dark",
minimap: { enabled: false },
readOnly: props.readonly || props.disabled,
hover: {
enabled: true,
},
...ctx.config,
});
// @event `change`
instance.onDidChangeModelContent(event => {
const value = instance.getValue();
if (props.modelValue !== value) {
emits("change", value);
emitValue(value);
}
});
instanceRef = instance;
ctx.instance = instance;
emits("ready", ctx);
return instance;
}
async function initJavascript(ctx: EditorCodeCtx) {
await importJavascriptContribution();
monaco.languages.register({ id: "javascript" });
}
async function initJson(ctx: EditorCodeCtx) {
await importJsonContribution();
monaco.languages.register({ id: "json" });
const schemas = [];
if (ctx.schema) {
schemas.push({
// uri: "http://myserver/foo-schema.json", // id of the first schema
fileMatch: ["*"], // associate with our model
schema: {
...ctx.schema,
},
});
}
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
validate: true,
enableSchemaRequest: false,
schemas,
});
}
async function initYaml(ctx: EditorCodeCtx) {
await importYamlContribution();
const { configureMonacoYaml } = await importMonacoYaml();
monaco.languages.register({ id: "yaml" });
const schemas = [];
if (ctx.schema) {
schemas.push({
fileMatch: ["*"], // associate with our model
schema: {
...ctx.schema,
},
uri: "http://myserver/foo-schema.json",
});
}
configureMonacoYaml(monaco, {
schemas,
format: true,
hover: true,
completion: true,
validate: true,
isKubernetes: false,
enableSchemaRequest: false,
});
const uri = monaco.Uri.parse(`fs-editor-code-yaml-${props.id || ""}.yaml`);
const oldModel = monaco.editor.getModel(uri);
if (oldModel) {
oldModel.dispose();
}
ctx.config.model = monaco.editor.createModel(props.modelValue, "yaml", uri);
}
async function doInit() {
await initWorkers();
const ctx: EditorCodeCtx = {
monaco,
language: props.language || "javascript",
config: cloneDeep(props.config || {}),
schema: props.schema,
};
if (ctx.language === "javascript") {
await initJavascript(ctx);
} else if (ctx.language === "yaml") {
await initYaml(ctx);
} else if (ctx.language === "json") {
await initJson(ctx);
}
await createEditor(ctx);
}
// watch(
// () => {
// return {
// language: props.language,
// config: props.config,
// };
// },
// (value: any) => {
// doInit();
// }
// );
watch(
() => {
return props.modelValue;
},
newValue => {
if (instanceRef) {
const editor = instanceRef;
if (newValue !== editor.getValue()) {
editor.setValue(newValue);
}
}
}
);
onMounted(async () => {
await doInit();
});
</script>
<style lang="less">
.fs-editor-code {
min-height: 100px;
width: 100%;
border: 1px solid #eee;
border-radius: 5px;
position: relative;
}
.monaco-editor .hover-content {
z-index: 1000 !important;
}
</style>

View File

@@ -0,0 +1,37 @@
import { importJsYaml } from "./async-import";
const jsonRule = {
validator: async (rule: any, value: any) => {
//校验value json的有效性
if (value) {
try {
JSON.parse(value);
} catch (e: any) {
console.error(e);
throw new Error("json格式错误:" + e.message);
}
}
},
message: "json格式错误",
};
const yamlRule = {
validator: async (rule: any, value: any) => {
//校验value yaml的有效性
if (value) {
try {
const yaml = await importJsYaml();
yaml.load(value, { schema: yaml.JSON_SCHEMA });
} catch (e: any) {
console.error(e);
throw new Error("yaml格式错误:" + e.message);
}
}
},
message: "yaml格式错误",
};
export const FsEditorCodeValidators = {
jsonRule,
yamlRule,
};

View File

@@ -0,0 +1,59 @@
import { importWorks } from "./async-import";
const WorkerBucket: any = {};
/**
* 注册自定义worker
* @param name
* @param worker
*/
export function registerWorker(name: string, worker: any) {
WorkerBucket[name] = worker;
}
export async function initWorkers() {
if (window.MonacoEnvironment) {
return;
}
// const { editorWorker, jsonWorker, cssWorker, htmlWorker, tsWorker } = await importWorks();
//
// // const editorWorker = new Worker(new URL("monaco-editor/esm/vs/editor/editor.worker.js", import.meta.url));
// // const jsonWorker = new Worker(new URL("monaco-editor/esm/vs/language/json/json.worker.js", import.meta.url));
// // const cssWorker = new Worker(new URL("monaco-editor/esm/vs/language/css/css.worker.js", import.meta.url));
// // const htmlWorker = new Worker(new URL("monaco-editor/esm/vs/language/html/html.worker.js", import.meta.url));
// // const tsWorker = new Worker(new URL("monaco-editor/esm/vs/language/typescript/ts.worker.js", import.meta.url));
// // const yamlWorker = new Worker(new URL("./yaml.worker.js", import.meta.url));
const editorWorker = await import("monaco-editor/esm/vs/editor/editor.worker?worker");
const jsonWorker = await import("monaco-editor/esm/vs/language/json/json.worker?worker");
const cssWorker = await import("monaco-editor/esm/vs/language/css/css.worker?worker");
const htmlWorker = await import("monaco-editor/esm/vs/language/html/html.worker?worker");
const tsWorker = await import("monaco-editor/esm/vs/language/typescript/ts.worker?worker");
const yamlWorker = await import("./yaml.worker?worker");
//@ts-ignore
window.MonacoEnvironment = {
//@ts-ignore
getWorker(_, label) {
const custom = WorkerBucket[label];
if (custom) {
return new custom();
}
if (label === "json") {
return new jsonWorker.default();
} else if (label === "css" || label === "scss" || label === "less") {
return new cssWorker.default();
} else if (label === "html" || label === "handlebars" || label === "razor") {
return new htmlWorker.default();
} else if (label === "typescript" || label === "javascript") {
return new tsWorker.default();
} else if (label === "yaml" || label === "yml") {
debugger;
//@ts-ignore
return new yamlWorker.default();
}
return new editorWorker.default();
},
};
}

View File

@@ -0,0 +1 @@
export * from "monaco-yaml/yaml.worker.js";