From d4078d50d4f0ad453b79586ff03b03d0ee2f504c Mon Sep 17 00:00:00 2001 From: Jonatan Heyman Date: Mon, 16 Jan 2023 15:31:46 +0100 Subject: [PATCH] Move theme/mode related preload code into it's own module --- electron/preload/index.ts | 28 +++------------------------- electron/preload/theme-mode.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 25 deletions(-) create mode 100644 electron/preload/theme-mode.ts diff --git a/electron/preload/index.ts b/electron/preload/index.ts index 472e907..a046bb0 100644 --- a/electron/preload/index.ts +++ b/electron/preload/index.ts @@ -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']) { diff --git a/electron/preload/theme-mode.ts b/electron/preload/theme-mode.ts new file mode 100644 index 0000000..cbae8d1 --- /dev/null +++ b/electron/preload/theme-mode.ts @@ -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(), +}