Merge pull request #3545 from matrix-org/bwindels/fix-edit-unmount-when-no-selection-release

Fix: edit unmount when no selection
pull/21833/head
Bruno Windels 2019-10-10 16:45:44 +00:00 committed by GitHub
commit 7900e2292d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 2 deletions

View File

@ -209,9 +209,18 @@ export default class EditMessageComposer extends React.Component {
} }
componentWillUnmount() { componentWillUnmount() {
// store caret and serialized parts in the
// editorstate so it can be restored when the remote echo event tile gets rendered
// in case we're currently editing a pending event
const sel = document.getSelection(); const sel = document.getSelection();
const {caret} = getCaretOffsetAndText(this._editorRef, sel); let caret;
if (sel.focusNode) {
caret = getCaretOffsetAndText(this._editorRef, sel).caret;
}
const parts = this.model.serializeParts(); const parts = this.model.serializeParts();
// if caret is undefined because for some reason there isn't a valid selection,
// then when mounting the editor again with the same editor state,
// it will set the cursor at the end.
this.props.editState.setEditorState(caret, parts); this.props.editState.setEditorState(caret, parts);
} }
@ -238,7 +247,7 @@ export default class EditMessageComposer extends React.Component {
_getInitialCaretPosition() { _getInitialCaretPosition() {
const {editState} = this.props; const {editState} = this.props;
let caretPosition; let caretPosition;
if (editState.hasEditorState()) { if (editState.hasEditorState() && editState.getCaret()) {
// if restoring state from a previous editor, // if restoring state from a previous editor,
// restore caret position from the state // restore caret position from the state
const caret = editState.getCaret(); const caret = editState.getCaret();

View File

@ -92,6 +92,10 @@ function getSelectionOffsetAndText(editor, selectionNode, selectionOffset) {
// gets the caret position details, ignoring and adjusting to // gets the caret position details, ignoring and adjusting to
// the ZWS if you're typing in a caret node // the ZWS if you're typing in a caret node
function getCaret(node, offsetToNode, offsetWithinNode) { function getCaret(node, offsetToNode, offsetWithinNode) {
// if no node is selected, return an offset at the start
if (!node) {
return new DocumentOffset(0, false);
}
let atNodeEnd = offsetWithinNode === node.textContent.length; let atNodeEnd = offsetWithinNode === node.textContent.length;
if (node.nodeType === Node.TEXT_NODE && isCaretNode(node.parentElement)) { if (node.nodeType === Node.TEXT_NODE && isCaretNode(node.parentElement)) {
const zwsIdx = node.nodeValue.indexOf(CARET_NODE_CHAR); const zwsIdx = node.nodeValue.indexOf(CARET_NODE_CHAR);