camper/web/static/camper.js

114 lines
3.1 KiB
JavaScript

/**
* SPDX-FileCopyrightText: 2023 jordi fita mas <jordi@tandem.blog>
* SPDX-License-Identifier: AGPL-3.0-only
*/
function ready(fn) {
if (document.readyState !== 'loading') {
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(function () {
const snackBar = Object.assign(
document.body.appendChild(document.createElement('section')),
{
id: 'snackbar',
}
);
const errorMessage = snackBar.appendChild(document.createElement('div'));
errorMessage.setAttribute('role', 'alert');
const openClass = 'open';
const toasts = [];
let timeoutId = null;
function showError(message) {
toasts.push(message);
popUp();
}
function popUp() {
if (toasts.length === 0) {
return;
}
if (errorMessage.classList.contains(openClass)) {
dismiss();
return;
}
if (errorMessage.innerText !== "") {
// it will show after remove calls popUp again.
return;
}
errorMessage.innerText = toasts[0];
errorMessage.classList.add(openClass);
timeoutId = setTimeout(dismiss, 4000);
}
function dismiss() {
if (!errorMessage.classList.contains(openClass)) {
// already dismissed
return;
}
errorMessage.classList.remove(openClass);
clearTimeout(timeoutId);
timeoutId = setTimeout(remove, 350);
}
function remove() {
clearTimeout(timeoutId);
toasts.splice(0, 1);
errorMessage.innerText = "";
popUp();
}
document.body.addEventListener('htmx:error', function (evt) {
const errorInfo = evt.detail.errorInfo;
const error = errorInfo.xhr && errorInfo.xhr.responseText || errorInfo.error;
showError(error);
});
})
ready(function () {
const textareas = document.querySelectorAll('textarea.html');
for (const textarea of textareas) {
const canvas = document.createElement('div');
textarea.parentNode.insertBefore(canvas, textarea.nextSibling);
textarea.style.display = 'none';
const textareaStorage = (editor) => {
editor.Storage.add('textarea', {
load() {
editor.setComponents(textarea.value);
},
store(data) {
const component = editor.Pages.getSelected().getMainComponent();
textarea.value = component.getInnerHTML();
},
});
}
const editor = grapesjs.init({
container: canvas,
height: '500px',
width: 'auto',
plugins: [
textareaStorage,
'gjs-blocks-basic',
'grapesjs-plugin-ckeditor',
'grapesjs-preset-webpage',
],
storageManager: {
type: 'textarea',
autosave: true,
autoload: true,
stepsBeforeSave: 1,
},
});
}
})