Skip to content

Commit

Permalink
feat: upgrade to latest SD and remove redundant options
Browse files Browse the repository at this point in the history
  • Loading branch information
jorenbroekema committed Mar 21, 2024
1 parent 71b1dea commit fe710ce
Show file tree
Hide file tree
Showing 11 changed files with 77 additions and 62 deletions.
27 changes: 27 additions & 0 deletions .changeset/sweet-foxes-float.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
'@tokens-studio/sd-transforms': minor
---

BREAKING: remove options `addAttributeCTI` & `casing`.
Since `transformGroup` can now be combined with `transforms`, this is now much easier to accomplish in Style-Dictionary without additional sd-transforms options.

Before:

```js
registerTransforms(StyleDictionary, { addAttributeCTI: true, casing: 'kebab' });
```

After:

```json
{
"platforms": {
"css": {
"transformGroup": "tokens-studio",
"transforms": ["attribute/cti", "name/kebab"]
}
}
}
```

> From this version onwards, Style-Dictionary v4.0.0-prerelease.19 minimum is required.
28 changes: 12 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ Android:

- Transform typography objects to Android Compose shorthand -> `ts/typography/compose/shorthand`

Registers the **generic** and **CSS** transforms, in addition to `name/cti/camel` for naming purposes, as a transform group called `tokens-studio`.
Registers the **generic** and **CSS** transforms as a transform group called `tokens-studio`.

## Installation

Expand All @@ -72,6 +72,7 @@ const sd = StyleDictionary.extend({
platforms: {
css: {
transformGroup: 'tokens-studio',
transforms: ['name/kebab'], // <-- add a token name transform for generating token names, default is camel
buildPath: 'build/css/',
files: [
{
Expand All @@ -95,19 +96,17 @@ To run it use the following command
node build-output.js
```

> Note: make sure to choose either the full transformGroup, **OR** its separate transforms so you can adjust or add your own.
> [Combining a transformGroup with a transforms array can give unexpected results](https://github.com/amzn/style-dictionary/issues/813).
> From Style-Dictionary `4.0.0-prerelease.18`, [`transformGroup` and `transforms` can now be combined in a platform inside your config](https://github.com/amzn/style-dictionary/blob/v4/CHANGELOG.md#400-prerelease18).
### Using the transforms

In your Style-Dictionary config, you can **either** use the `tokens-studio` transformGroup **or** the separate transforms (all of the names of those are listed):

```json
{
"source": ["**/*.tokens.json"],
"platforms": {
"css": {
"transformGroup": "tokens-studio",
"transforms": ["name/kebab"],
"buildPath": "build/css/",
"files": [
{
Expand All @@ -117,7 +116,7 @@ In your Style-Dictionary config, you can **either** use the `tokens-studio` tran
]
},
"css": {
"transforms": ["ts/size/px", "ts/opacity"],
"transforms": ["ts/size/px", "ts/opacity", "name/kebab"],
"buildPath": "build/css/",
"files": [
{
Expand Down Expand Up @@ -148,26 +147,24 @@ StyleDictionary.registerTransform({

### Custom Transform Group

In Style-Dictionary, [`transformGroup` and `transforms` cannot be combined in a platform inside your config](https://github.com/amzn/style-dictionary/issues/813).
> From Style-Dictionary `4.0.0-prerelease.18`, [`transformGroup` and `transforms` can now be combined in a platform inside your config](https://github.com/amzn/style-dictionary/blob/v4/CHANGELOG.md#400-prerelease18).
Therefore, if you wish to use the transform group, but adjust, add or remove a few transforms, your best option is to create a custom transform group:
You can create a custom transformGroup that includes the individual transforms from this package.
If you wish to use the transformGroup, but adjust or remove a few transforms, your best option is to create a custom transform group:

```js
const { transforms } = require('@tokens-studio/sd-transforms');
const StyleDictionary = require('style-dictionary');

// Register custom tokens-studio transform group
// without 'px' being added to numbers without a unit
// and also adding 'name/cti/camel' for the token names
// and also adding 'name/constant' for the token names
StyleDictionary.registerTransformGroup({
name: 'custom/tokens-studio',
transforms: [...transforms, 'name/cti/camel'].filter(transform => transform !== 'ts/size/px'),
transforms: [...transforms, 'name/constant'].filter(transform => transform !== 'ts/size/px'),
});
```

> Note: it is easy to change the casing or to add attributes/cti transform to the group, without needing to create a custom transform group.
> For this, see section "Options" below for the `casing` and `addAttributeCTI` option.
### Options

You can pass options to the `registerTransforms` function.
Expand Down Expand Up @@ -195,17 +192,14 @@ Options:
| name | type | required | default | description |
| ----------------------------- | ------------------------ | -------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| excludeParentKeys | boolean || `false` | Whether or not to exclude parent keys from your token files |
| addAttributeCTI | boolean || `false` | Whether or not to add `'attribute/cti'` predefined transform to the `tokens-studio` transformGroup |
| alwaysAddFontStyle | boolean || `false` | Whether or not to always add a 'normal' fontStyle property to typography tokens which do not have explicit fontStyle |
| casing | string || `camel` | What kind of casing to use for token names. Options: [`camel`, `pascal`, `snake`, `kebab`, `constant`] |
| expand | boolean \| ExpandOptions || See props below | `false` to not register the parser at all. By default, expands composition tokens. Optionally, border, shadow and typography as well. |
| expand.composition | boolean \| ExpandFilter || `true` | Whether or not to expand compositions. Also allows a filter callback function to conditionally expand per token/filePath |
| expand.typography | boolean \| ExpandFilter || `false` | Whether or not to expand typography. Also allows a filter callback function to conditionally expand per token/filePath |
| expand.shadow | boolean \| ExpandFilter || `false` | Whether or not to expand shadows. Also allows a filter callback function to conditionally expand per token/filePath |
| expand.border | boolean \| ExpandFilter || `false` | Whether or not to expand borders. Also allows a filter callback function to conditionally expand per token/filePath |
| ['ts/color/modifiers'] | ColorModifierOptions || See props below | Color modifier options |
| ['ts/color/modifiers'].format | ColorModifierFormat || `undefined` | Color modifier output format override ('hex' \| 'hsl' \| 'lch' \| 'p3' \| 'srgb'), uses local format or modifier space as default |
| |

> Note: you can also import and use the `parseTokens` function to run the parsing steps on your tokens object manually.
> Handy if you have your own parsers set up (e.g. for JS files), and you want the parser-based features like composites-expansion to work there too.
Expand Down Expand Up @@ -238,6 +232,7 @@ async function run() {
platforms: {
css: {
transformGroup: 'tokens-studio',
transforms: ['name/kebab'],
files: [
{
destination: `vars-${theme.name}.css`,
Expand Down Expand Up @@ -368,6 +363,7 @@ async function run() {
platforms: {
css: {
transformGroup: 'tokens-studio',
transforms: ['name/kebab'],
files: [
{
destination: `vars-${name}.css`,
Expand Down
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"expr-eval-fork": "^2.0.2",
"is-mergeable-object": "^1.1.1",
"postcss-calc-ast-parser": "^0.1.4",
"style-dictionary": "^4.0.0-prerelease.16"
"style-dictionary": "^4.0.0-prerelease.19"
},
"devDependencies": {
"@changesets/cli": "^2.26.0",
Expand Down
2 changes: 0 additions & 2 deletions src/TransformOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ export interface ColorModifierOptions {
}

export interface TransformOptions {
addAttributeCTI?: boolean;
casing?: 'camel' | 'pascal' | 'snake' | 'kebab' | 'constant';
alwaysAddFontStyle?: boolean;
expand?: ExpandOptions | false;
excludeParentKeys?: boolean;
Expand Down
13 changes: 3 additions & 10 deletions src/registerTransforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,17 +205,10 @@ export async function registerTransforms(
transformer: token => transformColorModifiers(token, transformOpts?.['ts/color/modifiers']),
});

const casing = transformOpts?.casing ?? 'camel';
const casingTransform = `name/cti/${casing}`;
sd.registerTransformGroup({
name: 'tokens-studio',
transforms: [
...(transformOpts?.addAttributeCTI === true ? ['attribute/cti'] : []),
...transforms,
// by default we go with camel, as having no default will likely give the user
// errors straight away. This can be overridden by manually passing an array of transforms
// instead of this transformGroup, or by doing a name conversion in your custom format
casingTransform,
],
// add a default name transform, since this is almost always needed
// it's easy to override by users, adding their own "transforms"
transforms: [...transforms, 'name/camel'],
});
}
2 changes: 1 addition & 1 deletion test/integration/output-references.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const cfg = {
source: ['test/integration/tokens/output-references.tokens.json'],
platforms: {
css: {
transforms: ['ts/resolveMath', 'name/cti/kebab'],
transforms: ['ts/resolveMath', 'name/kebab'],
prefix: 'sd',
buildPath: outputDir,
files: [
Expand Down
26 changes: 24 additions & 2 deletions test/integration/sd-transforms.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,18 @@ describe('sd-transforms smoke tests', () => {
it('allows easily changing the casing', async () => {
await cleanup(dict);

dict = await init(cfg, { 'ts/color/modifiers': { format: 'hex' }, casing: 'kebab' });
dict = await init(
{
...cfg,
platforms: {
css: {
...cfg.platforms.css,
transforms: ['name/kebab'],
},
},
},
{ 'ts/color/modifiers': { format: 'hex' } },
);
const file = await promises.readFile(outputFilePath, 'utf-8');
expect(file).to.include(`:root {
--sd-dimension-scale: 2;
Expand Down Expand Up @@ -125,7 +136,18 @@ describe('sd-transforms smoke tests', () => {

it('allows easily adding attribute/cti transform to tokens-studio group', async () => {
await cleanup(dict);
dict = await init(cfg, { 'ts/color/modifiers': { format: 'hex' }, addAttributeCTI: true });
dict = await init(
{
...cfg,
platforms: {
css: {
...cfg.platforms.css,
transforms: ['attribute/cti'],
},
},
},
{ 'ts/color/modifiers': { format: 'hex' } },
);
const enrichedTokens = await dict?.exportPlatform('css'); // platform to parse for is 'css' in this case
expect(enrichedTokens?.dimension.scale.attributes).to.eql({
category: 'dimension',
Expand Down
2 changes: 1 addition & 1 deletion test/integration/swift-UI-color.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const cfg = {
'ts/color/modifiers',
'attribute/cti',
'transitive/color/UIColorSwift',
'name/cti/camel',
'name/camel',
],
buildPath: outputDir,
files: [
Expand Down
12 changes: 1 addition & 11 deletions test/spec/parsers/add-font-styles.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,23 +109,13 @@ describe('add font style', () => {
},
};

// let error;
// try {
addFontStyles(inputTokens as DeepKeyTokenMap<false>);
// } catch (e) {
// if (e instanceof Error) {
// error = e.message;
// }
// }
restore();

expect(stub.calls.size).to.equal(1);
expect(stub.firstCall?.args[0].message).to.equal(
`Reference doesn't exist: tries to reference fwRef, which is not defined.`,
`tries to reference fwRef, which is not defined.`,
);
// expect(error).to.equal(
// "Reference doesn't exist: tries to reference fwRef, which is not defined.",
// );
});

it(`allows always adding a default fontStyle`, () => {
Expand Down
13 changes: 1 addition & 12 deletions test/spec/parsers/expand.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -707,8 +707,6 @@ describe('expand', () => {

it(`should throw when token reference in a composite cannot be resolved`, () => {
const stub = stubMethod(console, 'error');
// let error;
// try {
expandComposites(
{
ref: {
Expand All @@ -723,22 +721,13 @@ describe('expand', () => {
},
'foo/bar.json',
);
// } catch (e) {
// if (e instanceof Error) {
// error = e.message;
// }
// }

restore();

expect(stub.calls.size).to.equal(1);
expect(stub.firstCall?.args[0].message).to.equal(
`Reference doesn't exist: tries to reference typography.foo, which is not defined.`,
`tries to reference typography.foo, which is not defined.`,
);

// expect(error).to.equal(
// "Reference doesn't exist: tries to reference typography.foo, which is not defined.",
// );
});

it('should not trip up when the recursed token contains a primitive value', () => {
Expand Down

0 comments on commit fe710ce

Please sign in to comment.