Zero base exclusive Markdown online editor development

Online case

Markdown is also a markup language, similar to HTML, not CSS. We usually use and see Markdown editor (Typora, etc.) display styles are converted to HTML, plus the built-in style CSS display;

But now, Markdown writing + HTML display is no longer limited to client writing, more and more favored by all kinds of websites, especially blog/forum websites, such as gold nuggets community, CSDN, blog Park, etc. What these sites have in common is the ability for authors to write and edit articles online, and basically follow the Markdown writing + HTML presentation model.

1. Markdown and HTML

1) Name difference

HTML full name hypertext Markup Language (hypertext Markup Language), which focuses on the word markup, translated into markup;

Markdown is the opposite of markup, so we can temporarily understand the meaning of markdown.

2) Functional differences

HTML focuses on the presentation of content, including form, style, format, etc. For a page user, as long as the page display is beautiful enough, will not focus on the simple or complex source code; Simple HTML can display basic styles of content, such as H1, H2… headings, and so on, along with CSS styles to make the content more elegant.

Markdown pays more attention to the way of writing content (source code) and rules. Simple and efficient writing and rules make users get twice the result with half the effort. Therefore, Markdown’s primary users are content producers, such as document writers, etc.

2, Markdown to HTML

The principle of Markdown conversion to HTML is not difficult. Essentially, it is a string conversion, such as identifying the MD content to the # level 1 header, determining that it starts with # # Spaces and ends with \n newlines, corresponding to the HTML string content generated by the < H1 > level 1 header
. Of course, the actual conversion of all formats is far more complicated than I have described. For example, the principles and production drawings of nuclear bombs are already publicly available, but there are only a few countries that can build them.

There are already a lot of Markdown to HTML libraries, so we can skip the wheel and just stand on the shoulders of giants. The implementation of the MD online editor described in this article uses the technologies Vite+Vue3+TypeScript+ Markedjs

First look at the results :(online editing + save + change theme, etc.)

! [image-20220224114821238](/Users/haolian/Library/Application Support/typora-user-images/image-20220224114821238.png)

1) marked. Js

Back to this article, after a brief investigation, I finally chose to use marked. Js to convert Markdown to HTML. Install and use the same way as most Node libraries:

/ / installation
npm install marked
// Import (ES module)
import { marked } from "marked";
// Use mdStr: markdown text data, HTML: converted HTML text data
let html = marked.parse(mdStr)
Copy the code

2) Markdown to HTML display

1. Define the md2HTML function

// mdParser.ts
import { marked } from "marked";

export async function md2html(mdStr: string) {
    let html = await marked.parse(mdStr)
    return html;
}
Copy the code

2. Online HTML Content Rendering (V-HTML)

Marked converts MD to HTML, then uses V-HTML to bind the converted htmlValue to the defined DIV, and a simple MD to HTML renders the page online.

// mdEditor. Vue <template> ··· <div class="markdown "id="markdown" V-html ="htmlValue"></div> </template> <script Lang ='ts'> ··· import {md2html} from '.. /utils/mdParser'; ··· export default defineComponent({setup() {··· · let mdValue = ref<string>(''); let htmlValue = ref<string>(''); ·· htmlValue.value = await md2html(mdValue.value); return { htmlValue } } }) </script>Copy the code

3) MD online editing and HTML real-time rendering

  • Dividing the page area:MD editor area(Textarea implementation),HTML rendering area– HTML (v);
  • Listening to theMD editor areaData changes, real-time updatesHTML rendering area;
// mdEditor. Vue <template> ··· <div class="editor-area"> ··· <div class="m-text"> <a-textarea id="text-area" class="m-textarea boxshadow" v-model:value="mdValue" style="padding: 10px" /> </div> ···· <div class=" m-LR boxshadow"> <div class="markdown-body" id="markdown" V-html ="htmlValue"></div> < / div >... < / div >... < / template > < script lang = 'ts' >... import {md2html} from'.. /utils/mdParser'; ··· export default defineComponent({setup() {··· · let mdValue = ref<string>(''); let htmlValue = ref<string>(''); ··· watch([mdValue], async () => {let md = await md2html(mdValue.value); htmlValue.value = md; }); return { htmlValue, mdValue } } }) </script>Copy the code

4) Change the MD theme

The theme is actually a series of CSS styles that apply to various elements in the MD-to-HTML format. I’m going to be lazy here and borrow some of the theme directly from the nuggets; Open the source code of the article, we can see that the Denver MD area has made an obvious distinction, comparing all topics, we found that the CLASS of the MD area is written as markdown-body, and the CSS style of the relevant topic is directly placed under the DOM, which is very convenient for us to refer to 😂

The specific reference is as follows:

  • To find the gold digger articleMD Render area(red box);
  • Copy the style in the style TAB (green box);
  • The theme CSS styles are stored in the database for easy retrieval, replacement, and rendering.

Of course, if you have the time and energy to write the theme style directly, it is not advisable to borrow from me like this.

The final success is shown as follows:

Directly on the code:

<div class="m-b"> <a-select style="margin-right: 10px; width: 200px" V-model :value="selectTheme" :options="options" ></a-select> </div> ···· <div class="editor-area"> ··· <a-textarea  id="text-area" class="m-textarea boxshadow" v-model:value="mdValue" style="padding: 10px" /> ··· <div class=" M-LR boxshadow"> <div class="markdown-body" id="markdown" V-html ="htmlValue"></div> </div> ··· </div> </a-card> </template> <script lang='ts'> ··· import {defineComponent, onMounted, reactive, ref, watch } from 'vue'; import { md2html } from '.. /utils/mdParser'; import { getAllTheme } from '.. /api/blog'; Export default defineComponent({··· setup() {··· let mdValue = ref<string>(''); let htmlValue = ref<string>(''); let selectTheme = ref<string>(''); let mdTitle = ref<string>(''); let options = reactive<Array<{ value: string; label: string }>>([]); Const getTheme = async () => {const theme: any = await getAllTheme(); theme.forEach((item) => { options.push({ label: item.theme, value: item.style, }); }); SelectTheme. Value = options[0]. Value; }; onMounted(getTheme); Watch ([mdValue, selectTheme], async () => {let md = await md2html(mdValue.value); htmlValue.value = selectTheme.value ? selectTheme.value + md : md; }); return { selectTheme, options, mdValue, htmlValue, mdTitle, chnageType, }; }}); </script>Copy the code

5) File preservation

Here use file-saver to save data in different formats. The specific use method is Baidu/Google look at the document, very simple!

conclusion

Through the above content is not hard to find, the original online editor is not difficult to develop a MD, on the one hand, thanks to strong and comprehensive front-end ecology, on the one hand, thanks to the excellent project of learning and using for reference, or just write a native MD parser is enough we drink a pot of, again go to customize various topics need various cost more, That’s enough to dissuade most developers.

Write last, benefit from The Times, will also feedback to The Times, you and I are practitioners!

See the last, feel that can move to praise, collect, pay attention to 😄, code word unceasingly, adhere to update!

Personal homepage: www.wawow.xyz