Introduction to the

Markdown is a markdown editor developed using marked and highlight.js. In addition to the usual Markdown syntax, it supports quick input, image paste, code copy, full-screen editing, preview, and other functions.

It’s easy to use, just a few lines of code, to introduce a Markdown editor to your page, with editing area support like a professional editor.

The editor covers common Markdown editor functions and can be configured through existing properties, basic configuration of editor functions and styles, and in-depth customization as required.

The project address

The document address

The sample

The characteristics of

  • Easy to use, only need to install the NPM package, import the project can use, do not need tedious initial configuration.
  • Supports common function configurations and in-depth customization based on actual requirements.
  • Small and fast to load, the NPM package removes dependencies in highlight.js and Codemirror.
  • Flexible themes that support four code block styles by default, or can be customized according to actual needs
  • Powerful, professional edition editor support, using Codemirror for editing window, markdown syntax recognition
  • Keyboard event monitoring, such as save, paste, enter the last input syntax judgment
  • Strong scalability, in addition to providing the attribute configuration editor, but also directly on the basis of the original components for secondary development

Implementation approach

The input Markdown syntax is compiled in real time and rendered to the preview area by listening for changes in the text input area.

The editor is roughly divided into three parts: the header menu bar, the content input area on the left and the preview area on the right. The header menu is mainly a customized title area and a menu button. The menu button can be displayed and hidden through the configuration file. The left editing area is developed using Textarea to meet basic requirements for the simple version and codemirror for the professional version. The editing area supports manual text input and insertion through the header menu. The preview area on the right can preview the input text in real time, and the edit area and preview area can be switched through the menu button.

installation

Install using NPM

  1. Install dependencies
npm i -S vue-meditor
Copy the code

Copy components into your project

  1. Pull git repository code locally
git clone https://github.com/zhaoxuhui1122/vue-markdown.git
Copy the code
  1. Copy the contents from the SRC folder to the Components folder

Used in the project

NPM package installation

Simple version of

import Markdown from 'vue-meditor'
Copy the code

pro

import { MarkdownPro } from 'vue-meditor'
Copy the code

Preview component

import { MarkdownPreview } from 'vue-meditor'
Copy the code

Copying components locally (recommended)

Simple version of

import Markdown from '@/components/markdown/... ';
Copy the code

pro

import MarkdownPro from '@/components/markdown/pro';
Copy the code

Preview component

import MarkdownPreview from '@/components/markdown/preview';
Copy the code

Use within the page

<template>
    <div class="markdown">
        <Markdown/>
    </div>
</template>

<script>
    import Markdown from 'vue-meditor';
    
    export default {
        name: "markdown",
        components: {
            Markdown
        }
    }
</script>
Copy the code

API

Editor basic properties

value

  • Type: String/Number
  • Default: ' '

Text entered by the editor, with support for setting the editor content and getting the editor’s value via v-dodel data bidirectional binding.

width

  • Type: String/Number
  • Default: auto

The initialization width of the editor.

height

  • Type: Number
  • Default: 600

Initialization height of the editor.

bordered

  • Type: Boolean
  • Default: true

Whether the editor contains borders.

toolbars

  • Type: Object
  • Default: See the table below

The head menu button is controlled by setting true or false to decide whether to display it or not. The current configuration supports the display and hiding of the control button, and the subsequent configuration will support the display and ordering.

The name of the instructions Default display
strong The bold is
italic italics is
overline Delete the line is
h1 Title 1 is
h2 Title 2 is
h3 Title 3 is
h4 The title 4 no
h5 Title 5 no
h6 The title 6 no
hr The divider is
quote reference is
ul Unordered list is
ol An ordered list is
code The code block is
link link is
image image is
table form is
checked Completed list is
notChecked Unfinished list is
preview preview is
split The split screen mode is switched is
print print no
theme Subject switch is
fullscreen Full screen is
exportmd Export the file as *.md is
importmd Import the local *. Md file is
save Save button no
clear Empty content no

theme

  • Type: String
  • Default: light

Editor code block theme, currently support light, dark, oneDark, gitHub four code block styles, you can customize the theme and modify the style file.

When you customize a theme, you will add a class for markdown-theme-[theme] to the preview area.

autoSave

  • Type: Boolean
  • Default: false

Whether to enable auto-save, set to enable the binding of on-save events to get values and code block topics in the editor.

<Markdown @on-save="handleOnSave"/>
Copy the code
 handleOnSave({value, theme}){
        console.log(value, theme);
    }
Copy the code

interval

  • Type: Number
  • Default: 10000

AutoSave interval (unit: mm). The default value is 10000mm. This parameter is valid only when autoSave is set to true.

exportFileName

  • Type: String
  • Default: unnamed

The exported MD file name, default is dingle.md.

markedOptions

  • Type: Object
  • Default: {}

Marked Indicates the configuration item, which can be customized based on requirements.

<Markdown :markedOptions="{baseUrl:'http://***.oss-cn-shanghai.aliyuncs.com/'}"/>
Copy the code

isPreview

  • Type: Boolean
  • Default: false

Whether it is in preview mode, the function of the preview component is the same as that of the preview component.

copyCode

  • Type: Boolean
  • Default: true

Whether copying the contents of a code block is supported.

copyBtnText

  • Type: String
  • Default: Copy the code

Copy code button to display text.

Preview basic component properties

initialValue

  • Type: String/Number
  • Default: ' '

Preview component initializes content and supports dynamic updates.

theme

  • Type: String
  • Default: light

Code block theme, consistent with the editor editor code block theme.

markedOptions

  • Type: Object
  • Default: {}

Marked Indicates the configuration item, consistent with the configuration in the editor.

copyCode

  • Type: Boolean
  • Default: true

Whether copying the contents of a code block is supported.

copyBtnText

  • Type: String
  • Default: Copy the code

Copy code button to display text.

on-ready

Fired when editor initialization is complete and returns a value of Object, including the component itself and the insertContent method.

on-save

Editor save event, automatic save or manual save triggered, support CTRL + S or Command + S trigger save, return value type is Object, including the current input value value and the selected code block theme.

on-paste-image

Monitor editor paste image event, triggered when manually pasting images in the editing area, can be used to support paste and insert image files, return file files, upload files can be combined with insertContent returned in on-Ready event to insert images.

on-copy

Copy the contents of the code block, which returns the text of the current code block when triggered, only valid when copyCode is turned on.

Secondary development

Paste and insert picture

On-paste -image supports listening for image paste events, but does not handle the logic of uploading images to the server and inserting links into the editor.

Currently, if you want to support paste and insert images, you need to upload the image file in the on-paste-image method, and then use the insertContent method returned in the on-ready method to insert the image.

The above operation is too complicated, you can extend the handlePaste method in mixins directly in the source code. After uploading the image, you can call this.insertContent directly to insert the image.

Modify/markdown/mixins/common. Js

handlePaste(_, e) {// Paste the image
    const { clipboardData = {} } = e;
    const { types = [], items } = clipboardData;
    let item = null;
    for (let i = 0; i < types.length; i++) {
        if (types[i] === 'Files') {
            item = items[i];
            break; }}if (item) {
        const file = item.getAsFile();
        if (/image/gi.test(file.type)) {
            e.preventDefault();
            // 1. Upload operation
            // 2. Insert the image this.insertContent('! [image](imgUrl)`)}}}Copy the code

Supports flowchart and Gantt chart syntax

At present, the editor only supports common code syntax. If functions such as flow chart need to be implemented, it needs to be further extended. Taking a simple flow chart as an example, the specific implementation ideas are as follows:

By default, Markedjs parses the incoming code block using the renderer.code method and supports syntax highlighting with highlight.js. Flowsheet syntax can be input into code blocks with notations of language; code parsing method of marked.Renderer can be rewritten; flowchart flowchart can be parsed with flowchart flowchart flowchart code and return text content.

Modify ` / markdown/libs/js/simple. Js

import hljs from './hljs';
import index from 'index';
import {parse} from 'flowchart.js'

hljs.initHighlightingOnLoad();

const renderer = new index.Renderer();
renderer.code = (code, language) = > {
    if (language === 'flow') {/ / process flow diagram
        const dom = document.createElement('div');
        const flowchart = parse(code);
        flowchart.drawSVG(dom, {/* Related configuration */});
        return  dom.innerHTML;
    } else {// Default resolution
        return `<pre class="hljs"><code class="${language}">${hljs.highlightAuto(code).value}</code></pre>`}}export default index.setOptions({
    renderer,
    gfm: true.tables: true.breaks: false.pedantic: false.sanitize: false.smartLists: true.highlight: function (code) {
        returnhljs.highlightAuto(code).value; }})Copy the code

Custom Markdown syntax conversions

The ‘index.js’ used in the project is its default configuration function. If special transformation is required, the internal parsing method can be overwritten, that is, the renderer-related method reference document can be overwritten.

Automatically generate document directories

The preview area and the document preview component do not support automatic directory generation

  • rewriterenderer.headingMethod to add an ID to the generated title by entering a specific shortcut key, such as[TOC]Find all title labels in the preview area, analyze the hierarchical relationship, and generate directory labels

Icon to replace

Please refer to /assets/font/index.html for all ICONS and names in the project. Please note that the checkbox in the preview area is icon. Change the :after style of input[type=”checkbox”] in /assets/ CSS /index.less.

Code volume optimization

Common code extraction

When the NPM package is built, the three components are completely independent and not separated from the public file, so when two or three of the components are introduced in the same project, there is some duplication of code, mainly for highlight. Js, marked, iconfont, CSS styles.

Workaround: Copy components to your local project and pull these files out as public files when you package.

Note: The iconfont used in the three components is the same. If you simply use the Preview component, it will introduce the iconfont used in the whole project. You can delete the introduction of iconFONT and rewrite the input[type=”checkbox”] style. Preview component volume will be reduced by half, the style file is located in the markdown/assets/CSS/index. The less.

Codemirror volume optimization

Codemirror main points is given priority to, mode related documents and the style file, master file unusually large size, mode file now only use CSS/five jsvascript/markdown/meta/XML documents, including markdown. Js and meta. Js for must be referenced, Common programming language code styles have been defined in the project as one of CSS/JS/XML, such as less/sass/ SCSS parsed according to CSS rules and HTML /vue parsed according to XML rules. Optimization can start from the following aspects

  • Reduce the codemirror main file size
  • Reduce the mode dependency of references

Highlight.js volume optimization

Highlight.js is also large in size, mainly because parsing files are introduced during compilation to support various code languages. The project has been filtered according to common code languages and imported as needed

See the SRC/markdown/libs/js/HLJS js, currently supported languages

import hljs from 'highlight.js/lib/highlight'

import javascript from 'highlight.js/lib/languages/javascript'
import java from 'highlight.js/lib/languages/java';
import css from 'highlight.js/lib/languages/css';
import less from 'highlight.js/lib/languages/less';
import go from 'highlight.js/lib/languages/go';
import markdown from src;
import php from 'highlight.js/lib/languages/php';
import python from 'highlight.js/lib/languages/python';
import ruby from 'highlight.js/lib/languages/ruby';
import stylus from 'highlight.js/lib/languages/stylus';
import typescript from 'highlight.js/lib/languages/typescript';
import xml from 'highlight.js/lib/languages/xml';

const languages = {
    javascript,
    java,
    css,
    less,
    markdown,
    go,
    php,
    python,
    ruby,
    stylus,
    typescript,
    xml
}
Object.keys(languages).forEach(key= > {
    hljs.registerLanguage(key, languages[key])
})

export default hljs;
Copy the code

Professional edition editor codemirror/simple.js

Optimization idea: None

Iconfont volume optimization

Avoid introducing all ICONS when you only need the Preview component and refer to the icon replacement method in the feature extensions.

Upgrade path

  • The normal edition editor operates on selected text
  • Document catalog function
  • Optimize the volume of the Pro editor
  • The react edition development
  • .

The problem of feedback

You can raise Issues about functional defects, usage methods, and functions that you want to expand.