auto dark mode

This commit is contained in:
qishibo 2024-12-24 15:09:49 +08:00
parent ba8f8473f2
commit fa3d69edbd
2 changed files with 41 additions and 31 deletions

View File

@ -19,27 +19,12 @@
}
function globalChangeTheme(theme) {
if (!theme) {
theme = localStorage.theme;
!['system', 'light', 'dark'].includes(theme) && (theme = 'system');
}
// ipcRenderer.invoke('changeTheme', theme).then(shouldUseDarkColors => {
// changeCSS(shouldUseDarkColors ? 'dark' : 'light')
// });
// return;
// system
if (theme == 'system') {
ipcRenderer.invoke('changeTheme', theme).then(shouldUseDarkColors => {
changeCSS(shouldUseDarkColors ? 'dark' : 'light')
});
}
// light/dark change directly to reduce delay
else {
changeCSS(theme);
ipcRenderer.invoke('changeTheme', theme);
}
ipcRenderer.invoke('changeTheme', theme).then(shouldUseDarkColors => {
// delay to avoid stuck
setTimeout(() => {
changeCSS(shouldUseDarkColors ? 'dark' : 'light');
}, 100);
});
}
// triggered by OS theme changed
@ -49,11 +34,30 @@
return;
}
changeCSS(arg.shouldUseDarkColors ? 'dark' : 'light');
})
setTimeout(() => {
changeCSS(arg.shouldUseDarkColors ? 'dark' : 'light');
}, 100);
});
// theme init at startup
globalChangeTheme();
(() => {
let theme = localStorage.theme;
if (!['system', 'light', 'dark'].includes(theme)) {
theme = 'system';
}
// follow system OS
if (theme == 'system') {
const dark = (new URL(window.location.href)).searchParams.get('dark');
changeCSS(dark === 'true' ? 'dark' : 'light');
}
// setted light or dark
else {
changeCSS(theme);
ipcRenderer.invoke('changeTheme', theme);
}
})();
</script>
<div id="app"></div>

View File

@ -70,12 +70,15 @@ function createWindow() {
// mainWindow.loadFile('index.html');
mainWindow.loadURL(url.format({
protocol: 'file',
slashes: true,
pathname: path.join(__dirname, 'index.html'),
query: { version: app.getVersion() },
query: {version: app.getVersion(), dark: nativeTheme.shouldUseDarkColors},
}));
} else {
mainWindow.loadURL(`http://localhost:9988/?version=${app.getVersion()}`);
mainWindow.loadURL(url.format({
protocol: 'http',
host: 'localhost:9988',
query: {version: app.getVersion(), dark: nativeTheme.shouldUseDarkColors},
}));
}
// Open the DevTools.
@ -149,10 +152,13 @@ ipcMain.handle('changeTheme', (event, theme) => {
// OS theme changed
nativeTheme.on('updated', () => {
mainWindow.webContents.send('os-theme-updated', {
shouldUseDarkColors: nativeTheme.shouldUseDarkColors,
themeSource: nativeTheme.themeSource
});
// delay send to prevent webcontent stuck
setTimeout(() => {
mainWindow.webContents.send('os-theme-updated', {
shouldUseDarkColors: nativeTheme.shouldUseDarkColors,
themeSource: nativeTheme.themeSource
});
}, 50);
});
ipcMain.handle('getTempPath', (event, arg) => app.getPath('temp'));