]> git.immae.eu Git - github/bastienwirtz/homer.git/blame - src/components/DarkMode.vue
cycle between automatic-light-dark themes
[github/bastienwirtz/homer.git] / src / components / DarkMode.vue
CommitLineData
b9c5fcf0
BW
1<template>
2 <a
3 v-on:click="toggleTheme()"
4 aria-label="Toggle dark mode"
5 class="navbar-item is-inline-block-mobile"
6 >
4a1e8717 7 <i :class="`${faClasses[mode]}`" class="fa-fw"></i>
b9c5fcf0
BW
8 </a>
9</template>
10
11<script>
12export default {
13 name: "Darkmode",
14 data: function () {
15 return {
16 isDark: null,
4a1e8717
GC
17 faClasses: null,
18 mode: null,
b9c5fcf0
BW
19 };
20 },
21 created: function () {
4a1e8717
GC
22 this.faClasses = ["fas fa-adjust", "fas fa-circle", "far fa-circle"];
23 this.mode = 0;
24 if ("overrideDark" in localStorage) {
25 // Light theme is 1 and Dark theme is 2
26 this.mode = JSON.parse(localStorage.overrideDark) ? 2 : 1;
27 }
28 this.isDark = this.getIsDark();
b9c5fcf0
BW
29 this.$emit("updated", this.isDark);
30 },
31 methods: {
32 toggleTheme: function () {
4a1e8717
GC
33 this.mode = (this.mode + 1) % 3
34 switch(this.mode) {
35 // Default behavior
36 case 0:
37 localStorage.removeItem("overrideDark");
38 break
39 // Force light theme
40 case 1:
41 localStorage.overrideDark = false;
42 break
43 // Force dark theme
44 case 2:
45 localStorage.overrideDark = true;
46 break
47 default:
48 // Should be unreachable
49 break
50 }
51
52 this.isDark = this.getIsDark();
b9c5fcf0
BW
53 this.$emit("updated", this.isDark);
54 },
4a1e8717
GC
55
56 getIsDark: function() {
57 const values = [matchMedia("(prefers-color-scheme: dark)").matches, false, true];
58 return values[this.mode];
59 }
b9c5fcf0
BW
60 },
61};
62</script>