熬夜写的解析掘金新版本编辑器源码

377次阅读  |  发布于3年以前

掘金(字节跳动)MD编辑器源码解析

写在开头

最近我写了一个前端学架构100集,会慢慢更新,请大家别着急,目前在反复修改推敲内容

正式开始

如果你比较菜,不懂pnpm,没事,我有文章:https://juejin.cn/post/6932046455733485575

nvm install 12.17
npm i pnpm -g
pnpm i
npm link或者yalc

如果你比较菜,不会这两种方式,没事,我也有文章:https://mp.weixin.qq.com/s/t6u6snq_S3R0X7b1MbvDVA,总之不会的来公众号翻翻,都有。我的前端学架构100集里面也会都有

React版本的源码解析

先看看在React里面怎么使用的

import 'bytemd/dist/index.min.css';
import { Editor, Viewer } from '@bytemd/react';
import gfm from '@bytemd/plugin-gfm';

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

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

  return (
    <Editor
      value={value}
      plugins={plugins}
      onChange={(v) => {
        setValue(v);
      }}
    />
  );
};
import React, { useEffect, useRef } from 'react';
import * as bytemd from 'bytemd';

export interface EditorProps extends bytemd.EditorProps {
  onChange?(value: string): void;
}

export const Editor: React.FC<EditorProps> = ({
  children,
  onChange,
  ...props
}) => {
  const ed = useRef<bytemd.Editor>();
  const el = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!el.current) return;

    const editor = new bytemd.Editor({
      target: el.current,
      props,
    });
    editor.$on('change', (e: CustomEvent<{ value: string }>) => {
      onChange?.(e.detail.value);
    });
    ed.current = editor;

    return () => {
      editor.$destroy();
    };
  }, []);

  useEffect(() => {
    // TODO: performance
    ed.current?.$set(props);
  }, [props]);

  return <div ref={el}></div>;
};
bytemd的源码入口文件
/// <reference types="svelte" />
import Editor from './editor.svelte';
import Viewer from './viewer.svelte';

export { Editor, Viewer };
export * from './utils';
export * from './types';

好家伙,这个Editor是用sveltejs写的,地址是:https://www.sveltejs.cn/

所以这里可以看出来,掘金(字节跳动)非常看重性能

什么是Svelte?

这篇文章写得很全面,关于Svelte,https://zhuanlan.zhihu.com/p/97825481,由于本文重点是源码,不是环境,不是框架底层介绍,点到为止,有兴趣的去看文章~

编辑器划分为几个区域

先来一波性能测试

编辑器这玩意,能找到合适开源的二次封装,就是好事,我刚工作那会为了写一个微信这种桌面端编辑器(又是跨平台的,Electron),那两个月差点去世了,重构了N次,换了N次方案,顺便把React源码都学了一遍,最后用原生手写实现了

找到CodeMirror入口文件

import { CodeMirror } from "./edit/main.js"

export default CodeMirror

CodeMirror怎么用的

  var editor = CodeMirror.fromTextArea(document.getElementById("editorArea"), {
                lineNumbers: true,        //是否在编辑器左侧显示行号
                matchBrackets: true,      // 括号匹配
                mode: "text/x-c++src",    //C++
                indentUnit:4,             // 缩进单位为4
                indentWithTabs: true,     //
                smartIndent: true,        //自动缩进,设置是否根据上下文自动缩进(和上一行相同的缩进量)。默认为true。
                styleActiveLine: true,       // 当前行背景高亮
                theme: 'midnight',         // 编辑器主题

            });

            editor.setSize('600px','400px'); //设置代码框大小

向编辑器的父节点之前插入一个节点,然后传入CodeMirror函数

CodeMirror函数
if (!(this instanceof CodeMirror)) 
{return new CodeMirror(place, options)
}

确保被构造调用,this指向

 this.options = options = options ? copyObj(options) : {}
export function copyObj(obj, target, overwrite) {
 if (!target) target = {}
 for (let prop in obj)
   if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
     target[prop] = obj[prop]
 return target
}
copyObj(defaults, options, false)

这样传入的options就有了默认配置的选项~

let doc = options.value
  if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction)
  else if (options.mode) doc.modeOption = options.mode
  this.doc = doc
let Doc = function(text, mode, firstLine, lineSep, direction) {
  if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep, direction)
  if (firstLine == null) firstLine = 0

  BranchChunk.call(this, [new LeafChunk([new Line("", null)])])
  this.first = firstLine
  this.scrollTop = this.scrollLeft = 0
  this.cantEdit = false
  this.cleanGeneration = 1
  this.modeFrontier = this.highlightFrontier = firstLine
  let start = Pos(firstLine, 0)
  this.sel = simpleSelection(start)
  this.history = new History(null)
  this.id = ++nextDocId
  this.modeOption = mode
  this.lineSep = lineSep
  this.direction = (direction == "rtl") ? "rtl" : "ltr"
  this.extend = false

  if (typeof text == "string") text = this.splitLines(text)
  updateDoc(this, {from: start, to: start, text: text})
  setSelection(this, simpleSelection(start), sel_dontScroll)
}
let start = Pos(firstLine, 0)

POS方法:

// A Pos instance represents a position within the text.
export function Pos(line, ch, sticky = null) {
  if (!(this instanceof Pos)) return new Pos(line, ch, sticky)
  this.line = line
  this.ch = ch
  this.sticky = sticky
}

这个函数,我大概知道是什么意思,但是看到这里,我还不能很好的解答。于是我们这个地方先留着,知道它是记录位置的(但是不知道记录什么位置)

this.sel = simpleSelection(start)

//simpleSelection方法
export function simpleSelection(anchor, head) {
  return new Selection([new Range(anchor, head || anchor)], 0)
}

这里先科普下RangeSelect对象

window.getSelection();

下方蓝色选中部分就是这个方法返回值

可以用 Document 对象的 Document.createRange 方法创建 Range,也可以用 Selection 对象的 getRangeAt 方法获取 Range。另外,还可以通过 Document 对象的构造函数 Range() 来得到 Range。

if (typeof text == "string") text = 
this.splitLines(text)

//splitLines方法
 splitLines: function(str) {
    if (this.lineSep) return str.split(this.lineSep)
    return splitLinesAuto(str)
  },

split() 方法使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。

export let splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? string => {
  let pos = 0, result = [], l = string.length
  while (pos <= l) {
    let nl = string.indexOf("\n", pos)
    if (nl == -1) nl = string.length
    let line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl)
    let rt = line.indexOf("\r")
    if (rt != -1) {
      result.push(line.slice(0, rt))
      pos += rt + 1
    } else {
      result.push(line)
      pos = nl + 1
    }
  }
  return result
} : string => string.split(/\r\n?|\n/)
updateDoc(this, {from: start, to: 
 start, text: text})

写到这里,我有点怀疑人生了,我本想着clone源码下来,半个小时搞定的。(因为我写过编辑器),结果这个代码特别难阅读,跟node.js源码一样,方法和属性大都是挂载在原型上的,特别链路这么长,所以大家现在理解写一篇好的文章多难了吧。说多了都是泪,还好我币圈昨天梭哈抄底,今天大涨。我今晚就是再怎么样也要写完

首先定义了几个函数,先不看

// Perform a change on the document data structure.
export function updateDoc(doc, change, markedSpans, estimateHeight) {
  function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  function update(line, text, spans) {
    updateLine(line, text, spans, estimateHeight)
    signalLater(line, "change", line, change)
  }
  function linesFor(start, end) {
    let result = []
    for (let i = start; i < end; ++i)
      result.push(new Line(text[i], spansFor(i), estimateHeight))
    return result
  }
  ...

接着获取了外部传入的数据,例如from,to,text,第一行,最后的内容等

 let from = change.from, to = change.to, text = change.text
  let firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line)
  let lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line
 // Adjust the line structure
  if (change.full) {
    doc.insert(0, linesFor(0, text.length))
    doc.remove(text.length, doc.size - text.length)
  } else if (isWholeLineUpdate(doc, change)) {
    // This is a whole-line replace. Treated specially to make
    // sure line objects move the way they are supposed to.
    let added = linesFor(0, text.length - 1)
    update(lastLine, lastLine.text, lastSpans)
    if (nlines) doc.remove(from.line, nlines)
    if (added.length) doc.insert(from.line, added)
  } else if (firstLine == lastLine) {
    if (text.length == 1) {
      update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)
    } else {
      let added = linesFor(1, text.length - 1)
      added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight))
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
      doc.insert(from.line + 1, added)
    }
  } else if (text.length == 1) {
    update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))
    doc.remove(from.line + 1, nlines)
  } else {
    update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
    update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)
    let added = linesFor(1, text.length - 1)
    if (nlines > 1) doc.remove(from.line + 1, nlines - 1)
    doc.insert(from.line + 1, added)
  }

  signalLater(doc, "change", doc, change)

上面代码的意思:

 doc.insert(0, linesFor(0, text.length))
 doc.remove(text.length, doc.size - text.length)
else if (isWholeLineUpdate(doc, change)) {
    // This is a whole-line replace. Treated specially to make
    // sure line objects move the way they are supposed to.
    let added = linesFor(0, text.length - 1)
    update(lastLine, lastLine.text, lastSpans)
    if (nlines) doc.remove(from.line, nlines)
    if (added.length) doc.insert(from.line, added)
  } 

如果第一行等于最后一行

else if (firstLine == lastLine) {
    if (text.length == 1) {
      update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)
    } else {
      let added = linesFor(1, text.length - 1)
      added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight))
      update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
      doc.insert(from.line + 1, added)
    }
  } 

如果只有一行

 else if (text.length == 1) {
    update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))
    doc.remove(from.line + 1, nlines)
  } 

否则就执行默认逻辑

 else {
    update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
    update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)
    let added = linesFor(1, text.length - 1)
    if (nlines > 1) doc.remove(from.line + 1, nlines - 1)
    doc.insert(from.line + 1, added)
  }

这里具体的逻辑大都是数据处理,根据不同条件来进行什么样的数据处理。主要给大家梳理下这些调用逻辑

Doc的原型上挂载的方法有四百多行代码,我选择几个有代表意义的讲解下:

//插入
insert: function(at, lines) {
    let height = 0
    for (let i = 0; i < lines.length; ++i) height += lines[i].height
    this.insertInner(at - this.first, lines, height)
  },

//移除
remove: function(at, n) { this.removeInner(at - this.first, n) },

//替换光标对象
replaceRange: function(code, from, to, origin) {
    from = clipPos(this, from)
    to = to ? clipPos(this, to) : from
    replaceRange(this, code, from, to, origin)
},

//获取光标对象
getRange: function(from, to, lineSep) {
    let lines = getBetween(this, clipPos(this, from), clipPos(this, to))
    if (lineSep === false) return lines
    if (lineSep === '') return lines.join('')
    return lines.join(lineSep || this.lineSeparator())
  },

//获取行
getLine: function(line) {let l = this.getLineHandle(line); return l && l.text},

//获取第一行
firstLine: function() {return this.first},

//获取最后一行
lastLine: function() {return this.first + this.size - 1},

input样式初始化

let input = new CodeMirror.inputStyles[options.inputStyle](this)

把编辑器的输入节点和格式化后的doc一起传入Display方法

if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction)
  else if (options.mode) doc.modeOption = options.mode
  this.doc = doc

  let input = new CodeMirror.inputStyles[options.inputStyle](this)
  let display = this.display = new Display(place, doc, input, options)

这个display的方法,我认为大部分都是样式处理,这里不展开讲了。回到整个文章和源码的精髓

回到Doc

当然是更改Selection对象

setValue: docMethodOp(function(code) {
    let top = Pos(this.first, 0), last = this.first + this.size - 1
    makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
                      text: this.splitLines(code), origin: "setValue", full: true}, true)
    if (this.cm) scrollToCoords(this.cm, 0, 0)
    //更新编辑器重点
    setSelection(this, simpleSelection(top), sel_dontScroll) 
  }),

重点 - 设置新的selection:

// Set a new selection.
export function setSelection(doc, sel, options) {
  setSelectionNoUndo(doc, sel, options)
  addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)
}
export function setSelectionNoUndo(doc, sel, options) {
  if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
    sel = filterSelectionChange(doc, sel, options)

  let bias = options && options.bias ||
    (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1)
  setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))

  if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
    ensureCursorVisible(doc.cm)
}

没有发现阻断的return代码,应该种带你观察setSelectionInner这个方法

function setSelectionInner(doc, sel) {
  if (sel.equals(doc.sel)) return

  doc.sel = sel

  if (doc.cm) {
    doc.cm.curOp.updateInput = 1
    doc.cm.curOp.selectionChanged = true
    signalCursorActivity(doc.cm)
  }
  signalLater(doc, "cursorActivity", doc)
}

如果此刻存在编辑器实例,那么就去更新它上面的一些属性,例如selectionChanged,它应该是一把类似锁的标识,告诉其他调用它的地方,Selection对象改变了,最后调用signalLater对象的方法

最后的代码需要回到使用来讲解

import React, { useEffect, useRef } from 'react';
import * as bytemd from 'bytemd';

export interface EditorProps extends bytemd.EditorProps {
  onChange?(value: string): void;
}

export const Editor: React.FC<EditorProps> = ({
  children,
  onChange,
  ...props
}) => {
  const ed = useRef<bytemd.Editor>();
  const el = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!el.current) return;

    const editor = new bytemd.Editor({
      target: el.current,
      props,
    });
    editor.$on('change', (e: CustomEvent<{ value: string }>) => {
      onChange?.(e.detail.value);
    });
    ed.current = editor;

    return () => {
      editor.$destroy();
    };
  }, []);

  useEffect(() => {
    // TODO: performance
    ed.current?.$set(props);
  }, [props]);

  return <div ref={el}></div>;
};

看重点:

 editor.$on('change', (e: CustomEvent<{ value: string }>) => {
      onChange?.(e.detail.value);
    });
  signalLater(doc, "cursorActivity", doc)

//signalLater方法
export function signalLater(emitter, type /*, values...*/) {
  let arr = getHandlers(emitter, type)
  if (!arr.length) return
  let args = Array.prototype.slice.call(arguments, 2), list
  if (operationGroup) {
    list = operationGroup.delayedCallbacks
  } else if (orphanDelayedCallbacks) {
    list = orphanDelayedCallbacks
  } else {
    list = orphanDelayedCallbacks = []
    setTimeout(fireOrphanDelayed, 0)
  }
  for (let i = 0; i < arr.length; ++i)
    list.push(() => arr[i].apply(null, args))
}

会将所有的监听事件触发一次,这样例如:我每次设置一个新的Selection,就会触发外部的change事件。

 list.push(() => arr[i].apply(null, args))
   editor.$on('change', (e: CustomEvent<{ value: string }>) => {
      onChange?.(e.detail.value);
    });

梳理本次看源码的流程

写在最后

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8