mcServerWebsite/assets/controllers/theme_toggle_controller.js
2026-03-25 19:49:56 +01:00

44 lines
1.1 KiB
JavaScript

import { Controller } from '@hotwired/stimulus';
/**
* Contrôleur Stimulus pour le toggle du thème
* Compatible avec Turbo et les rechargements traditionnel
*/
export default class extends Controller {
static targets = ['button'];
connect() {
this.applyBackground();
this.setupListener();
}
setupListener() {
this.buttonTarget.addEventListener('click', (e) => {
e.preventDefault();
this.toggle();
});
}
toggle() {
const current = document.documentElement.getAttribute('data-theme');
const next = current === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', next);
localStorage.setItem('mc-theme', next);
this.applyBackground();
}
applyBackground() {
const body = document.getElementById('page-body');
if (!body) return;
const theme = document.documentElement.getAttribute('data-theme');
const bg = theme === 'dark' ? body.dataset.bgDark : body.dataset.bgLight;
if (bg) {
body.style.backgroundImage = `url('${bg}')`;
}
}
}