Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion parsers/to-jss/to-jss.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,36 @@ describe('To jss', () => {

it('Get tokens - apply parsers - with snakeCase formatName options', async () => {
const options: OptionsType = {
formatName: 'snakeCase'!,
formatName: 'snakeCase',
formatTokens: { colorFormat: 'hsl' },
};
const result = await toJss(seeds().tokens as Array<Token>, options, libs);
const color = seeds().tokens.find(token => token.type === 'color') as ColorToken;
const measurement = seeds().tokens.find(
token => token.type === 'measurement',
) as MeasurementToken;

const fnFormatColor = libs._[options.formatName!](color.name);
expect(
result.includes(
`${fnFormatColor}: "${libs
.tinycolor(color.value as ColorValue)
.toString(options.formatTokens?.colorFormat)}",`,
),
).toBe(true);

const fnFormatMeasurement = libs._[options.formatName!](measurement.name);
expect(
result.includes(
`${fnFormatMeasurement}: "${measurement.value.measure}${measurement.value.unit}",`,
),
).toBe(true);
return;
});

it('Get tokens - apply parsers - with pascalCase formatName options', async () => {
const options: OptionsType = {
formatName: 'pascalCase',
formatTokens: { colorFormat: 'hsl' },
};
const result = await toJss(seeds().tokens as Array<Token>, options, libs);
Expand Down
8 changes: 5 additions & 3 deletions parsers/to-tailwind/to-tailwind.parser.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { IToken, PartialRecord, TokensType } from '../../types';
import { LibsType } from '../global-libs';
import prettier from 'prettier';
import os from 'os';
import * as _ from 'lodash';
import { groupBy } from 'lodash';
import { ColorsFormat, FormatName, TailwindTokenClass, TailwindType } from './to-tailwind.type';
import * as TokensClass from './tokens';
import deepmerge from 'deepmerge';
import { initFormatterFunction } from './utils/getNameFormatterFunction';
import { LibsType } from '../global-libs';

export type OutputDataType = string;
export type InputDataType = Array<
Expand Down Expand Up @@ -63,7 +64,7 @@ class ToTailwind {
this.exportDefault = options?.formatConfig?.exportDefault ?? true;
this.module = options?.formatConfig?.module ?? 'es6';
this.tokens = tokens;
this.tokensGroupedByType = _.groupBy(tokens, 'type');
this.tokensGroupedByType = groupBy(tokens, 'type');
this.styles = {};
}

Expand Down Expand Up @@ -122,6 +123,7 @@ export default async function (
{ _ }: Pick<LibsType, '_'>,
): Promise<OutputDataType> {
try {
initFormatterFunction(_, options?.formatName);
const parserInstance = new ToTailwind(tokens, options);
return parserInstance.exec();
} catch (err) {
Expand Down
73 changes: 31 additions & 42 deletions parsers/to-tailwind/to-tailwind.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
MeasurementToken,
OpacityToken,
ShadowToken,
TextStyleToken
TextStyleToken,
} from '../../types';
import libs from '../global-libs';
import toTailwind from './to-tailwind.parser';
Expand All @@ -32,41 +32,30 @@ describe('To tailwind', () => {
return;
});


describe('Should generate correct casing for output variable value', () => {
beforeAll(() => {
jest.mock('lodash', () => ({
...jest.requireActual('lodash'),
pascalCase: _.flow(_.camelCase, _.upperFirst),
}));
});

afterAll(() => {
jest.clearAllMocks();
});

const allCaseTypes: FormatName[][] = [['pascalCase'], ['snakeCase'], ['kebabCase'], ['camelCase']];

test.each(allCaseTypes)(
'should generate output variables in %s',
async formatName => {
const tokens = seeds().tokens.filter(token => token.type === 'color') as Array<ColorToken>;
const result = await toTailwind(
tokens,
{ formatName, formatConfig: { useVariables: true } },
libs,
);

tokens.forEach(({ name }) => {
const transformNameFn = getNameFormatterFunction(formatName);
const formatted = transformNameFn(name);
const allCaseTypes: FormatName[][] = [
['pascalCase'],
['snakeCase'],
['kebabCase'],
['camelCase'],
['none'],
];

test.each(allCaseTypes)('should generate output variables in %s', async formatName => {
const tokens = seeds().tokens.filter(token => token.type === 'color') as Array<ColorToken>;
const result = await toTailwind(
tokens,
{ formatName, formatConfig: { useVariables: true } },
libs,
);

expect(result).toEqual(expect.stringContaining(`var(--${formatted})`));
});
tokens.forEach(({ name }) => {
const formatted = libs._[formatName](name);
expect(result).toEqual(expect.stringContaining(`var(--${formatted})`));
});

return;
},
);
return;
});
});

it('Should user raw color value', async () => {
Expand Down Expand Up @@ -585,7 +574,7 @@ describe('To tailwind', () => {
);

tokens.forEach(({ name, value }) => {
const transformedName = getNameFormatterFunction(formatName)(name);
const transformedName = getNameFormatterFunction()(name);
expect(result).toEqual(expect.stringContaining(`${borderWidthPrefix}${transformedName}`));
expect(result).toEqual(expect.stringContaining(`${borderColorPrefix}${transformedName}`));

Expand Down Expand Up @@ -622,7 +611,7 @@ describe('To tailwind', () => {
);

tokens.forEach(({ name }) => {
const transformedName = getNameFormatterFunction(formatName)(name);
const transformedName = getNameFormatterFunction()(name);
expect(result).toEqual(expect.stringContaining(`${prefix}${transformedName}`));
});
});
Expand All @@ -648,7 +637,7 @@ describe('To tailwind', () => {
);

tokens.forEach(({ name }) => {
const transformedName = getNameFormatterFunction(formatName)(name);
const transformedName = getNameFormatterFunction()(name);
expect(result).toEqual(expect.stringContaining(`${prefix}${transformedName}`));
});
});
Expand Down Expand Up @@ -676,7 +665,7 @@ describe('To tailwind', () => {
);

tokens.forEach(({ name }) => {
const transformedName = getNameFormatterFunction(formatName)(name);
const transformedName = getNameFormatterFunction()(name);
expect(result).toEqual(expect.stringContaining(`${prefix}${transformedName}`));
});
});
Expand Down Expand Up @@ -704,7 +693,7 @@ describe('To tailwind', () => {
);

tokens.forEach(({ name }) => {
const transformedName = getNameFormatterFunction(formatName)(name);
const transformedName = getNameFormatterFunction()(name);
expect(result).toEqual(expect.stringContaining(`${prefix}${transformedName}`));
});
});
Expand Down Expand Up @@ -732,7 +721,7 @@ describe('To tailwind', () => {
);

tokens.forEach(({ name }) => {
const transformedName = getNameFormatterFunction(formatName)(name);
const transformedName = getNameFormatterFunction()(name);
expect(result).toEqual(expect.stringContaining(`${prefix}${transformedName}`));
});
});
Expand All @@ -758,7 +747,7 @@ describe('To tailwind', () => {
);

tokens.forEach(({ name }) => {
const transformedName = getNameFormatterFunction(formatName)(name);
const transformedName = getNameFormatterFunction()(name);
expect(result).toEqual(expect.stringContaining(`${prefix}${transformedName}`));
});
});
Expand All @@ -784,7 +773,7 @@ describe('To tailwind', () => {
);

tokens.forEach(({ name }) => {
const transformedName = getNameFormatterFunction(formatName)(name);
const transformedName = getNameFormatterFunction()(name);
expect(result).toEqual(expect.stringContaining(`${prefix}${transformedName}`));
});
});
Expand Down Expand Up @@ -848,7 +837,7 @@ describe('To tailwind', () => {
);

tokens.forEach(({ name, value }) => {
const transformedName = getNameFormatterFunction(formatName)(name);
const transformedName = getNameFormatterFunction()(name);

expect(result).toEqual(expect.stringContaining(`${fontSizePrefix}${transformedName}`));
expect(result).toEqual(expect.stringContaining(`${lineHeightPrefix}${transformedName}`));
Expand Down
8 changes: 7 additions & 1 deletion parsers/to-tailwind/to-tailwind.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,5 +107,11 @@ export interface TailwindTokenClassInstance {
generate(options: OptionsType, spTokens: InputDataType): Partial<Record<TailwindType, any>>;
}

export const formatNameArray = ['camelCase', 'kebabCase', 'snakeCase', 'pascalCase'] as const;
export const formatNameArray = [
'camelCase',
'kebabCase',
'snakeCase',
'pascalCase',
'none',
] as const;
export type FormatName = typeof formatNameArray[number];
16 changes: 4 additions & 12 deletions parsers/to-tailwind/tokens/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { Token } from '../../../types';
import Template from '../../../libs/template';
import * as _ from 'lodash';
import { pascalCase } from 'lodash';
import { getNameFormatterFunction } from '../utils/getNameFormatterFunction';
import { TailwindType } from '../to-tailwind.type';
import { OptionsType } from '../to-tailwind.parser';
import { getClassNameAsCSSVariable } from '../utils/getClassNameAsCSSVariable';

export * from './color';
export * from './gradient';
Expand Down Expand Up @@ -36,20 +34,14 @@ export abstract class Utils {
return token.name!;
}

static getValue(key: string, value: unknown, options: OptionsType) {
if (options?.formatConfig?.useVariables) {
return getClassNameAsCSSVariable(String(key), options.formatName);
}

return value
}

static go<T>(token: T, options: OptionsType, tailwindKey: TailwindType, value: unknown) {
const keyName = this.getTemplatedTokenName(token, options?.renameKeys?.[tailwindKey]);
const keys = [...(options?.splitBy ? keyName.split(new RegExp(options.splitBy)) : [keyName])];

const key = keys.map(k => getNameFormatterFunction(options?.formatName)(k)).join('.');
const val = Utils.getValue(key, value, options);
const key = keys.map(k => getNameFormatterFunction()(k)).join('.');
const val = options?.formatConfig?.useVariables
? `var(--${getNameFormatterFunction()(key)})`
: value;

return _.setWith({}, key, val, Object);
}
Expand Down
11 changes: 0 additions & 11 deletions parsers/to-tailwind/utils/getClassNameAsCSSVariable.ts

This file was deleted.

16 changes: 12 additions & 4 deletions parsers/to-tailwind/utils/getNameFormatterFunction.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import * as _ from 'lodash';

import { FormatName } from '../to-tailwind.type';
import { LibsType } from '../../global-libs';

let formatterFn: ((a: string) => string) | null = null;

export function initFormatterFunction(_: LibsType['_'], format: FormatName = 'camelCase') {
formatterFn = _[format];
}

export function getNameFormatterFunction(format: FormatName = 'camelCase') {
return _[format];
export function getNameFormatterFunction() {
if (!formatterFn) {
throw new Error('Formatter function is not initialized');
}
return formatterFn;
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,31 @@ export type opacity = 'subtle' | 'transparent' | 'visible'

"
`;

exports[`Tokens to Typescript types definitions Should generate all the types with name in pascalCase 1`] = `
"export type bitmap = 'AcmeLogo' | 'PhotoExample' | 'PhotoExample' | 'PhotoExample'

export type vector = 'Activity' | 'Airplay' | 'AlertCircle' | 'AlertOctagon' | 'AlertTriangle' | 'AlertTriangle' | 'AlignCenter' | 'AlignCenter' | 'UserMask' | 'UserMask'

export type depth = 'Background' | 'Foreground' | 'Middle'

export type duration = 'Base' | 'Long' | 'Short' | 'VeryLong'

export type measurement = 'BaseSpace01' | 'BaseSpace02' | 'BaseSpace03' | 'BaseSpace04' | 'BaseSpace05' | 'BaseSpace06' | 'BaseSpace07' | 'BaseSpace08' | 'BaseSpace09' | 'BaseSpace10'

export type textStyle = 'Body' | 'BodyWithOpacity' | 'Code' | 'List' | 'Title'

export type border = 'BorderAccent' | 'BorderAccentWithOpacity' | 'BorderAccentWithoutRadii' | 'BorderDashed'

export type color = 'ColorsAccent' | 'ColorsAlmostBlack' | 'ColorsBlack' | 'ColorsGreen' | 'ColorsGrey' | 'ColorsOrange' | 'ColorsPureBlack' | 'ColorsRed' | 'ColorsWhite'

export type shadow = 'Elevation1' | 'Elevation2' | 'Elevation3'

export type font = 'FiraCodeMedium' | 'InterMedium' | 'InterSemiBold' | 'RobotoRegular'

export type gradient = 'GradientsColored' | 'GradientsDark' | 'GradientsNeutral' | 'GradientsSafari'

export type opacity = 'Subtle' | 'Transparent' | 'Visible'

"
`;
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as _ from 'lodash';
import { IToken, TokensType } from '../../types';
import { LibsType } from '../global-libs';

Expand All @@ -20,16 +19,16 @@ export type OptionsType =

type groupedByType = Partial<{ [k in TokensType]: string[] }>;

const applyFormat = (str: string, fn?: format) => {
if (fn && fn !== 'none') return _[fn](str);
return str.includes(' ') || str.includes('\n') || str.includes('/') ? JSON.stringify(str) : str;
};

export default async function toTypescriptDefinition(
tokens: InputDataType,
options: OptionsType,
{ _ }: Pick<LibsType, '_'>,
): Promise<OutputDataType> {
const applyFormat = (str: string, fn?: format) => {
if (fn && fn !== 'none') return _[fn](str);
return str.includes(' ') || str.includes('\n') || str.includes('/') ? JSON.stringify(str) : str;
};

const grouped = tokens.reduce<groupedByType>((acc, current) => {
if (!acc[current.type])
return {
Expand Down
Loading