From df40b413d6a112f442736d38d0e21d420546aabf Mon Sep 17 00:00:00 2001 From: Kyrylo Shmidt Date: Mon, 20 Feb 2023 15:48:04 +0200 Subject: [PATCH] Add action to dynamically change theme --- src/api/index.ts | 4 +-- src/components/App/index.tsx | 47 ++++++++++++++++++++----- src/components/RecentActivity/index.tsx | 5 ++- 3 files changed, 44 insertions(+), 12 deletions(-) diff --git a/src/api/index.ts b/src/api/index.ts index 588c0321d..ebcd0788c 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -28,10 +28,10 @@ export const sendMessage = (message: { if (window.cefQuery) { return window.cefQuery({ request: JSON.stringify(message), - onSuccess: (response) => { + onSuccess: function (response) { console.info("cefQuery has been successfully sent: %s", response); }, - onFailure: (error_code, error_message) => { + onFailure: function (error_code, error_message) { console.error( "Failed to send cefQuery: %d, %s", error_code, diff --git a/src/components/App/index.tsx b/src/components/App/index.tsx index 6099e6c38..2a51f7466 100644 --- a/src/components/App/index.tsx +++ b/src/components/App/index.tsx @@ -1,10 +1,17 @@ +import { useEffect, useState } from "react"; import { ThemeProvider } from "styled-components"; +import { dispatcher } from "../../dispatcher"; import { Mode } from "../../globals"; +import { isObject } from "../../typeGuards/isObject"; import { RecentActivity } from "../RecentActivity"; import { GlobalStyle } from "./styles"; +const isMode = (mode: unknown): mode is Mode => { + return typeof mode === "string" && ["light", "dark"].includes(mode); +}; + const getMode = (): Mode => { - if (!window.theme) { + if (!isMode(window.theme)) { const bodyEl = document.getElementsByTagName("body"); const vscodeTheme = bodyEl[0].dataset.vscodeThemeKind === "vscode-light" ? "light" : "dark"; @@ -14,11 +21,33 @@ const getMode = (): Mode => { return window.theme; }; -export const App = () => ( - <> - - - - - -); +const actions = { + setColorMode: "GLOBAL/SET_THEME" +}; + +export const App = () => { + const [mode, setMode] = useState(getMode()); + + useEffect(() => { + const handleSetColorMode = (data: unknown) => { + if (isObject(data) && isMode(data.theme)) { + setMode(data.theme); + } + }; + + dispatcher.addActionListener(actions.setColorMode, handleSetColorMode); + + return () => { + dispatcher.removeActionListener(actions.setColorMode, handleSetColorMode); + }; + }, []); + + return ( + <> + + + + + + ); +}; diff --git a/src/components/RecentActivity/index.tsx b/src/components/RecentActivity/index.tsx index 990db1c06..a743d1ce1 100644 --- a/src/components/RecentActivity/index.tsx +++ b/src/components/RecentActivity/index.tsx @@ -81,7 +81,10 @@ export const RecentActivity = () => { return () => { clearInterval(refreshInterval); - dispatcher.addActionListener(actions.setData, handleRecentActivityData); + dispatcher.removeActionListener( + actions.setData, + handleRecentActivityData + ); }; }, []);