draft-js#RichUtils JavaScript Examples

The following examples show how to use draft-js#RichUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: markdownInput.js    From turqV2 with GNU General Public License v3.0 6 votes vote down vote up
handleKeyCommand(command, editorState) {
    const newState = RichUtils.handleKeyCommand(editorState, command);

    if (newState) {
      this.onChange(newState);
      return true;
    }

    return false;
  }
Example #2
Source File: EditorUtilities.js    From wix-style-react with MIT License 6 votes vote down vote up
_removeEntityFromBlock = (editorState, contentBlock, entity) => {
  const contentState = editorState.getCurrentContent();
  const selectionState = editorState.getSelection();

  let selectionWithEntity = null;

  contentBlock.findEntityRanges(
    character => character.getEntity() === entity,
    (start, end) => {
      // Creates a selection state that contains the whole text that's linked to the entity
      selectionWithEntity = selectionState.merge({
        anchorOffset: start,
        focusOffset: end,
      });
    },
  );

  // Removes the linking between the text and entity
  const contentStateWithoutEntity = Modifier.applyEntity(
    contentState,
    selectionWithEntity,
    null,
  );

  const newEditorState = EditorState.push(
    editorState,
    contentStateWithoutEntity,
    'apply-entity',
  );

  return RichUtils.toggleLink(newEditorState, selectionState, null);
}
Example #3
Source File: EditorUtilities.js    From wix-style-react with MIT License 6 votes vote down vote up
_attachLinkEntityToText = (editorState, { text, url }) => {
  const contentState = editorState.getCurrentContent();
  const selectionState = editorState.getSelection();
  const contentStateWithEntity = contentState.createEntity('LINK', 'MUTABLE', {
    url,
  });
  const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
  const startPosition = selectionState.getStartOffset();
  const endPosition = startPosition + text.length;

  // A key for the block that containing the start of the selection range
  const blockKey = selectionState.getStartKey();

  // Replaces the content in specified selection range with text
  const contentStateWithText = Modifier.replaceText(
    contentState,
    selectionState,
    text,
  );

  const newSelectionState = new SelectionState({
    anchorOffset: startPosition,
    anchorKey: blockKey,
    focusOffset: endPosition,
    focusKey: blockKey,
  });

  const newEditorState = EditorState.push(
    editorState,
    contentStateWithText,
    'insert-characters',
  );

  return RichUtils.toggleLink(newEditorState, newSelectionState, entityKey);
}
Example #4
Source File: index.jsx    From react-mui-draft-wysiwyg with MIT License 6 votes vote down vote up
function BlockTypeControl({ configuration, defaultConfiguration }) {
    const editor = useEditor();
    const editorFocus = useEditorFocus();
    const options = configuration.options || defaultConfiguration.options;
    const [value, setValue] = React.useState('default');

    React.useEffect(() => {
        setValue(
            getCurrentBlockType(
                editor.editorState,
                options.map((option) => option.value)
            )
        );
    }, [editor, options]);

    const handleChange = (newValue) => {
        setValue(newValue);
        const newEditorState = RichUtils.toggleBlockType(
            editor.editorState,
            newValue === 'normal' ? '' : newValue
        );
        editor.onChange(newEditorState);
        editorFocus();
    };

    return <DropdownControl options={options} onChange={handleChange} value={value} />;
}
Example #5
Source File: index.jsx    From react-mui-draft-wysiwyg with MIT License 6 votes vote down vote up
function LinkRemoveControl() {
    const editor = useEditor();

    const onClick = () => {
        const selection = editor.editorState.getSelection();
        editor.onChange(RichUtils.toggleLink(editor.editorState, selection, null));
    };

    return (
        <ButtonControl
            onClick={onClick}
            text={editor.translate('controls.linkRemove.title')}
            disabled={editor.editorState.getSelection().isCollapsed()}>
            <LinkOffIcon />
        </ButtonControl>
    );
}
Example #6
Source File: ToggleBlockTypeButtonControl.jsx    From react-mui-draft-wysiwyg with MIT License 6 votes vote down vote up
function ToggleBlockTypeButtonControl({ blockType, children, text }) {
    const editor = useEditor();
    const editorFocus = useEditorFocus();

    const onClick = () => {
        const newEditorState = RichUtils.toggleBlockType(editor.editorState, blockType);
        editor.onChange(newEditorState);
        editorFocus();
    };

    return (
        <ButtonControl text={text} onClick={onClick}>
            {children}
        </ButtonControl>
    );
}
Example #7
Source File: ToggleInlineStyleButtonControl.jsx    From react-mui-draft-wysiwyg with MIT License 6 votes vote down vote up
function ToggleInlineStyleButtonControl({ inlineStyle, children, text }) {
    const editor = useEditor();
    const editorFocus = useEditorFocus();
    const [isActive, setIsActive] = React.useState(false);

    React.useEffect(() => {
        setIsActive(hasAllSelectionTheInlineStyle(editor.editorState, inlineStyle));
    }, [editor.editorState, inlineStyle]);

    const onClick = () => {
        const newEditorState = RichUtils.toggleInlineStyle(editor.editorState, inlineStyle);
        editor.onChange(newEditorState);
        editorFocus();
    };

    return (
        <ButtonControl
            text={text}
            onClick={onClick}
            active={isActive}
            disabled={editor.editorState.getSelection().isCollapsed()}>
            {children}
        </ButtonControl>
    );
}
Example #8
Source File: editorStateUtils.js    From react-mui-draft-wysiwyg with MIT License 6 votes vote down vote up
toggleMappedInlineStyle = (editorState, styleKeys, newInlineStyle) => {
    const selection = editorState.getSelection();

    // Turn off the other mapped inline styled in selection
    const newContentState = styleKeys.reduce(
        (contentState, inlineStyle) =>
            Modifier.removeInlineStyle(contentState, selection, inlineStyle),
        editorState.getCurrentContent()
    );

    let newEditorState = EditorState.push(editorState, newContentState, 'change-inline-style');

    const currentStyle = editorState.getCurrentInlineStyle();

    if (selection.isCollapsed()) {
        newEditorState = currentStyle.reduce((state, inlineStyle) => {
            return RichUtils.toggleInlineStyle(state, inlineStyle);
        }, newEditorState);
    }
    // If the inline style is being toggled on, apply it.
    if (!currentStyle.has(newInlineStyle)) {
        newEditorState = RichUtils.toggleInlineStyle(newEditorState, newInlineStyle);
    }

    return newEditorState;
}
Example #9
Source File: markdownInput.js    From turqV2 with GNU General Public License v3.0 5 votes vote down vote up
_toggleInlineStyle(inlineStyle) {
    this.onChange(
      RichUtils.toggleInlineStyle(
        this.state.editorState,
        inlineStyle
      )
    );
  }
Example #10
Source File: texteditor.js    From GitMarkonics with MIT License 5 votes vote down vote up
//toggles inline styling of the text to bold
  _onBoldClick() {
    this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, "BOLD"));
  }
Example #11
Source File: markdownInput.js    From turqV2 with GNU General Public License v3.0 5 votes vote down vote up
_toggleBlockType(blockType) {
    this.onChange(
      RichUtils.toggleBlockType(
        this.state.editorState,
        blockType
      )
    );
  }
Example #12
Source File: EditorUtilities.js    From wix-style-react with MIT License 5 votes vote down vote up
toggleBlockType = (editorState, toggledBlockType) => {
  return RichUtils.toggleBlockType(
    keepCurrentSelection(editorState),
    toggledBlockType,
  );
}
Example #13
Source File: EditorUtilities.js    From wix-style-react with MIT License 5 votes vote down vote up
toggleStyle = (editorState, toggledStyle) => {
  return RichUtils.toggleInlineStyle(
    keepCurrentSelection(editorState),
    toggledStyle,
  );
}
Example #14
Source File: editorStateUtils.js    From react-mui-draft-wysiwyg with MIT License 5 votes vote down vote up
getCurrentBlockType = (editorState, availableBlockTypes) => {
    const blockType = RichUtils.getCurrentBlockType(editorState);
    if (availableBlockTypes.find((avBlockType) => avBlockType === blockType)) return blockType;
    return 'default';
}
Example #15
Source File: plugin.js    From react-mui-draft-wysiwyg with MIT License 5 votes vote down vote up
EditorLink = ({ contentState, entityKey, blockKey, start, end, children }) => {
    const [anchorEl, setAnchorEl] = React.useState(null);
    const editor = useEditor();
    const editorFocus = useEditorFocus();
    const { url } = contentState.getEntity(entityKey).getData();

    const showOptions = (ev) => {
        setAnchorEl(ev.currentTarget);
    };

    const hideOptions = () => {
        setAnchorEl(null);
    };

    const openLink = (ev) => {
        ev.preventDefault();
        ev.stopPropagation();
        window.open(url, '_blank');
    };

    const removeLink = (ev) => {
        ev.preventDefault();
        ev.stopPropagation();
        const linkSelection = SelectionState.createEmpty(blockKey).merge({
            anchorKey: blockKey,
            anchorOffset: start,
            focusKey: blockKey,
            focusOffset: end,
        });

        editor.onChange(RichUtils.toggleLink(editor.editorState, linkSelection, null));
        editorFocus();
    };

    return (
        <React.Fragment>
            <Link
                href={url}
                rel="noopener noreferrer"
                target="_blank"
                aria-label={url}
                onClick={showOptions}>
                {children}
            </Link>
            <Popover
                open={Boolean(anchorEl)}
                onClose={hideOptions}
                anchorEl={anchorEl}
                anchorOrigin={{
                    vertical: 'bottom',
                    horizontal: 'center',
                }}
                transformOrigin={{
                    vertical: 'top',
                    horizontal: 'center',
                }}>
                <ButtonGroup size="small" aria-label="Link options">
                    <Button onClick={openLink} title={`Open ${url}`}>
                        <LaunchIcon />
                    </Button>
                    <Button onClick={removeLink} title="Remove link">
                        <LinkOffIcon />
                    </Button>
                </ButtonGroup>
            </Popover>
        </React.Fragment>
    );
}
Example #16
Source File: texteditor.js    From GitMarkonics with MIT License 5 votes vote down vote up
// heading tags
  handleHeadingChange(event) {
    this.onChange(
        RichUtils.toggleBlockType(this.state.editorState, event.target.value)
    );
    this.setState({ value: event.target.value });
  }
Example #17
Source File: texteditor.js    From GitMarkonics with MIT License 5 votes vote down vote up
//ordered list
  _onNumberClick(event) {
    this.onChange(
        RichUtils.toggleBlockType(this.state.editorState, "ordered-list-item")
    );
    this.setState({ value: event.target.value });
  }
Example #18
Source File: texteditor.js    From GitMarkonics with MIT License 5 votes vote down vote up
//ordered list
  _onBulletClick(event) {
    this.onChange(
        RichUtils.toggleBlockType(this.state.editorState, "unordered-list-item")
    );
    this.setState({ value: event?.target.value || ""});
  }
Example #19
Source File: texteditor.js    From GitMarkonics with MIT License 5 votes vote down vote up
//underline
  _onUnderlineClick() {
    this.onChange(
        RichUtils.toggleInlineStyle(this.state.editorState, "UNDERLINE")
    );
  }
Example #20
Source File: texteditor.js    From GitMarkonics with MIT License 5 votes vote down vote up
//blockqoute
  _onBlockQuoteClick() {
    this.onChange(
        RichUtils.toggleBlockType(this.state.editorState, "blockquote")
    );
  }
Example #21
Source File: texteditor.js    From GitMarkonics with MIT License 5 votes vote down vote up
//toggles inline styling of the text to italic
  _onItalicClick() {
    this.onChange(
        RichUtils.toggleInlineStyle(this.state.editorState, "ITALIC")
    );
  }
Example #22
Source File: index.jsx    From react-mui-draft-wysiwyg with MIT License 4 votes vote down vote up
/**
 * Material UI Draft.js editor
 *
 * @version 1.0.3
 * @author [Rubén Albarracín](https://github.com/Kelsier90)
 */
function MUIEditor({
    editorState,
    onChange,
    onFocus = null,
    onBlur = null,
    config = defaultConfig,
}) {
    const editorFactories = new EditorFactories(config);
    const editorRef = React.useRef(null);
    const translateRef = React.useRef(function () {});
    const translationsRef = React.useRef(null);
    const toolbarVisibleConfig = editorFactories.getConfigItem('toolbar', 'visible');
    const [isToolbarVisible, setIsToolbarVisible] = React.useState(toolbarVisibleConfig);
    const [isResizeImageDialogVisible, setIsResizeImageDialogVisible] = React.useState(false);
    const [resizeImageEntityKey, setResizeImageEntityKey] = React.useState(null);

    translationsRef.current = editorFactories.getTranslations();
    translateRef.current = React.useCallback((id) => {
        const translator = new Translator(translationsRef.current);
        return translator.get(id);
    }, []);
    const classes = useStyles();

    React.useEffect(() => {
        setIsToolbarVisible(toolbarVisibleConfig);
    }, [toolbarVisibleConfig]);

    const toolbar = (
        <EditorToolbar
            visible={isToolbarVisible}
            style={editorFactories.getConfigItem('toolbar', 'style')}
            className={editorFactories.getConfigItem('toolbar', 'className')}>
            {editorFactories.getToolbarControlComponents()}
        </EditorToolbar>
    );

    const top = editorFactories.getToolbarPosition() === 'top' ? toolbar : null;
    const bottom = editorFactories.getToolbarPosition() === 'bottom' ? toolbar : null;

    const handleKeyCommand = (command) => {
        const newState = RichUtils.handleKeyCommand(editorState, command);
        if (newState) {
            onChange(newState);
            return 'handled';
        }
        return 'not-handled';
    };

    const handleFocus = (ev) => {
        if (onFocus) onFocus(ev);
    };

    const handleBlur = (ev) => {
        if (onBlur) onBlur(ev);
    };

    const editorWrapperProps = {
        style: editorFactories.getConfigItem('editor', 'style'),
        className: `${classes.editorWrapper} ${editorFactories.getConfigItem(
            'editor',
            'className'
        )}`,
        onClick: () => editorRef.current.focus(),
    };

    const editorWrapperElement = editorFactories.getConfigItem('editor', 'wrapperElement');

    if (editorWrapperElement === Paper) {
        editorWrapperProps.elevation = 3;
    }

    const EditorWrapper = React.createElement(
        editorWrapperElement,
        editorWrapperProps,
        <Editor
            {...editorFactories.getConfigItem('draftEditor')}
            ref={editorRef}
            editorState={editorState}
            onChange={onChange}
            onFocus={(ev) => handleFocus(ev)}
            onBlur={(ev) => handleBlur(ev)}
            handleKeyCommand={handleKeyCommand}
            blockStyleFn={editorFactories.getBlockStyleFn()}
            customStyleMap={editorFactories.getCustomStyleMap()}
            blockRenderMap={editorFactories.getBlockRenderMap()}
            blockRendererFn={editorFactories.getBlockRendererFn()}
        />
    );

    return (
        <EditorContext.Provider
            value={{
                editorState,
                onChange,
                ref: editorRef.current,
                translate: translateRef.current,
                showResizeImageDialog: (entityKey) => {
                    setIsResizeImageDialogVisible(true);
                    setResizeImageEntityKey(entityKey);
                },
                hideResizeImageDialog: () => {
                    setIsResizeImageDialogVisible(false);
                    setResizeImageEntityKey(null);
                },
                isResizeImageDialogVisible,
                resizeImageEntityKey,
            }}>
            {top}
            {EditorWrapper}
            {bottom}
        </EditorContext.Provider>
    );
}
Example #23
Source File: TextEditor.js    From paras-landing with GNU General Public License v3.0 4 votes vote down vote up
TextEditor = ({
	content,
	readOnly = false,
	title,
	hideTitle = false,
	setTitle = () => {},
	showCardModal,
	showCollectionModal,
	setContent = () => {},
}) => {
	const { localeLn } = useIntl()
	const toast = useToast()
	const editor = useRef(null)

	let className = 'RichEditor-editor text-lg'
	var contentState = content.getCurrentContent()
	if (!contentState.hasText()) {
		if (contentState.getBlockMap().first().getType() !== 'unstyled') {
			className += ' RichEditor-hidePlaceholder'
		}
	}

	const onAddLocalImage = async (e) => {
		let imgUrl
		if (e.target.files[0]) {
			if (e.target.files[0].size > 3 * 1024 * 1024) {
				toast.show({
					text: (
						<div className="font-semibold text-center text-sm">{localeLn('MaximumSize3MB')}</div>
					),
					type: 'error',
					duration: null,
				})
				return
			}
			const compressedImg =
				e.target.files[0].type === 'image/gif'
					? e.target.files[0]
					: await compressImg(e.target.files[0])
			imgUrl = await readFileAsUrl(compressedImg)
		}
		setContent(imagePlugin.addImage(content, imgUrl))
	}

	const onAddVideo = async (src) => {
		setContent(
			videoPlugin.addVideo(content, {
				src: src,
			})
		)
	}

	const handleKeyCommand = (command, editorState) => {
		const newState = RichUtils.handleKeyCommand(editorState, command)
		if (newState) {
			setContent(newState)
			return true
		}
		return false
	}

	const mapKeyToEditorCommand = (e) => {
		if (e.keyCode === 9) {
			const newEditorState = RichUtils.onTab(e, content, 4)
			if (newEditorState !== content) {
				setContent(newEditorState)
			}
			return
		}
		return getDefaultKeyBinding(e)
	}

	return (
		<div>
			{!hideTitle && (
				<div className="titlePublication text-4xl font-bold pb-0 text-white">
					<Editor
						editorKey={'title'}
						placeholder="Title"
						editorState={title}
						onChange={setTitle}
						handleReturn={() => 'handled'}
						readOnly={readOnly}
					/>
				</div>
			)}
			<div className="RichEditor-root text-white">
				<div className={className} onClick={editor.focus}>
					<Editor
						editorKey={'content'}
						blockStyleFn={getBlockStyle}
						customStyleMap={styleMap}
						editorState={content}
						handleKeyCommand={handleKeyCommand}
						keyBindingFn={mapKeyToEditorCommand}
						onChange={setContent}
						placeholder="Tell a story..."
						plugins={plugins}
						readOnly={readOnly}
						ref={editor}
					/>
					<InlineToolbar>
						{(externalProps) => (
							<div className="inline-block md:flex items-center">
								<BoldButton {...externalProps} />
								<ItalicButton {...externalProps} />
								<UnderlineButton {...externalProps} />
								<linkPlugin.LinkButton {...externalProps} />
							</div>
						)}
					</InlineToolbar>
				</div>
				{!readOnly && (
					<Toolbar className="flex">
						{(externalProps) => (
							<div className="inline-block md:flex px-1 items-center">
								<BoldButton {...externalProps} />
								<ItalicButton {...externalProps} />
								<UnderlineButton {...externalProps} />
								<CodeButton {...externalProps} />
								<HeadlineOneButton {...externalProps} />
								<HeadlineTwoButton {...externalProps} />
								<HeadlineThreeButton {...externalProps} />
								<UnorderedListButton {...externalProps} />
								<OrderedListButton {...externalProps} />
								<BlockquoteButton {...externalProps} />
								<CodeBlockButton {...externalProps} />
								<linkPlugin.LinkButton {...externalProps} onOverrideContent={() => {}} />
								<DividerButton {...externalProps} />
								<ImageButton {...externalProps} onChange={onAddLocalImage} />
								<VideoButton {...externalProps} onAddVideo={onAddVideo} />
								<CardButton {...externalProps} onClick={showCardModal} />
								<CollectionButton {...externalProps} onClick={showCollectionModal} />
							</div>
						)}
					</Toolbar>
				)}
			</div>
		</div>
	)
}