]> git.immae.eu Git - github/bastienwirtz/homer.git/blob - src/components/DarkMode.vue
f0f823db198977917425fe7685e05e66201d5479
[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 this.watchIsDark();
51 },
52 methods: {
53 toggleTheme: function () {
54 this.mode = (this.mode + 1) % 3;
55 switch (this.mode) {
56 // Default behavior
57 case 0:
58 localStorage.removeItem("overrideDark");
59 break;
60 // Force light theme
61 case 1:
62 localStorage.overrideDark = false;
63 break;
64 // Force dark theme
65 case 2:
66 localStorage.overrideDark = true;
67 break;
68 default:
69 // Should be unreachable
70 break;
71 }
72
73 this.isDark = this.getIsDark();
74 this.$emit("updated", this.isDark);
75 },
76
77 getIsDark: function () {
78 const values = [
79 matchMedia("(prefers-color-scheme: dark)").matches,
80 false,
81 true,
82 ];
83 return values[this.mode];
84 },
85
86 watchIsDark: function () {
87 matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
88 this.isDark = this.getIsDark();
89 this.$emit("updated", this.isDark);
90 });
91 },
92 },
93 };
94 </script>