docbrown/app/assets/javascripts/initializers/initializeCommentPreview.js
rhymes f9506affb5
Use faster JS selection methods (#11409)
* Add JS tips section to frontend documentation

* Replace document.getElementsByTagName('body') with document.body

* Replace querySelectorAll with faster selecting methods where appropriate

* Replace querySelector with faster selecting methods where appropriate

* Fix typo

* Fix forEach and getElementsByClassName

* Change querySelector* to faster methods in erb files

* Change querySelector* to faster methods in ruby files

* Fix runkit tag

* Various fixes

* Update app/assets/javascripts/initializers/initializeEllipsisMenu.js

Co-authored-by: Ridhwana <Ridhwana.Khan16@gmail.com>

* Update app/assets/javascripts/utilities/slideSidebar.js

Co-authored-by: Ridhwana <Ridhwana.Khan16@gmail.com>

* Commenting out flaky spec

Co-authored-by: Ridhwana <Ridhwana.Khan16@gmail.com>
2020-11-16 17:35:50 +01:00

55 lines
1.6 KiB
JavaScript

/* global activateRunkitTags */
function getAndShowPreview(preview, editor) {
function successCb(body) {
preview.innerHTML = body.processed_html; // eslint-disable-line no-param-reassign
activateRunkitTags();
}
const payload = JSON.stringify({
comment: {
body_markdown: editor.value,
},
});
getCsrfToken()
.then(sendFetch('comment-preview', payload))
.then((response) => {
return response.json();
})
.then(successCb)
.catch((err) => {
console.log('error!'); // eslint-disable-line
console.log(err); // eslint-disable-line no-console
});
}
function handleCommentPreview(event) {
event.preventDefault();
const { form } = event.target;
const editor = form.getElementsByClassName('comment-textarea')[0];
const preview = form.getElementsByClassName('comment-form__preview')[0];
const trigger = form.getElementsByClassName('preview-toggle')[0];
if (editor.value !== '') {
if (form.classList.contains('preview-open')) {
form.classList.toggle('preview-open');
trigger.innerHTML = 'Preview';
} else {
getAndShowPreview(preview, editor);
const editorHeight = editor.offsetHeight + 43; // not ideal but prevents jumping screen
preview.style.minHeight = `${editorHeight}px`;
trigger.innerHTML = 'Continue editing';
form.classList.toggle('preview-open');
}
}
}
function initializeCommentPreview() {
const previewButton = document.getElementsByClassName('preview-toggle')[0];
if (!previewButton) {
return;
}
previewButton.addEventListener('click', handleCommentPreview);
}