
Security News
TypeScript is Porting Its Compiler to Go for 10x Faster Builds
TypeScript is porting its compiler to Go, delivering 10x faster builds, lower memory usage, and improved editor performance for a smoother developer experience.
The next generation of Markdown editor, built for the future
Vditor is a browser-side Markdown editor, implemented using TypeScript. Support native JavaScript, Vue, React and Angular. Provide Desktop
Welcome to Vditor Official Discussion Forum to learn more.
In the initial stage of developing Sym, we directly used WYSIWYG rich text editor. At that time, HTML-based editors were very popular, and it was very convenient to quote them in the project, which also conformed to the usage habits of users at that time.
Later, the rise of Markdown gradually changed everyone's typography. In addition, several of our other projects are for programmer users, so it is also a general trend to migrate to md. We chose CodeMirror, which is an excellent editor, it provides a rich programming interface for developers, and is also compatible with various browsers. it is good.
Later, as the business needs of our projects have precipitated, using CodeMirror sometimes feels more "cumbersome." For example, to implement @automatically complete the user name list, insert Emoji, upload files, etc., it requires more in-depth secondary development, and these business requirements are precisely common and necessary in many project scenarios.
Finally, we decided to start implementing the editor ourselves in Sym. With the iterations of several versions, Sym's editor has matured. In the community HacPai that we operate, people have asked us if we can separate the editor for everyone to use. At the same time, our front-end main programmer V also felt a little bit overwhelmed with maintaining the editors scattered in various projects, plus a good impression of TypeScript, so I decided Use ts to implement a new browser-side md editor.
So, Vditor was born.
WYSIWYG mode is more friendly to users who are not familiar with Markdown, and you can use it seamlessly if you are familiar with Markdown.
Instant Rendering mode should not be unfamiliar to users who are familiar with Typora. In theory, this is the most elegant Markdown editing method.
The traditional Split View mode is suitable for Markdown editing on a large screen.
npm install vditor --save
import Vditor from 'vditor'
import "~vditor/src/assets/scss/index" // Or use dark
const vditor = new Vditor(id, {options...})
<!-- ⚠️Please specify the version number in the production environment, such as https://cdn.jsdelivr.net/npm/vditor@x.x.x/dist... -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vditor/dist/index.css" />
<script src="https://cdn.jsdelivr.net/npm/vditor/dist/index.min.js" defer></script>
class="vditor-reset"
(classic theme) or class="vditor-reset vditor-reset--dark"
(black theme) attribute on the content display element can display the content more friendlyCan be filled with element id
or element itself HTMLElement
⚠️: When filling in the element's HTMLElement
, you need to set options.cache.id
or set options.cache.enable
to false
Explanation | Default | |
---|---|---|
after | Callback method after editor asynchronous rendering is completed | - |
height | Total editor height | 'auto' |
minHeight | Editing area minimum height | - |
width | Total editor width, supports % | 'auto' |
placeholder | Tips when the input area is empty | '' |
lang | i18n: en_US, ko_KR, zh_CN | 'zh_CN' |
input | Trigger after input (value: string, previewElement?: HTMLElement): void | - |
focus | Trigger after focusing (value: string): void | - |
blur | Trigger after out of focus (value: string): void | - |
esc | Trigger after pressing esc (value: string): void | - |
ctrlEnter | Trigger after pressing ⌘/ctrl+enter (value: string): void | - |
select | Triggered after selecting text in the editor (value: string): void | - |
tab | tab key operation string, support \ t and any string | - |
typewriterMode | Whether to enable typewriter mode | false |
cdn | Configure self-built CDN address | https://cdn.jsdelivr.net/npm/vditor@${VDITOR_VERSION} |
mode | Editing mode: sv, ir, wysiwyg | 'wysiwyg' |
debugger | Whether to display the log | false |
value | Editor initialization value | '' |
theme | Theme: classic, dark | 'classic' |
outline | show outline | false |
toolbar: ['emoji', 'br', 'bold', '|', 'line']
. See default src/ts/util/Options.tsemoji
, headings
, bold
, italic
, strike
, |
, line
, quote
, list
, ordered-list
, check
,outdent
,indent
, code
, inline-code
, insert-after
, insert-before
, code-theme
, content-theme
, export
, undo
, redo
, upload
, link
, table
, record
, edit-mode
, both
, preview
, format
, fullscreen
, outline
, devtools
, info
, help
, br
name
is not in the enumeration, you can add a custom button in the following format:{
hotkey: '⌘-⇧-f',
name: 'format',
tipPosition: 'ne',
tip: 'format',
className: '',
icon: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="768" height="768" viewBox="0 0 768 768"><path d="M342 426v-84h426v84h-426zM342 256v-86h426v86h-426zM0 0h768v86h-768v-86zM342 598v-86h426v86h-426zM0 214l170 170-170 170v-340zM0 768v-86h768v86h-768z"></path></svg>',
click: () => {
alert('custom toolbar')
},
}
Explanation | Default | |
---|---|---|
name | Unique label | - |
icon | svg icon | - |
tip | Prompt | - |
tipPosition | Prompt location: ne, nw | - |
hotkey | Shortcut keys, support ⌘/ctrl-key or ⌘/ctrl-⇧/shift-key format configuration, do not support wysiwyg mode | - |
suffix | Insert the suffix in the editor | - |
prefix | Insert the prefix in the editor | - |
click | Custom event triggered when button is clicked (): void | - |
className | Style name | '' |
toolbar?: Array<options.toolbar> | sub menu | - |
Explanation | Default | |
---|---|---|
hide | Whether to hide the toolbar | false |
pin | Whether to pin the toolbar | false |
Explanation | Default | |
---|---|---|
enable | Whether to use counter | false |
max | max counter | - |
type | counter type: md, text | 'md' |
Explanation | Default | |
---|---|---|
enable | Whether to use localStorage for caching | true |
id | Cache key, the first parameter is an element and when caching is enabled required | - |
Explanation | Default | |
---|---|---|
delay | Preview debounce millisecond interval | 1000 |
maxWidth | Preview area maximum width | 800 |
mode | Display mode: both, editor | 'both' |
url | md parsing request | - |
parse | Preview callback (element: HTMLElement): void | - |
transform | Callback before rendering (html: string): string | - |
Explanation | Default | |
---|---|---|
enable | Whether to enable code syntax highlighting | true |
style | For optional values, see Chroma | github |
lineNumber | Whether to enable line number | false |
Explanation | Default | |
---|---|---|
autoSpace | Autospace | false |
fixTermTypo | Automatically correct terminology | false |
chinesePunct | Automatic punctuation correction | false |
toc | Insert Table of Contents | false |
footnotes | Footnotes | true |
codeBlockPreview | Whether to render code blocks in wysiwyg and ir modes | true |
theme | Content Theme | 'light' |
setext | Whether to parse the setext header | true |
paragraphBeginningSpace | Two spaces before the paragraph | false |
sanitize | Use XSS | true |
listMarker | add data-marker attribute | false |
Explanation | Default | |
---|---|---|
inlineDigit | Whether numbers are allowed after the inline math formula starting with $ | false |
macros | Macro definition passed in when rendering with MathJax | {} |
engine | Math formula rendering engine: KaTeX, MathJax | 'KaTeX' |
Explanation | Default | |
---|---|---|
delay | Tip debounce millisecond interval | 200 |
emoji | The default emoji can be selected from lute/emoji_map, or can be customized | { '+1': '👍', '-1': '👎', 'heart': '❤️', 'cold_sweat': '😰' } |
emojiTail | Common emoji | - |
emojiPath | Emoji path | https://cdn.jsdelivr.net/npm/vditor@${VDITOR_VERSION}/dist/images/emoji |
at | @user callback (value: string): Array<any>, Need to return array synchronously [{value: '', html: ''}] | - |
format
for conversion.// POST data
xhr.send(formData); // formData = FormData.append("file[]", File)
// return data
{
"msg": "",
"code": 0,
"data": {
"errFiles": ['filename', 'filename2'],
"succMap": {
"filename3": "filepath3",
"filename3": "filepath3"
}
}
}
linkToImgUrl
can transfer the off-site picture addresses in the clipboard to the server for saving and processing. The data structure is as follows:// POST data
xhr.send(JSON.stringify({url: src})); // src is the address of the image outside the station
// return data
{
msg: '',
code: 0,
data : {
originalURL: '',
url: ''
}
}
Explanation | Default | |
---|---|---|
url | Upload url | '' |
max | The largest upload file Byte | 10 * 1024 * 1024 |
linkToImgUrl | When the clipboard contains the image address, use this url to re-upload | '' |
success | Upload success callback (editor: HTMLPreElement, msg: string): void | - |
error | Upload failure callback (msg: string): void | - |
token | CORS upload verification, header is X-Upload-Token | - |
withCredentials | Cross-site access control | false |
headers | Request header settings | - |
filename | Sanitizing file names (name: string): string | name => name.replace(/\W/g, '') | |
accept | File upload type, same as input accept | - |
validate | Check, return true if successful, otherwise return error message (files: File[]) => string | boolean | - |
handler | Custom upload, return error message when an error occurs (files: File[]) => string | null | - |
format | Transform the data returned by the server to meet the built-in data structure (files: File[], responseText: string): string | - |
file | Process the uploaded file before returning (files: File[]): File[] | - |
setHeaders | Use the return value to set the header before uploading (): { [key: string]: string } | - |
extraData | Append data to FormData { [key: string]: string | Blob } |
Explanation | Default | |
---|---|---|
enable | Whether to support size drag | false |
position | Drag column position:top, bottom | 'bottom' |
after | Callback when dragging ends (height: number): void | - |
Explanation | Default | |
---|---|---|
preview | Preview on the element className | '' |
Explanation | Default | |
---|---|---|
deleteLine | Delete the cursor line or selected line | '⌘-Backspace' |
duplicate | Copy current line or selected content | '⌘-D' |
Explanation | |
---|---|
getValue() | Get editor content |
getHTML() | Get preview area content |
insertValue(value: string, render = true) | Insert content at the focus and markdown rendering by default |
focus() | Focus on the editor |
blur() | Make the editor out of focus |
disabled() | Disable editor |
enable() | Unedit editor |
setSelection(start: number, end: number) | Select the string from start to end and does not support wysiwyg mode |
getSelection(): string | Returns the selected string |
setValue(markdown: string) | Set editor content |
renderPreview(value?: string) | Set preview area content |
getCursorPosition():{top: number, left: number} | Get focus position |
deleteValue() | Delete selected content |
updateValue(value: string) | Update selected content |
isUploading() | Whether the upload is still in progress |
clearCache() | clear cache |
disabledCache() | Disable cache |
enableCache() | Enable caching |
html2md(value: string) | HTML to md |
tip(text: string, time: number) | notification. time is 0 will always display |
setPreviewMode(mode: "both" | "editor") | Set preview mode |
setTheme(theme: "dark" | "classic", contentTheme?: string, codeTheme?: string) | Set theme |
getCurrentMode(): string | Get the editor's current editing mode |
method.min.js
and directly callVditor.mermaidRender(document)
import VditorPreview from 'vditor/dist/method.min'
VditorPreview.mermaidRender(document)
preview
method with the following parameters:previewElement: HTMLDivElement, // Use this element for rendering
markdown: string, // The original markdown to be rendered
options?: IPreviewOptions {
anchor?: number; // 0: no render, 1: render left, 2: render right
customEmoji?: { [key: string]: string }; // Custom emoji, default is {}
lang?: (keyof II18nLang); // Language, default is 'zh_CN'
emojiPath?: string; // Emoji picture path
hljs?: IHljs; // Refer to options.preview.hljs
speech?: { // Read the selected content
enable?: boolean,
};
math?: IMath; // Math formula rendering configuration
transform?(html: string): string; // Callback method before rendering
after?(): void; // Callback method after rendering
cdn?: string; // Self-built CDN address
lazyLoadImage?: string; // use "https://cdn.jsdelivr.net/npm/vditor/dist/images/img-loading.svg" to lazy load image
markdown?: options.preview.markdown;
renderers?: ILuteRender; // Custom rendering method https://hacpai.com/article/1588412297062
}
method.min.js
and index.min.js
cannot be introduced at the same timeExplanation | |
---|---|
mermaidRender(element: HTMLElement, className = ".language-mermaid", cdn = options.cdn) | Convert elements in class to className in element to flowchart/sequence diagram/gantt diagram |
codeRender(element: HTMLElement, lang: (keyof II18nLang) = "zh_CN") | Add a copy button for the code block in element |
chartRender(element: (HTMLElement| Document) = document, cdn = options.cdn) | Chart rendering |
abcRender(element: (HTMLElement| Document) = document, cdn = options.cdn) | Stave rendering |
outlineRender(contentElement: HTMLElement, targetElement: Element, vditor?: IVditor) | Outline rendering |
md2html(mdText: string, options?: IPreviewOptions): Promise<string> | Markdown text is converted to HTML, this method needs to use asynchronous programming |
preview(previewElement: HTMLDivElement, markdown: string, options?: IPreviewOptions) | Page Markdown article rendering |
highlightRender(hljsOption?: IHljs, element?: HTMLElement | Document, cdn = options.cdn) | Highlight the code block in element |
mediaRender(element: HTMLElement) | Rendering as specific link as video, audio, embedded iframe |
mathRender(element: HTMLElement, options?: {cdn?: string, math?: IMath}) | Render math formulas |
speechRender(element: HTMLElement, lang?: (keyof II18nLang)) | Read the selected text |
graphvizRender(element: HTMLElement, cdn?: string) | Render graphviz |
lazyLoadImageRender(element: (HTMLElement | Document) = document) | Render lazy load image |
setCodeTheme (codeTheme: string, cdn = options.cdn) | update code theme |
setContentTheme (contentTheme: string, cdn = options.cdn) | update content theme |
mindmapRender (element: (HTMLElement | Document) = document, cdn = options.cdn) | Render mind map |
npm install
in the root directorynpm run start
Start the local server, open http: // localhost: 9000npm run build
package code to dist directoryDue to the on-demand loading mechanism, the default CDN is https://cdn.jsdelivr.net/npm/vditor@version number
If the code is modified or you need to use a self-built CDN, you can follow the steps below:
options
and IPreviewOptions
need to add cdn
configurationhighlightRender
, mathRender
, abcRender
, chartRender
, mermaidRender
methods need to add cdn parameterPlease read CHANGELOG carefully when upgrading the version.
Vditor uses the MIT open source license.
FAQs
♏ 易于使用的 Markdown 编辑器,为适配不同的应用场景而生
The npm package vditor receives a total of 30,613 weekly downloads. As such, vditor popularity was classified as popular.
We found that vditor demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
TypeScript is porting its compiler to Go, delivering 10x faster builds, lower memory usage, and improved editor performance for a smoother developer experience.
Research
Security News
The Socket Research Team has discovered six new malicious npm packages linked to North Korea’s Lazarus Group, designed to steal credentials and deploy backdoors.
Security News
Socket CEO Feross Aboukhadijeh discusses the open web, open source security, and how Socket tackles software supply chain attacks on The Pair Program podcast.