Mantra Theme Color Variables

Mantra started as a black and white theme - let's add color for the background, text, and links.

First we need to know how to set variables and use them in css.

See this class: https://www.andrewsclasses.com/classs/css-variables

Here is a script to set the variables and add styles to the body for a proof of concept.

(($, Drupal, drupalSettings) => {
  Drupal.behaviors.setColorVars = {
    attach: function attach() {
      let body = document.querySelector('body')
      body.style.setProperty('--link-color', 'magenta')
      body.style.setProperty('--text-color', 'mediumvioletred')
      body.style.setProperty('--background-color', 'indigo')
      let linkStyles = document.createElement('style')

      linksStyles.innerHTML = `
body {color: var(--text-color); background-color: var(--background-color);}
a {color: var(--link-color);}
h1 a, h2 a, h3 a, h4 a, h5 a, h6 a {color: var(--text-color);}
.site-name a {color: var(--text-color);}`

      body.appendChild(linkStyles)
    }
  }
})(jQuery, Drupal, drupalSettings)

Now we need to set up the theme settings form to set these options.

theme-settings.php

function mantratheme_form_system_theme_settings_alter(&$form, &$form_state) {

  $form['mantratheme']['text_color'] = [
    '#type' => 'textfield',
    '#title' => t('Text color'),
    '#default_value' => theme_get_setting('text_color'),
  ];

  $form['mantratheme']['background_color'] = [
    '#type' => 'textfield',
    '#title' => t('Background color'),
    '#default_value' => theme_get_setting('background_color'),
  ];

  $form['mantratheme']['link_color'] = [
    '#type' => 'textfield',
    '#title' => t('Link color'),
    '#default_value' => theme_get_setting('link_color'),
  ];

}

Set drupalSettings variables in HOOK_preprocess_page().

function mantratheme_preprocess_page(&$variables) {
  $settings = &$variables['#attached']['drupalSettings']['setColorVars'];

  $settings['backgroundColor'] = theme_get_setting('background_color');
  $settings['textColor'] = theme_get_setting('text_color');
  $settings['linkColor'] = theme_get_setting('link_color');
}

We need to have the theme's schema defined for these values, and set install defaults.

config/scheme/mantratheme.schema.yml

mantratheme.settings:
  type: theme_settings
  label: 'Mantra settings'
  mapping:
    text_color:
      type: string
      label: Text color
    background_color:
      type: string
      label: Background color
    link_color:
      type: string
      label: Link color

config/install/mantratheme.settings.yml

text_color: black
background_color: white
link_color: blue;

Finally, adjust the script to use the variables.

body.style.setProperty('--background-color', drupalSettings.setColorVars.backgroundColor)
body.style.setProperty('--text-color', drupalSettings.setColorVars.textColor)
body.style.setProperty('--link-color', drupalSettings.setColorVars.linkColor)
Project
Tags