Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions ts/themes/globals.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -179,14 +179,35 @@ export function getThemeValue(key: ThemeKeys) {
return getComputedStyle(document.documentElement).getPropertyValue(key);
}

let themeStyleEl: HTMLStyleElement | null = null;
const themeVariables = new Map<string, string>();

function getOrCreateThemeStyleEl(): HTMLStyleElement {
if (!themeStyleEl) {
themeStyleEl = document.createElement('style');
themeStyleEl.id = 'session-theme-variables';
document.head.appendChild(themeStyleEl);
}
return themeStyleEl;
}

function rebuildThemeStyleEl() {
const el = getOrCreateThemeStyleEl();
const declarations = [...themeVariables.entries()].map(([k, v]) => ` ${k}: ${v};`).join('\n');
el.textContent = `:root {\n${declarations}\n}`;
}

export function setThemeValues(variables: Theme) {
// eslint-disable-next-line no-restricted-syntax
for (const [key, value] of Object.entries(variables)) {
document.documentElement.style.setProperty(
key,
typeof value === 'string' ? value : value.toString()
);
themeVariables.set(key, typeof value === 'string' ? value : value.toString());
}
rebuildThemeStyleEl();
}

export function setSingleThemeValue(key: ThemeKeys, value: string) {
themeVariables.set(key, value);
rebuildThemeStyleEl();
}

// These are only set once in the global style (at root).
Expand Down
3 changes: 2 additions & 1 deletion ts/themes/switchPrimaryColor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Dispatch } from '@reduxjs/toolkit';
import { find } from 'lodash';
import { applyPrimaryColor } from '../state/ducks/primaryColor';
import { COLORS, ColorsType, getPrimaryColors, PrimaryColorStateType } from './constants/colors';
import { setSingleThemeValue } from './globals';

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

document.documentElement.style.setProperty(
setSingleThemeValue(
'--primary-color',
COLORS.PRIMARY[`${color.toUpperCase() as keyof ColorsType['PRIMARY']}`]
);
Expand Down