export const listenToVariables = () => { const allVariables = { colorPalette: [ { variable: 'paletteColor1', type: 'color:color1' }, { variable: 'paletteColor2', type: 'color:color2' }, { variable: 'paletteColor3', type: 'color:color3' }, { variable: 'paletteColor4', type: 'color:color4' }, { variable: 'paletteColor5', type: 'color:color5' }, ], buttonColor: [ { selector: ':root', variable: 'buttonInitialColor', type: 'color:default' }, { selector: ':root', variable: 'buttonHoverColor', type: 'color:hover' } ], } const maybePromoteScalarValueIntoResponsive = value => /** * Responsive value must necessarily have the desktop key attached to it */ value.desktop ? value : { desktop: value, tablet: value, mobile: value } const replaceVariableInStyleTag = ( variableDescriptor, value, device = 'desktop' ) => { const deviceMapping = { desktop: 'ct-main-styles-inline-css', tablet: 'ct-main-styles-tablet-inline-css', mobile: 'ct-main-styles-mobile-inline-css' } const cssContainer = document.querySelector(`#${deviceMapping[device]}`) const existingCss = cssContainer.innerText const selector = variableDescriptor.selector || ':root' const selectorRegex = new RegExp(`${selector}\\s?{[\\s\\S]*?}`, 'gm') const matchedSelector = existingCss.match(selectorRegex) if (!matchedSelector) return cssContainer.innerText = existingCss.replace( selectorRegex, matchedSelector[0].replace( new RegExp( `--${variableDescriptor.variable}:[\\s\\S]*?;`, 'gm' ), `--${variableDescriptor.variable}: ${value};` ) ) } const handleSingleVariableFor = (variableDescriptor, value) => [ ...(variableDescriptor.selector ? document.querySelectorAll(variableDescriptor.selector) : [document.documentElement]) ].map(el => { if (!variableDescriptor.responsive) { replaceVariableInStyleTag( variableDescriptor, `${ (variableDescriptor.type || '').indexOf('color') > -1 ? value[ variableDescriptor.type === 'color' ? 'default' : variableDescriptor.type.split(':')[1] ].color : value }${variableDescriptor.unit || ''}` ) return } value = maybePromoteScalarValueIntoResponsive(value) replaceVariableInStyleTag( variableDescriptor, `${value.desktop}${variableDescriptor.unit || ''}`, 'desktop' ) replaceVariableInStyleTag( variableDescriptor, `${value.tablet}${variableDescriptor.unit || ''}`, 'tablet' ) replaceVariableInStyleTag( variableDescriptor, `${value.mobile}${variableDescriptor.unit || ''}`, 'mobile' ) }) wp.customize.bind( 'change', e => allVariables[e.id] && (Array.isArray(allVariables[e.id]) ? allVariables[e.id] : [allVariables[e.id]] ).map(d => handleSingleVariableFor(d, e())) ) }