diff --git a/client/src/components/Draftail/sources/DocumentSource.js b/client/src/components/Draftail/sources/DocumentSource.js index 7ddf8ab187..851e2bcbc8 100644 --- a/client/src/components/Draftail/sources/DocumentSource.js +++ b/client/src/components/Draftail/sources/DocumentSource.js @@ -12,7 +12,7 @@ class DocumentSource extends ModalSource { this.onConfirm({ id: data.id, url: data.url, - }); + }, data.title); } componentDidMount() { diff --git a/client/src/components/Draftail/sources/LinkSource.js b/client/src/components/Draftail/sources/LinkSource.js index a01202c2b3..52e463d748 100644 --- a/client/src/components/Draftail/sources/LinkSource.js +++ b/client/src/components/Draftail/sources/LinkSource.js @@ -19,6 +19,9 @@ const buildInitialUrl = (entity, openAtParentId, canChooseRoot, pageTypes) => { allow_external_link: true, allow_email_link: true, can_choose_root: canChooseRoot ? 'true' : 'false', + // This does not initialise the modal with the currently selected text. + // This will need to be implemented in the future. + // See https://github.com/jpuri/draftjs-utils/blob/e81c0ae19c3b0fdef7e0c1b70d924398956be126/js/block.js#L106. link_text: '', }; @@ -57,7 +60,7 @@ class LinkSource extends ModalSource { parsedData.parentId = data.parentId; } - this.onConfirm(parsedData); + this.onConfirm(parsedData, data.title, data.prefer_this_title_as_link_text); } componentDidMount() { diff --git a/client/src/components/Draftail/sources/ModalSource.js b/client/src/components/Draftail/sources/ModalSource.js index 104d849745..ea9f453f8b 100644 --- a/client/src/components/Draftail/sources/ModalSource.js +++ b/client/src/components/Draftail/sources/ModalSource.js @@ -1,6 +1,6 @@ import PropTypes from 'prop-types'; import React from 'react'; -import { AtomicBlockUtils, RichUtils } from 'draft-js'; +import { AtomicBlockUtils, RichUtils, Modifier, EditorState } from 'draft-js'; const $ = global.jQuery; @@ -16,12 +16,21 @@ class ModalSource extends React.Component { $(document.body).off('hidden.bs.modal', this.onClose); } - onConfirm(data) { + onConfirm(data, text = null, overrideText = false) { const { editorState, entityType, onComplete } = this.props; const contentState = editorState.getCurrentContent(); const contentStateWithEntity = contentState.createEntity(entityType.type, 'MUTABLE', data); const entityKey = contentStateWithEntity.getLastCreatedEntityKey(); - const nextState = RichUtils.toggleLink(editorState, editorState.getSelection(), entityKey); + const selection = editorState.getSelection(); + const shouldOverrideText = overrideText || selection.isCollapsed(); + let nextState; + + if (shouldOverrideText) { + const newContent = Modifier.replaceText(editorState.getCurrentContent(), selection, text, null, entityKey); + nextState = EditorState.push(editorState, newContent, 'insert-characters'); + } else { + nextState = RichUtils.toggleLink(editorState, selection, entityKey); + } onComplete(nextState); }