Move theme/mode related preload code into it's own module

This commit is contained in:
Jonatan Heyman 2023-01-16 15:31:46 +01:00
parent 818d7f0260
commit d4078d50d4
2 changed files with 30 additions and 25 deletions

View File

@ -1,30 +1,8 @@
const { contextBridge, ipcRenderer } = require('electron')
const { contextBridge } = require('electron')
import darkMode from "./theme-mode"
const getComputedTheme = () => window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" : "light"
const mediaMatch = window.matchMedia('(prefers-color-scheme: dark)')
let darkModeChangeListener = null
contextBridge.exposeInMainWorld('darkMode', {
set: (mode) => ipcRenderer.invoke('dark-mode:set', mode),
get: async () => {
const mode = await ipcRenderer.invoke('dark-mode:get')
return {
theme: mode,
computed: getComputedTheme(),
}
},
onChange: (callback) => {
darkModeChangeListener = (event) => {
callback(event.matches ? "dark" : "light")
}
mediaMatch.addEventListener('change', darkModeChangeListener)
return mediaMatch
},
removeListener() {
mediaMatch.removeEventListener('change', darkModeChangeListener)
},
initial: getComputedTheme(),
})
contextBridge.exposeInMainWorld('darkMode', darkMode)
function domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {

View File

@ -0,0 +1,27 @@
const { ipcRenderer } = require('electron')
const getComputedTheme = () => window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" : "light"
const mediaMatch = window.matchMedia('(prefers-color-scheme: dark)')
let darkModeChangeListener = null
export default {
set: (mode) => ipcRenderer.invoke('dark-mode:set', mode),
get: async () => {
const mode = await ipcRenderer.invoke('dark-mode:get')
return {
theme: mode,
computed: getComputedTheme(),
}
},
onChange: (callback) => {
darkModeChangeListener = (event) => {
callback(event.matches ? "dark" : "light")
}
mediaMatch.addEventListener('change', darkModeChangeListener)
return mediaMatch
},
removeListener() {
mediaMatch.removeEventListener('change', darkModeChangeListener)
},
initial: getComputedTheme(),
}