Skip to content

Commit e47d5c5

Browse files
committed
chore: make the css vars be a root instead of html style itself
1 parent 61b5bf4 commit e47d5c5

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

ts/themes/globals.tsx

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -179,14 +179,35 @@ export function getThemeValue(key: ThemeKeys) {
179179
return getComputedStyle(document.documentElement).getPropertyValue(key);
180180
}
181181

182+
let themeStyleEl: HTMLStyleElement | null = null;
183+
const themeVariables = new Map<string, string>();
184+
185+
function getOrCreateThemeStyleEl(): HTMLStyleElement {
186+
if (!themeStyleEl) {
187+
themeStyleEl = document.createElement('style');
188+
themeStyleEl.id = 'session-theme-variables';
189+
document.head.appendChild(themeStyleEl);
190+
}
191+
return themeStyleEl;
192+
}
193+
194+
function rebuildThemeStyleEl() {
195+
const el = getOrCreateThemeStyleEl();
196+
const declarations = [...themeVariables.entries()].map(([k, v]) => ` ${k}: ${v};`).join('\n');
197+
el.textContent = `:root {\n${declarations}\n}`;
198+
}
199+
182200
export function setThemeValues(variables: Theme) {
183201
// eslint-disable-next-line no-restricted-syntax
184202
for (const [key, value] of Object.entries(variables)) {
185-
document.documentElement.style.setProperty(
186-
key,
187-
typeof value === 'string' ? value : value.toString()
188-
);
203+
themeVariables.set(key, typeof value === 'string' ? value : value.toString());
189204
}
205+
rebuildThemeStyleEl();
206+
}
207+
208+
export function setSingleThemeValue(key: ThemeKeys, value: string) {
209+
themeVariables.set(key, value);
210+
rebuildThemeStyleEl();
190211
}
191212

192213
// These are only set once in the global style (at root).

ts/themes/switchPrimaryColor.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Dispatch } from '@reduxjs/toolkit';
22
import { find } from 'lodash';
33
import { applyPrimaryColor } from '../state/ducks/primaryColor';
44
import { COLORS, ColorsType, getPrimaryColors, PrimaryColorStateType } from './constants/colors';
5+
import { setSingleThemeValue } from './globals';
56

67
export function findPrimaryColorId(hexCode: string): PrimaryColorStateType | undefined {
78
const primaryColors = getPrimaryColors();
@@ -13,7 +14,7 @@ export async function switchPrimaryColorTo(color: PrimaryColorStateType, dispatc
1314
await window.Events.setPrimaryColorSetting(color);
1415
}
1516

16-
document.documentElement.style.setProperty(
17+
setSingleThemeValue(
1718
'--primary-color',
1819
COLORS.PRIMARY[`${color.toUpperCase() as keyof ColorsType['PRIMARY']}`]
1920
);

0 commit comments

Comments
 (0)