draft.jsでMathJaxを使ってみます。
機械学習とか確率統計の記事を書いていて、やはり数式をきれいに書けるのは特別なことだと思いました。あらためてクヌース先生は偉大です。
1.環境設定
今回は以下のライブラリを使います。
Draft.js
Rectのrich text editorのフレームワークです。facebook製。
draft-js-plugins-editor
Draft.js の React Plugin Architecture です。
draft-js-mathjax-plugin
Draft.js のLatex pluginです。draft-js-plugins-editor対応。
draft-js - Github
DraftJS Plugins - Github
DraftJS MathJax Plugin - Github
Awesome Draft.js - Github
基本的な環境はcreate-react-appを使います。
npx create-react-app draftjs-mathjax
cd draftjs-mathjax
rm -rf src
npm i draft-js draft-js-plugins-editor draft-js-mathjax-plugin --save
以下のソースは、ほぼ「DraftJS MathJax Plugin - Github」のコピペです。
import React, { Component } from 'react'
import { render } from 'react-dom'
import { EditorState } from 'draft-js'
import Editor from 'draft-js-plugins-editor'
import createMathjaxPlugin from 'draft-js-mathjax-plugin'
const mathjaxPlugin = createMathjaxPlugin(/* optional configuration object */)
const plugins = [
mathjaxPlugin,
]
class App extends Component {
state = {
editorState: EditorState.createEmpty(),
}
onChange = (editorState) => {
this.setState({
editorState,
})
}
render() {
return (
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={plugins}
/>
)
}
}
render(<App />, document.getElementById('root'))
2.試してみる
以下のコードでサーバを立ち上げます。
npm start
キーの「$」を押すと、黄色い入力画面が表示されますので、そこにTexで数式を入力します。
ちょっと複雑な数式です。
入力中は、小さくって少し見にくいですが、確定すればそれなりです。
もっと複雑な、ガウス積分の公式関連の式も入力してみましょう。
まあ、いい感じでした。
このコンテンツを保存したり再読み込みできるようなエディタを作ればよいわけですね。
数式エディタに関しては、Reactを中心にして、もう少し調べてみたいです。
draft.jsでMathJaxを使ってみる - 数式エディタ - Qiita
markdown-it-katexを使ってみる - 数式エディタ - Qiita