• Stars
    star
    679
  • Rank 66,532 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 1 year ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

ByteMD v1 repository

ByteMD

This is ByteMD v1 repository.

v2 is under development actively, see HashMD.

ByteMD is a Markdown editor component built with Svelte. It could also be used in other libraries/frameworks such as React, Vue and Angular.

Playground here: https://bytemd.js.org/playground/

Features

  1. Lightweight and framework agnostic: ByteMD is built with Svelte. It compiles to vanilla JS DOM manipulation without importing any UI Framework runtime bundle, which makes it lightweight, and easily adapted to other libraries/frameworks.
  2. Easy to extend: ByteMD has a plugin system to extend the basic Markdown syntax, which makes it easy to add additional features such as code syntax highlight, math equation and Mermaid flowcharts. You can also write your own plugin if these ones don't meet your needs.
  3. Secure by default: Cross-site scripting(XSS) attack such as <script> and <img onerror> have been correctly handled by ByteMD. No need to introduce extra DOM sanitize steps.
  4. SSR compatible: ByteMD could be used in the Server-side rendering(SSR) environment without extra config. SSR is widely used in some cases due to its better SEO and fast time-to-content in slow network connection.

Installation

Package Status Description
bytemd npm Svelte/Vanilla JS component
@bytemd/react npm React component
@bytemd/vue npm Vue 2 component
@bytemd/vue-next npm Vue 3 component

Legacy browsers support

The default entry of NPM package only supports modern browsers. To make legacy browsers (IE9+) work, You can compile it with ESNext -> ES5 transpilers, such as Babel or SWC.

The ES5 bundle will no longer be available after version 1.11.0. If you need it, you can use version 1.11.0 or earlier versions

Notice that polyfills are not included, and should be imported manually, see the legacy browser example.

Usage

There are two components: Editor and Viewer. Editor is the Markdown editor, as the name suggests; Viewer is commonly used to display rendered Markdown results without editing.

Before using the component, remember to import CSS file to make styles correct:

import 'bytemd/dist/index.css'

Svelte

<script>
  import { Editor, Viewer } from 'bytemd'
  import gfm from '@bytemd/plugin-gfm'

  let value
  const plugins = [
    gfm(),
    // Add more plugins here
  ]

  function handleChange(e) {
    value = e.detail.value
  }
</script>

<template>
  <Editor {value} {plugins} on:change={handleChange} />
</template>

React

import gfm from '@bytemd/plugin-gfm'
import { Editor, Viewer } from '@bytemd/react'

const plugins = [
  gfm(),
  // Add more plugins here
]

const App = () => {
  const [value, setValue] = useState('')

  return (
    <Editor
      value={value}
      plugins={plugins}
      onChange={(v) => {
        setValue(v)
      }}
    />
  )
}

Vue

<template>
  <Editor :value="value" :plugins="plugins" @change="handleChange" />
</template>

<script>
import gfm from '@bytemd/plugin-gfm'
import { Editor, Viewer } from '@bytemd/vue'

const plugins = [
  gfm(),
  // Add more plugins here
]

export default {
  components: { Editor },
  data() {
    return { value: '', plugins }
  },
  methods: {
    handleChange(v) {
      this.value = v
    },
  },
}
</script>

Vanilla JS

import gfm from '@bytemd/plugin-gfm'
import { Editor, Viewer } from 'bytemd'

const plugins = [
  gfm(),
  // Add more plugins here
]

const editor = new Editor({
  target: document.body, // DOM to render
  props: {
    value: '',
    plugins,
  },
})

editor.$on('change', (e) => {
  editor.$set({ value: e.detail.value })
})

Options

Viewer

Key Type Description
value string (required) Markdown text
plugins BytemdPlugin[] ByteMD plugin list
sanitize (schema: Schema) => Schema Sanitize strategy
remarkRehype documentation remark-rehype config options

Editor

Editor component also accepts the options of Viewer for preview. Besides that, there are some other options:

Key Type Description
mode split, tab, auto Editor display mode, default: auto
previewDebounce number Debounce time (ms) for preview, default: 300
placeholder string Editor placeholder
editorConfig documentation CodeMirror editor config
locale i18n locale. Available locales could be found at bytemd/locales, default: use en.json
uploadImages function Specify how to upload images. If set, the image icon will appear on the toolbar
maxLength number Maximum length (number of characters) of value

Style customization

Editor

The default height of ByteMD Editor is 300px. It could be overridden by CSS:

.bytemd {
  height: calc(100vh - 200px);
}

The other styles could also be overridden, see the default style.

Viewer

There is no built-in styles for the Viewer. You could use third-party markdown themes, for example juejin-markdown-themes and github-markdown-css.

Plugin System

ByteMD provides a powerful plugin system for customization. There are several official plugins to support features such as code syntax highlight, math equation and Mermaid flowcharts.

If you have more customized needs, you could also write your own plugin to support them.

Official Plugins

Package Status Description
@bytemd/plugin-breaks npm Support breaks
@bytemd/plugin-frontmatter npm Parse frontmatter
@bytemd/plugin-gemoji npm Support Gemoji shortcodes
@bytemd/plugin-gfm npm Support GFM (autolink literals, strikethrough, tables, tasklists)
@bytemd/plugin-highlight npm Highlight code blocks
@bytemd/plugin-highlight-ssr npm Highlight code blocks (SSR compatible)
@bytemd/plugin-math npm Support math formula
@bytemd/plugin-math-ssr npm Support math formula (SSR compatible)
@bytemd/plugin-medium-zoom npm Zoom images like Medium
@bytemd/plugin-mermaid npm Support Mermaid diagram

Technical Overview

ByteMD uses remark and rehype ecosystem to process Markdown. The complete process is as follows:

  1. The markdown text is parsed to an AST
  2. The Markdown AST could be manipulated by several remark plugins
  3. The Markdown AST is transformed to a HTML AST
  4. The HTML AST is sanitized for security reason
  5. The HTML AST could be manipulated by several rehype plugins
  6. The HTML AST is stringified to HTML
  7. Some extra DOM manipulation after the HTML being rendered

It could also be described as a flowchart:

plugin system

The 2,5,7 steps are designed for user customization via ByteMD plugin API.

Authoring a Plugin

We'll take Math formula plugin as an example to walk you through the process.

First of all, scaffold the project according to the BytemdPlugin type signature:

import type { BytemdPlugin } from 'bytemd'

export default function mathPlugin(): BytemdPlugin {
  return {
    // to be implement
  }
}

Then we look into the requirement more closely: If we want to render syntax like $a+b$ to Math formula, there are several things we need to do:

  • Support $a+b$ syntax as a Math formula in Markdown (step 2)
  • Render these nodes correctly in HTML (step 5 or 7)
  • Additionally, an extra icon in the toolbar would be great for user convenience

For the first thing, luckily, we don't need to implement it with our own because remark-math already did it. The only thing we need to do is to import and use it:

import type { BytemdPlugin } from 'bytemd'
+import remarkMath from 'remark-math'

export default function mathPlugin(): BytemdPlugin {
  return {
-    // to be implement
+    remark: (processor) => processor.use(remarkMath),
  }
}

Then consider the second thing, it would be a little complicated because we have two choices, do it in step 5 or 7. The difference is that step 5 is more friendly with SSR, while step 7 hand over the rendering to the client-side. This is why we have two plugin: @bytemd/plugin-math and @bytemd/plugin-math-ssr.

// if we choose step 5:
import type { BytemdPlugin } from 'bytemd'
import remarkMath from 'remark-math'
+import rehypeKatex from 'rehype-katex'

export default function mathPlugin(): BytemdPlugin {
  return {
    remark: (processor) => processor.use(remarkMath),
+   rehype: (processor) => processor.use(rehypeKatex),
  }
}

// if we choose step 7:
import type { BytemdPlugin } from 'bytemd'
import remarkMath from 'remark-math'
+import rehypeKatex from 'rehype-katex'

export default function mathPlugin(): BytemdPlugin {
  return {
    remark: (processor) => processor.use(remarkMath),
+   viewerEffect({ markdownBody }) {
+     const renderMath = async (selector: string, displayMode: boolean) => {
+       const katex = await import('katex').then((m) => m.default)
+
+       const els = markdownBody.querySelectorAll<HTMLElement>(selector)
+       els.forEach((el) => {
+         katex.render(el.innerText, el, { displayMode })
+       })
+     }
+
+     renderMath('.math.math-inline', false)
+     renderMath('.math.math-display', true)
+   },
  }
}

The last thing is to add an icon to the toolbar. we use the actions prop to implement it:

export default function mathPlugin(): BytemdPlugin {
  return {
    actions: [
      {
        title: 'Insert an math formula',
        icon: '', // 16x16 SVG icon
        handler: {
          type: 'action',
          click(ctx) {
            // to be implement:
            // the `ctx` is an instance of `BytemdEditorContext`, which has
            // several utility methods to help operate the CodeMirror editor state.

            // remember to call `focus` to avoid lost of focus
            editor.focus()
          },
        },
      },
    ],
  }
}

Now we have completed a minimalist version of the plugin! For more details and references please check out the source code.

Contributors

License

MIT

FOSSA Status

More Repositories

1

IconPark

🍎Transform an SVG icon into multiple themes, and generate React icons,Vue icons,svg icons
TypeScript
8,298
star
2

xgplayer

A HTML5 video player with a parser that saves traffic
JavaScript
8,260
star
3

sonic

A blazingly fast JSON serializing & deserializing library
Assembly
6,870
star
4

monoio

Rust async runtime based on io-uring.
Rust
3,864
star
5

byteps

A high performance and generic framework for distributed DNN training
Python
3,603
star
6

lightseq

LightSeq: A High Performance Library for Sequence Processing and Generation
C++
3,193
star
7

ByteX

ByteX is a bytecode plugin platform based on Android Gradle Transform API and ASM. 字节码插件开发平台
Java
2,865
star
8

Elkeid

Elkeid is an open source solution that can meet the security requirements of various workloads such as hosts, containers and K8s, and serverless. It is derived from ByteDance's internal best practices.
Go
2,226
star
9

AlphaPlayer

AlphaPlayer is a video animation engine.
Java
2,181
star
10

scene

Android Single Activity Framework compatible with Fragment.
Java
2,097
star
11

bhook

🔥 ByteHook is an Android PLT hook library which supports armeabi-v7a, arm64-v8a, x86 and x86_64.
C
2,073
star
12

flutter_ume

UME is an in-app debug kits platform for Flutter. Produced by Flutter Infra team of ByteDance
Dart
2,053
star
13

terarkdb

A RocksDB compatible KV storage engine with better performance
C++
2,044
star
14

btrace

🔥🔥 btrace(AKA RheaTrace) is a high performance Android trace tool which is based on Perfetto, it support to define custom events automatically during building apk and using bhook to provider more native events like Render/Binder/IO etc.
Kotlin
1,913
star
15

gopkg

Universal Utilities for Go
Go
1,704
star
16

android-inline-hook

🔥 ShadowHook is an Android inline hook library which supports thumb, arm32 and arm64.
C
1,660
star
17

bitsail

BitSail is a distributed high-performance data integration engine which supports batch, streaming and incremental scenarios. BitSail is widely used to synchronize hundreds of trillions of data every day.
Java
1,627
star
18

go-tagexpr

An interesting go struct tag expression syntax for field validation, etc.
Go
1,470
star
19

GiantMIDI-Piano

Python
1,431
star
20

appshark

Appshark is a static taint analysis platform to scan vulnerabilities in an Android app.
Kotlin
1,363
star
21

AabResGuard

The tool of obfuscated aab resources.(Android app bundle资源混淆工具)
Java
1,307
star
22

piano_transcription

Python
1,247
star
23

CodeLocator

Kotlin
1,163
star
24

BoostMultiDex

BoostMultiDex is a solution for quickly loading multiple dex files on low Android version devices (4.X and below, SDK <21).
Java
1,106
star
25

music_source_separation

Python
1,039
star
26

Fastbot_Android

Fastbot(2.0) is a model-based testing tool for modeling GUI transitions to discover app stability problems
C++
1,031
star
27

SALMONN

SALMONN: Speech Audio Language Music Open Neural Network
Python
1,000
star
28

memory-leak-detector

C
919
star
29

fedlearner

A multi-party collaborative machine learning framework
Python
892
star
30

monolith

ByteDance's Recommendation System
Python
844
star
31

sonic-cpp

A fast JSON serializing & deserializing library, accelerated by SIMD.
C++
811
star
32

godlp

sensitive information protection toolkit
Go
770
star
33

MVDream

Multi-view Diffusion for 3D Generation
Python
744
star
34

res-adapter

Official implementation of "ResAdapter: Domain Consistent Resolution Adapter for Diffusion Models".
Python
724
star
35

tailor

C
669
star
36

ibot

iBOT 🤖: Image BERT Pre-Training with Online Tokenizer (ICLR 2022)
Jupyter Notebook
663
star
37

RealRichText

A Tricky Solution for Implementing Inline-Image-In-Text Feature in Flutter.
Dart
658
star
38

guide

A new feature guide component by react 🧭
TypeScript
651
star
39

mockey

a simple and easy-to-use golang mock library
Go
622
star
40

magic-microservices

Make Web Components easier and powerful!😘
TypeScript
570
star
41

Fastbot_iOS

About Fastbot(2.0) is a model-based testing tool for modeling GUI transitions to discover app stability problems
Objective-C
553
star
42

flow-builder

A highly customizable streaming flow builder.
TypeScript
526
star
43

MVDream-threestudio

3D generation code for MVDream
Python
473
star
44

effective_transformer

Running BERT without Padding
C++
457
star
45

ByteTransformer

optimized BERT transformer inference on NVIDIA GPU. https://arxiv.org/abs/2210.03052
C++
449
star
46

Next-ViT

Python
426
star
47

matxscript

A high-performance, extensible Python AOT compiler.
C++
408
star
48

byteir

A model compilation solution for various hardware
MLIR
362
star
49

syllepsis

Syllepsis is an out-of-the-box rich text editor.
TypeScript
355
star
50

uss

This is the PyTorch implementation of the Universal Source Separation with Weakly labelled Data.
Python
324
star
51

OMGD

Online Multi-Granularity Distillation for GAN Compression (ICCV2021)
Python
323
star
52

neurst

Neural end-to-end Speech Translation Toolkit
Python
298
star
53

danmu.js

HTML5 danmu (danmaku) plugin for any DOM element
JavaScript
292
star
54

vArmor

vArmor is a cloud native container sandbox system based on AppArmor/BPF/Seccomp. It also includes multiple built-in protection rules that are ready to use out of the box.
Go
263
star
55

particle-sfm

ParticleSfM: Exploiting Dense Point Trajectories for Localizing Moving Cameras in the Wild. ECCV 2022.
C++
263
star
56

CloudShuffleService

Cloud Shuffle Service(CSS) is a general purpose remote shuffle solution for compute engines, including Spark/Flink/MapReduce.
Java
245
star
57

lynx-llm

paper: https://arxiv.org/abs/2307.02469 page: https://lynx-llm.github.io/
Python
227
star
58

g3

Enterprise-oriented Generic Proxy Solutions
Rust
227
star
59

xgplayer-vue

Vue component for xgplayer, a HTML5 video player with a parser that saves traffic
JavaScript
219
star
60

DEADiff

[CVPR 2024] Official implementation of "DEADiff: An Efficient Stylization Diffusion Model with Disentangled Representations"
Python
209
star
61

flux

A fast communication-overlapping library for tensor parallelism on GPUs.
C++
201
star
62

trace-irqoff

Interrupts-off or softirqs-off latency tracer
C
195
star
63

ParaGen

ParaGen is a PyTorch deep learning framework for parallel sequence generation.
Python
186
star
64

ByteMLPerf

AI Accelerator Benchmark focuses on evaluating AI Accelerators from a practical production perspective, including the ease of use and versatility of software and hardware.
Python
181
star
65

MoMA

MoMA: Multimodal LLM Adapter for Fast Personalized Image Generation
Jupyter Notebook
177
star
66

AWERTL

An non-invasive iOS framework for quickly adapting Right-To-Left style UI
Objective-C
175
star
67

Bytedance-UnionAD

Ruby
170
star
68

keyhouse

Keyhouse is a skeleton of general-purpose Key Management System written in Rust.
Rust
163
star
69

react-model

The next generation state management library for React
TypeScript
162
star
70

LargeBatchCTR

Large batch training of CTR models based on DeepCTR with CowClip.
Python
162
star
71

ic_flow_platform

IFP (ic flow platform) is an integrated circuit design flow platform, mainly used for IC process specification management and data flow contral.
Python
154
star
72

DanmakuRenderEngine

DanmakuRenderEngine is a lightweight and scalable Android danmaku library. 轻量级高扩展安卓弹幕渲染引擎
Kotlin
149
star
73

primus

Java
148
star
74

diat

A CLI tool to help with diagnosing Node.js processes basing on inspector.
JavaScript
146
star
75

coconut_cvpr2024

Jupyter Notebook
143
star
76

Hammer

An efficient toolkit for training deep models.
Python
138
star
77

ns-x

An easy-to-use, flexible network simulator library in Go.
Go
116
star
78

pv3d

Python
113
star
79

fc-clip

This repo contains the code for our paper Convolutions Die Hard: Open-Vocabulary Segmentation with Single Frozen Convolutional CLIP
Python
109
star
80

RLFN

Winner of runtime track in NTIRE 2022 challenge on Efficient Super-Resolution
Python
106
star
81

DCFrame

DCFrame is a Swift UI collection framework, which can easily create complex UI.
Swift
100
star
82

trace-noschedule

Trace noschedule thread
C
99
star
83

decoupleQ

A quantization algorithm for LLM
Cuda
99
star
84

tar-wasm

A faster experimental wasm-based tar implementation for browsers.
Rust
95
star
85

TWIST

Official codes: Self-Supervised Learning by Estimating Twin Class Distribution
Python
95
star
86

magic-portal

⚡ A blazing fast micro-component and micro-frontend solution uses web-components under the hood.
TypeScript
91
star
87

xgplayer-react

React component for xgplayer, a HTML5 video player with a parser that saves traffic
JavaScript
84
star
88

fe-foundation

UI Foundation for React Hooks and Vue Composition Api
TypeScript
80
star
89

nnproxy

Scalable NameNode RPC Proxy for HDFS Federation
Java
79
star
90

dbatman

Go
74
star
91

Elkeid-HUB

Elkeid HUB is a rule/event processing engine maintained by the Elkeid Team that supports streaming/offline (not yet supported by the community edition) data processing. The original intention is to solve complex data/event processing and external system linkage requirements through standardized rules.
Python
74
star
92

FreeSeg

Python
69
star
93

pull_to_refresh

Flutter pull_to_refresh widget
Dart
67
star
94

Jeddak-DPSQL

DPSQL (Privacy Protection SQL Query Service) - This project is a microservice Middleware located between the database engine ( Hive , Clickhouse , etc.) and the application system. It provides transparent SQL query result desensitization capabilities.
Python
62
star
95

terark-zip

A data structure and algorithm library built for TerarkDB
C++
62
star
96

trace-runqlat

C
61
star
97

ipmb

An interprocess message bus system built in Rust.
Rust
60
star
98

X-Portrait

Source code for the SIGGRAPH 2024 paper "X-Portrait: Expressive Portrait Animation with Hierarchical Motion Attention"
Python
59
star
99

kernel

ByteDance kernel for use on cloud.
C
57
star
100

scroll_kit

Dart
56
star