All files / tailwind-colorize-plugin/src helpers.ts

100% Statements 60/60
100% Branches 21/21
100% Functions 5/5
100% Lines 60/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 601x 1x 1x 1x 1x 1x 23x 1x 1x 22x 22x 23x 23x 23x 23x 8x 23x 6x 23x 8x 23x 23x 1x 1x 15x 7x 7x 7x 7x 1x 1x 6x 6x 15x 15x 1x 1x 11x 11x 1x 1x 8x 8x 8x 8x 8x 8x 8x 3x 3x 5x 8x 8x 8x 8x 1x 1x 1x 1x 1x
import Color from "color";
import { get } from "lodash";
 
export function useTheme({ theme: config }: any) {
 
    function transformArgument(arg: any): any {
        if(Array.isArray(arg)) {
            return transform(<[Color, Function[]]>arg);
        }
        
        switch(arg.id) {
            case 'ShortHexCode':
            case 'LongHexCode':
            case 'RgbFunction':
            case 'HslFunction':
                return Color(arg.code)
            case 'LiteralValue':
                return arg.value;
            case 'ThemeColor':
                return themeColor(arg.name, arg.weight)
        }
    }
 
    function transform([subject, calls]: [Color, Function[]]) {
        return calls.reduce((carry: any, call: any) => {
            const args = call.args.map(transformArgument)
                .filter((value: any) => value !== undefined);
 
            if(typeof carry[call.name] !== 'function') {
                throw new Error(`${call.name} is not a method on ${carry}`);
            }
 
            return carry[call.name](...args);
        }, transformArgument(subject))
    }
 
    function theme(path: string, defaultValue?: any) {
        return get(config, path, defaultValue);
    }
 
    function themeColor(path: string, weight?: any, defaultValue?: any): Color|string {
        const themePath = ['colors', path, weight]
            .filter(value => !!value)
            .join('.');
        
        const match = theme(themePath, defaultValue);
 
        if(typeof match === 'string') {
            return Color(match);
        }
 
        const keys = Object.keys(match || theme(themePath.split('.').slice(0, themePath.split('.').length - 1).join('.')));
 
        throw new Error(`"${path}" is not a valid theme color. You must give a valid modifier: ${keys}.`)
    }
    
    return {
        transform,
    };
}