]> git.immae.eu Git - github/bastienwirtz/homer.git/blob - src/components/DarkMode.vue
4318c228bbf0a940d27a104f09b83bcf04129d3c
[github/bastienwirtz/homer.git] / src / components / DarkMode.vue
1 <template>
2 <a
3 @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 props: {
19 defaultValue: String,
20 },
21 data: function () {
22 return {
23 isDark: null,
24 faClasses: null,
25 titles: null,
26 mode: null,
27 };
28 },
29 created: function () {
30 this.faClasses = ["fas fa-adjust", "fas fa-circle", "far fa-circle"];
31 this.titles = ["Auto-switch", "Light theme", "Dark theme"];
32 this.mode = 0;
33 if ("overrideDark" in localStorage) {
34 // Light theme is 1 and Dark theme is 2
35 this.mode = JSON.parse(localStorage.overrideDark) ? 2 : 1;
36 } else {
37 switch (this.defaultValue) {
38 case "light":
39 this.mode = 1;
40 break;
41 case "dark":
42 this.mode = 2;
43 break;
44 default:
45 this.mode = 0;
46 }
47 }
48 this.isDark = this.getIsDark();
49 this.$emit("updated", this.isDark);
50 },
51 methods: {
52 toggleTheme: function () {
53 this.mode = (this.mode + 1) % 3;
54 switch (this.mode) {
55 // Default behavior
56 case 0:
57 localStorage.removeItem("overrideDark");
58 break;
59 // Force light theme
60 case 1:
61 localStorage.overrideDark = false;
62 break;
63 // Force dark theme
64 case 2:
65 localStorage.overrideDark = true;
66 break;
67 default:
68 // Should be unreachable
69 break;
70 }
71
72 this.isDark = this.getIsDark();
73 this.$emit("updated", this.isDark);
74 },
75
76 getIsDark: function () {
77 const values = [
78 matchMedia("(prefers-color-scheme: dark)").matches,
79 false,
80 true,
81 ];
82 return values[this.mode];
83 },
84 },
85 };
86 </script>