Summernote Editor теряет фокус после выполнения таких операций, как копирование, вставка и просмотр исходного кода - PullRequest
0 голосов
/ 04 марта 2020

Я использую текстовый редактор summernote. Почему-то я сталкиваюсь с тем, что курсор теряет фокус, когда я выполняю несколько операций, таких как

  • Ctrl + B или выделение жирным шрифтом
  • Ctrl + I или выделение италий c
  • При просмотре исходного кода
  • При вставке содержимого

Курсор внезапно перемещается в самое начало строки редактора.

Я не знаю, есть ли еще какие-либо события, но в настоящее время это вызывает проблемы на данный момент.

Ниже приведен код, который я использую для вставки содержимого

function CleanPastedHTML(input)
        {
            // 1. remove line breaks / Mso classes
            var stringStripper = /(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
            var output = input.replace(stringStripper, ' ');
            // 2. strip Word generated HTML comments
            var commentSripper = new RegExp('<!--(.*?)-->','g');
            var output = output.replace(commentSripper, '');
            var tagStripper = new RegExp('<(/)*(meta|link|span|p|div|\\?xml:|st1:|o:|font)(.*?)>','gi');
            // 3. remove tags leave content if any
            output = output.replace(tagStripper, '');
            // 4. Remove everything in between and including tags '<style(.)style(.)>'
            var badTags = ['style','script','applet','embed','noframes','noscript'];

            for (var i=0; i< badTags.length; i++)
                {
                    tagStripper = new RegExp('<'+badTags[i]+'.*?'+badTags[i]+'(.*?)>', 'gi');
                    output = output.replace(tagStripper, '');
                }
            // 5. remove attributes ' style="..."'
            var badAttributes = ['style', 'start'];
            for (var i=0; i< badAttributes.length; i++)
                {
                    var attributeStripper = new RegExp(' ' + badAttributes[i] + '="(.*?)"','gi');
                    output = output.replace(attributeStripper, '');
                }
            return output;
        }

Ниже кода я Я использую для преобразования тегов, таких как <b> в <strong> и <i> в <em>

function clean_html(editor, type, value)
        {
            if (value.indexOf("<"+type+">") >= 0)
                {
                    if(type == "b")
                        {
                            marca = /<b(?:.*?)>(?:.*?)<\/b>/g;
                            replaceIniTag = "<strong>";
                            replaceEndTag = "</strong>";
                        }
                    else
                        {
                            marca = /<i(?:.*?)>(?:.*?)<\/i>/g;
                            replaceIniTag = "<em>";
                            replaceEndTag = "</em>";
                        }
                    var matches = value.match(marca), 
                    len = matches.length,
                    i;
                    for (i = 0; i < len; i++)
                        {
                            str = $(matches[i]).text();
                            str = replaceIniTag+str+replaceEndTag;
                            value = value.replace(matches[i], str);
                        }
                    $('#post_content').summernote('code', value); //Replace the editor content
                    $('#post_content').summernote('restoreRange');
                }
        }

Ниже код, который я использую для его инициализации

$('#post_content').summernote(
        {
            height: 200,
            focus: false,
            disableDragAndDrop: true,
            popover: {
                        image: [],
                        link: [],
                        air: []
                      },
            // disableResizeEditor: true,
            placeholder: "Type Your Post Content...",
            toolbar: [
                        ['cleaner',['cleaner']], // The Button
                        ['style', ['style']],
                        // ['style', ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'clear']],
                        ['style', ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript']],
                        // ['fontname', ['fontname']],
                        ['fontsize', ['fontsize']],
                        ['color', ['color']],
                        ['para', ['ul', 'ol', 'paragraph']],
                        ['height', ['height']],
                        ['table', ['table']],
                        ['insert', ['link', 'hr']],
                        // ['insert', ['link', 'picture', 'video', 'hr', 'readmore']],
                        ['view', ['fullscreen', 'codeview']]
                        // ['help', ['help']]
                    ],
            cleaner:{
                          action: 'both', // both|button|paste 'button' only cleans via toolbar button, 'paste' only clean when pasting content, both does both options.
                          newline: '<br>', // Summernote's default is to use '<p><br></p>'
                          notStyle: 'position:absolute;top:0;left:0;right:0', // Position of Notification
                          icon: '<i class="note-icon-row-remove"></i> &nbsp;Clean',
                          keepHtml: false, // Remove all Html formats
                          keepOnlyTags: ['<p>', '<br>', '<ul>', '<li>', '<b>', '<strong>','<i>', '<a>'], // If keepHtml is true, remove all tags except these
                          keepClasses: false, // Remove Classes
                          badTags: ['style', 'script', 'applet', 'embed', 'noframes', 'noscript', 'html'], // Remove full tags with contents
                          badAttributes: ['style', 'start'], // Remove attributes from remaining tags
                          limitChars: false, // 0/false|# 0/false disables option
                          limitDisplay: 'both', // text|html|both
                          limitStop: false // true/false
                    },
                callbacks:
                    {
                        onPaste: function (e)
                            {
                                var thisNote = $(this);
                                var updatePastedText = function(someNote)
                                    {
                                        // var original = ;
                                        var cleaned = CleanPastedHTML( someNote.summernote('code') ); //this is where to call whatever clean function you want. I have mine in a different file, called CleanPastedHTML.
                                        someNote.summernote('code', cleaned); //this sets the displayed content editor to the cleaned pasted code.
                                    };
                                setTimeout(function ()
                                    {
                                        //the function is called before the text is really pasted.
                                        updatePastedText(thisNote);
                                    }, 10);
                            },
                        onChange: function(contents, $editable)
                            {
                                $('#post_content').summernote('saveRange');
                                clean_html(this, "b", contents);
                                clean_html(this, "i", contents);
                            }
                    }
        });

I Я не могу понять, где ошибка / ошибка, но она всегда сводит меня с ума, когда я печатаю.

Может ли кто-нибудь помочь мне с помощью патча / руководства, что следует делать здесь?

...