]> git.immae.eu Git - github/bastienwirtz/homer.git/blame - src/components/DarkMode.vue
Linting update
[github/bastienwirtz/homer.git] / src / components / DarkMode.vue
CommitLineData
b9c5fcf0
BW
1<template>
2 <a
a46bede2 3 @click="toggleTheme()"
b9c5fcf0
BW
4 aria-label="Toggle dark mode"
5 class="navbar-item is-inline-block-mobile"
6 >
edc336bb
GC
7 <i
8 :class="`${faClasses[mode]}`"
9 class="fa-fw"
10 :title="`${titles[mode]}`"
11 ></i>
b9c5fcf0
BW
12 </a>
13</template>
14
15<script>
16export default {
17 name: "Darkmode",
5db2414d
A
18 props: {
19 defaultValue: String,
20 },
b9c5fcf0
BW
21 data: function () {
22 return {
23 isDark: null,
4a1e8717 24 faClasses: null,
c0044cc7 25 titles: null,
4a1e8717 26 mode: null,
b9c5fcf0
BW
27 };
28 },
29 created: function () {
4a1e8717 30 this.faClasses = ["fas fa-adjust", "fas fa-circle", "far fa-circle"];
edc336bb 31 this.titles = ["Auto-switch", "Light theme", "Dark theme"];
4a1e8717
GC
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;
5db2414d
A
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 }
4a1e8717
GC
47 }
48 this.isDark = this.getIsDark();
b9c5fcf0 49 this.$emit("updated", this.isDark);
6cfa1643 50 this.watchIsDark();
b9c5fcf0
BW
51 },
52 methods: {
53 toggleTheme: function () {
edc336bb
GC
54 this.mode = (this.mode + 1) % 3;
55 switch (this.mode) {
4a1e8717
GC
56 // Default behavior
57 case 0:
58 localStorage.removeItem("overrideDark");
edc336bb 59 break;
4a1e8717
GC
60 // Force light theme
61 case 1:
62 localStorage.overrideDark = false;
edc336bb 63 break;
4a1e8717
GC
64 // Force dark theme
65 case 2:
66 localStorage.overrideDark = true;
edc336bb 67 break;
4a1e8717
GC
68 default:
69 // Should be unreachable
edc336bb 70 break;
4a1e8717
GC
71 }
72
73 this.isDark = this.getIsDark();
b9c5fcf0
BW
74 this.$emit("updated", this.isDark);
75 },
4a1e8717 76
edc336bb
GC
77 getIsDark: function () {
78 const values = [
79 matchMedia("(prefers-color-scheme: dark)").matches,
80 false,
81 true,
82 ];
4a1e8717 83 return values[this.mode];
edc336bb 84 },
6cfa1643
GC
85
86 watchIsDark: function () {
de4b7e61
BW
87 matchMedia("(prefers-color-scheme: dark)").addEventListener(
88 "change",
89 () => {
90 this.isDark = this.getIsDark();
91 this.$emit("updated", this.isDark);
92 },
93 );
6cfa1643 94 },
b9c5fcf0
BW
95 },
96};
97</script>