jpuri / html-to-draftjs Goto Github PK
View Code? Open in Web Editor NEWLicense: MIT License
License: MIT License
This happens in both the Editor and this package. It seems you use the window
in the code which is not available when compiling in a nodejs environment.
Can we remove window object from the code?
Hi,
Trying to recover <a href="/some/relative/url"> a link </a>
but the url is not transformed.
It works fine with absolute urls such as http://something.com
but did not with /some/relative/url
Thanks
I use react-draft-wysiwyg
editor, to save data to database, I use draftjs-to-html
to convert content to HTML:
const rawContentState = convertToRaw(this.state.editorState.getCurrentContent());
const rawHTML = draftToHtml(rawContentState);
then use html-to-draftjs
to convert it back to draftjs contentState
const blocksFromHtml = htmlToDraft(rawHTML);
const contentBlocks = blocksFromHtml.contentBlocks;
const contentState = ContentState.createFromBlockArray(contentBlocks);
The problem is it added more one empty line at <br>\n
.
for example, the original editor looks like this:
One line
Other line
Other paragraph
become this:
One line
Other line
Other paragraph
versions:
"draft-js": "^0.10.1",
"html-to-draftjs": "0.1.0-beta7",
"react-draft-wysiwyg": "^1.10.0",
"draftjs-to-html":"^0.7.2"
Thank you.
how to support video audio and custom tag
Hi, following a couple frustrating hours trying to get the example working I finally found that the NPM version does not contain customChunkGenerator. Can you please update?
Thank you.
Hi jpuri,
When i tried to use "npm install html-to-draftjs" , i am getting v 1.4.0 and when i checked the dist folder file it is showing me the "april 25th 2018" dated file. This file doesn't have latest changes of the module. Can you please release a newer version of this package asap. We can fix couple of issues in our application.
Thanks,
Jaffar
it's there any version support golang
Hi,
i need to override processInlineTag method in htmlToDraft js. or else is there any way to pass reference of custom processInlineTag method to htmlToDraft so that it i will call the custome processInlineTag.
Regards,
Jaffar
I am not sure is it a bug or a feature but the code below raises an error:
const html = 'some plain text without tags';
const blocksFromHTML = htmlToDraft(html);
const contentState = ContentState.createFromBlockArray(blocksFromHTML.contentBlocks);
editorState = EditorState.createWithContent(contentState);
The error is:
TypeError: t.blocks[r] is undefined
I think it would be great if the library can convert plain text into the editor state
@jpuri i can try to make a pull request if you point me on basic moments how to fix it.
Hi,
this HTML code <span style="font-weight:bold;">bold</span>
is transformed as <p>bold</p>
. I'm using the following code for testing purposes:
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import htmlToDraft from 'html-to-draftjs';
import draftToHtml from 'draftjs-to-html';
export const createEditorStatefromHTML = (data: string): EditorState => {
const contentBlock = htmlToDraft(data);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(
contentBlock.contentBlocks,
contentBlock.entityMap
);
return EditorState.createWithContent(contentState);
} else {
return EditorState.createEmpty();
}
};
export const mapEditorStateToHTML = (editorState: EditorState): string => {
if (!editorState) {
return null;
}
return draftToHtml(convertToRaw(editorState.getCurrentContent()));
};
export const test = () => {
console.log(
mapEditorStateToHTML(
createEditorStatefromHTML(
`<span style="font-weight:bold;">bold</span>`
)
)
);
};
Can you please help me if I'm doing something wrong?
Thanks,
M.
Here is the code:
import {EditorState, ContentState, convertToRaw} from 'draft-js'
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
const contentBlock = htmlToDraft('<p></p>');
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
const outputEditorState = EditorState.createWithContent(contentState);
const rawContent = convertToRaw(outputEditorState.getCurrentContent());
const html = draftToHtml(rawContent);
console.log(html, 'html');
Is it possible to avoid the error? I used such html code because previously i saved converted empty state to database and after that i wanted to edit the html but i got the error.
On server side htmlToDraft returns null
import { EditorState, ContentState } from 'draft-js';
import htmlToDraft from 'html-to-draftjs';
const blocksFromHtml = htmlToDraft(this.props.content);
/* Is this line not right ? */
const { contentBlocks, entityMap } = blocksFromHtml.contentBlocks;
const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
const editorState = EditorState.createWithContent(contentState);
How to use it in “react-draft-wysiwyg”?
Hi @jpuri, Thank you for all the support you are doing for the react-draft-wysiwyg editor.
since this html-to-draft suppose to show html styles as for the text I suspect that color and font size do not getting applied.
Example HTML would be,
<P ALIGN="LEFT"><FONT SIZE="11" COLOR="#339966">Green Colored Text</FONT></P><P ALIGN="LEFT"><FONT SIZE="11" COLOR="#000000">Black Colored Text</FONT></P>
currently It shows just plain text with applying only </P>
s. (new lines)
Since I am moving from old version to HTML5 I need to show already saved html based data by customers in my new editor. is there any solution for this?
Relates to jpuri/draftjs-to-html#36
Per the CSS spec, font-size
can take absolute and relative values, as well as global values, e.g:
font-size: medium;
font-size: larger;
font-size: inherit;
This library currently assumes all font sizes are in pixels, and just removes the last two characters.
Steps to reproduce:
Result:
The outputted html has font-size: medipx
.
I am working on a fix for this and hope to get a PR open shortly.
Is there a way I can keep the ids and classes applied to the elements. If you can just point me in the right direction then I can fork the repo and modify the code.
For Example -
Initial input
<p><b>CHIEF COMPLAINT</b><p id=5b7596aa84089257123ef7af">[The patient presents with a complaint of headache.]</p>
Final Output
<p><b>CHIEF COMPLAINT</b><p>[The patient presents with a complaint of headache.]</p>
Expected Output
<p><b>CHIEF COMPLAINT</b><p id=5b7596aa84089257123ef7af">[The patient presents with a complaint of headache.]</p>
entityConfig.src = node.src;
does not work when I am using images. I had to change it to entityConfig.src = node.getAttribute('src');
. The src property is not up to date with the attributes property on the node. Does this have to be changed to getAttribute or am I doing something wrong?
So if I import htmlToDraft like this
import htmlToDraft from "html-to-draftjs";
I am getting error Window is not defined
So I did
const htmlToDraft = dynamic( () => import("draftjs-to-html").then((mod) => mod.htmlToDraft), { ssr: false } );
Then error is not coming but when I use it like
`useEffect(() => {
props.getDescription().then((res) => {
// console.log(res.data);
const blocksFromHtml = htmlToDraft(res.data);
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(
contentBlocks,
entityMap
);
setEditor(EditorState.createWithContent(contentState));
});
}, []);`
Error is coming: TypeError: htmlToDraft is not a function
@jpuri Can you help me?
I use shift+enter inside a code block to add a line... it works fine.
Then I go to the beginning of the code block and do the same thing and BOOM, it blows up.
GitHub doesn't let me upload an mp4, so I zipped and attached a zipped mp4 of the sequence of events.
Thoughts on how to fix?
I have different types of atomic blocks but currently getData() returns nothing. I've managed to get things working by passing the data to getAtomicBlockChunk with the following changes;
https://github.com/jpuri/html-to-draftjs/blob/master/src/library/index.js (37)
if (customChunkGenerator) {
const value = customChunkGenerator(nodeName, node);
if (value) {
const entityId = Entity.__create(
value.type,
value.mutability,
value.data || {},
);
// return { chunk: getAtomicBlockChunk(entityId) };
return { chunk: getAtomicBlockChunk(entityId, value.data) };
}
}
https://github.com/jpuri/html-to-draftjs/blob/master/src/library/chunkBuilder.js (74)
// export const getAtomicBlockChunk = (entityId: number): Object => {
export const getAtomicBlockChunk = (entityId: number, data: any): Object => {
return {
text: '\r ',
inlines: [new OrderedSet()],
entities: [entityId],
blocks: [{
type: 'atomic',
depth: 0,
// data: new Map({})
data: new Map(data)
}],
};
};
Would it be possible to add this by default please?
Thank you.
Let's say I pass this HTML:
<p><u>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</u></p>
When I convert it to DraftJS content and set it as editor state, the editor shows no trace of any underlined text. I checked if the issue is possibly with the package that I use to convert back to HTML string, but it doesn't seems like it.
Here's what I do:
`
setEditorState = (slide = this.props.editor.slide) => {
const blocksFromHTML = htmlToDraft(slide.text.text || '');
const state = blocksFromHTML.contentBlocks
? EditorState.createWithContent(
ContentState.createFromBlockArray(
blocksFromHTML.contentBlocks,
blocksFromHTML.entityMap
)
)
: createEditorStateWithText('');
return state;
};
`
Am I doing something wrong, or is there a bug with the package?
Check https://www.webpackbin.com/bins/-Kyp64q5ZU8BbzOt-DFj
Font-size is 30px, in the draft-js it doesn't show.
All of our testing environments broke down because of the recent changes.
This is the error that appears on launch:
at Object.<anonymous> (/opt/webui/node_modules/html-to-draftjs/dist/html-to-draftjs.js:1:335)
at Module._compile (module.js:570:32)
at Module._extensions..js (module.js:579:10)
at Object.require.extensions.(anonymous function) [as .js] (/opt/webui/node_modules/babel-register/lib/node.js:152:7)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
The issue can be resolved by returning to version 1.4.0.
Hi @jpuri first of all, thank you for all your great work on this suite of projects for the react-draft-wysiwyg editor. Everything is working great, the only problem I am running is that enclosing DIV tags are getting stripped out somewhere. Basically, I have a templating system that should include some Bootstrap classes and they are all getting stripped out (not sure if this happens in draftToHtml or htmlToDraft functions. I'm using both of these plugins to handle HTML in / HTML out. Can you tell me if there is a workaround for this? Here is some sample code (assume that the argument 'newContent' looks something like this):
const newContent = '
appendContent = (newContent) => {
const { editorState } = this.state
// const content = stateToHTML(editorState.getCurrentContent())
const content = draftToHtml(convertToRaw(editorState.getCurrentContent()))
console.log(newContent)
const newHTML = htmlToDraft(<div>${content}${newContent}</div>
)
const state = ContentState.createFromBlockArray(newHTML.contentBlocks)
this.setState({
editorState: EditorState.createWithContent(state)
},
() => {
this.setState({ dialogOpen: false })
console.log(draftToHtml(convertToRaw(this.state.editorState.getCurrentContent())))
}
)
}
When I go to pull the content as HTML, all of the DIV tags are gone. Can you tell me if there is a work-around for this? Thanks, Steve
Hi, I'm trying to upgrade to react 16 and enzyme 3. However, my tests which were working before are now failing due to missing HtmlElement. Can you please have a look?
I've been trying to find a solution online for a while now, for a seemingly simple task. DraftJS doesn't render tag as bold as default (it seems to use ), but I have lots of content with tags so I need that to be supported. Seems relatively easy right?
Well, the problem is that I can't find a documentation ANYWHERE on what types etc. are supported with customChunkRenderer. My problem is as simple as "render as ", and I've tried to achieve that with this:
const content = htmlToDraft(value, (nodename, node) => { if (nodename === 'b') { console.log('Found a tag', node); return { type: 'STRONG', mutability: 'MUTABLE', data: { innerText: node.innerText, innerHTML: node.innerHTML } } } });
I've gathered this example by searching some other examples from the internet, but I seriously haven't found a good source that explains the values of the return object, ie. what different types are available, what should the 'data' object contain etc.
I tracked this one down to this line here https://github.com/jpuri/html-to-draftjs/blob/master/src/library/index.js#L143 , if chunk.text == ''
then chunk.text.split('\r') == ['']
. later, when the index of the array item is used https://github.com/jpuri/html-to-draftjs/blob/master/src/library/index.js#L161 , chunk.blocks
is empty.
Uncaught TypeError: Cannot read property 'type' of undefined
at eval (webpack:///./src/library/index.js?:161:46)
at Array.map (native)
at eval (webpack:///./src/library/index.js?:147:49)
at htmlToDraft (webpack:///./src/library/index.js?:174:6)
at htmlToContentState (webpack:///./src/index.js?:47:75)
at new Playground (webpack:///./src/index.js?:66:24)
at eval (webpack:///./~/react-dom/lib/ReactCompositeComponent.js?:295:18)
at measureLifeCyclePerf (webpack:///./~/react-dom/lib/ReactCompositeComponent.js?:75:12)
at ReactCompositeComponentWrapper._constructComponentWithoutOwner (webpack:///./~/react-dom/lib/ReactCompositeComponent.js?:294:16)
at ReactCompositeComponentWrapper._constructComponent (webpack:///./~/react-dom/lib/ReactCompositeComponent.js?:280:21)
Version must be ...-beta.N
but not ...-betaN
.
Currently 0.1.0-beta15
< 0.1.0-beta9
.
> semver.lt('0.1.0-beta15', '0.1.0-beta9')
true
> semver.gt('0.1.0-beta15', '0.1.0-beta9')
false
> semver.gt('0.1.0-beta.15', '0.1.0-beta.9')
true
"html-to-draftjs": "^0.1.0-beta15"
$ npm outdated
Package Current Wanted Latest Location
html-to-draftjs 0.1.0-beta15 0.1.0-beta9 0.1.0-beta15 ...
So, npm update
actually does downgrade to beta9
.
this HTML code <b>bold</b>
is not getting added in draft inlineStyleRanges: [].
But when I give <span style="font-weight:bold;">bold</span>
inline style: "BOLD" is getting added in inlineStyleRanges.
In my editor, I provided custom HTML code. In this code, I have some tags that have specific data attribute. In my example, you can see var tag. For that, I use the htmlToDraft method, with a customChunkRenderer for my personal tag
constructor(props: TMyEditorProps) {
super(props);
const html = '<p><span style="font-size: 16px;font-family: Georgia, serif;">test with default style <var data-name="$test"></span></p>'
+ '<p><span style="font-size: 16px;font-family: Georgia, serif;"><strong>test bold</strong></span></p>'
+ '<p><span style="font-size: 16px;font-family: Georgia, serif;"><em>test italic</em></span></p>'
+ '<p><span style="font-size: 16px;font-family: Georgia, serif;"><ins>test underline</ins></span></p>'
+ '<p><span style="font-size: 16px;font-family: Georgia, serif;"><strong><em><ins>test bold & italic & underline</ins></em></strong></span></p>'
+ '<p><span style="font-size: 17px;font-family: Georgia, serif;">test 17px</span></p>'
+ '<p><span style="font-size: 16px;font-family: cursive;">test cursive</span></p>'
+ '<p><span style="font-size: 17px;font-family: cursive;">test 17px & </span><span style="color: rgb(0,0,0);font-size: 17px;font-family: cursive;">cursive</span></p>'
+ '<p><span style="color: rgb(255,0,0);font-size: 16px;font-family: Georgia, serif;">red font</span></p>'
+ '<p><span style="color: rgb(0,0,0);background-color: rgb(0,128,255);font-size: 16px;font-family: Georgia, serif;">blue background</span></p>'
+ '<p><span style="color: rgb(255,0,0);background-color: rgb(255,255,0);font-size: 16px;font-family: Georgia, serif;">red font & yellow background</span></p>'
+ '<p><span style="color: rgb(255,0,0);background-color: rgb(255,255,0);font-size: 20px;font-family: cursive;">font & yellow background & 20px & cursive</span></p>',
contentBlock = htmlToDraft(html, MyEditor.customChunkRenderer),
compositeDecorator = MyEditor.getCompositeDecorator();
let editorState: EditorState;
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
editorState = EditorState.createWithContent(contentState, compositeDecorator);
} else {
editorState = EditorState.createEmpty(compositeDecorator);
}
extractInlineStyle(editorState);
this.state = {
editorState
};
this.onChangeEditor = this.onChangeEditor.bind(this);
this.onChangeBold = this.onChangeBold.bind(this);
this.onChangeItalic = this.onChangeItalic.bind(this);
this.onChangeUnderline = this.onChangeUnderline.bind(this);
this.onChangeFontFamily = this.onChangeFontFamily.bind(this);
this.onChangeFontSize = this.onChangeFontSize.bind(this);
this.onChangeColor = this.onChangeColor.bind(this);
this.onChangeBGColor = this.onChangeBGColor.bind(this);
this.onSelectAll = this.onSelectAll.bind(this);
this.onClickRemoveAllInlineStyle = this.onClickRemoveAllInlineStyle.bind(this);
this.onAddVariable = this.onAddVariable.bind(this);
}
private static customChunkRenderer(nodeName: string, node: HTMLElement): RawDraftEntity | undefined {
let draftEntity: RawDraftEntity | undefined;
if (nodeName === 'var') {
const data = {
name: node.dataset.name
};
draftEntity = {
type: 'VARIABLE',
mutability: 'IMMUTABLE',
data: data
};
}
return draftEntity;
}
...
private static getCompositeDecorator(): CompositeDecorator {
const compositeDecorator: CompositeDecorator = new CompositeDecorator([
{
strategy: MyEditor.findLinkEntities,
component: MyEditor.variableComponent
}
]);
return compositeDecorator;
}
private static findLinkEntities(contentBlock: ContentBlock, callback: FStrategyCallback) {
contentBlock.findEntityRanges(
(character) => {
const entityKey = character.getEntity();
return (
entityKey !== null &&
Entity.get(entityKey).getType() === VariableType
);
},
callback
);
}
private static variableComponent(props): JSX.Element {
const data: TVariableData = props.contentState.getEntity(props.entityKey).getData();
return <span style={{ textDecoration: 'underline' }}>{data.name}</span>;
}
...
Unfortunately, when displaying my var tag in my editor, it does not display correctly. The displayed text does not seem to be in the span that contains all of the style I want to associate with it anymore.
I would like my var tag to display with the style of the span that contains it and on the same line as the previous text.
When I get the html code from the editor state, with the draftToHtml method (git draftjs-to-html project), we see that my var tag is outside the starting span. You can see it in the textarea below the editor.
Thank you very much
Hello, I am working on my project and I used react draft wysiwyg
and stored the HTML
in my database, now I want to show the editor state from my HTML and I find many ways to convert it but my goal is to convert
1. Raw HTML
2. Raw HTML inline styles
3. Image
those into editor state but I can't match all of the three criteria with my code, so can you suggest to me how to convert it, let me give you the example I tried.
In the below Code,
import htmlToDraft from "html-to-draftjs";
import { ContentState, EditorState } from "draft-js";
const blocksFromHTML = htmlToDraft(data.notes);
const contentState = ContentState.createFromBlockArray(
blocksFromHTML.contentBlocks,
blocksFromHTML.entityMap
);
const editorState = EditorState.createWithContent(contentState);
In the below Code,
import { ContentState, convertFromHTML, EditorState } from "draft-js";
const blocksFromHTML = convertFromHTML(data.notes);
const contentState = ContentState.createFromBlockArray(
blocksFromHTML.contentBlocks,
blocksFromHTML.entityMap
);
const editorState = EditorState.createWithContent(contentState);
do you have a solution where all the above 3 will work fine??
When using plug-in html-to-draftjs, if there are a lot of inline styles in the text, and multiple images will be wrong.
Error: Unknown DraftEntity key: null.
at invariant (roadhog.dll.js:5142)
at Object.__get (roadhog.dll.js:35372)
at ContentState.getEntity (roadhog.dll.js:45659)
at eval (react-draft-wysiwyg.js?3aba:66)
at DraftEditorContents.render (roadhog.dll.js:158320)
at roadhog.dll.js:113670
at measureLifeCyclePerf (roadhog.dll.js:112950)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (roadhog.dll.js:113669)
at ReactCompositeComponentWrapper._renderValidatedComponent (roadhog.dll.js:113696)
at ReactCompositeComponentWrapper.performInitialMount (roadhog.dll.js:113236)
html like this is wrong
<p>sdad</p>
<p>fsasf </p>
<p>dsfafa</p>
<p></p>
<img src="http://qqd.oss-cn-shanghai.aliyuncs.com/qqd/files/image/1511319379141.jpg?E…OSSAccessKeyId=LTAIL65DTXQAWPOw&Signature=aZe%2BHxuxvugALiJat3cck0a8xKk%3D" alt="" style="float:none;height: auto;width: 100px"/>
<p>sdfsfsdfsdfdsffsf</p>
<p>sfadasdffdgnsmgngdsfsf</p>
<p><span style="color: rgb(36,41,46);background-color: rgb(255,255,255);font-size: 14px;">The example is a bit misleading. It probably shouldn't try to use</span> <span style="color: rgb(36,41,46);background-color: rgb(255,255,255);font-size: 14px;"><code>img</code></span> <span style="color: rgb(36,41,46);background-color: rgb(255,255,255);font-size: 14px;">directly as the atomic block, but should instead use a wrapper div and apply the width to that. Then the</span> <span style="color: rgb(36,41,46);background-color: rgb(255,255,255);font-size: 14px;"><code>img</code></span> <span style="color: rgb(36,41,46);background-color: rgb(255,255,255);font-size: 14px;">can be an arbitrary width, but the div width should remain 100%.</span></p>
<img src="http://qqd.oss-cn-shanghai.aliyuncs.com/qqd/files/image/1511319471896.jpg?E…OSSAccessKeyId=LTAIL65DTXQAWPOw&Signature=jm9S1ji7g57sDn%2B3zQg5bfW3KYY%3D" alt="" style="float:none;height: auto;width: 200px"/>
A html string like this will display normally:
<p>222</p>
<p>kl khjhj jk hk </p>
<p> </p>
<img src="http://qqd.oss-cn-shanghai.aliyuncs.com/qqd/files/image/1511314523589.jpg?E…2&OSSAccessKeyId=LTAIL65DTXQAWPOw&Signature=sVUmBEUhZzrm4QlJuUZQNPTFW4o%3D" alt="" style="float:none;height: auto;width: 100px"/>
<p>dsaad </p>
<p>dfafafasfdaf</p>
<p> </p>
<img src="http://qqd.oss-cn-shanghai.aliyuncs.com/qqd/files/image/1511323398697.jpg?E…0&OSSAccessKeyId=LTAIL65DTXQAWPOw&Signature=E6vctlCqQxORqScZZLlP5ogg1sQ%3D" alt="" style="float:none;height: auto;width: auto"/>
<p>dsdadadadadas</p>
@jpuri I'm still getting the same issue:
My package.json
"html-to-draftjs": "^0.1.0-beta11"
"react-draft-wysiwyg": "^1.10.7"
As I need this feature soon, is there any workaround?
WARNING: DraftEntity.create will be deprecated soon!
Please use "contentState.createEntity" instead.
When htmlToDraft is used, above warning is throwed.
Hi,
I am trying to use html-draft and draft-html libraries to convert a html markup like below with custom tags.
<h2>I'm a heading</h2> Custom data <custom index="1" data="custom">Custom</custom><br/> Html text <em>Italic</em><strong>strong</strong><bold><em>bold italic</em></bold>
I have defined the customChunkGenerator for this custom tag which generates the entity for this block.
When i use the same to convert back to html, it removes all the data after the custom tag.
Is this supported with custom tags and html markups around it?
<p>Hello jpuri. How are you?</p>
<blockquote><p>Hello erika</p></blockquote>
Hello jpuri. How are you?
Hello erika
<p>Fine :)</p>
<blockquote>
<p>Hello jpuri. How are you?</p>
<blockquote><p>Hello erika</p></blockquote>
</blockquote>
Fine :)
Hello jpuri. How are you?
Hello erika
htmlToDraft
generate blockquote separates and the content out from them, like this:<p>Fine :)</p>
<blockquote></blockquote>
Hello jpuri. How are you?
<blockquote></blockquote>
Hello erika
Fine :)
.Hello jpuri. How are you?
.Hello erika
I'm having trouble with Error: Unknown DraftEntity key.
with following code:
const htmlToContentState = (html = "") => {
const {contentBlocks, entityMap} = htmlToDraft(html);
return ContentState.createFromBlockArray(contentBlocks, entityMap);
}
"html-to-draftjs": "0.1.0-beta14",
"react-draft-wysiwyg": "^1.10.7",
This is my html sample:
<p><strong>Hỗ trợ công nghệ</strong><strong> cảm ứng thông minh, dễ dàng một chạm để điều khiển cuộc gọi và âm nhạc. Tương thích với hầu hết thiết bị hiện nay, smartphone, máy tính bảng, laptop...</strong></p>
<figure><img alt="" src="http://i.imgur.com/qSq4vIa.jpg"/></figure>
const ArticleForm = (props) => {
const {article} = props
const classes = useStyles();
const dispatch = useDispatch()
const router = useRouter()
const [editorState, setEditorState] = useState(EditorState.createEmpty());
const blocksFromHtml = htmlToDraft(article.body);
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
const loadedEditorState= EditorState.createWithContent(contentState);
debugger
setEditorState(loadedEditorState)
the setEditorState is causing this error:
I noticed that when an image with URL is proccessed by htmlToDraft function, the result contains the image as a source data in base64 encoded. It is posible to mantain URL after htmlToDraft??
let html='<img src="https://estaticos.sport.es/resources/jpg/0/7/leo-messi-ficha-bio-utilizar-1375639723270.jpg"/>'
const contentBlock = htmlToDraft(html);
In the object contentBlock there is something like this:
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABA{...}"/>
It's works fine in FireFox and Chrome, but breaks completly in IE9.
Here is just one of the scripts that is throwing an error... SCRIPT600: Invalid target element for this operation.
import draftToHtml from 'draftjs-to-html';
const blocksFromHtml = htmlToDraft('<p></p>');
Hi, I have an error if the string that I try to parse contains tags even with no href attributes
E.g.
import htmlToDraft from 'html-to-draftjs';
htmlToDraft('<p>www <a>site</a> </p>');
Error I get:
TypeError: n.Entity.__create is not a function
Through the constructor
initialization state,
const sampleMarkup = '<p><b>Bold text</b><a href="http://baidu.com">baidu.com</a></p><p><img src="https://avatars3.githubusercontent.com/u/1481983?v=3&s=88"/></p>';
const contentBlock = htmlToDraft(sampleMarkup);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
this.state.initState = EditorState.createWithContent(contentState);
}
Initialize shows that there is no problem, but when the editor be focused, and show some error tips
full code:
import React, {Component, PropTypes} from 'react';
import {Editor} from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import {convertToRaw, convertFromHTML, ContentState, EditorState} from 'draft-js';
import uploadImageCallBack from './plugins/UploadImageEditor';
import './RichTextEditor.css';
class RichTextEditor extends Component {
constructor(props) {
super(props);
const sampleMarkup = '<p><b>Bold text</b><a href="http://baidu.com">baidu.com</a></p><p><img src="https://avatars3.githubusercontent.com/u/1481983?v=3&s=88"/></p>';
const contentBlock = htmlToDraft(sampleMarkup);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
this.state.initState = EditorState.createWithContent(contentState);
}
};
static propTypes = {
onChange: PropTypes.func,
value: PropTypes.string
};
state = {
outputEditorState: undefined
};
onEditorStateChange = function(inputEditorState) {
const rawContent = convertToRaw(inputEditorState.getCurrentContent());
const html = draftToHtml(rawContent);
const contentBlock = htmlToDraft(html);
if (contentBlock) {
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
const outputEditorState = EditorState.createWithContent(contentState);
this.setState({inputEditorState, outputEditorState});
}
if (typeof this.props.onChange === 'function') {
this.props.onChange(html);
}
};
render() {
return (<Editor onEditorStateChange={this.onEditorStateChange.bind(this)} editoerState={this.state.outputEditorState} defaultEditorState={this.state.initState} uploadCallback={uploadImageCallBack} wrapperClassName="global-rte-class" editorClassName="editor-class" toolbarClassName="toolbar-class"/>);
}
};
export default RichTextEditor;
Thanks
const blocksFromHtml = htmlToDraft(this.props.value);
const { contentBlocks, entityMap } = blocksFromHtml;
const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
const editorState = EditorState.createWithContent(contentState);
this.state = {
editorState,
loading: false
};
<Editor editorState={this.state.editorState} defaultEditorState={this.state.editorState}/>
here props value just is img tag with src
it will throw an error Unknown DraftEntity key: null.
why ????
and if i pass
<p></p>
<img src="..."/>
it will work
and if i pass
<p></p>
<img src="..."/>
<span>it will invisible or miss in editor<span>
// or
<p></p>
<img src="..."/>it will invisible or miss in editor
it will invisible all the element after img tag
Hope to get the answer
image attribute can't tranformed to entity
html-to-draftjs/src/index.js
// const html = '<p>123</p>'
// Note This line is replaced with the following to see the effect
const html = '<p><span style="color: rgb(251,160,38);">123</span></p>'
html-to-draftjs: doesn't render <p>
tags, instead that I see <span data-text="true">...</span>
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.