sstur / draft-js-utils Goto Github PK
View Code? Open in Web Editor NEWDraftJS: import/export ContentState to and from HTML/Markdown
License: ISC License
DraftJS: import/export ContentState to and from HTML/Markdown
License: ISC License
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
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
Peer dependency immutable is not referenced anywhere except in package.json and should be removed
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
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
after i update to react 16 it error Cannot resolve module 'react-dom/lib/CSSProperty'
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 ?
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. </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?
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;
}
}
draft-js
uses the u
tag in the convertFromHTML
function. Because draft-js-export-html
uses ins
, when you export to HTML and then convert back from HTML you loose the underline information. I suggest to use u
instead.
I have some html generated from the contentState, Is it possible for me to reverse it and get the contentState?
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 :)
This does not behave as expected. linkInstance.getData()
returns object with 'href' key, not 'url'. As a result my links are exported as anchors without an href attribute
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>
...
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?
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?
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)
?
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.
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!
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
fromdraft-js-import-markdown
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.
Hello,
Is it possible to change the way Image gets rendered as HTML?
For my task it would be enough to override ENTITY_ATTR_MAP for the image.
More context: I am using Image Alignment plugin (https://www.draft-js-plugins.com/plugin/alignment) and need to propagate align property to the generated html
We need a way to import DOMParser when on the server but use the global one when on the client.
This issue is a followup to sstur/draft-js-import-html#16 by @meteorplus.
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.
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.
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?
Once the html has been exported, is there currently the ability to switch back into the ContentState
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.
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!
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
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 script tags
Does anyone have any idea why this happens? Thanks in advance.
// 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>
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
I would like to know if there are any plans to support iframe in the future?
Thanks for this btw...
Related to sstur/draft-js-import-element#31
This should be an easy fix.
Hi
I'm not using node. Where can I download a .min.js version of this library?
Thanks,
Dagur
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:
Symbol
polyfill is required.for ... of
.I'm happy to submit a PR for either of these.
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.
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
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?🙂
At the moment we have hardcoded the tags that can be exported, would be great if we could leverage from DefaultDraftBlockRenderMap or the RichTextEditor.blockRenderMap props to correctly export to html. Leveraging from the new API from facebookarchive/draft-js@e203798
Possibly update draft js dependency from 0.5.0 to latest(0.7.0 as of today)?
Hi, I need to create a migration, to convert existing draft-js raw content to html. Can use this library on the backend?
I guess there is no support for stateFromHTML on IE9. Please check. @sstur.
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!
How can I warp and export multiline code block in one single tag ?
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.