Add syntax highlighting support to your DraftJS editor
Switch branches/tags
Nothing to show
Clone or download
mxstbr Merge pull request #22 from withspectrum/depfu/update/yarn/prettier-1…
….15.3

Update prettier: 1.15.2 → 1.15.3 (patch)
Latest commit cf4fab3 Dec 3, 2018
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
flow-typed/npm Initial commit Sep 21, 2017
src Update draft-js-prism, remove unnecessary render method override Mar 21, 2018
.babelrc Initial commit Sep 21, 2017
.flowconfig Initial commit Sep 21, 2017
.gitignore Initial commit Sep 21, 2017
.npmignore Initial commit Sep 21, 2017
LICENSE.md Initial commit Sep 21, 2017
README.md (Improve Doc) Import prism.css file Jul 10, 2018
package.json Update prettier to version 1.15.3 Dec 1, 2018
yarn.lock Update prettier to version 1.15.3 Dec 1, 2018

README.md

draft-js-prism-plugin

A DraftJS plugin to add syntax highlighting support to your code blocks. Use in combination with draft-js-plugins.

Usage

First, create the plugin and add it to the plugins array of your PluginsEditor:

import Prism from 'prismjs';
import createPrismPlugin from 'draft-js-prism-plugin';
import "prismjs/themes/prism.css"; // add prism.css to add highlights  

class MyEditor extends React.Component {
  constructor(props) {
    super(props);

    const prismPlugin = createPrismPlugin({
      // It's required to provide your own instance of Prism
      prism: Prism
    });

    this.state = {
      plugins: [prismPlugin]
    }
  }

  render() {
    return (
      <PluginsEditor
        plugins={this.state.plugins}
      />
    )
  }
}

Now add a language key to the data of the code block you want to highlight:

// TODO: Somehow get a code block and its key, this is up to you
const { block, key } = getCurrentBlock();
if (block.getType() !== "code-block") return;

// Replace the code block with a new one with the data.language changed to "javascript"
const data = block.getData().merge({ language: 'javascript' });
const newBlock = block.merge({ data });
const newContentState = currentContent.merge({
  blockMap: blockMap.set(key, newBlock),
  selectionAfter: currentSelection
})

// Now that code block will be highlighted as JavaScript!
this.setState({
  editorState: EditorState.push(editorState, newContentState, "change-block-data")
})

License

This code uses the draft-js-prism decorator by @SamyPesse and is based on code extracted from the draft-js-markdown-shortcuts-plugin by @ngs.

Licensed under the MIT License, Copyright ©️ 2017 Space Program Inc. See LICENSE.md for more information.