Undoing an action may lead to a misplaced caret
authorAlexander Ebert <ebert@woltlab.com>
Thu, 15 Feb 2018 23:18:33 +0000 (00:18 +0100)
committerAlexander Ebert <ebert@woltlab.com>
Thu, 15 Feb 2018 23:18:33 +0000 (00:18 +0100)
wcfsetup/install/files/js/3rdParty/redactor2/plugins/WoltLabCaret.js

index 07eacfdd4e15ee530e07b100c216ac3cbb0c90bb..529c9718ef237bee318a62779e909aa0bb7636bb 100644 (file)
@@ -95,9 +95,11 @@ $.Redactor.prototype.WoltLabCaret = function() {
                                
                                mpRestoreInstant.call(this, saved);
                                
+                               var selection = window.getSelection();
+                               if (!selection.rangeCount) return;
+                               
                                if (localSaved.isAtNodeStart === true) {
-                                       var selection = window.getSelection();
-                                       if (selection.rangeCount && !selection.isCollapsed) {
+                                       if (!selection.isCollapsed) {
                                                var range = selection.getRangeAt(0);
                                                var start = range.startContainer;
                                                
@@ -130,6 +132,21 @@ $.Redactor.prototype.WoltLabCaret = function() {
                                                }
                                        }
                                }
+                               else if (selection.isCollapsed) {
+                                       var anchorNode = selection.anchorNode;
+                                       var editor = this.core.editor()[0];
+                                       
+                                       // Restoring a selection may fail if the node does was removed from the DOM,
+                                       // causing the caret to be inside a text node with the editor being the
+                                       // direct parent. We can safely move the caret inside the adjacent container,
+                                       // using `caret.start()`.
+                                       if (anchorNode.nodeType === Node.TEXT_NODE && anchorNode.parentNode === editor && selection.anchorOffset === anchorNode.textContent.length) {
+                                               var p = anchorNode.nextElementSibling;
+                                               if (p && p.nodeName === 'P') {
+                                                       this.caret.start(p);
+                                               }
+                                       }
+                               }
                        }).bind(this);
                },