As an example of what I'd like to do, in Draft.js I'd like to allow the users to include a slideshow of images in the page that could change externally later on. So if there is a slideshow defined in my app, the user could select that slideshow to put in their page, and if the images were changed later then they would automatically update on the page. A visual representation in the editor would a nice-to-have as well. Am I asking too much or is this possible in Draft.js?
Asked
Active
Viewed 418 times
1 Answers
0
It never fails. I post a question and almost immediately I find something that might answer my question. Draft.js has what is called "decorators", which are currently documented here: https://draftjs.org/docs/advanced-topics-decorators.html
Basically you'd create a series of decorators using functions / components. Strategy takes a function, component is obvious.
const compositeDecorator = new CompositeDecorator([
{
strategy: handleStrategy,
component: HandleSpan,
},
{
strategy: hashtagStrategy,
component: HashtagSpan,
},
]);
Strategies can be defined using regexes. This enables you to write your own syntax or use that of a template engine's for embedding widgets. The strategies in the documentation are a fairly good example:
// Note: these aren't very good regexes, don't use them!
const HANDLE_REGEX = /\@[\w]+/g;
const HASHTAG_REGEX = /\#[\w\u0590-\u05ff]+/g;
function handleStrategy(contentBlock, callback, contentState) {
findWithRegex(HANDLE_REGEX, contentBlock, callback);
}
function hashtagStrategy(contentBlock, callback, contentState) {
findWithRegex(HASHTAG_REGEX, contentBlock, callback);
}
function findWithRegex(regex, contentBlock, callback) {
const text = contentBlock.getText();
let matchArr, start;
while ((matchArr = regex.exec(text)) !== null) {
start = matchArr.index;
callback(start, start + matchArr[0].length);
}
}
And then here are the components:
const HandleSpan = (props) => {
return <span {...props} style={styles.handle}>{props.children}</span>;
};
const HashtagSpan = (props) => {
return <span {...props} style={styles.hashtag}>{props.children}</span>;
};

eltiare
- 1,817
- 1
- 20
- 28
-
I'll wait a couple of days to see if anyone posts a better solution before accepting this one. – eltiare Mar 31 '17 at 00:59