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