Skip to content

Commit

Permalink
Fix dark mode flickering (thomiceli#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
thomiceli committed Jun 1, 2023
1 parent da970d7 commit 8880e00
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 19 deletions.
23 changes: 4 additions & 19 deletions public/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,10 @@ import moment from 'moment';
import md from 'markdown-it';
import hljs from 'highlight.js';

document.addEventListener('DOMContentLoaded', () => {

document.addEventListener('DOMContentLoaded', () => {
const themeMenu = document.getElementById('theme-menu')!;

const checkTheme = () => {
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
}

checkTheme()

window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change',({ matches }) => {
checkTheme()
}
)

document.getElementById('light-mode')!.onclick = (e) => {
e.stopPropagation()
localStorage.theme = 'light';
Expand Down Expand Up @@ -81,9 +65,10 @@ document.addEventListener('DOMContentLoaded', () => {
if (lang && hljs.getLanguage(lang)) {
try {
return '<pre class="hljs"><code>' +
hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
hljs.highlight(str, {language: lang, ignoreIllegals: true}).value +
'</code></pre>';
} catch (__) {}
} catch (__) {
}
}

return '<pre class="hljs"><code>' + md().utils.escapeHtml(str) + '</code></pre>';
Expand Down
18 changes: 18 additions & 0 deletions templates/base/base_header.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,24 @@
<html lang="en" class="h-full">
<head>
<meta charset="UTF-8" />
<script>
const checkTheme = () => {
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
}

checkTheme()

window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', ({matches}) => {
checkTheme()
}
)

</script>
<link rel="icon" type="image/svg+xml" href="{{ asset "favicon.svg" }}" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="{{ asset "main.css" }}" />
Expand Down

0 comments on commit 8880e00

Please sign in to comment.