class CodeComponent extends HTMLElement {
constructor() {
super();
this.code = '';
this.description = '';
}
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.render();
// Listen for code updates
document.addEventListener('show-code', (e) => {
this.code = e.detail.code;
this.description = e.detail.description;
this.render();
});
}
render() {
this.shadowRoot.innerHTML = `
${this.code ? `
${escapeHtml(this.code)}
` : `
Aucun code généré
Demandez à Rosalinda de générer du code pour voir le résultat ici.
`}
`;
// Initialize feather icons
const featherScript = document.createElement('script');
featherScript.src = 'https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js';
this.shadowRoot.appendChild(featherScript);
featherScript.onload = () => {
feather.replace();
};
// Add event listeners
if (this.code) {
// Copy code button
this.shadowRoot.querySelector('.copy-code').addEventListener('click', () => {
const code = this.shadowRoot.querySelector('.copy-code').getAttribute('data-code');
navigator.clipboard.writeText(code).then(() => {
const button = this.shadowRoot.querySelector('.copy-code');
const originalText = button.innerHTML;
button.innerHTML = ' Copié !';
feather.replace();
setTimeout(() => {
button.innerHTML = originalText;
feather.replace();
}, 2000);
});
});
// Download code button
this.shadowRoot.querySelector('.download-code').addEventListener('click', () => {
const code = this.shadowRoot.querySelector('.download-code').getAttribute('data-code');
const element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(code));
element.setAttribute('download', 'code.html');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
});
// Save to project button
this.shadowRoot.getElementById('save-project').addEventListener('click', () => {
document.dispatchEvent(new CustomEvent('save-project', {
detail: {
code: this.code,
description: this.description
}
}));
alert('Projet sauvegardé avec succès !');
});
// New chat button
this.shadowRoot.getElementById('new-chat').addEventListener('click', () => {
document.dispatchEvent(new CustomEvent('navigate', { detail: 'chat' }));
});
} else {
// Go to chat button
this.shadowRoot.getElementById('go-to-chat').addEventListener('click', () => {
document.dispatchEvent(new CustomEvent('navigate', { detail: 'chat' }));
});
}
}
}
// Helper function to escape HTML
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
customElements.define('code-component', CodeComponent);