Electron实现MarkDown编辑器

558 阅读2分钟

Electron实现Markdown编辑器

封面

工具介绍

  • Electron: 用于构建跨平台的桌面应用程序
  • Vite: 提供快速的开发启动和热重载
  • TypeScript: 提供类型检查和编译时静态分析
  • React:构建用户界面的JavaScript库
  • CodeMirror:在网页实现可定制的代码编辑体验
  • react-markdown:专门渲染Markdown的React组件

脚手架

vite-electron-builder 使用这个模板 进入工作目录 enter 安装依赖 依赖 运行 npm run watch 样板

从Vue切换到React

装包

npm uninstall @vitejs/plugin-vue @vue/compiler-sfc eslint-plugin-vue vue vue-router vue-tsc
npm i react@18.2.0 react-dom@18.2.0
npm i -D @types/react @types/react-dom # 作为开发依赖项,在ts中获得React和 ReactDOM的类型支持
npm i -D eslint eslint-config-prettier @typescript-eslint/eslint-plugin @typescript-eslint/parser

配置eslint, prettier, typescript

eslintrc.json配置eslint eslintrc packages\renderer\tsconfig.json配置typescript 在这里插入图片描述 创建prettire.config.js文件 代码格式化工具

配置Vite

挪走vue remove remove 使用React Hello 使用 效果 记得写上两个css

窗口模糊

依赖

VS的依赖 npm install electron-acrylic-window 安装成功

效果

效果

集成 codemirror6

在网页中创建和编辑代码编辑器的 JavaScript 库

npm install @codemirror/state @codemirror/commands  @codemirror/view 
npm install @codemirror/language @codemirror/language-data @codemirror/lang-javascript @codemirror/lang-markdown
npm install @codemirror/theme-one-dark @lezer/highlight

use-codemirror

import {useEffect, useState, useRef} from 'react';
import {EditorState} from '@codemirror/state';
import {EditorView,keymap, highlightActiveLine,lineNumbers, highlightActiveLineGutter} from '@codemirror/view';
import {defaultKeymap, history, historyKeymap}  from '@codemirror/commands';
import {indentOnInput,bracketMatching, HighlightStyle, syntaxHighlighting} from '@codemirror/language';
import { tags} from '@lezer/highlight';
import { javascript } from '@codemirror/lang-javascript';
import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
import { languages } from '@codemirror/language-data';
import { oneDark } from '@codemirror/theme-one-dark'
import type React from 'react'
export const transparentTheme = EditorView.theme({
    '&': {
      backgroundColor: 'rgba(0,0,0,0.7) !important',
      height: '100%'
    }
  })
  const myHighLightStyle = HighlightStyle.define([
    {tag: tags.heading1, color: '#f07178', fontWeight: 'bold', fontSize: '1.6em'},
    {tag: tags.heading2, color: '#f07178', fontWeight: 'bold', fontSize: '1.4em'},
    {tag: tags.heading3, color: '#f07178', fontWeight: 'bold', fontSize: '1.2em'}
  ]);
interface Props{
    initialDoc: string,
    onChange?: (state: EditorState)=>void
  }
  
  const useCodeMirror = < T extends Element>(
  props: Props
  ): [React.MutableRefObject<T | null> , EditorView?]=>{
    const refContainer = useRef<T>(null)
    const [editorView,setEditorView] = useState<EditorView>()
    const { onChange } = props
  
    useEffect(()=>{
      if(!refContainer.current) return
      const startState = EditorState.create({
       doc: props.initialDoc,
       extensions: [
          keymap.of(Array.prototype.concat(defaultKeymap , historyKeymap)),
          lineNumbers(),
          highlightActiveLineGutter(),
          history(),
          bracketMatching(),
          syntaxHighlighting(myHighLightStyle),
          indentOnInput(),
          highlightActiveLine(),
          markdown({
            base: markdownLanguage,
            codeLanguages: languages,
            addKeymap: true
          }),
          oneDark,
          transparentTheme,
          javascript(),
          EditorView.lineWrapping,
          EditorView.updateListener.of(update=>{
            if(update.changes){
              onChange && onChange(update.state)
            }
          })
       ]
      })
      const view = new EditorView({
        state: startState,
        parent: refContainer.current
      })
      setEditorView(view)
    },[refContainer])
    return [refContainer,editorView]
  }
  export default useCodeMirror
  

editor

import React, {useCallback,useEffect} from 'react'
import useCodeMirror from './use-codemirror'
import { EditorState } from '@codemirror/state'
interface Props {
  initialDoc: string,
  onChange: (doc: string) => void
}
const Editor: React.FC<Props> = (props) => {
  const { onChange, initialDoc } = props
  const handleChange = useCallback(
    (state: EditorState) => onChange(state.doc.toString()),
    [onChange]
  )
  const [ refContainer, editorView]  = useCodeMirror<HTMLDivElement>({
    initialDoc: initialDoc,
    onChange: handleChange
  })

  useEffect(()=>{
    if(editorView) {
      // Do nothing for now
    }
  },[editorView])
  return <div className='editor-wrapper' ref={refContainer}></div>
}
export default Editor

app

import React , {FC,useState,useCallback} from 'react'
import './app.css'
import Editor from './editor'
const App: FC = () => {
    const [doc,setDoc]=useState<string>('# Hello World!\n')
    const handleDocChange = useCallback((newDoc:string)=>{
        setDoc(newDoc)
    },[])
    return (
        <div className='app'>
            <Editor onChange={handleDocChange} initialDoc={doc}/>
        </div>
    )
}  
export default App

效果

编辑器收工

预览组件

npm i react-markdown 调整

预览样式-添加代码的高亮

npm i react-syntax-highlighter
npm i @types/react-syntax-highlighter

添加样式 效果 很好

功能扩展-插件的使用

npm i remark-gfm

插件1

效果 效果

打包

npm run compile

我的应用 代码提交,跳过代码检查 跳过代码检查 github地址

收工

作为结束