import { themesType, themeType, UIThemeConfig } from './theme.types' // Must be relative as doing publish import __themes from './themes.json' // Must be relative as doing publish import { overrideElementTheme as _overrideElementTheme, globalVariables } from './themeMerge' const _default: themeType = __themes.redGreen const themes: themesType = __themes // Re-exported for back-compat with consumers that imported it directly. // The implementation lives in `themeMerge.ts` so the build-time codegen // can reuse it without dragging in browser-globals from the rest of this // module. export const overrideElementTheme = _overrideElementTheme export function appendGlobalCssVariables (cssData: { [key: string]: string }, appendTo: HTMLElement) { Object.entries(cssData).forEach(([ variableName, variableValue ]) => { appendTo.style.setProperty(`--${variableName}`, variableValue) }) } export async function getThemeConfigData (themeConfig?: UIThemeConfig) { let currentTheme = _default if (themeConfig) { if (themeConfig.type === 'local') { if (themes[themeConfig.themeName]) { currentTheme = themes[themeConfig.themeName] } else { console.warn(`[VoicenterUI-plus] No such theme: ${themeConfig.themeName}`) } } if (themeConfig.type === 'remote') { let body = JSON.stringify( { SectionList: [ themeConfig.brandingSectionName ], Domain: window.location.hostname } ) if (themeConfig.payloadData) { body = JSON.stringify(themeConfig.payloadData) } const apiStyling = await fetch(themeConfig.apiUrl, { method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json' }, referrerPolicy: 'no-referrer', body }) .then(res => res.json()) .then(res => res.Data) .then(res => { return Object.fromEntries(Object.entries(res).map(([ key, value ]) => { return [ key.replace(`${themeConfig.brandingSectionName}.`, ''), String(value) ] })) }) .catch(e => console.error(e)) if (apiStyling) { currentTheme = apiStyling } } if (themeConfig.type === 'customJson') { currentTheme = themeConfig.config ?? {} } } return currentTheme } export default async function (themeConfig?: UIThemeConfig, appendTo: HTMLElement = document.documentElement) { if (themeConfig?.type === 'none') { return themeConfig?.onSetupCallback ? themeConfig?.onSetupCallback({}) : {} } const currentTheme = await getThemeConfigData(themeConfig) appendGlobalCssVariables( { ...overrideElementTheme(currentTheme), ...globalVariables }, appendTo ) if (themeConfig?.onSetupCallback) { themeConfig.onSetupCallback(currentTheme) } }