]> git.immae.eu Git - github/bastienwirtz/homer.git/blob - src/components/DarkMode.vue
cycle between automatic-light-dark themes
[github/bastienwirtz/homer.git] / src / components / DarkMode.vue
1 <template>
2 <a
3 v-on:click="toggleTheme()"
4 aria-label="Toggle dark mode"
5 class="navbar-item is-inline-block-mobile"
6 >
7 <i :class="`${faClasses[mode]}`" class="fa-fw"></i>
8 </a>
9 </template>
10
11 <script>
12 export default {
13 name: "Darkmode",
14 data: function () {
15 return {
16 isDark: null,
17 faClasses: null,
18 mode: null,
19 };
20 },
21 created: function () {
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();
29 this.$emit("updated", this.isDark);
30 },
31 methods: {
32 toggleTheme: function () {
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();
53 this.$emit("updated", this.isDark);
54 },
55
56 getIsDark: function() {
57 const values = [matchMedia("(prefers-color-scheme: dark)").matches, false, true];
58 return values[this.mode];
59 }
60 },
61 };
62 </script>