Giter VIP home page Giter VIP logo

draft-js-utils's Introduction

draft-js-utils's People

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  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  avatar  avatar

Watchers

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

draft-js-utils's Issues

Attribute href of link isn't created

Hello, I have the following state, stored into database:
{"entityMap":{"0":{"type":"LINK","mutability":"MUTABLE","data":{"href":"google.com"}},"1":{"type":"LINK","mutability":"MUTABLE","data":{"href":"google.com"}}},"blocks":[{"key":"bamiu","text":"test link 1","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[{"offset":0,"length":11,"key":0}],"data":{}},{"key":"1ffmj","text":"","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"13o8k","text":"test link 2","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[{"offset":0,"length":11,"key":1}],"data":{}}]}
Then i'm trying to:

import {stateToHTML} from 'draft-js-export-html';
import {convertFromRaw} from 'draft-js';

const contentState = loaded_from_DB_as_a_string value;
stateToHTML(convertFromRaw(JSON.parse(contentState)));

It renders HTML well, but links are without href attr.

How can i get my iframe tags converted ?

Now it is possible to add embedded youtube content in draft js editor by using the draft js video plugin.
However, draft-js-export-html seems to ignore iframe tags.
All iframes are converted into

<figure>&nbps</figure>

It's very annoying, i really need to "stringify iframes "
Is there a tips to turn iframe tags into string html ?

Thanks for your support

iframe support?

I would like to know if there are any plans to support iframe in the future?
Thanks for this btw...

Convert to raw to HTML conversion

So right now I can convert the content state from the editor into html using the module below

import {stateToHTML} from 'draft-js-export-html';
let html = stateToHTML(contentState);

We're looking to take the output of convertFromRaw(contentState) which is saved into our database and then to turn this into html on the backend so we can send it as the body of an email.

Have you got any plans for rawToHTML(rawContent)?

images are not being included

// JSON.stringify(this.state.editorState.getCurrentContent())
{
  "entityMap": {},
  "blocks": [
    {
      "key": "cv5ve",
      "text": "test",
      "type": "unstyled",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": [],
      "data": {}
    },
    {
      "key": "bup2p",
      "text": "",
      "type": "atomic",
      "depth": 0,
      "inlineStyleRanges": [],
      "entityRanges": [],
      "data": {
        "src": "http://i.imgur.com/ARlToD4.jpg",
        "type": "image",
        "display": "medium",
        "caption": "caption",
        "rightsHolder": "rights"
      }
    }
  ]
}

// stateToHTML(this.state.editorState.getCurrentContent())
<p>test</p>
<figure><br></figure>
<p><br></p>
<p><br></p>

converToHtml give back string

The convertToHtml method gives back a sting and shows up as
example <div>EDITOR TEXT HERE</div>

rather than

example EDITOR TEXT HERE

is this expected behaviour or is this something wrong happening in my case... (i am using ssr and i am able to parse string to html with react's dangerouslySetInnerHTML)

Thank you

could it support 'inlineStyleFn'

There are some inline styles like 'fontSize'-'color'-'backgroundColor' that I want to set.
Here is customStyleFn that I used in Draft Editor Component:

this.customStyleFn = (style) => {
      const output = {};
      let fontSize = style.filter(value => value.startsWith('fontSize_')).first();
      if (fontSize) {
        fontSize = fontSize.replace('fontSize_', '');
        output.fontSize = fontSize;
      }
      let color = style.filter(value => value.startsWith('color_')).first();
      if (color) {
        color = color.replace('color_', '');
        output.color = color;
      }
      let backgroundColor = style.filter(value => value.startsWith('backgroundColor_')).first();
      if (backgroundColor) {
        backgroundColor = backgroundColor.replace('backgroundColor_', '');
        output.backgroundColor = backgroundColor;
      }
      return output;
};

So, I hope the stateToHTML has the same option like this. Will it be added?πŸ™‚

Fail to export image

Hi,

First thanks for the great work!
Just I encountered this issue when I tried to export atomic block type (image), but finally located the cause of this problem:

// draft-js-export-html/src/stateToHTML.js
renderBlockContent(block: ContentBlock): string {
  ...
  return entityPieces.map(([entityKey, stylePieces]) => {
      let content = stylePieces.map(([text, style]) => {
      ...
      let entity = entityKey ? Entity.get(entityKey) : null;
      let entityType = (entity == null) ? null : entity.getType();
      // entity.getType() returns downcased 'image'
      if (entityType != null && entityType === ENTITY_TYPE.LINK) {
        ...
      } else if (entityType != null && entityType === ENTITY_TYPE.IMAGE) {
        // Did not enter this block since entityType is downcased 'image' while ENTITY_TYPE.IMAGE returns uppercased 'IMAGE'. 
        // Use entity.getType().toUpperCase() instead shall fix it
        ...
      } else {
        return content;
      }
    }).join('');

Hope this can be patched asap :)

Codeblocks not working when converting from markdown

With some recent updates, blockquotes are now working beautifully! πŸ’―

The last bug I have is code blocks, neither indent-style nor backtick-style codeblocks are converted over right now; they just disappear. πŸ˜• Any ideas how that could be fixed?

Original issue: sstur/draft-js-import-markdown#1

NOTE: I'm running stateFromMarkdown from draft-js-import-markdown

Convert raw HTML containing datasets into a draftJS contentBlock and back again

Originally posted here.

The original post by @rpmonteiro is as follows:


We're trying to convert this into a valid contentBlock that draftJS can display (it's a custom entity of type 'PERSON'), and then eventually do the opposite with the export-html.

<p>This is a <span class="person" id="123" data-tag-id="100">special</span> element.</p>

How would we go about this? Is it possible using this library? We can't seem to hook any kind of data attributes when doing stateFromElement passing customBlockFn() in the options.

Thank you!

Broken on React 15.4.0

Fails with:

Error: Cannot find module "react/lib/CSSProperty"
ERROR in ./~/draft-js-export-html/lib/helpers/styleToCSS.js
Module not found: Error: Cannot resolve 'file' or 'directory' /[...]/node_modules/react/lib/CSSProperty in /[...]/node_modules/draft-js-export-html/lib/helpers
 @ ./~/draft-js-export-html/lib/helpers/styleToCSS.js 7:19-51

Probably because of:

React package and browser build no longer "secretly" includes React DOM. (@sebmarkbage in #7164 and #7168)

So there is no CSSProperty anymore.

Import as show in readme not working

Hi, awesome project ✌️

I'm unable to import stateToHtml with the following

import {stateToHTML} from 'draft-js-export-html';
console.log(stateToHtml) // undefined

However if I import it like this it works

import stateToHtml from 'draft-js-export-html/lib/stateToHTML';
console.log(stateToHtml)
// function stateToHTML(content, options) {
//   return new MarkupGenerator(content, options).generate();
// }
"webpack": "^2.2.0"
node -v // v7.7.3
cat node_modules/draft-js-export-html/package.json | grep version //"version": "0.5.4"
yarn --version // 0.22.0
macOS Sierra v 10.12.4

Do you have any idea why, all help is appreciated ?

Parse error

Hello, I'm using DraftJs 0.7.0, draft-js-export-html 0.4.0, and a Play backend which might apply a kind of parsing of the javascript in order to "optimize" it (Assets Google Closure Compiler).

The backend parser is giving me some error when parsing the draft-js-export-html code that I have got with NPM:
"Parse error. missing name after . operator" on the block code:

if (!_iteratorNormalCompletion && _iterator.return) {
    _iterator.return();

This is a part of code that exists in the lib files from npm package, but not in the src files from the github. This lib code seems to be generated and is maybe a problem for my backend parser because it is using "return" as a method while it is a keyword, which may be deprecated or something like this...
There is no problem anymore if I minimize the files, but in developer environment I prefer to not have all packages minimized so that I can debug.

Would it be possible to have directly a minimized javascript file in the NPM package or at least some code that is not generated like this?

Cannot resolve module 'react-dom/lib/CSSProperty'

Getting this error after installing 0.5.2:

ERROR in ./~/draft-js-export-html/lib/helpers/styleToCSS.js
Module not found: Error: Cannot resolve module 'react-dom/lib/CSSProperty' in /Users/dmt0/projects/web/node_modules/draft-js-export-html/lib/helpers
 @ ./~/draft-js-export-html/lib/helpers/styleToCSS.js 7:19-55

Newlines inside code blocks are output as <br>

Code blocks that contain \n have them replaced in encodeContent() with <br>\n, however this isn't necessary for preformatted content.

encodeContent() is called just before the code block check in renderBlockContent(). Not sure whether it'd be better to a) split the newline replacement into a new method, b) move the encoding to after the code block check, or c) undo the replacement for code blocks. Happy to PR one of these!

Custom Entity Export

I have a bunch of custom entities that I use in my app (e.g. placeholders) and I would like to be able to export them with custom markup so that I can easily load them into the Draft editor later. It'd be great if you could pass in an optional map from entityType to a function that renders the given entity, which would then be used in renderBlockContent before the else statement that returns the content.

Do the reverse?

I have some html generated from the contentState, Is it possible for me to reverse it and get the contentState?

Stripping classes, attributes etc

Hello, I've noticed the export is stripping attributes on elements...

const blockArray = Draft.convertFromHTML("<h1 class='myclass'>hello</h1>")
const contentState = ContentState.createFromBlockArray(blockArray)

this.state = {
  editorState: EditorState.createWithContent(contentState)
}

const contentState =  this.state.editorState.getCurrentContent()
const html = stateToHTML(contentState)

console.log(html) // <h1>hello</h1> missing class...

The h1 class is present in the rendered DOM. Is this the expected behaviour? I might be going about this completely backwards so any advice is appreciated.

Change LINK to open in new tab

Hi mate, your work is very nice. I have problem... I use draft-js plugins and i want to change default LINK element that it after click open it in new tab. thanks

InlineStyles

I've got a problem with using inline-styles. Fonts and colors are processed corretly, but font-size and text-align don't work.

Example:

let options = {
   inlineStyles: {
        //sizes
        'Medium': {element: "size", attributes: {size: 3}},
        //align
        'Left': {element: "family", attributes: {align: "Left"}},
      },
};
 stateToHTML(this.editor.content, options);

It igonres "medium" and "left" properties.
Is it bug or I'm doing something wrong?

Performance issue when converting HTML with many trailing space to editorState

Originally posted here.

The original text follows.


Performance issue when converting HTML to editorState (with stateFromHTML from draft-js-import-html)

Below is an example of some HTML that contains many trailing spaces which causes the parsing process to slow down. Time taken depends on how large the HTML is, it can take more than 1 minute for a fairly large block of HTML.

Also, I used performance.now() to measure the time taken when using stateFromHTML.

"<em> Nemo develops a smaller right fin <\/em> as a result of damage to his egg during the attack, which limits his <em> swimming ability <\/em> . <br><br> Worried about Nemo's safety, Marlin embarrasses Nemo during a school field trip. <br><br> Nemo sneaks away from the reef and is <em> captured by scuba divers <\/em> . <br><br> As the boat departs, a diver accidentally knocks his <a href=\"https:\/\/en.wikipedia.org\/wiki\/Diving_mask\"> <em> diving mask <\/em> <\/a> overboard. <br><br> While attempting to save Nemo, Marlin meets Dory, a good-hearted and optimistic <a href=\"https:\/\/en.wikipedia.org\/wiki\/Paracanthurus\"> <em> regal blue tang with <\/em> <\/a> <em> short-term memory loss <\/em> . <br><br> Marlin and Dory meet three <a href=\"https:\/\/en.wikipedia.org\/wiki\/Shark\"> <em> sharks <\/em> <\/a> – <em> Bruce, Anchor and Chum <\/em> – who claim to be <em> vegetarians <\/em> ."

Time taken:
1st round - 443.50ms
2nd round - 481.62ms
3rd round - 442.65ms

This HTML has the trailing spaces removed and it is working perfectly fine as you can see the result of the time taken to convert below.

"<em>Nemo develops a smaller right fin <\/em>as a result of damage to his egg during the attack, which limits his <em>swimming ability <\/em>.<br>\n<br>\nWorried about Nemo's safety, Marlin embarrasses Nemo during a school field trip.<br>\n<br>\nNemo sneaks away from the reef and is <em>captured by scuba divers <\/em>.<br>\n<br>\nAs the boat departs, a diver accidentally knocks his <a href=\"https:\/\/en.wikipedia.org\/wiki\/Diving_mask\"><em>diving mask <\/em><\/a>overboard.<br>\n<br>\nWhile attempting to save Nemo, Marlin meets Dory, a good-hearted and optimistic <a href=\"https:\/\/en.wikipedia.org\/wiki\/Paracanthurus\"><em>regal blue tang with <\/em><\/a><em>short-term memory loss <\/em>.<br>\n<br>\nMarlin and Dory meet three <a href=\"https:\/\/en.wikipedia.org\/wiki\/Shark\"><em>sharks <\/em><\/a>\u2013 <em>Bruce, Anchor and Chum <\/em>\u2013 who claim to be <em>vegetarians <\/em>."

Time taken:
1st round - 63.91ms
2nd round - 71.46ms
3rd round - 65.11ms

HTML to draft js

Once the html has been exported, is there currently the ability to switch back into the ContentState

React-DOM is no longer "secretly" included in React > 15.4.0 (CSSProperty require from react = error)

Since release 15.4.0, React package and browser build no longer "secretly" includes React DOM.

Resulting in

Failed to compile.

Error in ./~/draft-js-export-html/lib/helpers/styleToCSS.js
Module not found: 'react/lib/CSSProperty' in /Users/orditeck/Sites/MyProject/frontend/node_modules/draft-js-export-html/lib/helpers

 @ ./~/draft-js-export-html/lib/helpers/styleToCSS.js 7:19-51

Coming from this line, var _CSSProperty = require('react/lib/CSSProperty');

I'll open a pull request in a few minutes.

Add option to not render blocks with only whitespace

Is that behaviour intentional? Wouldn't it be better to return an empty string instead?

...
import { stateToHTML } from 'draft-js-export-html';

...

console.log(stateToHTML(EditorState.createEmpty().getCurrentContent()));
// <p><br></p>

const blockArray = convertFromHTML('');
const contentState = ContentState.createFromBlockArray(blockArray);
console.log(stateToHTML(contentState));
// <p><br></p>
...

Uncaught Invariant Violation: Unknown DraftEntity key throw.

hi dears,
it works for export h1 ,bold and such types.
but when i insert image using `AtomicBlockUtils.insertAtomicBlock``
i need your help to handle with this.

    var entity = entityKey ? _draftJs.Entity.get(entityKey) : null; //null

but i really got the entity type in mediaBlockRenderer

getEntityAt :1
VM2529 431ef83…-client-jsdeps.min.js:258entity.getType()IMAGE

Node.js support?

Hi, I need to create a migration, to convert existing draft-js raw content to html. Can use this library on the backend?

Apply element/attributes/style to block level elements

Currently you can configure inlineStyles elements to use custom element/attributes/style, but in order to do that for the block elements, you have to configure a blockRenderer, and override the part of the default behavior that you want.

For example, if I define a blockRenderer for this output

<p><strong class="inline inline--bold">Lorem ipsum dolor sit amet</strong>, consectetur <em class="inline inline--italic">adipiscing elit. In sit amet enim</em> auctor, sagittis enim sit amet, eleifend arcu. <ins class="inline inline--underline">Nam nisl quam</ins>, molestie eget egestas a, auctor non elit.&nbsp;</p>

such as this:

blockRenderers: {
    unstyled: block => {
      return `<p className="block">${block.getText()}</p>`
    }
  }

I get this (I lose the block rendering of the children)

<p className="block">Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sit amet enim auctor, sagittis enim sit amet, eleifend arcu. Nam nisl quam, molestie eget egestas a, auctor non elit. </p>

When I wanted to preserve the way the body is implemented, and only add the className

Is there a way to do that with the current configuration?

Intergrate prettier

It'd be great to integrate prettier with lint-staged in a pre-commit hook so folks who work on these libraries don't have to worry about linting anymore!

ul and ol list wrapper tags getting extra white space

I found that ul and ol tags get an extra indent which causes additional white space
e.g. <ul>...<li> spaces not dots though

This caused an issue for me because when Draft read that in, it was interpreted as a break so put a <p><br</p> between each list item. To be fair I am using draft-convert to import the html and this library for export, due to the much better performance of this library when converting on the onChange event.

Removing the indent in the openWrapperTag and closeWrapperTag fixed the issue for me. I could add a pr, but only if others experience the same issue.

 openWrapperTag(wrapperTag        ) {
   this.wrapperTag = wrapperTag;
   this.output.push(`<${wrapperTag}>\n`);
 }

 closeWrapperTag() {
   let {wrapperTag} = this;
   if (wrapperTag) {
     this.output.push(`</${wrapperTag}>\n`);
     this.wrapperTag = null;
   }
 }

Styling elemenet wrappers (ol, ul)

Hi

I want to apply some extra margin to ol and ul elements.

I am using blockRenderers option like this:

const options = {
        blockRenderers: {
          'header-one': (block) => {
            return `<h1 style="font-family:Helvetica,Arial,sans-serif;font-weight:400;margin:0 0 1em 0;padding:0">${block.getText()}</h1>`
          },
          'header-two': (block) => {
            return `<h2 style="font-family:Helvetica,Arial,sans-serif;font-weight:400;margin:0 0 1em 0;padding:0">${block.getText()}</h2>`
          },
          'ordered-list-item': (block) => {
            return `<li style="margin:10px 0">${block.getText()}</li>`
          },
          'unordered-list-item': (block) => {
            return `<li style="margin:10px 0">${block.getText()}</li>`
          },
          'unstyled': (block) => {
            const text = block.getText()
            return `<p style="margin:0 0 1em 0;padding:0">${text}</p>`
          },
        }
      }

But I'm not sure how to reach those elements

The Result Export <p> instead of <a>

Hi,

First, I would like to say thank you for your awesome work.

Currently I'm using DraftJS Plugins . I use its mention plugin which should be linked to a url. But when I try to get the content's HTML using this draft-js-export-html, the element is exported as <p> instead of <a>. Any thoughts?

Please update NPM module.

Can you please upgrade the NPM module to resolve the

WARNING: DraftEntity.get will be deprecated soon!
Please use "contentState.getEntity" instead.

deprecation warning? This was fixed in this pull request #71 which was merged into master

Options Blockrenderers

export const LFEditor = ({ editorState }) => {

  let options = {
    blockRenderers: {
      ATOMIC: (block) => {
        const type = contentBlock.getType();
        if (type == 'atomic') {
          return `<div>hello world</div>`;
        }
        return null;
      }
    }
  };
  let html = stateToHTML(editorState.getCurrentContent(), options);
  return <div dangerouslySetInnerHTML={_createMarkup(html)} />;
};

Unfortunately the returned hrml string doesn't contain the blocks supposedly mark up.

Js in html issues: Script tags not working but inline script works

Thanks for the awesome work. I used draft-js-import-html in my project and it worked pretty well.
I am trying to display the current time in the HTML and ran into problems:

Event handlers work but script tags do not.

An example of event handlers
screen shot 2017-05-19 at 2 22 14 pm

An example of script tags

screen shot 2017-05-19 at 2 23 03 pm

Does anyone have any idea why this happens? Thanks in advance.

Symbol polyfill implicitly required

Thanks for this plugin–it's been a breeze to use.

I noticed over the weekend that a code path taken from the compiled version of this lib fails on IE 11 and under if you don't have Symbol polyfilled. I got bit by this and figure that there are a couple paths to take to prevent other folks from experiencing this:

  1. Update the readme to state that a Symbol polyfill is required.
  2. Update the source to favor a different flavor of looping instead of for ... of.

I'm happy to submit a PR for either of these.

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.