Skip to content
Snippets Groups Projects
Commit 121d3d9e authored by Anthony's avatar Anthony
Browse files

Add link button

parent 3808b772
Branches
No related tags found
No related merge requests found
......@@ -8,6 +8,7 @@ import ItalicIcon from '@material-ui/icons/FormatItalic';
import { withStyles } from '@material-ui/core/styles';
import { stateToHTML } from 'draft-js-export-html';
import { stateFromHTML } from 'draft-js-import-html';
import { onAddLink } from './TextEditorLink';
/** */
class TextEditor extends Component {
......@@ -67,6 +68,7 @@ class TextEditor extends Component {
render() {
const { classes } = this.props;
const { editorState } = this.state;
const { setEditorState } = this.setState;
const currentStyle = editorState.getCurrentInlineStyle();
return (
......@@ -88,6 +90,11 @@ class TextEditor extends Component {
<ItalicIcon />
</ToggleButton>
</ToggleButtonGroup>
<button
onClick={() => onAddLink(editorState, setEditorState)}
>
link
</button>
<div className={classes.editorRoot} onClick={this.handleFocus}>
<Editor
......
// Add Link Component
import React from 'react';
import { CompositeDecorator, EditorState, Modifier } from 'draft-js';
/** */
function Link({ entityKey, contentState, children }) {
const { url } = contentState.getEntity(entityKey).getData();
return (
<a
style={{ color: 'blue', fontStyle: 'italic' }}
href={url}
target="_blank"
rel="noreferrer"
>
{children}
</a>
);
}
/** */
const findLinkEntities = (contentBlock, callback, contentState) => {
contentBlock.findEntityRanges((character) => {
const entityKey = character.getEntity();
return (
entityKey !== null
&& contentState.getEntity(entityKey).getType() === 'LINK'
);
}, callback);
};
/** */
export const createLinkDecorator = () => new
CompositeDecorator([
{
component: Link,
strategy: findLinkEntities,
},
]);
// call all together
/** */
export const onAddLink = (editorState, setEditorState) => {
const linkUrl = window.prompt('Add link http:// ');
const decorator = createLinkDecorator();
if (linkUrl) {
const displayLink = window.prompt('Display Text');
if (displayLink) {
const currentContent = editorState.getCurrentContent();
const createEntity = currentContent.createEntity('LINK', 'MUTABLE', {
url: linkUrl,
});
const entityKey = currentContent.getLastCreatedEntityKey();
const selection = editorState.getSelection();
const textWithEntity = Modifier.insertText(
currentContent,
selection,
displayLink,
null,
entityKey,
);
const newState = EditorState.createWithContent(textWithEntity, decorator);
setEditorState(newState);
}
}
};
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment