253 lines
9.8 KiB
JavaScript
Raw Permalink Normal View History

export default class WebsiteLegalSettingsForm {
constructor(config = {}) {
const defaultConfig = {
contentId: 'website-legal-settings-card',
forms: {
'legal_terminos_y_condiciones-nav': {
enabledCheckboxId: 'legal_terminos_y_condiciones-enabled',
quillSelector: '#legal_terminos_y_condiciones-content',
quillPlaceholder: 'Ingrese los términos y condiciones'
},
'legal_aviso_de_privacidad-nav': {
enabledCheckboxId: 'legal_aviso_de_privacidad-enabled',
quillSelector: '#legal_aviso_de_privacidad-content',
quillPlaceholder: 'Ingrese los aviso de privacidad'
},
'legal_politica_de_devoluciones-nav': {
enabledCheckboxId: 'legal_politica_de_devoluciones-enabled',
quillSelector: '#legal_politica_de_devoluciones-content',
quillPlaceholder: 'Ingrese los política de devoluciones y reembolsos'
},
'legal_politica_de_envios-nav': {
enabledCheckboxId: 'legal_politica_de_envios-enabled',
quillSelector: '#legal_politica_de_envios-content',
quillPlaceholder: 'Ingrese los política de envíos'
},
'legal_politica_de_cookies-nav': {
enabledCheckboxId: 'legal_politica_de_cookies-enabled',
quillSelector: '#legal_politica_de_cookies-content',
quillPlaceholder: 'Ingrese los política de cookies'
},
'legal_autorizaciones_y_licencias-nav': {
enabledCheckboxId: 'legal_autorizaciones_y_licencias-enabled',
quillSelector: '#legal_autorizaciones_y_licencias-content',
quillPlaceholder: 'Ingrese los autorizaciones y licencias'
},
'legal_informacion_comercial-nav': {
enabledCheckboxId: 'legal_informacion_comercial-enabled',
quillSelector: '#legal_informacion_comercial-content',
quillPlaceholder: 'Ingrese los información comercial'
},
'legal_consentimiento_para_el_login_de_terceros-nav': {
enabledCheckboxId: 'legal_consentimiento_para_el_login_de_terceros-enabled',
quillSelector: '#legal_consentimiento_para_el_login_de_terceros-content',
quillPlaceholder: 'Ingrese los consentimiento para el login de terceros'
},
'legal_leyendas_de_responsabilidad-nav': {
enabledCheckboxId: 'legal_leyendas_de_responsabilidad-enabled',
quillSelector: '#legal_leyendas_de_responsabilidad-content',
quillPlaceholder: 'Ingrese los leyendas de responsabilidad'
}
},
saveButtonId: 'save-button',
cancelButtonId: 'cancel-button',
notificationAreaSelector: '.notification-container'
};
this.config = { ...defaultConfig, ...config };
this.content = null;
this.saveButton = null;
this.cancelButton = null;
this.notificationArea = null;
this.currentFormKey = null;
this.quillInstances = {}; // Almacenar instancias de Quill
this.editState = {};
this.init();
}
init() {
this.content = document.getElementById(this.config.contentId);
this.saveButton = document.getElementById(this.config.saveButtonId);
this.cancelButton = document.getElementById(this.config.cancelButtonId);
this.notificationArea = this.content.querySelector(this.config.notificationAreaSelector);
// Puntero para rastrear si un formulario ha sido editado
this.editState = Object.keys(this.config.forms).reduce((state, key) => {
state[key] = false; // Inicializar todos los formularios como no editados
return state;
}, {});
this.switchToForm(Object.keys(this.config.forms)[0]); // Cargar el primer formulario
this.saveButton.addEventListener('click', () => this.handleSave());
this.cancelButton.addEventListener('click', () => this.handleCancel());
}
reload() {
const currentFormKey = this.currentFormKey;
if (currentFormKey) {
const quillInstance = this.quillInstances[currentFormKey];
const { quillSelector, enabledCheckboxId } = this.config.forms[currentFormKey];
const quillContainer = document.querySelector(quillSelector);
const checkbox = document.getElementById(enabledCheckboxId);
const textarea = document.getElementById(`${currentFormKey.replace('-nav', '')}-textarea`);
quillInstance.root.innerHTML = textarea.value;
// Agregar eventos
checkbox.addEventListener('change', () =>
this.handleCheckboxChange(checkbox, quillContainer, currentFormKey)
);
const isEnabled = checkbox.checked;
quillInstance.enable(isEnabled); // Sincronizar habilitación con el checkbox
}
}
switchToForm(formKey) {
if (!this.config.forms[formKey]) return;
this.currentFormKey = formKey;
const { quillSelector, quillPlaceholder, enabledCheckboxId } = this.config.forms[formKey];
const quillContainer = document.querySelector(quillSelector);
const checkbox = document.getElementById(enabledCheckboxId);
// Si la instancia de Quill no existe, inicialízala
if (!this.quillInstances[formKey]) {
this.quillInstances[formKey] = new Quill(quillSelector, {
placeholder: quillPlaceholder,
modules: { toolbar: this.getToolbar() },
theme: 'snow'
});
// Escuchar cambios en el editor
quillContainer.__quill = this.quillInstances[formKey];
this.quillInstances[formKey].on(
'text-change',
this.debounce(() => this.handleContentChange(formKey), 300)
);
setTimeout(() => {
const isEnabled = checkbox.checked;
quillContainer.__quill.enable(isEnabled); // Sincronizar habilitación con el checkbox
});
}
this.toggleButtonsState(this.editState[this.currentFormKey]);
// Asignar evento al checkbox (asegura no duplicar eventos)
if (!checkbox.dataset.bound) {
checkbox.addEventListener('change', () => this.handleCheckboxChange(checkbox, quillContainer, formKey));
checkbox.dataset.bound = true; // Marcar como manejado
}
}
handleContentChange(formKey) {
// Marcar el formulario como editado
this.editState[formKey] = true;
// Habilitar botones
this.toggleButtonsState(true);
}
handleCheckboxChange(checkbox, quillContainer, formKey) {
const isEnabled = checkbox.checked;
if (quillContainer.__quill) {
quillContainer.__quill.enable(isEnabled); // Habilitar o deshabilitar el editor
if (isEnabled) {
quillContainer.__quill.focus(); // Hacer focus si está habilitado
}
}
// Marcar el formulario como editado
this.editState[formKey] = true;
this.toggleButtonsState(true);
}
handleSave() {
const quillInstance = this.quillInstances[this.currentFormKey];
const textarea = document.getElementById(`${this.currentFormKey.replace('-nav', '-textarea')}`);
// Deshabilitar el estado de edición
this.editState[this.currentFormKey] = false;
//this.disableFormFields(this.content);
this.toggleButtonsState(false);
this.setButtonLoadingState(true);
// Actualizar el contenido del textarea para sincronizar con Livewire
textarea.value = quillInstance.root.innerHTML;
// Simular el evento 'input' para actualizar el contenido en el textarea
textarea.dispatchEvent(new Event('input', { bubbles: true }));
// Emitir el evento de guardar en Livewire
Livewire.dispatch('saveLegal');
}
handleCancel() {
// Restablecer el estado de edición del formulario actual
this.editState[this.currentFormKey] = false;
//this.disableFormFields();
this.toggleButtonsState(false);
}
disableFormFields(content) {
content.querySelectorAll('input, select, textarea').forEach(field => {
field.disabled = true;
});
if (this.fullEditor) {
this.fullEditor.enable(false); // Deshabilitar el editor
}
}
toggleButtonsState(state) {
this.saveButton.disabled = !state;
this.cancelButton.disabled = !state;
}
setButtonLoadingState(isLoading) {
const loadingText = this.saveButton.getAttribute('data-loading-text');
if (loadingText && isLoading) {
this.saveButton.innerHTML = loadingText;
} else {
this.saveButton.innerHTML = this.saveButton.getAttribute('data-original-text') || this.saveButton.innerHTML;
}
}
debounce(func, wait) {
let timeout;
return function (...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
getToolbar() {
return [
[{ font: [] }, { size: [] }],
['bold', 'italic', 'underline', 'strike'],
[{ color: [] }, { background: [] }],
[{ script: 'super' }, { script: 'sub' }],
[{ header: '1' }, { header: '2' }],
[{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
['link', 'clean']
];
}
}