chore: convert js to ts (#410)
All checks were successful
Build and Deploy / build-and-deploy (push) Has been skipped

This commit is contained in:
YangFong 2024-09-17 08:26:52 +08:00 committed by GitHub
parent b99ddef0ca
commit 21d5259f35
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
19 changed files with 136 additions and 139 deletions

View File

@ -93,7 +93,7 @@
} }
</script> </script>
<script id="MathJax-script" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script> <script id="MathJax-script" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
<script type="module" src="/src/main.js"></script> <script type="module" src="/src/main.ts"></script>
</body> </body>
<script src="https://cdn-doocs.oss-cn-shenzhen.aliyuncs.com/gh/wechatsync/article-syncjs@latest/dist/main.js"></script> <script src="https://cdn-doocs.oss-cn-shenzhen.aliyuncs.com/gh/wechatsync/article-syncjs@latest/dist/main.js"></script>
</html> </html>

View File

@ -1,4 +1,4 @@
<script setup> <script setup lang="ts">
import CodemirrorEditor from '@/views/CodemirrorEditor.vue' import CodemirrorEditor from '@/views/CodemirrorEditor.vue'
</script> </script>

View File

@ -1,4 +1,4 @@
<script setup> <script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from '@/stores' import { useStore } from '@/stores'
@ -23,7 +23,7 @@ function editTabName() {
}) })
} }
function handleTabsEdit(targetName, action) { function handleTabsEdit(targetName: string, action: string) {
if (action === `add`) { if (action === `add`) {
ElMessageBox.prompt(`请输入方案名称`, `新建自定义 CSS`, { ElMessageBox.prompt(`请输入方案名称`, `新建自定义 CSS`, {
confirmButtonText: `确认`, confirmButtonText: `确认`,
@ -86,7 +86,7 @@ function handleTabsEdit(targetName, action) {
<el-icon <el-icon
v-if="store.cssContentConfig.active === item.name" v-if="store.cssContentConfig.active === item.name"
class="ml-1" class="ml-1"
@click="editTabName(item.name)" @click="editTabName()"
> >
<ElIconEditPen /> <ElIconEditPen />
</el-icon> </el-icon>

View File

@ -1,4 +1,4 @@
<script setup> <script setup lang="ts">
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
@ -16,7 +16,7 @@ const props = defineProps({
const emit = defineEmits([`close`]) const emit = defineEmits([`close`])
function onUpdate(val) { function onUpdate(val: boolean) {
if (!val) { if (!val) {
emit(`close`) emit(`close`)
} }
@ -28,7 +28,7 @@ const links = [
{ label: `GitCode 仓库`, url: `https://gitcode.com/doocs/md` }, { label: `GitCode 仓库`, url: `https://gitcode.com/doocs/md` },
] ]
function onRedirect(url) { function onRedirect(url: string) {
window.open(url, `_blank`) window.open(url, `_blank`)
} }
</script> </script>

View File

@ -1,4 +1,4 @@
<script setup> <script setup lang="ts">
import { useStore } from '@/stores' import { useStore } from '@/stores'
const store = useStore() const store = useStore()

View File

@ -1,4 +1,4 @@
<script setup> <script setup lang="ts">
import { storeToRefs } from 'pinia' import { storeToRefs } from 'pinia'
import { useStore } from '@/stores' import { useStore } from '@/stores'

View File

@ -1,4 +1,4 @@
<script setup> <script setup lang="ts">
import { ref } from 'vue' import { ref } from 'vue'
import AboutDialog from './AboutDialog.vue' import AboutDialog from './AboutDialog.vue'

View File

@ -1,4 +1,4 @@
<script setup> <script setup lang="ts">
import { ref } from 'vue' import { ref } from 'vue'
import { storeToRefs } from 'pinia' import { storeToRefs } from 'pinia'
import { import {
@ -16,22 +16,23 @@ const { output } = storeToRefs(store)
const dialogVisible = ref(false) const dialogVisible = ref(false)
const form = ref({ const form = ref<any>({
title: ``, title: ``,
desc: ``, desc: ``,
thumb: ``, thumb: ``,
content: ``, content: ``,
auto: {},
}) })
function prePost() { function prePost() {
let auto = {} let auto = {}
try { try {
auto = { auto = {
thumb: document.querySelector(`#output img`)?.src, thumb: document.querySelector<HTMLImageElement>(`#output img`)?.src,
title: [1, 2, 3, 4, 5, 6] title: [1, 2, 3, 4, 5, 6]
.map(h => document.querySelector(`#output h${h}`)) .map(h => document.querySelector(`#output h${h}`)!)
.filter(h => h)[0].textContent, .filter(h => h)[0].textContent,
desc: document.querySelector(`#output p`).textContent, desc: document.querySelector(`#output p`)!.textContent,
content: output.value, content: output.value,
} }
} }
@ -45,10 +46,16 @@ function prePost() {
dialogVisible.value = true dialogVisible.value = true
} }
declare global {
interface Window {
syncPost: (data: { thumb: string, title: string, desc: string, content: string }) => void
}
}
function post() { function post() {
dialogVisible.value = false dialogVisible.value = false;
// 使 window.$syncer // 使 window.$syncer
window.syncPost({ (window.syncPost)({
thumb: form.value.thumb || form.value.auto.thumb, thumb: form.value.thumb || form.value.auto.thumb,
title: form.value.title || form.value.auto.title, title: form.value.title || form.value.auto.title,
desc: form.value.desc || form.value.auto.desc, desc: form.value.desc || form.value.auto.desc,
@ -56,7 +63,7 @@ function post() {
}) })
} }
function onUpdate(val) { function onUpdate(val: boolean) {
if (!val) { if (!val) {
dialogVisible.value = false dialogVisible.value = false
} }

View File

@ -1,15 +1,13 @@
<script setup> <script setup lang="ts">
import { nextTick, ref } from 'vue' import { nextTick, ref } from 'vue'
import { storeToRefs } from 'pinia' import { storeToRefs } from 'pinia'
import StyleOptionMenu from './StyleOptionMenu.vue' import StyleOptionMenu from './StyleOptionMenu.vue'
import { import {
HoverCard, HoverCard,
HoverCardContent, HoverCardContent,
HoverCardTrigger, HoverCardTrigger,
} from '@/components/ui/hover-card' } from '@/components/ui/hover-card'
import { import {
codeBlockThemeOptions, codeBlockThemeOptions,
colorOptions, colorOptions,
@ -45,10 +43,10 @@ const {
toggleShowCssEditor, toggleShowCssEditor,
} = store } = store
const colorPicker = ref(null) const colorPicker = ref<HTMLElement & { show: () => void } | null>(null)
function showPicker() { function showPicker() {
colorPicker.value.show() colorPicker.value?.show()
} }
// CSS // CSS
@ -56,11 +54,11 @@ function customStyle() {
toggleShowCssEditor() toggleShowCssEditor()
nextTick(() => { nextTick(() => {
if (!cssEditor.value) { if (!cssEditor.value) {
cssEditor.value.refresh() cssEditor.value!.refresh()
} }
}) })
setTimeout(() => { setTimeout(() => {
cssEditor.value.refresh() cssEditor.value!.refresh()
}, 50) }, 50)
} }
</script> </script>
@ -114,7 +112,7 @@ function customStyle() {
自定义主题色 自定义主题色
</HoverCardTrigger> </HoverCardTrigger>
<HoverCardContent side="right" class="w-min"> <HoverCardContent side="right" class="w-min">
<el-color-picker <ElColorPicker
ref="colorPicker" ref="colorPicker"
v-model="primaryColor" v-model="primaryColor"
:teleported="false" :teleported="false"

View File

@ -1,31 +1,20 @@
<script setup> <script setup lang="ts">
import { import {
MenubarItem, MenubarItem,
MenubarSub, MenubarSub,
MenubarSubContent, MenubarSubContent,
MenubarSubTrigger, MenubarSubTrigger,
} from '@/components/ui/menubar' } from '@/components/ui/menubar'
import type { IConfigOption } from '@/types'
const props = defineProps({ const props = defineProps<{
title: { title: string
type: String, options: IConfigOption[]
required: true, current: string
}, change: <T>(val: T) => void
options: { }>()
type: Array,
required: true,
},
current: {
type: String,
required: true,
},
change: {
type: Function,
required: true,
},
})
function setStyle(title, value) { function setStyle(title: string, value: string) {
switch (title) { switch (title) {
case `字体`: case `字体`:
return { fontFamily: value } return { fontFamily: value }

View File

@ -1,4 +1,4 @@
<script setup> <script setup lang="ts">
import { nextTick } from 'vue' import { nextTick } from 'vue'
import { storeToRefs } from 'pinia' import { storeToRefs } from 'pinia'
import { ElNotification } from 'element-plus' import { ElNotification } from 'element-plus'
@ -78,7 +78,7 @@ const formatItems = [
kbd: [altSign, shiftSign, `F`], kbd: [altSign, shiftSign, `F`],
emitArgs: [`formatContent`], emitArgs: [`formatContent`],
}, },
] ] as const
const store = useStore() const store = useStore()
@ -90,7 +90,7 @@ const { toggleDark, editorRefresh, citeStatusChanged } = store
function copy() { function copy() {
emit(`startCopy`) emit(`startCopy`)
setTimeout(() => { setTimeout(() => {
function modifyHtmlStructure(htmlString) { function modifyHtmlStructure(htmlString: string) {
// div HTML // div HTML
const tempDiv = document.createElement(`div`) const tempDiv = document.createElement(`div`)
tempDiv.innerHTML = htmlString tempDiv.innerHTML = htmlString
@ -98,7 +98,7 @@ function copy() {
const originalItems = tempDiv.querySelectorAll(`li > ul, li > ol`) const originalItems = tempDiv.querySelectorAll(`li > ul, li > ol`)
originalItems.forEach((originalItem) => { originalItems.forEach((originalItem) => {
originalItem.parentElement.insertAdjacentElement(`afterend`, originalItem) originalItem.parentElement!.insertAdjacentElement(`afterend`, originalItem)
}) })
// HTML // HTML
@ -114,7 +114,7 @@ function copy() {
nextTick(() => { nextTick(() => {
solveWeChatImage() solveWeChatImage()
const clipboardDiv = document.getElementById(`output`) const clipboardDiv = document.getElementById(`output`)!
clipboardDiv.innerHTML = mergeCss(clipboardDiv.innerHTML) clipboardDiv.innerHTML = mergeCss(clipboardDiv.innerHTML)
clipboardDiv.innerHTML = modifyHtmlStructure(clipboardDiv.innerHTML) clipboardDiv.innerHTML = modifyHtmlStructure(clipboardDiv.innerHTML)
clipboardDiv.innerHTML = clipboardDiv.innerHTML clipboardDiv.innerHTML = clipboardDiv.innerHTML
@ -125,14 +125,14 @@ function copy() {
.replaceAll(`var(--md-primary-color)`, primaryColor.value) .replaceAll(`var(--md-primary-color)`, primaryColor.value)
.replaceAll(/--md-primary-color:.+?;/g, ``) .replaceAll(/--md-primary-color:.+?;/g, ``)
clipboardDiv.focus() clipboardDiv.focus()
window.getSelection().removeAllRanges() window.getSelection()!.removeAllRanges()
const range = document.createRange() const range = document.createRange()
range.setStartBefore(clipboardDiv.firstChild) range.setStartBefore(clipboardDiv.firstChild!)
range.setEndAfter(clipboardDiv.lastChild) range.setEndAfter(clipboardDiv.lastChild!)
window.getSelection().addRange(range) window.getSelection()!.addRange(range)
document.execCommand(`copy`) document.execCommand(`copy`)
window.getSelection().removeAllRanges() window.getSelection()!.removeAllRanges()
clipboardDiv.innerHTML = output.value clipboardDiv.innerHTML = output.value
if (isBeforeDark) { if (isBeforeDark) {
@ -165,8 +165,8 @@ function copy() {
<MenubarContent class="w-60" align="start"> <MenubarContent class="w-60" align="start">
<MenubarItem <MenubarItem
v-for="{ label, kbd, emitArgs } in formatItems" v-for="{ label, kbd, emitArgs } in formatItems"
:key="kbd" :key="label"
@click="$emit(...emitArgs)" @click="emitArgs[0] === 'addFormat' ? $emit(emitArgs[0], emitArgs[1]) : $emit(emitArgs[0])"
> >
<el-icon class="mr-2 h-4 w-4" /> <el-icon class="mr-2 h-4 w-4" />
{{ label }} {{ label }}

View File

@ -1,4 +1,4 @@
<script setup> <script setup lang="ts">
import { ref, toRaw } from 'vue' import { ref, toRaw } from 'vue'
import { import {
Dialog, Dialog,
@ -17,7 +17,7 @@ const { toggleShowInsertFormDialog } = store
const rowNum = ref(3) const rowNum = ref(3)
const colNum = ref(3) const colNum = ref(3)
const tableData = ref({}) const tableData = ref<Record<string, string>>({})
function resetVal() { function resetVal() {
rowNum.value = 3 rowNum.value = 3
@ -32,12 +32,12 @@ function insertTable() {
cols: colNum.value, cols: colNum.value,
data: tableData.value, data: tableData.value,
}) })
toRaw(store.editor).replaceSelection(`\n${table}\n`, `end`) toRaw(store.editor!).replaceSelection(`\n${table}\n`, `end`)
resetVal() resetVal()
toggleShowInsertFormDialog() toggleShowInsertFormDialog()
} }
function onUpdate(val) { function onUpdate(val: boolean) {
if (!val) { if (!val) {
toggleShowInsertFormDialog(false) toggleShowInsertFormDialog(false)
} }

View File

@ -1,9 +1,9 @@
<script setup> <script setup lang="ts">
import { nextTick, onBeforeMount, ref, watch } from 'vue' import { nextTick, onBeforeMount, ref, watch } from 'vue'
import CodeMirror from 'codemirror/lib/codemirror'
import { ElMessage } from 'element-plus' import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue' import { UploadFilled } from '@element-plus/icons-vue'
import CodeMirror from 'codemirror'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { checkImage, removeLeft } from '@/utils' import { checkImage, removeLeft } from '@/utils'
@ -50,6 +50,7 @@ const formQiniu = ref({
bucket: ``, bucket: ``,
domain: ``, domain: ``,
region: ``, region: ``,
path: ``,
}) })
const minioOSS = ref({ const minioOSS = ref({
@ -61,7 +62,7 @@ const minioOSS = ref({
secretKey: ``, secretKey: ``,
}) })
const formCustom = ref({ const formCustom = ref<{ code: string, editor: CodeMirror.EditorFromTextArea | null }>({
code: code:
localStorage.getItem(`formCustomConfig`) localStorage.getItem(`formCustomConfig`)
|| removeLeft(` || removeLeft(`
@ -76,7 +77,7 @@ const formCustom = ref({
errCb(err) errCb(err)
}) })
`).trim(), `).trim(),
editor: undefined, editor: null,
}) })
const options = [ const options = [
@ -116,7 +117,7 @@ const options = [
const imgHost = ref(`default`) const imgHost = ref(`default`)
const formCustomElInput = ref(null) const formCustomElInput = ref<(HTMLInputElement & { $el: HTMLElement }) | null>(null)
const activeName = ref(`upload`) const activeName = ref(`upload`)
watch( watch(
@ -124,12 +125,10 @@ watch(
async (val) => { async (val) => {
if (val === `formCustom`) { if (val === `formCustom`) {
nextTick(() => { nextTick(() => {
const textarea = formCustomElInput.value.$el.querySelector(`textarea`) const textarea = formCustomElInput.value!.$el.querySelector(`textarea`)!
formCustom.value.editor formCustom.value.editor ||= CodeMirror.fromTextArea(textarea, {
= formCustom.value.editor mode: `javascript`,
|| CodeMirror.fromTextArea(textarea, { })
mode: `javascript`,
})
// formCustom.value.editor.setValue(formCustom.value.code) // formCustom.value.editor.setValue(formCustom.value.code)
}) })
} }
@ -141,25 +140,25 @@ watch(
onBeforeMount(() => { onBeforeMount(() => {
if (localStorage.getItem(`githubConfig`)) { if (localStorage.getItem(`githubConfig`)) {
formGitHub.value = JSON.parse(localStorage.getItem(`githubConfig`)) formGitHub.value = JSON.parse(localStorage.getItem(`githubConfig`)!)
} }
// if (localStorage.getItem(`giteeConfig`)) { // if (localStorage.getItem(`giteeConfig`)) {
// formGitee.value = JSON.parse(localStorage.getItem(`giteeConfig`)) // formGitee.value = JSON.parse(localStorage.getItem(`giteeConfig`)!)
// } // }
if (localStorage.getItem(`aliOSSConfig`)) { if (localStorage.getItem(`aliOSSConfig`)) {
formAliOSS.value = JSON.parse(localStorage.getItem(`aliOSSConfig`)) formAliOSS.value = JSON.parse(localStorage.getItem(`aliOSSConfig`)!)
} }
if (localStorage.getItem(`txCOSConfig`)) { if (localStorage.getItem(`txCOSConfig`)) {
formTxCOS.value = JSON.parse(localStorage.getItem(`txCOSConfig`)) formTxCOS.value = JSON.parse(localStorage.getItem(`txCOSConfig`)!)
} }
if (localStorage.getItem(`qiniuConfig`)) { if (localStorage.getItem(`qiniuConfig`)) {
formQiniu.value = JSON.parse(localStorage.getItem(`qiniuConfig`)) formQiniu.value = JSON.parse(localStorage.getItem(`qiniuConfig`)!)
} }
if (localStorage.getItem(`minioConfig`)) { if (localStorage.getItem(`minioConfig`)) {
minioOSS.value = JSON.parse(localStorage.getItem(`minioConfig`)) minioOSS.value = JSON.parse(localStorage.getItem(`minioConfig`)!)
} }
if (localStorage.getItem(`imgHost`)) { if (localStorage.getItem(`imgHost`)) {
imgHost.value = localStorage.getItem(`imgHost`) imgHost.value = localStorage.getItem(`imgHost`)!
} }
}) })
@ -251,12 +250,12 @@ function saveQiniuConfiguration() {
} }
function formCustomSave() { function formCustomSave() {
const str = formCustom.value.editor.getValue() const str = formCustom.value.editor!.getValue()
localStorage.setItem(`formCustomConfig`, str) localStorage.setItem(`formCustomConfig`, str)
ElMessage.success(`保存成功`) ElMessage.success(`保存成功`)
} }
function beforeImageUpload(file) { function beforeImageUpload(file: File) {
// check image // check image
const checkResult = checkImage(file) const checkResult = checkImage(file)
if (!checkResult.ok) { if (!checkResult.ok) {
@ -277,7 +276,7 @@ function beforeImageUpload(file) {
return true return true
} }
function uploadImage(params) { function uploadImage(params: { file: any }) {
emit(`uploadImage`, params.file) emit(`uploadImage`, params.file)
} }
</script> </script>

View File

@ -1,4 +1,4 @@
<script setup> <script setup lang="ts">
import { onMounted, ref } from 'vue' import { onMounted, ref } from 'vue'
const loading = ref(true) const loading = ref(true)

View File

@ -2,9 +2,10 @@ import { ElLoading, ElMessage } from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue' import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'element-plus/dist/index.css' import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css' import 'element-plus/theme-chalk/dark/css-vars.css'
import type { App } from 'vue'
export default { export default {
install(app) { install(app: App<Element>) {
// app.use(ElementPlus, { size: `default` }) // app.use(ElementPlus, { size: `default` })
app.config.globalProperties.$loading = ElLoading.service app.config.globalProperties.$loading = ElLoading.service

View File

@ -173,7 +173,7 @@ async function qiniuUpload(file: File) {
const dir = path ? `${path}/` : `` const dir = path ? `${path}/` : ``
const dateFilename = dir + getDateFilename(file.name) const dateFilename = dir + getDateFilename(file.name)
const observable = qiniu.upload(file, dateFilename, token, {}, { region }) const observable = qiniu.upload(file, dateFilename, token, {}, { region })
return new Promise((resolve, reject) => { return new Promise<string>((resolve, reject) => {
observable.subscribe({ observable.subscribe({
next: (result) => { next: (result) => {
console.log(result) console.log(result)
@ -229,7 +229,7 @@ async function txCOSFileUpload(file: File) {
SecretId: secretId, SecretId: secretId,
SecretKey: secretKey, SecretKey: secretKey,
}) })
return new Promise((resolve, reject) => { return new Promise<string>((resolve, reject) => {
cos.putObject( cos.putObject(
{ {
Bucket: bucket, Bucket: bucket,
@ -277,7 +277,7 @@ async function minioFileUpload(content: string, filename: string) {
if (isCustomPort) { if (isCustomPort) {
conf.port = p conf.port = p
} }
return new Promise((resolve, reject) => { return new Promise<string>((resolve, reject) => {
const minioClient = new Minio.Client(conf) const minioClient = new Minio.Client(conf)
try { try {
minioClient.putObject(bucket, dateFilename, buffer, (e) => { minioClient.putObject(bucket, dateFilename, buffer, (e) => {
@ -309,7 +309,7 @@ async function formCustomUpload(content: string, file: File) {
${localStorage.getItem(`formCustomConfig`)} ${localStorage.getItem(`formCustomConfig`)}
} }
` `
return new Promise((resolve, reject) => { return new Promise<string>((resolve, reject) => {
const exportObj = { const exportObj = {
content, // 待上传图片的 base64 content, // 待上传图片的 base64
file, // 待上传图片的 file 对象 file, // 待上传图片的 file 对象

View File

@ -253,10 +253,10 @@ export function createTable({ data, rows, cols }: { data: { [k: string]: string
} }
export function toBase64(file: Blob) { export function toBase64(file: Blob) {
return new Promise((resolve, reject) => { return new Promise<string>((resolve, reject) => {
const reader = new FileReader() const reader = new FileReader()
reader.readAsDataURL(file) reader.readAsDataURL(file)
reader.onload = () => resolve((reader.result as string).split(`,`).pop()) reader.onload = () => resolve((reader.result as string).split(`,`).pop()!)
reader.onerror = error => reject(error) reader.onerror = error => reject(error)
}) })
} }

View File

@ -1,7 +1,8 @@
<script setup> <script setup lang="ts">
import type { ComponentPublicInstance } from 'vue'
import { onMounted, ref, toRaw, watch } from 'vue' import { onMounted, ref, toRaw, watch } from 'vue'
import { storeToRefs } from 'pinia' import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus' import { ElCol, ElMessage } from 'element-plus'
import CodeMirror from 'codemirror' import CodeMirror from 'codemirror'
import fileApi from '@/utils/file' import fileApi from '@/utils/file'
@ -45,28 +46,29 @@ const {
} = store } = store
const isImgLoading = ref(false) const isImgLoading = ref(false)
const timeout = ref(0) const timeout = ref<NodeJS.Timeout>()
const preview = ref(null) const preview = ref<typeof ElCol | null>(null)
// 使 // 使
function leftAndRightScroll() { function leftAndRightScroll() {
const scrollCB = (text) => { const scrollCB = (text: string) => {
let source, target let source: HTMLElement
let target: HTMLElement
clearTimeout(timeout.value) clearTimeout(timeout.value)
if (text === `preview`) { if (text === `preview`) {
source = preview.value.$el source = preview.value!.$el
target = document.querySelector(`.CodeMirror-scroll`) target = document.querySelector<HTMLElement>(`.CodeMirror-scroll`)!
editor.value.off(`scroll`, editorScrollCB) editor.value!.off(`scroll`, editorScrollCB)
timeout.value = setTimeout(() => { timeout.value = setTimeout(() => {
editor.value.on(`scroll`, editorScrollCB) editor.value!.on(`scroll`, editorScrollCB)
}, 300) }, 300)
} }
else if (text === `editor`) { else {
source = document.querySelector(`.CodeMirror-scroll`) source = document.querySelector<HTMLElement>(`.CodeMirror-scroll`)!
target = preview.value.$el target = preview.value!.$el
target.removeEventListener(`scroll`, previewScrollCB, false) target.removeEventListener(`scroll`, previewScrollCB, false)
timeout.value = setTimeout(() => { timeout.value = setTimeout(() => {
@ -89,8 +91,8 @@ function leftAndRightScroll() {
scrollCB(`preview`) scrollCB(`preview`)
} }
preview.value.$el.addEventListener(`scroll`, previewScrollCB, false) (preview.value!.$el).addEventListener(`scroll`, previewScrollCB, false)
editor.value.on(`scroll`, editorScrollCB) editor.value!.on(`scroll`, editorScrollCB)
} }
onMounted(() => { onMounted(() => {
@ -120,7 +122,7 @@ function endCopy() {
}, 800) }, 800)
} }
function beforeUpload(file) { function beforeUpload(file: File) {
// validate image // validate image
const checkResult = checkImage(file) const checkResult = checkImage(file)
if (!checkResult.ok) { if (!checkResult.ok) {
@ -142,20 +144,20 @@ function beforeUpload(file) {
} }
// //
function uploaded(imageUrl) { function uploaded(imageUrl: string) {
if (!imageUrl) { if (!imageUrl) {
ElMessage.error(`上传图片未知异常`) ElMessage.error(`上传图片未知异常`)
return return
} }
toggleShowUploadImgDialog(false) toggleShowUploadImgDialog(false)
// //
const cursor = editor.value.getCursor() const cursor = editor.value!.getCursor()
const markdownImage = `![](${imageUrl})` const markdownImage = `![](${imageUrl})`
// Markdown URL // Markdown URL
toRaw(store.editor).replaceSelection(`\n${markdownImage}\n`, cursor) toRaw(store.editor!).replaceSelection(`\n${markdownImage}\n`, cursor as any)
ElMessage.success(`图片上传成功`) ElMessage.success(`图片上传成功`)
} }
function uploadImage(file, cb) { function uploadImage(file: File, cb?: { (url: any): void, (arg0: unknown): void } | undefined) {
isImgLoading.value = true isImgLoading.value = true
toBase64(file) toBase64(file)
@ -176,7 +178,7 @@ function uploadImage(file, cb) {
}) })
} }
const changeTimer = ref(0) const changeTimer = ref<NodeJS.Timeout>()
// //
watch(isDark, () => { watch(isDark, () => {
@ -186,7 +188,7 @@ watch(isDark, () => {
// //
function initEditor() { function initEditor() {
const editorDom = document.querySelector(`#editor`) const editorDom = document.querySelector<HTMLTextAreaElement>(`#editor`)!
if (!editorDom.value) { if (!editorDom.value) {
editorDom.value = editorContent.value editorDom.value = editorContent.value
@ -200,7 +202,7 @@ function initEditor() {
autoCloseBrackets: true, autoCloseBrackets: true,
extraKeys: { extraKeys: {
[`${shiftKey}-${altKey}-F`]: function autoFormat(editor) { [`${shiftKey}-${altKey}-F`]: function autoFormat(editor) {
formatDoc(editor.getValue(0)).then((doc) => { formatDoc(editor.getValue()).then((doc) => {
editor.setValue(doc) editor.setValue(doc)
}) })
}, },
@ -241,7 +243,7 @@ function initEditor() {
}) })
// //
editor.value.on(`paste`, (cm, e) => { editor.value.on(`paste`, (_cm, e) => {
if (!(e.clipboardData && e.clipboardData.items) || isImgLoading.value) { if (!(e.clipboardData && e.clipboardData.items) || isImgLoading.value) {
return return
} }
@ -249,7 +251,7 @@ function initEditor() {
const item = e.clipboardData.items[i] const item = e.clipboardData.items[i]
if (item.kind === `file`) { if (item.kind === `file`) {
// //
const pasteFile = item.getAsFile() const pasteFile = item.getAsFile()!
const isValid = beforeUpload(pasteFile) const isValid = beforeUpload(pasteFile)
if (!isValid) { if (!isValid) {
continue continue
@ -263,33 +265,34 @@ function initEditor() {
const container = ref(null) const container = ref(null)
// //
function addFormat(cmd) { function addFormat(cmd: string | number) {
editor.value.options.extraKeys[cmd](editor.value) (editor.value as any).options.extraKeys[cmd](editor.value)
} }
const codeMirrorWrapper = ref(null) const codeMirrorWrapper = ref<ComponentPublicInstance<typeof ElCol> | null>(null)
// markdown 线 // markdown 线
// todo // todo
function mdLocalToRemote() { function mdLocalToRemote() {
const dom = codeMirrorWrapper.value.$el const dom = codeMirrorWrapper.value!.$el as HTMLElement
console.log(`dom`, dom)
// md // md
const uploadMdImg = async ({ md, list }) => { const uploadMdImg = async ({ md, list }: { md: { str: string, path: string, file: File }, list: { path: string, file: File }[] }) => {
const mdImgList = [ const mdImgList = [
...(md.str.matchAll(/!\[(.*?)\]\((.*?)\)/g) || []), ...(md.str.matchAll(/!\[(.*?)\]\((.*?)\)/g) || []),
].filter((item) => { ].filter((item) => {
return item // return item //
}) })
const root = md.path.match(/.+?\//)[0] const root = md.path.match(/.+?\//)![0]
const resList = await Promise.all( const resList = await Promise.all<{ matchStr: string, url: string }>(
mdImgList.map((item) => { mdImgList.map((item) => {
return new Promise((resolve) => { return new Promise((resolve) => {
let [, , matchStr] = item let [, , matchStr] = item
matchStr = matchStr.replace(/^.\//, ``) // 处理 ./img/ img/ 统一相对路径风格 matchStr = matchStr.replace(/^.\//, ``) // 处理 ./img/ img/ 统一相对路径风格
const { file } const { file }
= list.find(f => f.path === `${root}${matchStr}`) || {} = list.find(f => f.path === `${root}${matchStr}`) || {}
uploadImage(file, (url) => { uploadImage(file!, (url) => {
resolve({ matchStr, url }) resolve({ matchStr, url })
}) })
}) })
@ -300,16 +303,16 @@ function mdLocalToRemote() {
.replace(`](./${item.matchStr})`, `](${item.url})`) .replace(`](./${item.matchStr})`, `](${item.url})`)
.replace(`](${item.matchStr})`, `](${item.url})`) .replace(`](${item.matchStr})`, `](${item.url})`)
}) })
editor.value.setValue(md.str) editor.value!.setValue(md.str)
} }
dom.ondragover = evt => evt.preventDefault() dom.ondragover = evt => evt.preventDefault()
dom.ondrop = async (evt) => { dom.ondrop = async (evt: any) => {
evt.preventDefault() evt.preventDefault()
for (const item of evt.dataTransfer.items) { for (const item of evt.dataTransfer.items) {
item.getAsFileSystemHandle().then(async (handle) => { item.getAsFileSystemHandle().then(async (handle: { kind: string, getFile: () => any }) => {
if (handle.kind === `directory`) { if (handle.kind === `directory`) {
const list = await showFileStructure(handle) const list = await showFileStructure(handle) as { path: string, file: File }[]
const md = await getMd({ list }) const md = await getMd({ list })
uploadMdImg({ md, list }) uploadMdImg({ md, list })
} }
@ -322,14 +325,14 @@ function mdLocalToRemote() {
} }
// md // md
async function getMd({ list }) { async function getMd({ list }: { list: { path: string, file: File }[] }) {
return new Promise((resolve) => { return new Promise<{ str: string, file: File, path: string }>((resolve) => {
const { path, file } = list.find(item => item.path.match(/\.md$/)) const { path, file } = list.find(item => item.path.match(/\.md$/))!
const reader = new FileReader() const reader = new FileReader()
reader.readAsText(file, `UTF-8`) reader.readAsText(file!, `UTF-8`)
reader.onload = (evt) => { reader.onload = (evt) => {
resolve({ resolve({
str: evt.target.result, str: evt.target!.result as string,
file, file,
path, path,
}) })
@ -338,7 +341,7 @@ function mdLocalToRemote() {
} }
// //
async function showFileStructure(root) { async function showFileStructure(root: any) {
const result = [] const result = []
let cwd = `` let cwd = ``
try { try {
@ -385,7 +388,7 @@ onMounted(() => {
/> />
<main class="container-main flex-1"> <main class="container-main flex-1">
<el-row class="container-main-section h-full border-1"> <el-row class="container-main-section h-full border-1">
<el-col <ElCol
ref="codeMirrorWrapper" ref="codeMirrorWrapper"
:span="isShowCssEditor ? 8 : 12" :span="isShowCssEditor ? 8 : 12"
class="codeMirror-wrapper border-r-1" class="codeMirror-wrapper border-r-1"
@ -427,8 +430,8 @@ onMounted(() => {
</ContextMenuItem> </ContextMenuItem>
</ContextMenuContent> </ContextMenuContent>
</ContextMenu> </ContextMenu>
</el-col> </ElCol>
<el-col <ElCol
id="preview" id="preview"
ref="preview" ref="preview"
:span="isShowCssEditor ? 8 : 12" :span="isShowCssEditor ? 8 : 12"
@ -445,7 +448,7 @@ onMounted(() => {
</div> </div>
</div> </div>
</div> </div>
</el-col> </ElCol>
<CssEditor /> <CssEditor />
</el-row> </el-row>
</main> </main>