Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added theme switcher with match-system option #1273

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 1 addition & 10 deletions frontend/html/layout.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,6 @@
{% block meta %}
{% include "common/meta.html" %}
{% endblock %}
<script>
const theme = localStorage.getItem('theme');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В некоторых местах далее проверяется typeof localStorage !== 'undefined' перед юзанием LS. Предлагаю что тут, что далее юзать nullsafe, т.е. вместо проверок и дерева из if, просто юзать

const theme = localStorage?.getItem('theme') ?? 'auto'

if (theme !== null) {
document.documentElement.setAttribute('theme', theme);
}
</script>

{% block feeds %}
<link rel="alternate" type="application/rss+xml"
Expand Down Expand Up @@ -62,10 +56,7 @@
CC BY-SA
</div>
<div class="footer-right">
<label class="theme-switcher" for="checkbox">
<input type="checkbox" id="checkbox" />
<span class="slider round"></span>
</label>
<theme-switcher></theme-switcher>

{% if me %}
<form method="POST" action="{% url "logout" %}">
Expand Down
90 changes: 90 additions & 0 deletions frontend/html/misc/theme_switcher.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<starlight-theme-select>
<label style='width: 6.25em'>
<span class="sr-only">Выберите тему</span>
<select value="auto" width="6.25em">
<option value="dark">Темная тема</option>
<option value="light">Светлая тема</option>
<option value="auto">Системная тема</option>
</select>
</label>
</starlight-theme-select>


<script>
const storageKey = 'theme';

const parseTheme = (theme) =>
theme === 'auto' || theme === 'dark' || theme === 'light' ? theme : 'auto';

const loadTheme = () =>
parseTheme(typeof localStorage !== 'undefined' && localStorage.getItem(storageKey));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Выше уже писал, предлагаю юзать nullsafe

parseTheme(localStorage?.getItem(storageKey));


function storeTheme(theme) {
if (typeof localStorage !== 'undefined') {
localStorage.setItem(storageKey, theme === 'light' || theme === 'dark' ? theme : '');
}
}
Comment on lines +22 to +26
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зачем это в глобальной видимости?


const getPreferredColorScheme = () =>
matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';

matchMedia(`(prefers-color-scheme: light)`).addEventListener('change', () => {
if (loadTheme() === 'auto') onThemeChange('auto');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

onThemeChange метод находится в классе StarlightThemeSelect, это просто не работает и вызывает ошибку.

});

class StarlightThemeProvider {
storedTheme = loadTheme();

constructor() {
const theme = this.storedTheme ||
(window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
document.documentElement.dataset.theme = theme === 'light' ? 'light' : 'dark';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dataset оперирует data- аттрибутами, в данном случае как я понял предполагается поменять theme аттрибут, а не data-theme.

}

updatePickers(theme = this.storedTheme || 'auto') {
document.querySelectorAll('starlight-theme-select').forEach((picker) => {
console.log('picker', picker);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Надо бы кильнуть, пакер не убирает логи из продакшен-бандла

const select = picker.querySelector('select');
if (select) select.value = theme;

/** @type {HTMLTemplateElement | null} */
const tmpl = document.querySelector(`#theme-icons`);
const newIcon = tmpl && tmpl.content.querySelector('.' + theme);
if (newIcon) {
const oldIcon = picker.querySelector('starlight-theme-select i.label-icon');
if (oldIcon) {
oldIcon.replaceChildren(...newIcon.cloneNode(true).childNodes);
}
}
Comment on lines +51 to +58
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

});
}
}


class StarlightThemeSelect extends HTMLElement {
themeProvider = new StarlightThemeProvider();

constructor() {
super();
this.onThemeChange(loadTheme());
this.querySelector('select')?.addEventListener('change', (e) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем тут nullsafe?

if (e.currentTarget instanceof HTMLSelectElement) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

событие change, прослушиваемое на select теге всегда же будет возвращать этот самый селект как target, зачем проверять?

this.onThemeChange(parseTheme(e.currentTarget.value));
}
});

this.themeProvider.updatePickers(loadTheme());

matchMedia(`(prefers-color-scheme: light)`).addEventListener('change', () => {
if (loadTheme() === 'auto') this.onThemeChange('auto');
});
}

onThemeChange(theme) {
this.themeProvider.updatePickers(theme);
document.documentElement.setAttribute("theme", theme === 'auto' ? getPreferredColorScheme() : theme);
storeTheme(theme);
}
}
customElements.define('starlight-theme-select', StarlightThemeSelect);
</script>
35 changes: 6 additions & 29 deletions frontend/static/js/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
createFileInput,
createMarkdownEditor,
handleFormSubmissionShortcuts,
imageUploadOptions
imageUploadOptions,
} from "./common/markdown-editor";
import { getCollapsedCommentThreadsSet } from "./common/comments";

Expand Down Expand Up @@ -38,40 +38,17 @@ const App = {
initializeEmojiForPoorPeople() {
const isApple = /iPad|iPhone|iPod|OS X/.test(navigator.userAgent) && !window.MSStream;
if (!isApple) {
document.body = twemoji.parse(
document.body,
{ base: "https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/" }
);
document.body = twemoji.parse(document.body, {
base: "https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/",
});
}
},
initializeThemeSwitcher() {
const themeSwitch = document.querySelector('.theme-switcher input[type="checkbox"]');
const mediaQueryList = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)");

themeSwitch.addEventListener(
"change",
function (e) {
let theme = "light";
if (e.target.checked) {
theme = "dark";
}
document.documentElement.setAttribute("theme", theme);
localStorage.setItem("theme", theme);
},
false
);

const theme = localStorage.getItem("theme");
themeSwitch.checked = theme ? theme === "dark" : mediaQueryList.matches;

const setFaviconHref = (e) => {
const svgFavicon = document.querySelector('link[type="image/svg+xml"]');
const isDark = e.matches;

if (!theme) {
themeSwitch.checked = isDark;
}

svgFavicon.href = isDark ? "/static/images/favicon/favicon-dark.svg" : "/static/images/favicon/favicon.svg";
};

Expand All @@ -91,7 +68,7 @@ const App = {

const fullMarkdownEditors = [...document.querySelectorAll(".markdown-editor-full")].reduce(
(editors, element) => {
const fileInputEl = createFileInput({ allowedTypes: imageUploadOptions.allowedTypes })
const fileInputEl = createFileInput({ allowedTypes: imageUploadOptions.allowedTypes });
const editor = createMarkdownEditor(element, {
autosave: {
enabled: false,
Expand Down Expand Up @@ -145,7 +122,7 @@ const App = {
{
name: "upload-file",
action: () => {
fileInputEl.click()
fileInputEl.click();
},
className: "fa fa-paperclip",
text: "Upload image",
Expand Down
84 changes: 84 additions & 0 deletions frontend/static/js/components/ThemeSwitcher.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<template>
<label style="width: 6.25em">
<span class="sr-only">Выберите тему</span>
<select value="auto" width="6.25em" @input="setTheme">
<option value="dark">Темная тема</option>
<option value="light">Светлая тема</option>
<option value="auto">Системная тема</option>
</select>
</label>
</template>

<script>
const storageKey = "theme";

const parseTheme = (theme) => (theme === "auto" || theme === "dark" || theme === "light" ? theme : "auto");

const loadTheme = () => parseTheme(typeof localStorage !== "undefined" && localStorage.getItem(storageKey));

function storeTheme(theme) {
if (typeof localStorage !== "undefined") {
localStorage.setItem(storageKey, theme === "light" || theme === "dark" ? theme : "");
}
}

const getPreferredColorScheme = () => (matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark");

matchMedia(`(prefers-color-scheme: light)`).addEventListener("change", () => {
if (loadTheme() === "auto") onThemeChange("auto");
});

// class ThemeProvider {
// storedTheme = loadTheme();

// constructor() {
// const theme =
// this.storedTheme || (window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark");
// document.documentElement.dataset.theme = theme === "light" ? "light" : "dark";
// }

// updatePickers(theme = this.storedTheme || "auto") {
// document.querySelectorAll("starlight-theme-select").forEach((picker) => {
// console.log("picker", picker);
// const select = picker.querySelector("select");
// if (select) select.value = theme;

// /** @type {HTMLTemplateElement | null} */
// const tmpl = document.querySelector(`#theme-icons`);
// const newIcon = tmpl && tmpl.content.querySelector("." + theme);
// if (newIcon) {
// const oldIcon = picker.querySelector("starlight-theme-select i.label-icon");
// if (oldIcon) {
// oldIcon.replaceChildren(...newIcon.cloneNode(true).childNodes);
// }
// }
// });
// }
// }

// const themeProvider = new ThemeProvider();

export default {
name: "PostUpvote",
props: {},
data() {
const theme = loadTheme();
onThemeChange(theme);
// themeProvider.updatePickers(theme);
},
methods: {
setTheme(option) {
if (!option) {
return;
}

const theme = parseTheme(option.value);

onThemeChange(theme);
// themeProvider.updatePickers(theme);
document.documentElement.setAttribute("theme", theme === "auto" ? getPreferredColorScheme() : theme);
storeTheme(theme);
},
},
};
</script>
3 changes: 2 additions & 1 deletion frontend/static/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Vue.component("v-select", vSelect);
Vue.component("tag-select", () => import("./components/TagSelect.vue"));
Vue.component("simple-select", () => import("./components/SimpleSelect.vue"));
Vue.component("reply-form", () => import("./components/ReplyForm.vue"));
Vue.component("theme-switcher", () => import("./components/ThemeSwitcher.vue"));

// Since our pages have user-generated content, any fool can insert "{{" on the page and break it.
// We have no other choice but to completely turn off template matching and leave it on only for components.
Expand Down Expand Up @@ -77,7 +78,7 @@ new Vue({
}
},
showReplyForm(commentId, username, draftKey) {
this.replyTo = { commentId, username, draftKey }
this.replyTo = { commentId, username, draftKey };
},
},
});
Loading