Decorate pasted links so that they look like links

By default, draftjs will represent pasted `<a>` tags as `LINK` entities, but it doesn't do any default decoration of these links. Add a decorator to do so.

Most of this was taken from https://github.com/facebook/draft-js/blob/v0.8.1/examples/link/link.html (note the version, v0.8.1).
This commit is contained in:
Luke Barnard 2017-07-13 13:26:13 +01:00
parent 4cc8b5621d
commit 55e1202c09

View file

@ -16,9 +16,9 @@ limitations under the License.
import React from 'react'; import React from 'react';
import type SyntheticKeyboardEvent from 'react/lib/SyntheticKeyboardEvent'; import type SyntheticKeyboardEvent from 'react/lib/SyntheticKeyboardEvent';
import {Editor, EditorState, RichUtils, CompositeDecorator, import {Editor, EditorState, RichUtils, CompositeDecorator, Modifier,
convertFromRaw, convertToRaw, Modifier, EditorChangeType, getDefaultKeyBinding, KeyBindingUtil, ContentState, ContentBlock, SelectionState,
getDefaultKeyBinding, KeyBindingUtil, ContentState, ContentBlock, SelectionState} from 'draft-js'; Entity} from 'draft-js';
import classNames from 'classnames'; import classNames from 'classnames';
import escape from 'lodash/escape'; import escape from 'lodash/escape';
@ -144,15 +144,37 @@ export default class MessageComposerInput extends React.Component {
this.client = MatrixClientPeg.get(); this.client = MatrixClientPeg.get();
} }
findLinkEntities(contentBlock, callback) {
contentBlock.findEntityRanges(
(character) => {
const entityKey = character.getEntity();
return (
entityKey !== null &&
Entity.get(entityKey).getType() === 'LINK'
);
}, callback,
);
}
/* /*
* "Does the right thing" to create an EditorState, based on: * "Does the right thing" to create an EditorState, based on:
* - whether we've got rich text mode enabled * - whether we've got rich text mode enabled
* - contentState was passed in * - contentState was passed in
*/ */
createEditorState(richText: boolean, contentState: ?ContentState): EditorState { createEditorState(richText: boolean, contentState: ?ContentState): EditorState {
let decorators = richText ? RichText.getScopedRTDecorators(this.props) : const decorators = richText ? RichText.getScopedRTDecorators(this.props) :
RichText.getScopedMDDecorators(this.props), RichText.getScopedMDDecorators(this.props);
compositeDecorator = new CompositeDecorator(decorators); decorators.push({
strategy: this.findLinkEntities.bind(this),
component: (props) => {
const {url} = Entity.get(props.entityKey).getData();
return (
<a href={url}>
{props.children}
</a>
);
},
});
const compositeDecorator = new CompositeDecorator(decorators);
let editorState = null; let editorState = null;
if (contentState) { if (contentState) {