Skip to content
Open
Changes from 1 commit
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
22 changes: 13 additions & 9 deletions site/lib/src/layouts/dash_layout.dart
Original file line number Diff line number Diff line change
Expand Up @@ -171,16 +171,20 @@ ga('send', 'pageview');
// avoid a flash of the initial theme on load.
raw('''
<script>
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)');
try {
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)');

const storedTheme = window.localStorage.getItem('theme') ?? 'light-mode';
if (storedTheme === 'auto-mode') {
document.body.classList.add(
'auto-mode',
prefersDarkMode.matches ? 'dark-mode' : 'light-mode',
);
} else {
document.body.classList.add(storedTheme);
const storedTheme = window.localStorage.getItem('theme') ?? 'light-mode';
if (storedTheme === 'auto-mode') {
document.body.classList.add(
'auto-mode',
prefersDarkMode.matches ? 'dark-mode' : 'light-mode',
);
} else {
document.body.classList.add(storedTheme);
}
Comment on lines +175 to +185
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

For a minor performance improvement and to scope variables more tightly, you can move the prefersDarkMode declaration inside the if (storedTheme === 'auto-mode') block, since it's only used there. This avoids an unnecessary call to window.matchMedia when the theme is not set to 'auto-mode'.

Suggested change
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)');
const storedTheme = window.localStorage.getItem('theme') ?? 'light-mode';
if (storedTheme === 'auto-mode') {
document.body.classList.add(
'auto-mode',
prefersDarkMode.matches ? 'dark-mode' : 'light-mode',
);
} else {
document.body.classList.add(storedTheme);
const storedTheme = window.localStorage.getItem('theme') ?? 'light-mode';
if (storedTheme === 'auto-mode') {
document.body.classList.add(
'auto-mode',
prefersDarkMode.matches ? 'dark-mode' : 'light-mode',
);
} else {
document.body.classList.add(storedTheme);
}
const storedTheme = window.localStorage.getItem('theme') ?? 'light-mode';
if (storedTheme === 'auto-mode') {
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)');
document.body.classList.add(
'auto-mode',
prefersDarkMode.matches ? 'dark-mode' : 'light-mode',
);
} else {
document.body.classList.add(storedTheme);
}

} catch (e) {
// localStorage is not available, do nothing and fallback to default.
}
</script>
'''),
Expand Down