From ed66b70400c78608065b2bd464e219e265f0c521 Mon Sep 17 00:00:00 2001
From: anisa kusumadewi <kusumadewi@itc.rwth-aachen.de>
Date: Wed, 26 Oct 2022 10:13:27 +0200
Subject: [PATCH] wip: fix edit and add img comments fix for comments download

---
 action.php                                    |   4 +-
 lib.php                                       |  38 ++--
 locallib.php                                  |  35 +++-
 model/comment.class.php                       |   2 +-
 shared/index.js                               | 184 ++++++++++--------
 templates/comment.mustache                    |   1 +
 .../edit_comment_editor_placeholder.mustache  |   7 +-
 version.php                                   |   2 +-
 8 files changed, 167 insertions(+), 106 deletions(-)

diff --git a/action.php b/action.php
index 0ee9b23..5edbb9e 100644
--- a/action.php
+++ b/action.php
@@ -615,7 +615,7 @@ if ($action === 'getCommentsToPrint') {
         foreach ($conversations as $conversation) {
             $post = new stdClass();
             $post->answeredquestion = pdfannotator_handle_latex($context, $conversation->answeredquestion);
-            $post->answeredquestion = pdfannotator_extract_images($post->answeredquestion);
+            $post->answeredquestion = pdfannotator_extract_images($post->answeredquestion, $conversation->id, $context);
             $post->page = $conversation->page;
             $post->annotationtypeid = $conversation->annotationtypeid;
             $post->author = $conversation->author;
@@ -626,7 +626,7 @@ if ($action === 'getCommentsToPrint') {
             foreach ($conversation->answers as $ca) {
                 $answer = new stdClass();
                 $answer->answer = pdfannotator_handle_latex($context, $ca->answer);
-                $answer->answer = pdfannotator_extract_images($answer->answer);
+                $answer->answer = pdfannotator_extract_images($answer->answer, $ca->id, $context);
                 $answer->author = $ca->author;
                 $answer->timemodified = $ca->timemodified;
                 $post->answers[$answercount] = $answer;
diff --git a/lib.php b/lib.php
index c5355aa..84281b8 100644
--- a/lib.php
+++ b/lib.php
@@ -771,26 +771,40 @@ function pdfannotator_print_recent_mod_activity($activity, $courseid, $detail, $
  */
 function mod_pdfannotator_output_fragment_open_edit_comment_editor($args) {
     global $DB;
+
     $context = context_module::instance($args['cmid']);
-    $html = '';
 
-    $draftitemid = pdfannotator_data_preprocessing($context, 'editarea' . $args['commentid'], 'editor-editcomment-inputs' . $args['commentid'], 0);
-    $comment = $DB->get_record('pdfannotator_comments', ['id' => $args['commentid']]);
-    $html = pdfannotator_file_prepare_draft_area($draftitemid, $context->id, 'mod_pdfannotator', 'post',
-    $args['commentid'], pdfannotator_get_editor_options($context), $comment->content);
+    $data = pdfannotator_data_preprocessing($context, 'editarea' . $args['uuid'], 0);
+    $comment = $DB->get_record('pdfannotator_comments', ['id' => $args['uuid']]);
+    $displaycontent = pdfannotator_file_prepare_draft_area($data['draftItemId'], $context->id, 'mod_pdfannotator', 'post',
+    $args['uuid'], pdfannotator_get_editor_options($context), $comment->content);
+
+    /* $params = ['draftitemid' => $data['draftItemId'], 'editorformat' => $data['editorFormat'], $args['action'], 'targetId' => 'editor-editcomment-inputs-' . $args['uuid'], $args['uuid']];
+    $PAGE->requires->js_init_call('loadEditorInputFields', $params); */
 
-    return $html;
+    // Input fields.
+    $out = '';
+    $out .= html_writer::empty_tag('input', ['type' => 'hidden', 'class' => 'pdfannotator_' . $args['action'] . 'comment' . '_editoritemid', 'name' => 'input_value_editor', 'value' => $data['draftItemId']]);
+    $out .= html_writer::empty_tag('input', ['type' => 'hidden', 'class' => 'pdfannotator_' . $args['action'] . 'comment' . '_editorformat', 'name' => 'input_value_editor', 'value' => $data['editorFormat']]);
+    $out .= 'displaycontent:' . $displaycontent;
+    
+    return $out;
 }
 
+/**
+ * Initialize the editor for adding a comment.
+ * @param type $args
+ * @return string
+ */
 function mod_pdfannotator_output_fragment_open_add_comment_editor($args) {
-    global $DB;
     $context = context_module::instance($args['cmid']);
 
-    $data = pdfannotator_data_preprocessing($context, 'id_pdfannotator_content', "editor-commentlist-inputs", 0);
-    file_prepare_draft_area($draftitemid, $context->id, 'mod_pdfannotator', 'post', 0, pdfannotator_get_editor_options($context));
+    $data = pdfannotator_data_preprocessing($context, 'id_pdfannotator_content', 0);
+    $text = file_prepare_draft_area($data['draftItemId'], $context->id, 'mod_pdfannotator', 'post', 0, pdfannotator_get_editor_options($context));
     
-    $out = html_writer::empty_tag('input', ['type' => 'hidden', 'class' => 'pdfannotator_' . $args['section'] . '_editoritemid', 'name' => 'input_value_editor', 'value' => $data['draftItemId']]);
-    $out .= html_writer::empty_tag('input', ['type' => 'hidden', 'class' => 'pdfannotator_' . $args['section'] . '_editorformat', 'name' => 'input_value_editor', 'value' => $data['editorFormat']]);
+    $out = '';
+    $out = html_writer::empty_tag('input', ['type' => 'hidden', 'class' => 'pdfannotator_' . $args['action'] . 'comment' . '_editoritemid', 'name' => 'input_value_editor', 'value' => $data['draftItemId']]);
+    $out .= html_writer::empty_tag('input', ['type' => 'hidden', 'class' => 'pdfannotator_' . $args['action'] . 'comment' . '_editorformat', 'name' => 'input_value_editor', 'value' => $data['editorFormat']]);
 
     return $out;
-}
+}
\ No newline at end of file
diff --git a/locallib.php b/locallib.php
index a178ad1..fc9a247 100644
--- a/locallib.php
+++ b/locallib.php
@@ -128,7 +128,7 @@ function pdfannotator_get_editor_options($context) {
         'return_types' => 15,
         'enable_filemanagement' => true, 
         'removeorphaneddrafts' => false, 
-        'autosave' => true,
+        'autosave' => false,
         'noclean' => false, 
         'trusttext' => 0,
         'subdirs' => true,
@@ -147,7 +147,7 @@ function pdfannotator_get_relativelink($content, $commentid, $context) {
     return $content;
 }
 
-function pdfannotator_extract_images($contentarr) {
+function pdfannotator_extract_images($contentarr, $itemid, $context=null) {
     // Remove quotes here, in case if there is no math form.
     if (gettype($contentarr) === 'string') {
         $str = preg_replace('/[\"]/', "", $contentarr);
@@ -161,12 +161,12 @@ function pdfannotator_extract_images($contentarr) {
             $res[] = $content;
             continue;
         }
-        $res = pdfannotator_split_content_image($content, $res);
+        $res = pdfannotator_split_content_image($content, $res, $itemid, $context);
     }
     return $res;
 }
 
-function pdfannotator_split_content_image($content, $res) {
+function pdfannotator_split_content_image($content, $res, $itemid, $context=null) {
     $imgmatch = [];
     $firststr = '';
     $data = [];
@@ -190,11 +190,26 @@ function pdfannotator_split_content_image($content, $res) {
             $format[0] = 'jpeg';
         }
 
-        $imagedata = file_get_contents($url[0]);
-        $data['image'] = $url[0];
+        $data['format'] = strtoupper($format[0]);
+
+        $fs = get_file_storage();
+        $files = $fs->get_area_files($context->id, 'mod_pdfannotator', 'post', $itemid);
+        $fileinfo = [];
+        foreach($files as $file) {
+            if ($file->is_directory() and $file->get_filepath() === '/') {
+                continue;
+            }
+            //$fileinfo['fileid'] = $file->file_record['id'];
+            $fileinfo['filename'] = $file->get_filename();
+            $fileinfo['filepath'] = $file->get_filepath();
+            $fileinfo['filecontent'] = $file->get_content();
+            $fileinfo['filesize'] = $file->get_filesize();
+        }
+        //$imagedata = file_get_contents($fileinfo['filecontent']);
+        $imagedata = 'data:image/' . strtolower($data['format']) . ';base64,' .  base64_encode($fileinfo['filecontent']);
+        $data['image'] = $imagedata;
 
         //$data['image'] = $url[0];
-        $data['format'] = strtoupper($format[0]);
         preg_match('/height=[0-9]+/', $imgstr, $height);
         $data['imageheight'] = str_replace("\"", "", explode('=', $height[0])[1]);
         preg_match('/width=[0-9]+/', $imgstr, $width);
@@ -208,7 +223,7 @@ function pdfannotator_split_content_image($content, $res) {
     return $res;
 }
 
-function pdfannotator_data_preprocessing($context, $textarea, $classname, $draftitemid = 0) {
+function pdfannotator_data_preprocessing($context, $textarea, $draftitemid = 0) {
     global $PAGE;
 
     $options = pdfannotator_get_editor_options($context);
@@ -240,6 +255,8 @@ function pdfannotator_data_preprocessing($context, $textarea, $classname, $draft
         $args->env = 'filepicker';
         // advimage plugin
         $image_options = (object)initialise_filepicker($args);
+        $image_options->context = $context;
+        $image_options->client_id = uniqid();
         $image_options->maxbytes = get_config('mod_pdfannotator', 'maxbytes');
         $image_options->maxfiles = PDFANNOTATOR_EDITOR_UNLIMITED_FILES;
         $image_options->autosave = false;
@@ -256,7 +273,7 @@ function pdfannotator_data_preprocessing($context, $textarea, $classname, $draft
 
     //$PAGE->requires->js_init_call('inputDraftItemID', [$draftitemid, (int)$editorformat, $classname]);
     
-    return ['draftItemId' => $draftitemid, 'editorFormat' => $editorformat, 'className' => $classname];
+    return ['draftItemId' => $draftitemid, 'editorFormat' => $editorformat];
 }
 
 /**
diff --git a/model/comment.class.php b/model/comment.class.php
index 220e2be..3b5e2c7 100644
--- a/model/comment.class.php
+++ b/model/comment.class.php
@@ -61,7 +61,7 @@ class pdfannotator_comment {
         $datarecord->id = $commentuuid;
         
         // Get the draftitemid and prepare the draft area.
-        $draftitemid = required_param('pdfannotator_content_editoritemid', PARAM_INT);
+        $draftitemid = required_param('pdfannotator_addcomment_editoritemid', PARAM_INT);
         $options = pdfannotator_get_editor_options($context);
 
         $text = file_save_draft_area_files($draftitemid, $context->id, "mod_pdfannotator", "post",  $commentuuid, $options, $datarecord->content, true);
diff --git a/shared/index.js b/shared/index.js
index f0f3ee7..f3f1002 100644
--- a/shared/index.js
+++ b/shared/index.js
@@ -269,11 +269,11 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
              * @returns {unresolved}
              */
             addComment(documentId, annotationId, content, visibility = "public", isquestion = 0) {
-                var pdfannotator_content_editoritemid = document.querySelectorAll('.pdfannotator_content_editoritemid')[0].value;  
+                var pdfannotator_addcomment_editoritemid = document.querySelectorAll('.pdfannotator_addcomment_editoritemid')[0].value;  
                 return $.ajax({
                     type: "POST",
                     url: "action.php",
-                    data: { "documentId": documentId, "annotationId": annotationId, "content": content, "visibility": visibility, "action": 'addComment', "isquestion": isquestion, "cmid":_cm.id, "pdfannotator_content_editoritemid": pdfannotator_content_editoritemid, sesskey: M.cfg.sesskey}
+                    data: { "documentId": documentId, "annotationId": annotationId, "content": content, "visibility": visibility, "action": 'addComment', "isquestion": isquestion, "cmid":_cm.id, "pdfannotator_addcomment_editoritemid": pdfannotator_addcomment_editoritemid, sesskey: M.cfg.sesskey}
                 }).then(function(data){
                     data = data.substring(data.indexOf('{'),data.length);    
                     //TODO compare to data before data.substring
@@ -866,9 +866,10 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
                                         }
                                     }
                                     function printImage(data) {
+                                        // var url = data['image'];
+                                        // var imageElement = document.createElement("img");
+                                        // imageElement.src = url;
                                         var url = data['image'];
-                                        var imageElement = document.createElement("img");
-                                        imageElement.src = url;
                                         var height = data['imageheight'] * 0.264583333333334; // Convert pixel into mm.
 
                                         // Reduce height and witdh if its size more than a4height.
@@ -883,7 +884,7 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
                                             doc.addPage();
                                             count = contentTopBottomMargin;
                                         }
-                                        doc.addImage(imageElement, data['format'], contentRightMargin, count, width, height); // image data, format, offset to the left, offset to the top, width, height
+                                        doc.addImage(url, data['format'], contentRightMargin, count, width, height); // image data, format, offset to the left, offset to the top, width, height
                                         count += (5 + height);
                                     }
                                     /**
@@ -1756,31 +1757,29 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
              * @returns {undefined}
              */
             function createEditFormHandler(comment) {
-                var editorExists = false;
-                var editForm;
-                var editArea;
-                // If there is no editor in the comment already, we will insert it and than call this function.
-                var handleClickIfEditorExists = function() { 
-                    editForm = document.getElementById("edit"+comment.uuid);
-                    editArea = document.getElementById("editarea"+comment.uuid);
-                    var editAreaEditable = document.getElementById("editarea"+comment.uuid+"editable");
-                    var text = document.getElementById("chatmessage"+comment.uuid);
-                        if (editForm.style.display === "none") {
-                            editForm.style.display = "block";
-                            text.innerHTML = "";
-                        
-                        var isEmptyContent = false;
+                // Create an element for click.
+                var editButton = $('#editButton'+comment.uuid);
+                // Add an event handler to the click element that opens a textarea and fills it with the current comment.
+                editButton.click(function(e) {
+                    UI.loadEditor('edit', comment.uuid, handleClickIfEditorExists);
+                    function handleClickIfEditorExists() { 
                         // Add an event handler to the form for submitting any changes to the database.
+                        let editForm = document.getElementById(`edit${comment.uuid}`);
                         editForm.onsubmit = function (e) {
-                            let newContent = editArea.value.trim();
-                            var commentEditContentElements = document.querySelectorAll(`#editarea${comment.uuid}editable`)[0];
-                            var imgContents = commentEditContentElements.querySelectorAll('img');
-                            if(commentEditContentElements.innerText.replace('/\n/g', '').trim() === '') {
+                            let editTextarea =  document.getElementById(`editarea${comment.uuid}`);
+                            let editAreaEditable = document.getElementById(`editarea${comment.uuid}editable`);
+                            let chatMessage = document.getElementById(`chatmessage${comment.uuid}`);
+                            
+                            let newContent = editTextarea.value.trim();
+                            let imgContents = editAreaEditable.querySelectorAll('img');
+                            let isEmptyContent = false;
+                            if(editAreaEditable.innerText.replace('/\n/g', '').trim() === '') {
                                 isEmptyContent = true;
                             }
-                            var temp = commentEditContentElements.querySelectorAll('p')[0];
-                            if(temp) {
-                                if (temp.innerText.replace('/\n/g', '').trim() === '' && imgContents.length === 0) {
+                            let defaultPTag = editAreaEditable.querySelector('p');
+                            if(defaultPTag) {
+                                // No text and no images in default p tag of editor.
+                                if (defaultPTag.innerText.replace('/\n/g', '').trim() === '' && imgContents.length === 0) {
                                     isEmptyContent = true;
                                 }
                             }
@@ -1790,25 +1789,27 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
                                     message: M.util.get_string('min0Chars','pdfannotator'),
                                     type: "error"
                                 });
-                            } else if(newContent === comment.content) { // No changes.
+                            } else if(newContent === comment.displaycontent) { // No changes.
                                 editForm.style.display = "none";
-                                text.innerHTML = comment.displaycontent;
-                                renderMathJax(text);
+                                chatMessage.innerHTML = comment.displaycontent;
+                                renderMathJax(chatMessage);
                             } else { // Save changes.
                                 _2.default.getStoreAdapter().editComment(documentId, comment.uuid, newContent, editForm)
                                     .then(function(data){
                                         if (data.status === "success") {
                                             editForm.style.display = "none";
+                                            $(`edit_comment_editor_wrapper_${comment.uuid}`).remove();
                                             if (data.modifiedby) {
                                                 $('#comment_' + comment.uuid + ' .edited').html(M.util.get_string('editedComment', 'pdfannotator') + " " + data.timemodified + " " + M.util.get_string('modifiedby', 'pdfannotator') + " " + data.modifiedby);
                                             } else {
                                                 $('#comment_' + comment.uuid + ' .edited').html( M.util.get_string('editedComment', 'pdfannotator') + " " + data.timemodified);
                                             }
                                             newContent = data.newContent;
-                                            text.innerHTML = newContent;
+                                            chatMessage.innerHTML = newContent;
                                             comment.content = newContent;
-                                            editArea = newContent;
-                                            renderMathJax(text);
+                                            comment.displaycontent = newContent;
+                                            editTextarea = newContent;
+                                            renderMathJax(chatMessage);
                                             notification.addNotification({
                                                 message: M.util.get_string('successfullyEdited', 'pdfannotator'),
                                                 type: "success"
@@ -1827,31 +1828,24 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
                                     notificationpanel.removeChild(notificationpanel.firstChild);
                                 }
                             }, 4000);
-
+    
                             return false; // Prevents normal POST and page reload in favour of an asynchronous load.
                         };
-                            
-                        $('#comment_' + comment.uuid + ' #commentCancel').click(function(e){
+    
+                        let cancelBtn = $('#comment_' + comment.uuid + ' #commentCancel');
+                        cancelBtn.click(function(e){
+                            let editTextarea =  document.getElementById(`editarea${comment.uuid}`);
+                            let editAreaEditable = document.getElementById(`editarea${comment.uuid}editable`);
+                            let chatMessage = document.getElementById(`chatmessage${comment.uuid}`);
                             editForm.style.display = "none";
-                            editArea.innerHTML = '';
-                            editArea.innerHTML = comment.displaycontent;
+                            editTextarea.innerHTML = '';
+                            editTextarea.innerHTML = comment.displaycontent;
                             editAreaEditable.innerHTML = '';
                             editAreaEditable.innerHTML = comment.displaycontent;
-                            text.innerHTML = comment.displaycontent;
-                            renderMathJax(text);
+                            chatMessage.innerHTML = comment.displaycontent;
+                            renderMathJax(chatMessage);
                         });
-                    } else {
-                        editForm.style.display = "none";
-                        text.innerHTML = comment.displaycontent;
-                        renderMathJax(text);
-                    } 
-                }
-                // Create an element for click.
-                var editButton = $('#editButton'+comment.uuid);
-                // Add an event handler to the click element that opens a textarea and fills it with the current comment.
-                editButton.click(function(e) {
-                    UI.loadEditor('editcomment', 'edit', comment.uuid);
-                    handleClickIfEditorExists();
+                    }
                 });               
             }
             
@@ -1981,7 +1975,7 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
                                 _2.default.getStoreAdapter().addComment(documentId, annotationId, commentContentElements.innerHTML, commentVisibility, isquestion)
                                 .then(function (response) {
                                     var fn = (response) => insertComments(response);
-                                    UI.loadEditor('content', 'add', 0, fn, response);
+                                    UI.loadEditor('add', 0, fn, response);
                                 })
                                 .then(function (success) {
                                     if (!success) {
@@ -2007,7 +2001,7 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
                                 //render comments   
                                 insertComments(comments, markCommentid);
                             }
-                            UI.loadEditor('content', 'add', 0, fn, params);
+                            UI.loadEditor('add', 0, fn, params);
                                 
                         })
                         .catch(function (err){
@@ -5783,7 +5777,7 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
                     [textarea,data] = (0,_commentWrapper.openComment)(e,handleCancelClick,handleSubmitClick,handleToolbarClick,handleSubmitBlur,'pin');
                     renderPin();
                 }
-                _commentWrapper.loadEditor('content', 'add', 0, fn);
+                _commentWrapper.loadEditor('add', 0, fn);
             }
             
             // Reset dragging to false.
@@ -6168,14 +6162,14 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
                     let fn = () => {
                         [textarea,data] = (0,_commentWrapper.openComment)(e,handleCancelClick,handleSubmitClick,handleToolbarClick,handleSubmitBlur,_type);
                     }
-                    _commentWrapper.loadEditor('content', 'add', 0, fn);
+                    _commentWrapper.loadEditor('add', 0, fn);
                 }else if((rectsSelection=getSelectionRects()) && _type!=='area'){
                     renderRect(_type,[].concat(_toConsumableArray(rectsSelection)).map(function(r){return{top:r.top,left:r.left,width:r.width,height:r.height};}),null);
                     
                     let fn = () => {
                         [textarea,data] = (0,_commentWrapper.openComment)(e,handleCancelClick,handleSubmitClick,handleToolbarClick,handleSubmitBlur,_type);
                     }
-                    _commentWrapper.loadEditor('content', 'add', 0, fn);
+                    _commentWrapper.loadEditor('add', 0, fn);
                 }else{
                     enableRect(_type);
                     //Do nothing!
@@ -6386,8 +6380,7 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
                                 document.querySelector('.toolbar').removeEventListener('click',handleToolbarClick);
                                 //simulate an click on cursor
                                 document.querySelector('button.cursor').click();
-                                (0,_commentWrapper.showCommentsAfterCreation)(annotation.uuid);                                
-                                //_commentWrapper.loadEditor('content');
+                                (0,_commentWrapper.showCommentsAfterCreation)(annotation.uuid);
                             })
                             .catch(function(){
                                 //if there is an error in addComment, the annotation should be deleted!
@@ -6945,26 +6938,25 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
 
             /**
              * 
-             * @param {type} section is a part of class name of editor input: pdfannotator_${section}_editoritemid, pdfannotator_${section}_editorFormat.
-             * @param {type} action can be add or edit
+             * @param {type} action can be add for adding comments. Or edit for editing comments.
              * @param {int} uuid
              * @param {Function} fn a callback funtion. It will be called after the Promises in this funktion finish.
              *
              *  
              */
-            function loadEditor(section, action='add', uuid=0, fn=null, fnParams=null){
-                _ajaxloader.showLoader(`.editor-loader-placeholder-${action}`);
-                
+            function loadEditor(action='add', uuid=0, fn=null, fnParams=null){                
                 // search the placeholder for editor.
                 let addCommentEditor = document.querySelectorAll('#add_comment_editor_wrapper');
-                let editCommentEditor = document.querySelectorAll('#edit_comment_editor_wrapper').length;
+                let editCommentEditor = document.querySelectorAll (`#edit_comment_editor_wrapper_${uuid}`);
 
                 if (action === "add") {
+                    _ajaxloader.showLoader(`.editor-loader-placeholder-${action}`);
+
                     // remove old editor and old input values of draftitemid and editorformat, if exists.
                     if (addCommentEditor.length > 0) {
-                        $('div').remove('#add_comment_editor_wrapper');
+                        addCommentEditor[0].remove();
                     }
-                    $('input').remove('[name="input_value_editor"]');
+
                     let data = {};
                     templates.render('mod_pdfannotator/add_comment_editor_placeholder', data)
                     .then(function(html, js) {
@@ -6972,10 +6964,9 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
                         templates.prependNodeContents(commentListForm, html, js);
                     })
                     .then(function() {
-                        let args = {'section': section, 'cmid': _cm.id};
+                        let args = {'action': action, 'cmid': _cm.id};
                         Fragment.loadFragment('mod_pdfannotator', 'open_add_comment_editor', _contextId, args)
                         .done(function(html, js) {
-                            _ajaxloader.hideLoader(`.editor-loader-placeholder-${action}`);              
                             if (!html) {
                                 throw new TypeError("Invalid HMTL Input");
                             }
@@ -6983,29 +6974,68 @@ function startIndex(Y,_cm,_documentObject,_contextId, _userid,_capabilities, _to
                             if (fn instanceof Function) {
                                 (0,fn)(fnParams);
                             }
+                            _ajaxloader.hideLoader(`.editor-loader-placeholder-${action}`);
                             return true;
+                        })
+                        .then(function() {                            
+                            let commentText = document.getElementById('id_pdfannotator_contenteditable');
+                            if(commentText) {
+                                commentText.focus();
+                            }
                         });
                     })
                     .catch(notification.exception);
-                } else if(editCommentEditor > 0 && action === "edit") {
+                } else if(action === "edit") {
+                    _ajaxloader.showLoader(`.editor-loader-placeholder-${action}-${uuid}`);
+
+                    // remove old editor and old input values of draftitemid and editorformat, if exists.
+                    if (editCommentEditor.length > 0) {
+                        editCommentEditor[0].remove();
+                    }
+
                     let data = {'uuid': uuid};
+                    let editTextarea;
                     templates.render('mod_pdfannotator/edit_comment_editor_placeholder', data)
                     .then(function(html, js) {
-                        let editForm = document.querySelectorAll(`edit${uuid}`)[0];
-                        editForm.appendChild(html);
-                        return html;
+                        let editForm = document.getElementById(`edit${uuid}`);
+                        templates.prependNodeContents(editForm, html, js);
+                        editTextarea =  document.getElementById(`editarea${uuid}`);
+                        editTextarea.style.display = "none";
+                        return true;
                     })
                     .then(function() {
-                        $('input').remove('[name="input_value_editor"]');
-                        let args = {'section': section, 'cmid': _cm.id};
+                        let args = {'action': action, 'cmid': _cm.id, 'uuid': uuid};
                         Fragment.loadFragment('mod_pdfannotator', 'open_edit_comment_editor', _contextId, args)
                         .then(function(html, js) {
-                            _ajaxloader.hideLoader(`.editor-loader-placeholder-${action}`);              
                             if (!html) {
                                 throw new TypeError("Invalid HMTL Input");
                             }
-                            templates.replaceNode(document.getElementById('editor-commentlist-inputs'), html, js);
-                            return html;
+                            //templates.runTemplateJS(js);
+                            let editCommentEditorElement = document.getElementById(`edit_comment_editor_wrapper_${uuid}`);
+                            html = html.split('displaycontent:');
+                            let isreplaced = templates.appendNodeContents(editCommentEditorElement, html[0], js);
+                            editTextarea.innerText = html[1];
+    
+                            _ajaxloader.hideLoader(`.editor-loader-placeholder-${action}-${uuid}`);
+
+                            let editForm = document.getElementById(`edit${uuid}`)
+                            let chatMessage = document.getElementById(`chatmessage${uuid}`);
+                            let editAreaEditable = document.getElementById(`editarea${uuid}editable`);
+                            editAreaEditable.innerHTML = editTextarea.value;
+                            if(editForm.style.display === "none") {
+                                editForm.style.cssText += ';display:block;';
+                                chatMessage.innerHTML = "";
+                            }
+                            return true;
+                        })
+                        .then(function() {                            
+                            let commentText = document.getElementById(`editarea${uuid}`);
+                            if(commentText) {
+                                commentText.focus();
+                            }
+                            if (fn instanceof Function) {
+                                (0,fn)(fnParams);
+                            }
                         });
                     })
                     .catch(notification.exception);
diff --git a/templates/comment.mustache b/templates/comment.mustache
index 9851eaa..39e147d 100644
--- a/templates/comment.mustache
+++ b/templates/comment.mustache
@@ -57,6 +57,7 @@
                 {{#displayhidden}}<span id="taghidden{{uuid}}" class="tag tag-info">{{# str }} hiddenforparticipants, pdfannotator {{/ str }}</span>{{/displayhidden}}
 
                 <form id="edit{{ uuid }}" class="edit-comment-form" style="display:none;">
+                    <div class="editor-loader-placeholder-edit-{{ uuid }}"></div>
                     <input id="commentSubmit" class="owner btn btn-primary mb-1" type="submit" value="{{# str }} editButton, pdfannotator {{/ str }}">
                     <input id="commentCancel" class="owner btn btn-secondary mb-1" type="reset" value="{{# str }} cancelButton, pdfannotator {{/ str }}" >
                 </form>
diff --git a/templates/edit_comment_editor_placeholder.mustache b/templates/edit_comment_editor_placeholder.mustache
index b74f95b..5e56a8b 100644
--- a/templates/edit_comment_editor_placeholder.mustache
+++ b/templates/edit_comment_editor_placeholder.mustache
@@ -1,5 +1,4 @@
-<div id="edit_comment_editor_wrapper"> {{! necessary for atto-editor }}
-    <textarea id="editarea{{ uuid }}" placeholder="" cols="40" rows="3">{{{ displaycontent }}}</textarea>
-    <div class="editor-editcomment-inputs{{ uuid }}"></div>
-    <div class="editor-loader-placeholder-edit"></div>
+<div id="edit_comment_editor_wrapper_{{uuid}}"> {{! necessary for atto-editor }}
+    <div id="editor-editcomment-inputs-{{ uuid }}"></div>
+    <textarea id="editarea{{ uuid }}" placeholder="" cols="40" rows="3"></textarea>
 </div>
\ No newline at end of file
diff --git a/version.php b/version.php
index 1046564..3ab8919 100644
--- a/version.php
+++ b/version.php
@@ -25,7 +25,7 @@
 defined('MOODLE_INTERNAL') || die();
 
 $plugin->component = 'mod_pdfannotator';
-$plugin->version   = 2022090800;
+$plugin->version   = 2022102600;
 $plugin->release  = 'PDF Annotator v1.4 release 11';
 $plugin->requires  = 2021051700;
 $plugin->maturity  = MATURITY_STABLE;
-- 
GitLab