# All files / extensions themeGet.js

96.3% Statements 26/27
83.33% Branches 5/6
100% Functions 9/9
95.45% Lines 21/22

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60

    1752x
    62x
    62x
    2x

    60x

    1746x

    13x
    9x
    1x

    9x

    9x

    9x
    8x
    6x
    3x
    3x

    3x
    3x

    1x

    9x

    4x

     import { get } from 'lodash';
    import { NAMESPACE } from '../theme';

    const createGetter = key => props => {
      const result = get(props, `theme.${NAMESPACE}.${key}`);
      if (!result) {
        throw new Error(`Could not find value for theme style getter ${key}!`);
      }
      return result;
    };

    /**
     * Creates a getter which will retrieve the specified value from
     * a provided object which contains a `theme`. Use this to create
     * a function to pass to a styled component to select a theme value.
     *
     * Example usage:
     *
     * styled.div`
     *   color: ${themeGet('colors.primary.default')};
     * `;
     */
    const themeGet = key => createGetter(key);

    const createIf = existingConditions => (conditionFn, key) => {
      const chain = () => {
        throw new Error('themeGet.if() chains must be terminated by .else()');
      };

      const conditions = existingConditions.concat({
        test: conditionFn,
        themeKey: key,
      });

      chain.if = createIf(conditions);

      chain.else = elseKey => props => {
        const matched = conditions.find(({ test }) => test(props));
        if (matched) {
          return createGetter(matched.themeKey)(props);
        } else Eif (elseKey) {
          // if user provided an else key, try to get it from theme
          try {
            return createGetter(elseKey)(props);
          } catch (err) {
            // if not in theme, treat it as a literal value
            return elseKey;
          }
        } else {
          return '';
        }
      };

      return chain;
    };

    themeGet.if = createIf([]);

    export default themeGet;