Implement darkmode using stimulus.

This commit is contained in:
Jan Böhmer 2022-07-30 00:33:22 +02:00
parent 671e0944a2
commit 8ccf5652ab
3 changed files with 44 additions and 21 deletions

View file

@ -0,0 +1,41 @@
import {Controller} from "@hotwired/stimulus";
import Darkmode from "darkmode-js/src";
import "darkmode-js"
export default class extends Controller {
_darkmode;
connect() {
if (typeof window.getComputedStyle(document.body).mixBlendMode == 'undefined') {
console.warn("The browser does not support mix blend mode. Darkmode will not work.");
return;
}
try {
const darkmode = new Darkmode();
this._darkmode = darkmode;
//Unhide darkmode button
this._showWidget();
//Set the switch according to our current darkmode state
const toggler = document.getElementById("toggleDarkmode");
toggler.checked = darkmode.isActivated();
}
catch (e)
{
console.error(e);
}
}
_showWidget() {
this.element.classList.remove('hidden');
}
toggleDarkmode() {
this._darkmode.toggle();
}
}

View file

@ -50,6 +50,7 @@ import "./tristate_checkboxes";
//Define jquery globally
window.$ = window.jQuery = require("jquery")
/**
require('bootstrap-select');
@ -95,25 +96,6 @@ require('../ts_src/ajax_ui');
require('../ts_src/event_listeners');
//Register darkmode (we must do it here, TS does not support ES6 constructor...
try {
//The browser needs to support mix blend mode
if(typeof window.getComputedStyle(document.body).mixBlendMode !== 'undefined') {
const darkmode = new Darkmode();
$(document).on("ajaxUI:start ajaxUI:reload", function () {
//Show darkmode toggle to user
$('#toggleDarkmodeContainer, #toggleDarkmodeSeparator').removeAttr('hidden');
$('#toggleDarkmode').prop('checked', darkmode.isActivated());
$('#toggleDarkmode').change(function () {
darkmode.toggle();
});
});
}
} catch (e) {
//Ignore all errors (for compatibiltiy with old browsers)
}
//Start AjaxUI AFTER all event has been registered
//$(document).ready(ajaxUI.start());

View file

@ -58,9 +58,9 @@
aria-hidden="true"></i> {% trans %}user.login{% endtrans %}</a>
{% endif %}
<li role="separator" class="dropdown-divider" id="toggleDarkmodeSeparator"></li>
<div class="px-4 px-3" id="toggleDarkmodeContainer">
<div class="px-4 px-3" id="toggleDarkmodeContainer hidden" {{ stimulus_controller('common/darkmode') }}>
<div class="form-check form-switch">
<input type="checkbox" class="form-check-input" id="toggleDarkmode">
<input type="checkbox" class="form-check-input" id="toggleDarkmode" {{ stimulus_action('common/darkmode', 'toggleDarkmode', 'change') }}>
<label class="form-check-label"
for="toggleDarkmode">{% trans %}ui.toggle_darkmode{% endtrans %}</label>
</div>