Skip to content

Commit

Permalink
feat:实现html代码预览器最小版本
Browse files Browse the repository at this point in the history
  • Loading branch information
songxingguo committed May 25, 2024
1 parent 2a30bb9 commit a59aa50
Showing 1 changed file with 58 additions and 17 deletions.
75 changes: 58 additions & 17 deletions src/.vuepress/components/MiniSandbox.vue
Original file line number Diff line number Diff line change
@@ -1,44 +1,85 @@
<template>
<div class="box">
<div class="code" ref="editorRef"></div>
<div class="mini-sandbox"
style="height: 80vh;">
<div class="sandbox-head">
<div class="sandbox-tab">
<div class="sandbox-tab-item sandbox-tab-active"
data-index="1">
<span>{{ title }}</span>
</div>
</div>
</div>
<div class="sandbox-body"
style="flex-direction: row;">
<div class="sandbox-code">
<div ref="editorRef"></div>
</div>
<div class="sandbox-gutter"
style="width: 5px; height: 100%;"></div>
<div class="sandbox-render">
<iframe style="width: auto; height: 100%;"
:src="url"
frameborder="0"></iframe>
</div>
</div>
</div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { onMounted, onBeforeMount, ref } from "vue";
import {basicSetup, EditorView} from "codemirror"
import { javascript } from "@codemirror/lang-javascript";
import { oneDark } from "@codemirror/theme-one-dark";
import {EditorState } from "@codemirror/state"
import axios from "axios";
const editorRef = ref()
const code = ref(`console.log('Hello, world!');`);
const title = ref()
let url = ref();
onMounted(()=> {
const state = EditorState.create({
doc: code.value,
const getTitle = (data) => {
const regTitle = /<title[\s\S]*>[\s\S]*<\/title>/;
const titleStr = regTitle.exec(data);
if (!titleStr) return;
const title = titleStr[0]
.replace("</title>", "")
.replace(/<title[\s\S]*?>/, "");
return title;
};
const handleCodeChanged = (data) => {
const htmlFragment = [data];
const myBlob = new Blob(htmlFragment, { type: "text/html" });
url.value = URL.createObjectURL(myBlob);
}
const initEditor = (data) => {
const state = EditorState.create({
doc: data,
extensions: [
basicSetup,
javascript(), // 在extensions中配置语言
oneDark,
EditorView.updateListener.of((v) => {
console.log(v.state.doc.toString()) //监测得到的最新代码
const data = v.state.doc
handleCodeChanged(data)
}),
],
});
const editor = new EditorView({
state,
parent: editorRef.value,
});
})
}
onBeforeMount(async () => {
const { data } = await axios.get("/demo/HTMLBasic/EFileUpload.html");
title.value = getTitle(data);
initEditor(data)
handleCodeChanged(data)
});
</script>
<style>
.box {
width: 100%;
height: 300px;
border: 1px solid #f00;
}
.code {
width: 300px;
height: 300px;
.sandbox-code {
overflow: auto !important;
}
</style>

0 comments on commit a59aa50

Please sign in to comment.