102 lines
3.4 KiB
JavaScript

import { simpleNotification } from '../z_comps/notify.js';
// https://summernote.org/getting-started/#without-bootstrap-lite
$('#summernote').summernote({
placeholder: 'Escribe aquí...',
tabsize: 2,
toolbar: [
['misc', ['undo', 'redo', 'clear']],
['heading', ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']], // tamaño de encabezado
['style', ['style','bold', 'italic', 'underline']],
['fontsize', ['fontsize']],
['color', ['color']],
['height', ['height']],
['font', ['strikethrough', 'superscript', 'subscript', 'clear']],
['para', ['ul', 'ol', 'paragraph']],
['object', ['link', 'table', 'picture', 'video', 'hr']],
['misc', [ 'help', 'codeview']], //'fullscreen'
['fontname', ['fontname']],
// ['alignment', ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull']],
// ['paragraph', ['indent', 'outdent']],
// ['cleaner', ['removeFormat']],
],
callbacks: {
onInit: function () {
const btn = document.getElementById('btn-submit');
const toolbar = document.querySelector('.note-toolbar');
const iTitle = document.querySelector('input[name="title"]');
if (btn && toolbar && iTitle) {
// Crear un contenedor para el título en una nueva línea
const titleWrapper = document.createElement('div');
titleWrapper.classList.add('note-title-wrapper', 'mb-2'); // margen inferior
// Clonar el input o moverlo (según tu preferencia)
titleWrapper.appendChild(iTitle);
// Insertar al inicio de la barra de herramientas
toolbar.prepend(titleWrapper);
// Crear un contenedor para el botón de enviar
const btnGroup = document.createElement('div');
btnGroup.classList.add('note-btn-group', 'ms-2'); // margen izquierdo
// agregar btn enviar cambios
btnGroup.appendChild(btn);
toolbar.appendChild(btnGroup);
}
}
}
});
async function a_sendpost(title, body) {
try {
let response = await fetch('/user/save-post', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({"title": title, "body": body}),
credentials: 'include'
});
if (!response.ok) {
throw new Error('Error en la respuesta del servidor <-');
}
const result = await response.json();
simpleNotification('Éxito', `Publicación guardada: ${result.title_post}`, 'success');
// Opcional: Limpiar el editor después de guardar
$('#summernote').summernote('code', '');
document.querySelector("input[name='title']").value = '';
} catch (error) {
console.error('Error al guardar:', error);
simpleNotification('Error', 'No se pudo guardar la publicación', 'error');
}
}
function send_post(e) {
e.preventDefault();
let title_post = document.querySelector("input[name='title']").value.trim();
let body_post = $('#summernote').summernote('code'); // Obtener el contenido del editor
let body_gt11 = body_post.length > 11 ? body_post : '';
if (!title_post || (!body_post || body_gt11 === '')) {
simpleNotification('Campos obligatorios', 'Todos los campos son obligatorios', 'warning');
} else {
a_sendpost(title_post, body_post);
}
}
document.getElementById("post-form").addEventListener("submit", send_post);