]> git.immae.eu Git - github/bastienwirtz/homer.git/blob - src/components/DarkMode.vue
yarn lint
[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
8 :class="`${faClasses[mode]}`"
9 class="fa-fw"
10 :title="`${titles[mode]}`"
11 ></i>
12 </a>
13 </template>
14
15 <script>
16 export default {
17 name: "Darkmode",
18 data: function () {
19 return {
20 isDark: null,
21 faClasses: null,
22 titles: null,
23 mode: null,
24 };
25 },
26 created: function () {
27 this.faClasses = ["fas fa-adjust", "fas fa-circle", "far fa-circle"];
28 this.titles = ["Auto-switch", "Light theme", "Dark theme"];
29 this.mode = 0;
30 if ("overrideDark" in localStorage) {
31 // Light theme is 1 and Dark theme is 2
32 this.mode = JSON.parse(localStorage.overrideDark) ? 2 : 1;
33 }
34 this.isDark = this.getIsDark();
35 this.$emit("updated", this.isDark);
36 },
37 methods: {
38 toggleTheme: function () {
39 this.mode = (this.mode + 1) % 3;
40 switch (this.mode) {
41 // Default behavior
42 case 0:
43 localStorage.removeItem("overrideDark");
44 break;
45 // Force light theme
46 case 1:
47 localStorage.overrideDark = false;
48 break;
49 // Force dark theme
50 case 2:
51 localStorage.overrideDark = true;
52 break;
53 default:
54 // Should be unreachable
55 break;
56 }
57
58 this.isDark = this.getIsDark();
59 this.$emit("updated", this.isDark);
60 },
61
62 getIsDark: function () {
63 const values = [
64 matchMedia("(prefers-color-scheme: dark)").matches,
65 false,
66 true,
67 ];
68 return values[this.mode];
69 },
70 },
71 };
72 </script>