当前位置:网站首页>Analysis of the implementation principle of an open source markdown to rich text editor
Analysis of the implementation principle of an open source markdown to rich text editor
2022-07-03 09:32:00 【Technology stuff】
I usually write articles using Markdown
, However, some platforms do not support it when it is released Markdown
The situation of , Rearrangement is impossible , So they all use some Markdown
A tool for converting rich text , such as markdown-nice, If you use more, you will be curious about how it is realized , So there's this article .
markdown-nice
It's based on React
Projects built , Let's take a look at its overall page first :
A Top Toolbar , Three parallel areas in the middle , These are the editing areas 、 The preview area 、 Customize the theme area , The custom theme area is hidden by default .
It's basically a Markdown
Editor , Added some adaptations to various platforms .
Editor
The editor uses CodeMirror, Specifically, it is a secondary encapsulated component React-CodeMirror:
import CodeMirror from "@uiw/react-codemirror";
class App extends Component {
render() {
return (
<CodeMirror
value={this.props.content.content}
options={
{
theme: "md-mirror",// The theme
keyMap: "sublime",// Shortcut key
mode: "markdown",// Pattern , That is, the language type
lineWrapping: true,// Turn on extra long line feed
lineNumbers: false,// Don't show line numbers
extraKeys: {// Configure shortcut keys
...bindHotkeys(this.props.content, this.props.dialog),
Tab: betterTab,
RightClick: rightClick,
},
}}
onChange={this.handleThrottleChange}
onScroll={this.handleScroll}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
onDrop={this.handleDrop}
onPaste={this.handlePaste}
ref={this.getInstance}
/>
)
}
}
Copy code
Shortcut key 、 command
markdown-nice
adopt extraKeys
Option to set some shortcut keys , In addition, some shortcut buttons have been added to the toolbar :
The logic of these shortcut keys or command buttons to operate the text content is basically the same , Get the contents of the current selection first :
const selected = editor.getSelection()
Copy code
Then carry out machining modification :
`**${selected}**`
Copy code
Finally, replace the contents of the selection :
editor.replaceSelection(`**${selected}**`)
Copy code
In addition, you can modify the position of the cursor to improve the experience , For example, the cursor position will be behind the text after the bold operation , instead of *
The reason behind this is markdown-nice
After replacing the contents of the selected area, the cursor position is also modified :
export const bold = (editor, selection) => {
editor.replaceSelection(`**${selection}**`);
const cursor = editor.getCursor();
cursor.ch -= 2;// Two characters ahead of the cursor position
editor.setCursor(cursor);
};
Copy code
form
Markdown
The table grammar of is troublesome to write ,markdown-nice
For tables, it only provides the function of inserting table syntax symbols for you , You can enter the number of table rows and columns to insert :
The symbol will be automatically inserted after confirmation :
The implementation is actually a string splicing logic :
const text = this.buildFormFormat(this.state.rowNum, this.state.columnNum);
buildFormFormat = (rowNum, columnNum) => {
let formFormat = "";
// At least three rows will be created
for (let i = 0; i < 3; i++) {
formFormat += this.buildRow(i, columnNum);
}
// More than three lines
for (let i = 3; i <= rowNum; i++) {
formFormat += this.buildRow(i, columnNum);
}
return formFormat;
};
buildRow = (rowNum, columnNum) => {
let appendText = "|";
// The first line is the separation of header and content
if (rowNum === 1) {
appendText += " --- |";
for (let i = 0; i < columnNum - 1; i++) {
appendText += " --- |";
}
} else {
appendText += " |";
for (let i = 0; i < columnNum - 1; i++) {
appendText += " |";
}
}
return appendText + (/windows|win32/i.test(navigator.userAgent) ? "\r\n" : "\n");
};
Copy code
After the table characters are generated, you can replace the contents of the current selection :
handleOk = () => {
const {markdownEditor} = this.props.content;
const cursor = markdownEditor.getCursor();
const text = this.buildFormFormat(this.state.rowNum, this.state.columnNum);
markdownEditor.replaceSelection(text);
cursor.ch += 2;
markdownEditor.setCursor(cursor);
markdownEditor.focus();
};
Copy code
Also changed the cursor position and refocused the editor .
边栏推荐
- Failed building wheel for argon2 cffi when installing Jupiter
- 2022-2-13 learning xiangniuke project - version control
- ERROR: certificate common name “*.” doesn’t match requested ho
- Win10安装ELK
- Beego learning - JWT realizes user login and registration
- Numerical analysis notes (I): equation root
- [CSDN]C1训练题解析_第三部分_JS基础
- Modify idea code
- Redis learning (I)
- 307. Range Sum Query - Mutable
猜你喜欢
2022-2-14 learning xiangniuke project - Session Management
Idea uses the MVN command to package and report an error, which is not available
小王叔叔的博客目录【持续更新中】
Spark 概述
[kotlin learning] classes, objects and interfaces - classes with non default construction methods or attributes, data classes and class delegates, object keywords
Hudi learning notes (III) analysis of core concepts
【Kotlin学习】高阶函数的控制流——lambda的返回语句和匿名函数
Run flash demo on ECS
Computing level network notes
PolyWorks script development learning notes (III) -treeview advanced operation
随机推荐
Using Hudi in idea
LeetCode每日一题(2212. Maximum Points in an Archery Competition)
文件系统中的目录与切换操作
Crawler career from scratch (3): crawl the photos of my little sister ③ (the website has been disabled)
Jenkins learning (III) -- setting scheduled tasks
Go language - IO project
Flask+supervisor installation realizes background process resident
unbuntu(debian)下TFTP服务器搭建及测试
CATIA automation object architecture - detailed explanation of application objects (III) systemservice
ERROR: certificate common name “*.” doesn’t match requested ho
PolyWorks script development learning notes (I) - script development environment
LeetCode每日一题(931. Minimum Falling Path Sum)
MySQL installation and configuration (command line version)
从0开始使用pnpm构建一个Monorepo方式管理的demo
2022-2-13 learn the imitation Niuke project - Project debugging skills
LeetCode每日一题(2232. Minimize Result by Adding Parentheses to Expression)
LeetCode每日一题(2115. Find All Possible Recipes from Given Supplies)
PolyWorks script development learning notes (III) -treeview advanced operation
2022-2-13 learning xiangniuke project - version control
Spark 结构化流写入Hudi 实践