js: remake link insertion without document.execCommand main
authorFrédéric Péters <fpeters@0d.be>
Sat, 19 Jun 2021 09:08:26 +0000 (11:08 +0200)
committerFrédéric Péters <fpeters@0d.be>
Sat, 19 Jun 2021 09:08:26 +0000 (11:08 +0200)
chloro/phyll/static/js/chloro.js

index 816d022..10f91e2 100644 (file)
     }
     if (action == 'createLink') {
       var sel = window.getSelection();
+      var selected_link = get_parent(sel.anchorNode, 'A');
+      if (sel.anchorNode.nodeType == Node.TEXT_NODE) {
+        if (sel.anchorNode.length == sel.anchorOffset && sel.anchorNode.nextSibling.nodeName == 'A') {
+          selected_link = sel.anchorNode.nextSibling;
+        }
+      }
       var $input = $('input[name=link-target]');
       $input[0]._range = sel.getRangeAt(0);
-      if (sel.anchorNode instanceof Element) {
-        var elem = sel.anchorNode.childNodes[sel.anchorOffset];
-        if (elem.tagName == 'A') {
-          $input.val(elem.href);
-        }
+      if (selected_link) {
+        $input[0]._selected_link = selected_link;
+        $input.val(selected_link.href);
       }
       $input.addClass('shown');
       $input.focus();
       $input.removeClass('shown');
       var sel = window.getSelection();
       sel.addRange(this._range);
+      var selected_link = $input[0]._selected_link;
       if (url) {
-        document.execCommand('createLink', false, url);
+        if (selected_link) {
+          selected_link.href = url;
+        } else {
+          var $new_link = $('<a></a>', {text: sel.toString(), href: url});
+          this._range.deleteContents();
+          this._range.insertNode($new_link[0]);
+          sel.empty();
+          sel.collapse($new_link[0]);
+          sel.empty();
+        }
       } else {
-        document.execCommand('unlink', false, null);
+        if (selected_link) {
+          selected_link.replaceWith(document.createTextNode(selected_link.textContent));
+        }
       }
-      sel.empty();
       $input.val('');
+      $input[0]._selected_link = null;
     }
   }
   function focusout_link(ev) {