Giter Club home page Giter Club logo

draft-js-prism-plugin's Introduction

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.

draft-js-prism-plugin's People

Contributors

brianlovin avatar depfu[bot] avatar mxstbr avatar pindlebot avatar rahuldhawani avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

draft-js-prism-plugin's Issues

A working example would be really great.

I find it difficult to make this to work. Prism js requires the below structure

<pre>
  <code>
  </code>
</pre>

But when inserting 'code-block' in draftjs, we are getting only 'pre' tags and no 'code' tags.

I got struck on this for nearly a month. I highly appreciate any help on this.

thanks,
Rethna

Code not being highlighted + can't submit pull request

I had a previous issue opened just 2 hours ago at:
#3

I had to make a new thread because it was closed and I cannot reply in it.
(Regarding that console.log issue tried to submit a pull request to remove that but the console.log() code wasn't found on the index.js file in the src folder. It seems to only exist in the index.js inside /dist/ ?

Also, code still isn't being highlighted even when starting out text with "```javascript"

Screenshot below:

unhighlighted

It seems to be loading the styles from the .css style but keywords like "function" or "const" or etc aren't being highlighted with colors. Its just all white.

I am using the prism-okaidia.css stylesheet

Autodetect syntax

Right now you have to type ```<language> to get highlighting in <language>. We should somehow auto-detect which language is used and highlight based on that.

/cc @ngs

Can't get syntax highligth with draft-js-prism-plugin

Hi,

I face a serious issue using the prism-plugin.
I can't get any syntax highlighting ...

Any suggestion would be very, very appreciated :)

Thank you in advance,

Here is my source code:

import React, { Component } from 'react';
import { RichUtils, EditorState, ContentState, convertToRaw, convertFromRaw, DefaultDraftBlockRenderMap } from 'draft-js';
import Editor, { createEditorStateWithText } from 'draft-js-plugins-editor';
import createToolbarPlugin from 'draft-js-static-toolbar-plugin';
import Prism from 'prismjs';
import 'prismjs/themes/prism-solarizedlight.css';

import createCodeEditorPlugin from 'draft-js-code-editor-plugin';
import createPrismPlugin from 'draft-js-prism-plugin';

import {
  CodeBlockButton,
} from 'draft-js-buttons';

const toolbarPlugin = createToolbarPlugin({
  structure: [
    CodeBlockButton,
  ]
});

const { Toolbar } = toolbarPlugin;
const plugins = [
  toolbarPlugin,
  createCodeEditorPlugin(),
  createPrismPlugin({
    prism: Prism
  }),
];
const text = 'var i = 1;';

class CourseEditor extends Component {

  constructor(props) {
    super(props);
    this.state = {
      editorState: createEditorStateWithText(text),
    };

    this.onChange = this.onChange.bind(this);
  }

  onChange(editorState) {
    this.setState({
      editorState: editorState,
    });
  };

  getBlockStyle(block) {
    switch (block.getType()) {
      case 'code-block': return 'language-javascript';
      default: return null;
    }
  }

  // Render
  render() {
    return (
      <div className="editor">
        <Editor
          editorState={this.state.editorState}
          onChange={this.onChange}
          plugins={plugins}
          blockStyleFn={this.getBlockStyle}
          customStyleMap={styleMap}
        />
        <Toolbar />
      </div>
    );
  }
}

const styleMap = {
  CODE: {
    backgroundColor: 'rgba(0, 0, 0, 0.05)',
    fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace',
    fontSize: 16,
    padding: 2,
  },
};

export default CourseEditor;

Code is not being highlighted.

And the console is repeatedly logging "undefined" when I type something in the code block.
I looked at the source map and its coming from \node_modules\draft-js-prism-plugin\dist\index.js:

var prismPlugin = function prismPlugin(options) {
  if (!options || !options.prism) throw new Error('You must provide an instance of the prism.js library to draft-js-prism-plugin. See the documentation at https://github.com/withspectrum/draft-js-prism-plugin for more information!');
  var prism = options.prism;

  return {
    decorators: [new _draftJsPrism2.default({
      prism: prism,
      getSyntax: function getSyntax(block) {
        var language = block.getData().get('language');
        console.log(language);
        if (_typeof(prism.languages[language]) === 'object') {
          return language;
        }
        return null;
      },
      render: function render(_ref) {
        var type = _ref.type,
            children = _ref.children;

        return _react2.default.createElement(
          'span',
          { className: 'prism-token token ' + type },
          children
        );
      }
    })]
  };
};

The console logs undefined repeatedly once I am in a code-block. Why is it not being passed block data?

Rogue `console.log` on npm

I saw e7a8dbc which removes the rogue console.log from the source, but if you do the following you'll see it in there:

$ npm pack draft-js-prism-plugin
draft-js-prism-plugin-0.1.1.tgz
$ tar -xvzf draft-js-prism-plugin-0.1.1.tgz
$ cat package/dist/index.js 
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _draftJsPrism = require('draft-js-prism');

var _draftJsPrism2 = _interopRequireDefault(_draftJsPrism);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var prismPlugin = function prismPlugin(options) {
  if (!options || !options.prism) throw new Error('You must provide an instance of the prism.js library to draft-js-prism-plugin. See the documentation at https://github.com/withspectrum/draft-js-prism-plugin for more information!');
  var prism = options.prism;

  return {
    decorators: [new _draftJsPrism2.default({
      prism: prism,
      getSyntax: function getSyntax(block) {
        var language = block.getData().get('language');
        console.log(language);
        if (_typeof(prism.languages[language]) === 'object') {
          return language;
        }
        return null;
      },
      render: function render(_ref) {
        var type = _ref.type,
            children = _ref.children;

        return _react2.default.createElement(
          'span',
          { className: 'prism-token token ' + type },
          children
        );
      }
    })]
  };
};

Can you rebuild and publish a new version to npm please? ๐Ÿ™‚

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.