0

El problema es que cuando hago click en la opción/botón del editor de código HTML -> <> y pego algún código, contenido, texto o cualquier cosa, el código HTML que se muestra en el <textarea> se codifica en entidades HTML, por lo tanto, para que vuelva a ser código HTML tengo que hacer un enter o algún cambio en el texto del editor en las opciones de los botones Negrita -> B, cursiva -> I entre otros, para nuevamente se vuelva hacer código HTML.

    $(function() {
        function formatHtmlCode(str) {
            var p = document.createElement('p');
            p.innerHTML = str.trim();
            return format(p, 0).innerHTML;
        }
        function format(node, level) {
            var indentBefore = new Array(level++ + 1).join('  '),
            indentAfter = new Array(level - 1).join('  '),
            textNode;
            for (var i = 0; i < node.children.length; i++) {
                textNode = document.createTextNode('\n' + indentBefore);
                node.insertBefore(textNode, node.children[i]);
                format(node.children[i], level);
                if (node.lastElementChild == node.children[i]) {
                    textNode = document.createTextNode('\n' + indentAfter);
                    node.appendChild(textNode);
                }
            }
            return node;
        }
        $('#editControls a').click(function(e) {
            switch ($(this).data('role')) {
                case 'h2':
                case 'h3':
                case 'p':
                    document.execCommand('formatBlock', false, $(this).data('role'));
                    break;
                case 'code':
                    codeMode = !codeMode;
                    if (codeMode) {
                        var formattedHtml = formatHtmlCode(htmlDiv.html());
                        htmlDiv.css("white-space", "pre");
                        htmlDiv.text(formattedHtml);
                        var editor = $("#editor");
                        editor.addClass("black-bg-colr codeMode");
                        //editor.attr('id', 'editor newID');
                    } else {
                        htmlDiv.css("white-space", "normal");
                        htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
                        var editor = $("#editor");
                        editor.removeClass("black-bg-colr codeMode");
                        //editor.attr('id', 'editor');
                    }
                    break;
                default:
                    document.execCommand($(this).data('role'), false, null);
                    break;
            }
        });

        let codeMode = false;
        let htmlDiv = $("#editor");
        htmlDiv.on('keyup', function(e) {
            if (!e.shiftKey && e.keyCode === 13) {
                document.execCommand('formatBlock', false, 'p');
            } else if (e.shiftKey) {
                document.execCommand('formatBlock', false, 'p');
            }
        });

        htmlDiv.on("paste", function(e) {
            e.preventDefault();
            var text = (e.originalEvent || e).clipboardData.getData('text/plain');
            document.execCommand('formatBlock', false, 'p');
            document.execCommand('insertText', false, text);
        });

        htmlDiv.on("input", function(e) {
            $(".editor-preview").val(htmlDiv.html());
            $(".editor-preview").keyup();
        });
        
        $('.editor-preview').keyup(function() {
            var contentAttr = $(this).attr('class');
            if (!codeMode) {
                var value = $(this).val();
                $('.' + contentAttr).html(value);
            } else {
                $('.' + contentAttr).html(htmlDiv.text());
            }
        });

    });
.fieldsets {
    border: 1px solid #ccc;
    padding: 1em;
}
#editControls {
    overflow: auto;
    border-top: 1px solid transparent;
    border-left: 1px solid transparent;
    border-right: 1px solid transparent;
    border-color: silver;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    padding: .5em 1em .5em 1em;
    background-color: #fbfbfb;
    width: 100%;
    /* max-width: 950px; */
}
#editor {
    resize: vertical;
    overflow: auto;
    border: 1px solid silver;
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    min-height: 100px;
    padding: 1em;
    background-color: white;
    width: 100%;
    color: #333;
    /* max-width: 950px; */
}
#preview {
    padding: 1em;
    margin: 0 auto;
    width: 97%;
    border-top: 1px dotted #c8ccd0;
    border-bottom: 1px dotted #c8ccd0;
    clear: both;
}
.btn-group>.btn-editor:first-child {
    margin-left: 0;
    -webkit-border-top-left-radius: 4px;
    -moz-border-radius-topleft: 4px;
    border-top-left-radius: 4px;
    -webkit-border-bottom-left-radius: 4px;
    -moz-border-radius-bottomleft: 4px;
    border-bottom-left-radius: 4px;
}

.btn-group a {
    text-decoration: none;
}
.btn-not-space {
    position: relative;
    float: left;
    margin-left: 0 !important;
    border-radius: inherit;
    border: 1px solid transparent;
    border-color: #ccc;
}
.btn-editor {
    height: 30px;
    display: inline-block;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 11px;
    font-weight: normal;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border-radius: 4px;
    border: 1px solid transparent;
    color: #333;
    background-color: #fff;
    border-color: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset class="fieldsets">
                                        <div class="form-group">
        <div class="editor-wrapper">
            <div id="editControls">
                <div class="btn-group">
                    <a class="btn-editor btn-not-space" data-role="bold" data-ref="#">
                        <i class="icon-bold">B</i>
                    </a>
                    <a class="btn-editor btn-not-space" data-role="italic" data-ref="#">
                        <i class="icon-italic">I</i>
                    </a>
                    <a class="btn-editor btn-not-space" data-role="underline" data-ref="#">
                        <i class="icon-underline">U</i>
                    </a>
                </div>
                <div class="btn-group">
                    <a class="btn-editor btn-not-space" data-role="code" data-ref="#">
                        <i class="icon-code-view"><></i>
                    </a>
                </div>
            </div>
            <div id="editor" contenteditable=""></div>
            <br><br><br>
            <textarea id="textarea" class="editor-preview" name="detail"></textarea>
            <br><br><br>
            <div id="preview" class="editor-preview"></div>
        </div>
    </div>                              </fieldset>

Para ser más claro adjunto imagen del problema, en la número 1, escribo algún texto, ustedes se pueden dar cuenta que en el textarea dicho texto se adjunta con un código HTML ese texto es escrito desde el div editable, ahora en la imagen 2, doy click en la función editor de código <> ahí es el problema, porque cuando pego algún código o texto el código HTML se convierte en entidades HTML como se puede observar en el textarea de la imagen 3.

enter image description here

¿Cómo puedo resolver este problema, sin tener que dar enter en el div editable o realizar cambios en el texto desde los botones del editor?


Adjunto fiddle: https://jsfiddle.net/f4qhpov5/

2 respuestas 2

3

Si en realidad lo que soluciona tu problema es un Enter después de pegar el texto. Puedes disparar un Enter con JQuery para que se "presione" una tecla, en cuanto se detecte un evento paste.

$(document).ready(function() {
    $('#text-input').on("paste", function(e) {
      var event = $.Event("keypress");
      event.keyCode = 13;
      $(this).trigger(event);
   });
});

Así simularías que se haya presionado la tecla y problema resuelto

4
  • es una buena opción, pero eso no debería pasar, algo está mal en htmlDiv o codeMode usted puede ejecutar el proyecto en jsfiddle el código está completo y funcional amigo.
    – Valentina
    el 27 nov. 2020 a las 20:15
  • el pagar texto es cuando está en la opción modo código o programador en el botón <> justo ahí está el error, porque sin uso de modo programador eso no pasa.
    – Valentina
    el 27 nov. 2020 a las 20:18
  • Por favor crea el recurso en JSFiddle para los que quieran verlo funcional, lo puedan probar, sin necesidad de que cada usuario cree su propio JSFiddle. Edita tu pregunta para añadirlo, gracias :)
    – Chris
    el 27 nov. 2020 a las 22:21
  • 1
    Adjunto amigo jsfiddle.net/f4qhpov5
    – Valentina
    el 28 nov. 2020 a las 21:30
2
+200

Le hice algunas modificaciones para evitar el issue que en realidad era lo que se llama un side-effect.

Primero modifiqué tu HTML para evitarme le problema de modificar cosas que no quisiera:

<textarea id="textarea" class="editor-preview" name="detail"></textarea>
<div id="preview" class="editor-preview"></div>

Como puedes ver ambos elementos tienen la misma clase, así que eso nos creará sutiles problemas en la interacción.

Lo siguiente, me era muy dificil entender que hacía el botón <>, así que cuando me dí cuenta que no era un botón normal sino un toggle le agregué un cambio de estilo apra ver cuando estuviera activado y así dar una confirmación visual para facilitar la depuración.

En el CSS hice que se viera diferente activado y desactivado

a.btn-editor[active=true] {
  background-color: antiquewhite;
}

a.btn-editor[active=false] {
  background-color: #fff;
}

Y en el javascript debajo de tu cambio de estado también:

codeMode = !codeMode;
$("a[data-role='code']").attr('active', codeMode);

Para facilitar la depuración usé la S de SOLID y cree varios métodos que hicieran una sola cosa, así si algo fallaba sabría que no le pegaría sin querer a otras funcionalidades y me encargue que todo funcionara bien en el #editor.

Luego me encargué de que todo funcionara bien en el .editor-preview.

En ese momento solo restaba agregar código nuevo que no existía para el #textarea.

function settextAreacontent() {
    if (codeMode) {
        $('#textarea').val(htmlDiv.text());
    } else {
        $('#textarea').val(htmlDiv.html());
    }
}

Si estábamos en modo de edición visual debería de mostrar el HTML, pero si no... debería de mostrar el texto del editor y no su HTML, de esa manera se vería igual sin importar que pasara.

$(function() {

  let codeMode = false;
  let htmlDiv = $("#editor");


  function processCodeButtonClick() {
    changeCodeMode();
    if (codeMode) {
      var formattedHtml = formatHtmlCode(htmlDiv.html());
      htmlDiv.css("white-space", "pre");
      htmlDiv.text(formattedHtml);
      htmlDiv.addClass("black-bg-color codeMode");
      //editor.attr('id', 'editor newID');
      settextAreacontent();

      //  $(".editor-preview").val($.parseHTML(formattedHtml)[0]['wholeText']);
    } else {
      htmlDiv.css("white-space", "normal");
      htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
      htmlDiv.removeClass("black-bg-colr codeMode");
      //htmlDiv.attr('id', 'editor');
    }
    setPreviewContent();
  }

  function setPreviewContent() {
    if (codeMode) {
      $('.editor-preview').html(htmlDiv.text());
    } else {
      //var value = ; // $(".editor-preview").val(htmlDiv.html());
      //$('.editor-preview').val(value);
      $(".editor-preview").html(htmlDiv.html());
    }
  }

  function settextAreacontent() {
    if (codeMode) {
      $('#textarea').val(htmlDiv.text());
    } else {
      $('#textarea').val(htmlDiv.html());
    }
  }

  function changeCodeMode() {
    codeMode = !codeMode;
    $("a[data-role='code']").attr('active', codeMode);
    $("a.btn-editor:not([data-role='code'])").attr('disabled', codeMode);
    $('#editControls:has(a.btn-editor:not([data-role=\'code\']))').toggleClass('nopermitido')
  }

  function formatHtmlCode(str) {
    var p = document.createElement('p');
    p.innerHTML = str.trim();
    return format(p, 0).innerHTML;
  }

  function format(node, level) {
    var indentBefore = new Array(level++ + 1).join('  '),
      indentAfter = new Array(level - 1).join('  '),
      textNode;
    for (var i = 0; i < node.children.length; i++) {
      textNode = document.createTextNode('\n' + indentBefore);
      node.insertBefore(textNode, node.children[i]);
      format(node.children[i], level);
      if (node.lastElementChild == node.children[i]) {
        textNode = document.createTextNode('\n' + indentAfter);
        node.appendChild(textNode);
      }
    }
    return node;
  }



  $('#editControls a').click(function(e) {
    switch ($(this).data('role')) {
      case 'code':
        processCodeButtonClick();
        break;
      case 'h2':
      case 'h3':
      case 'p':
        document.execCommand('formatBlock', false, $(this).data('role'));
        break;
      default:
        document.execCommand($(this).data('role'), false, null);
        break;
    }
  });

  htmlDiv.on('keyup', function(e) {
    const ENTER_KEY = 13;
    if (!e.shiftKey && ENTER_KEY === e.keyCode) {
      document.execCommand('formatBlock', false, 'p');
    } else if (e.shiftKey) {
      document.execCommand('formatBlock', false, 'p');
    }
  });

  htmlDiv.on("paste", function(e) {
    e.preventDefault();
    var text = (e.originalEvent || e).clipboardData.getData('text/plain');
    document.execCommand('formatBlock', false, 'p');
    document.execCommand('insertText', false, text);
    setPreviewContent();
  });

  htmlDiv.on("input", function(e) {
    setPreviewContent();
    settextAreacontent();
  });

  $('#textArea').keyup(function() {
    setPreviewContent();

  });

  // text area

});
.fieldsets {
  border: 1px solid #ccc;
  padding: 1em;
}

#editControls {
  overflow: auto;
  border-top: 1px solid transparent;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-color: silver;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  padding: .5em 1em .5em 1em;
  background-color: #fbfbfb;
  width: 100%;
  /* max-width: 950px; */
}

#editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  background-color: white;
  width: 100%;
  color: #333;
  /* max-width: 950px; */
}

#preview {
  padding: 1em;
  margin: 0 auto;
  width: 97%;
  border-top: 1px dotted #c8ccd0;
  border-bottom: 1px dotted #c8ccd0;
  clear: both;
}

.btn-group>.btn-editor:first-child {
  margin-left: 0;
  -webkit-border-top-left-radius: 4px;
  -moz-border-radius-topleft: 4px;
  border-top-left-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-bottom-left-radius: 4px;
}

.btn-group a {
  text-decoration: none;
}

.btn-not-space {
  position: relative;
  float: left;
  margin-left: 0 !important;
  border-radius: inherit;
  border: 1px solid transparent;
  border-color: #ccc;
}

.btn-editor {
  height: 30px;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 11px;
  font-weight: normal;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border-radius: 4px;
  border: 1px solid transparent;
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}

a.btn-editor[active=true] {
  background-color: antiquewhite;
}

a.btn-editor[active=false] {
  background-color: #fff;
}

a.btn-editor[disabled="disabled"] {
  pointer-events: none;
  background-color: seashell;
}

.nopermitido {
  cursor: not-allowed !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset class="fieldsets">
  <div class="form-group">
    <div class="editor-wrapper">
      <div id="editControls">
        <div class="btn-group">
          <a class="btn-editor btn-not-space" data-role="bold" data-ref="#">
            <i class="icon-bold">B</i>
          </a>
          <a class="btn-editor btn-not-space" data-role="italic" data-ref="#">
            <i class="icon-italic">I</i>
          </a>
          <a class="btn-editor btn-not-space" data-role="underline" data-ref="#">
            <i class="icon-underline">U</i>
          </a>
        </div>
        <div class="btn-group">
          <a class="btn-editor btn-not-space" data-role="code" data-ref="#">
            <i class="icon-code-view">
                            <>
                        </i>
          </a>
        </div>
      </div>
      <div id="editor" contenteditable=""></div>
      <br><br><br>
      <textarea id="textarea" name="detail"></textarea>
      <br><br><br>
      <div id="preview" class="editor-preview"></div>
    </div>
  </div>
</fieldset>

2
  • Excelente amigo, me agrada :) sabes que sería interesante es deshabilitar el resto de botones cuando pasa a modo editor HTML :)
    – Valentina
    el 4 dic. 2020 a las 2:29
  • 1
    @Valentina Prueba ahora :) el 4 dic. 2020 a las 4:43

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.