facebook / draft-js Goto Github PK
View Code? Open in Web Editor NEWA React framework for building text editors.
Home Page: https://draftjs.org/
License: MIT License
A React framework for building text editors.
Home Page: https://draftjs.org/
License: MIT License
What's the reasoning behind preventing a code-block
entity from becoming unstyled by backspacing when it's empty. Right now it behaves differently from the other entities (all the other block types can be unstyled).
Related code: https://github.com/facebook/draft-js/blob/master/src/model/modifier/RichTextEditorUtil.js#L418
Currently, draft-js has its dependencies listed as 'React' and 'ReactDOM' but it appears that only the "components" need those dependencies.
As somebody who would like to leverage the "model" features of this framework inside of a library other than React and ReactDOM, I would like to have the ability to include just the "model" code as a dependency in my project.
I'm curious what your thoughts are regarding splitting this framework into two separate modules, presumably one being the "model" layer and the other being the (react) "components" (which will depend on the model).
If it is decided that this change makes sense, I'm open to helping out via pull-requests, ect...
Please let me know what I can do to help.
if you type a b
and call editorState.getCurrentContent().getPlainText()
the internal space is a normal space but the final space is ascii 160. This causes problems if you want to match this text against other strings. I fixed it externally with the code below, but maybe this fix should be handled internally?
cleanPlainText(editorState) {
const text = editorState.getCurrentContent().getPlainText();
const nbsp = String.fromCharCode(160);
const regex = new RegExp(`${nbsp}`, 'g');
return text.replace(regex, ' ');
},
I'd love to know what the ideal way to implement drag&drop of blocks, like the latex component in the tex example, would be. I see that the facebook notes editor does not provide such a feature for images. Any info on that?
As per our discussion on Twitter https://twitter.com/rgbkrk/status/702172656657764352.
Lets chat more here. Cc: @hellendag @vjeux @rgbkrk
ReferenceError: Can't find variable: convertToRaw
is thrown when clicking "Log State" in the link example.
Can we just add a node dependency to draft-js and include it via browserify?
I’m using the Rich example as a starting point for some testing. When I run the example locally it responds to interaction quickly, but when I drop it into an existing app the inline style actions begin to slow down noticeably.
Here is a video illustrating the difference in response times between block- and inline-style toggles: http://cloud.smallparade.com/fEwR
You’ll see there is a noticeable lag time when clicking any of the inline style buttons.
I’ve stripped the component down to nothing but Draft, but it still lags. Sometimes even >1 second. Any suggestion on what to look for, or common issues that cause this kind of behavior?
From the documentation
convertFromRaw(rawState: RawDraftContentState): ContentState
Given a raw state, convert it to ContentState object. This is useful when restoring contents to use within a Draft editor.
From my testing, convertFromRaw actually returns an Array of ContentBlock objects. To convert this back to a ContentState you must do the following:
ContentState.createFromBlockArray(convertFromRaw(rawData))
Warning: A component is
contentEditable
and containschildren
managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.
Is this needed for every onChange? Seems to do justice just on the component mounting.
Ps. This project made my day.
I am using node v4.3.1
examples/rich.html
Blockquote
The blockquote would delete allowing you to add new text type(s) to the line
The blockquote does not delete if there are other blockquotes below it, making it difficult to
go back and add lines above it.
The issue only occurs if the topmost line is a blockquote.
Hi, I'm working on a chrome extension that lets you input text through it. Unfortunately Draft.js breaks when inputting in a standard way.
Steps to reproduce:
document.execCommand("insertHTML", false, "X");
in the dev tools consoleResult expected:
X
is added to the input box
Actual result:
X
is added to the input box twice. You're able to delete one of the instances, but the other one is undeletable but is selectable.
Note: Once at least one character has been typed into the Draft.js input the command works as expected.
Repro:
Expected:
Actual:
As I typed this bug with Github Markdown editor, I noticed it also demonstrates this behavior (triple-clicking a line and applying bold will drop the trailing **
at the beginning of the next line). Maybe this is out of the hands of Draft. However, I do believe that fixing the issue would lead to more reasonable UX.
When integrating draft-js into an existing project I get
Warning: A component is
contentEditable
and containschildren
managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.
I am using the rich text example, and that gives me this warnings:
Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of
BlockStyleControls
. See https://fb.me/react-warning-keys for more information.Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of
InlineStyleControls
.
using the rich.html
example from the repository
I’d like to allow for users to save their content in a way that Draft will recognize when loaded again. What is the recommended way to retrieve the content in its current state? I assume the content would look something like this?
With this method, the editor seems to get its internal state corrupted.
EditorState.moveFocusToEnd(EditorState.createEmpty())
was required to actually clear the state properly.
The following is an example editor component
`
import React from 'react';
import {Editor, EditorState} from 'draft-js';
export default class MyEditor extends React.Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty()
};
}
onChange = (editorState) => {
this.setState({editorState});
}
render() {
const {editorState} = this.state;
return <Editor editorState={editorState} onChange={this.onChange} />;
}
}
`
And in my parent component
import MyEditor from './MyEditor'
.... // in the render() method
`
render() {
let error = this.getError();
return (
<form className="post__form">
{error}
<div className="form-group">
<label htmlFor="title">Title</label>
<input type="text" ref="title" className="form-control" id="title" placeholder="Title" />
</div>
<div className="form-group">
<label htmlFor="description">Description</label>
<MyEditor />
</div>
<button type="submit" onClick={this.onClickHandler.bind(this)} className="btn btn-default">Submit</button>
</form>
);
}
`
And I see this warning
Warning: A component is contentEditable
and contains children
managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.
_insertText() {
const editorState = this.state.editorState;
const selection = editorState.getSelection();
const contentState = editorState.getCurrentContent();
const ncs = Modifier.insertText(contentState, selection, "wefoiwjoefjwoiefjoiwjefio");
const es = EditorState.push(editorState, ncs, 'insert-fragment');
this.setState(es);
}
With above codes, i can't get the wef....
to be append to the end. I have work on this problem for hours, but still can't found the solution. The above code is written according to Tex
sample.
If you type Opt-Space to insert a nbsp (on http://facebook.github.io/draft-js/, for example) in Chrome Mac, the page scrolls down a screenful but it probably shouldn't move. Missing preventDefault() somewhere probably.
In a previous project similar to Draft.js I used JSS to create a dynamic stylesheet that I could manage classes and styles in real-time. Primarily for things like changing text color to a user-selected color, or changing font-size to something the user selects. This allowed for a lot of flexibility, but also meant that the styles didn’t have to be created up front. They were created on-the-fly, as the user selected them.
Is there a recommended way to create classes and/or styles (mostly inline) on-the-fly and applying to the selection?
http://facebook.github.io/draft-js/docs/overview.html#content
I'm pretty new to this component and want to try it out, so I just basically reuse what is in the overview section.
But the following error is what I get
Cannot read property 'editorState' of null
What suppose to be the initial editor state ?
Since the example just have const {editorState} = this.state;
Hi there,
As documented here the function convertFromRaw
should return a ContentState
object.
However it returns an array of ContentBlock
objects.
This works:
var data = '{"entityMap":{},"blocks":[{"key":"4oah6","text":"Dieser Test","type":"unstyled","depth":0,"inlineStyleRanges":[{"offset":7,"length":4,"style":"BOLD"},{"offset":0,"length":11,"style":"CODE"},{"offset":0,"length":6,"style":"ITALIC"}],"entityRanges":[]}]}'
var json = JSON.parse(data)
var blockArray = convertFromRaw(json);
var contentState = ContentState.createFromBlockArray(blockArray);
var editorState = EditorState.createWithContent(contentState);
However this throws an error:
var contentState = convertFromRaw(json);
var editorState = EditorState.createWithContent(contentState);
Is this a mistake in the docs or a bug?
On IE11, Facebook.github.io/draft-js doesn't show the editor. Similarly for a basic editor running locally.
if (!query.startsWith(name)) --> Object doesn't support property or method 'startsWith'
Great project, exactly what I'm looking for, after playing around I understand how to get a raw js representation of the content from the editorState
convertToRaw(editorState.getCurrentContent())
Is this Raw state what your are persisting to a DB?
Coupled with that - how are you handling display of the content? Are there any utilities to convert this to a viewable format e.g. HTML? It's fine if the answer is 'you need to write your own parsers for the raw format' but would be good to have some pointers to how best to parse Draft.js raw into other formats?
I guess you must be doing something kind of conversion at FB, but maybe that's a wrong assumption, any guidance would be much appreciated.
I got this error:
11:18 $ npm run build
> [email protected] prebuild /Users/cheng/Dev/draft-js
> node node_modules/fbjs-scripts/node/check-dev-engines.js package.json
assert.js:89
throw new assert.AssertionError({
^
AssertionError: Current node version is not supported for development, expected "5.6.0" to satisfy "4.x".
at Object.<anonymous> (/Users/cheng/Dev/draft-js/node_modules/fbjs-scripts/node/check-dev-engines.js:39:3)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:140:18)
at node.js:1001:3
The line which caused the error:
node node_modules/fbjs-scripts/node/check-dev-engines.js package.json
My node version is 5.6.0 (I am using nvm) which is what the error message expects:
11:20 $ node --version
v5.6.0
Any ideas of what I missed?
Thanks.
In Advanced Topics: Key Bindings, there is an example that imports KeyBindingUtil
from draft-js
.
This import results in KeyBindingUtil === undefined
, because KeyBindingUtil
is not included in src/Draft.js
, rendering the example unusable.
I tried to use Flow in combination with Draft, but couldn't get it up & running. Maybe I missed something, but there seem not any flow related files when downloading the package on npm.
As Draft has flowtypes it should be just a change in the build process. Im happy to do a PR in case you would want to see this as well.
Background info:
https://twitter.com/lbljeffmo/status/702928158518091782
http://flowtype.org/blog/2015/12/01/Version-0.19.0.html#declaration-files
When inserting a final space, the space is dropped, and when manually enterring text at the end, the enterred character is inserted after the cursor.
The following code reproduce the issue:
class MySpaceTestEditor extends React.Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty(),
};
}
onChange = (editorState) => {
this.setState({editorState});
};
onAdd = (value) => {
let editorState = this.state.editorState;
let contentState = editorState.getCurrentContent();
contentState = Modifier.replaceText(
contentState,
contentState.getSelectionAfter(),
', ',
editorState.getCurrentInlineStyle(),
null,
);
editorState = EditorState.push(editorState, contentState, 'add-coma');
this.setState({editorState: editorState});
};
render() {
const {editorState} = this.state;
return (
<div>
<Editor
editorState={editorState}
onChange={this.onChange}
/>
<input
onClick={this.onAdd}
type="button"
value="Test"
/>
</div>
);
}
example of use: emoji, @, tag, hashtag, etc
TypeError: contentState.getBlockMap is thrown when clicking on "Log State" in the entity example.
I'd love to see a few more examples of usage:
Is there any plans for adding support for tables to draft.js
? I can't find any mention of it in the documentation.
Hi
I get an error on npm run build with latest node and npm release
assert.js:89
throw new assert.AssertionError({
^
AssertionError: Current node version is not supported for development, expected "5.7.0" to satisfy "4.x".
npm ERR! Darwin 15.3.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "build"
npm ERR! node v5.7.0
npm ERR! npm v3.7.3
The EditorState
's push()
method seems really important since it controls all state changes. I'm looking to get a mental map of which EditorChangeType
strings to use on EditorState
after the various Modifier
methods (e.g. "insert-character" or what).
There's a reference of an advanced topic doc on undo/redo but it 404s. I don't see a doc in the repo to my knowledge.
Any chance it got missed on accident?
we are trying to refer to a non existing live example which I assume should be this
https://github.com/facebook/draft-js/blob/master/examples/color/color.html
but published
Hello and thank you for your yet another awesome solution.
Just watched the demo on project page and noticed it doesn't have context-oriented behaviour. What does it mean?
It seems the good example for improving UX is focusing on Apple Pages to get good ideas and inherit user expectations.
For use cases in which I have fragments of pre-existing HTML that I need to load into an editor as the initial content, my impression is that I'd need to make use of the built-in DraftPasteProcessor
that is part of the paste handling.
Something like this is working for me:
import Draft from 'draft-js';
const {Editor, EditorState, RichUtils, ContentState} = Draft;
import DraftPasteProcessor from 'draft-js/lib/DraftPasteProcessor';
const htmlFragment = '<div><p>Hello <b>world!</b></p><ul><li>again</li></ul></div>';
class RichEditorExample extends React.Component {
constructor(props) {
super(props);
const processedHTML = DraftPasteProcessor.processHTML(htmlFragment);
const initialState = ContentState.createFromBlockArray(processedHTML);
this.state = {editorState: EditorState.createWithContent(initialState)};
But it would appear that DraftPasteProcessor
isn't exported along with the built package, so the import syntax is less than ideal, and I cannot use it if including only the dist file on the front-end.
Is there a better method for loading pre-existing HTML content, or could the paste-cleaning tools be included as part of the exported dist?
Can we feed initial content data for initialization? If so, does it accept html as a format?
The reason is that I am seeking to find answers on how to convert an already existing project that was made with tinymce and access a possible migration to draft-js.
If there any flag or API to turn off the rich text saving of this component. We have an editor that we need to allow the user to view the source/html tags as well as the WYSIWYG output.
Thanks!
I'm just wondering, why is React.createClass()
being used in the code examples instead of using classes? It seems pretty inconsistent to me when ES6 is already being used and it's mixed up with ES5 stuff.
For a while now, content editing and especially backspacing over text (one has to press backspace one key at a time with pauses between presses) in the Pale Moon browser has been broken. With the editor having been released as open source here now, we've finally been able to get more details about the apparent cause of the issue.
Holding down or rapidly pressing the key inserts control characters apparently instead of actually acting on the control characters as expected.
Reference post and thread:
https://forum.palemoon.org/viewtopic.php?f=29&t=6480&p=79607#p79607
The demo page has the same issue as the live Facebook production site, and displays the following behavior:
Upon loading first the following is thrown in the console:
[] "Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `BlockStyleControls`. See https://fb.me/react-warning-keys for more information."
[] "Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `InlineStyleControls`. See https://fb.me/react-warning-keys for more information."
With every keypress, another warning is spawned in the console:
[] "Warning: A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."
In Advanced Topics: Key Bindings there is an example that relies on a function called getDefaultKeyBinding()
, which is not imported in the example. This means the developer has to grep through the source code to find out how to import getDefaultKeyBinding()
.
Furthermore, getDefaultKeyBinding()
is not included in src/Draft.js
, so it can't be imported.
I'm using Draft to highlight hashtags in a readonly block of text (I understand Draft might not be the right tool for the job considering I don't require selection).
From what I understand, the correct approach should be:
contentBlock
contentBlock
find (start, end)
ranges for each hashtagEntity
and a SelectionState
for the tagEntity
using Modifier.applyEntity
for the given SelectionState
.Here's what that looks like
const contentState = ContentState.createFromText(content);
contentState.getBlockMap().map(contentBlock => {
this._findWithRegex(HASHTAG_REGEX, contentBlock, (start, end) => {
let selectionState = SelectionState.createEmpty(contentBlock.getKey());
selectionState = selectionState.merge({
anchorOffset: start,
focusKey: contentBlock.getKey(),
focusOffset: end,
});
const tag = contentBlock.getText().slice(start, end);
const key = Entity.create('HASHTAG', 'MUTABLE', {tag: tag});
Modifier.applyEntity(contentState, selectionState, key);
});
});
where this._findWithRegex
is the same function from the tweet
example.
After doing this, I expect to be able to apply a decorator strategy using the following:
_findHashtagEntitiesStrategy(contentBlock, callback) {
contentBlock.findEntityRanges(
(character) => {
const entityKey = character.getEntity();
return (
entityKey !== null &&
Entity.get(entityKey).getType() === 'HASHTAG'
);
},
callback
);
}
However it seems that contentBlock.findEntityRanges
fails to find any Entity
s for the any of the ContentBlock
s.
The "Learn how to use Draft.js in your own project." link is broken.
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.