Skip to content

Commit

Permalink
task: eslint fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
skibinska committed Jun 27, 2024
1 parent 473d374 commit 1f198e9
Show file tree
Hide file tree
Showing 6 changed files with 135 additions and 125 deletions.
78 changes: 45 additions & 33 deletions build.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { promises } from "node:fs";

import StyleDictionary from 'style-dictionary';
import { permutateThemes, registerTransforms } from '@tokens-studio/sd-transforms';
import StyleDictionary from "style-dictionary";
import {
permutateThemes,
registerTransforms,
} from "@tokens-studio/sd-transforms";

import { generateSemanticFiles } from "./utils/generateSemanticFiles.js";

Expand All @@ -11,10 +14,7 @@ import { transformRem } from "./utils/transforms/transformRem.js";
const excludedFromSemantic = ["collection-core", "collection-theme"];

// Define the array of excluded token paths
const excludedPaths = [
'asset',
'annotations'
];
const excludedPaths = ["asset", "annotations"];

registerTransforms(StyleDictionary);

Expand All @@ -26,7 +26,7 @@ async function run() {
// collect all tokensets for all themes
const tokensets = [
...new Set(
Object.values(themes).reduce((acc, sets) => [...acc, ...sets], [])
Object.values(themes).reduce((acc, sets) => [...acc, ...sets], []),
),
];

Expand All @@ -42,68 +42,80 @@ async function run() {
source: sets.map((tokenset) => `tokens/${tokenset}.json`),
platforms: {
css: {
transformGroup: 'tokens-studio',
transforms: ["custom/attribute/themeable", "name/kebab", "custom/rem"],
buildPath: 'generatedTokens/css/',
transformGroup: "tokens-studio",
transforms: [
"custom/attribute/themeable",
"name/kebab",
"custom/rem",
],
buildPath: "generatedTokens/css/",
files: [
{
destination: "core.css",
format: "css/variables",
filter: 'custom/coreFilter',
filter: "custom/coreFilter",
},
{
destination: "product/collection.css",
format: "css/variables",
filter: 'custom/collectionFilter',
filter: "custom/collectionFilter",
},
...generateSemanticFiles(excludedFromSemantic, theme),
]
}
}
],
},
},
};
});


for (const cfg of configs) {
const sd = new StyleDictionary(cfg);

sd.registerTransform({
name: "custom/attribute/themeable",
type: "attribute",
transform: (token) => transformAttributeThemeable(token, themeableSets, sd.tokens),
transform: (token) =>
transformAttributeThemeable(token, themeableSets, sd.tokens),
});

sd.registerTransform({
name: 'custom/rem',
type: 'value',
name: "custom/rem",
type: "value",
transitive: true,
filter: token =>
['sizing', 'spacing', 'borderRadius', 'fontSizes', 'lineHeights', 'letterSpacing'].includes(
token.type,
),
transform: token => transformRem(token.value),
filter: (token) =>
[
"sizing",
"spacing",
"borderRadius",
"fontSizes",
"lineHeights",
"letterSpacing",
].includes(token.type),
transform: (token) => transformRem(token.value),
});

sd.registerFilter({
name: 'custom/coreFilter',
name: "custom/coreFilter",
filter: (token) => {
return token.filePath.endsWith("core.json") && !token.filePath.includes("collection") && !token.path.some(part => excludedPaths.includes(part))
}
return (
token.filePath.endsWith("core.json") &&
!token.filePath.includes("collection") &&
!token.path.some((part) => excludedPaths.includes(part))
);
},
});

sd.registerFilter({
name: 'custom/collectionFilter',
name: "custom/collectionFilter",
filter: (token) => {
return token.filePath.includes("collection")
}
return token.filePath.includes("collection");
},
});

await sd.cleanAllPlatforms();
await sd.buildAllPlatforms();
}


console.log('CSS files have been generated.');
console.log("CSS files have been generated.");
}

run();
run();
54 changes: 27 additions & 27 deletions split-json.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,52 @@
import fs from 'node:fs';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from "node:fs";
import path from "path";
import { fileURLToPath } from "url";

// Get the current directory of the script
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Read the JSON file
const jsonFile = path.join(__dirname, 'tokens.json');
const jsonFile = path.join(__dirname, "tokens.json");
const rawData = fs.readFileSync(jsonFile);
const jsonData = JSON.parse(rawData);

// Define the base output directory
const baseDir = path.join(__dirname, 'tokens');
const baseDir = path.join(__dirname, "tokens");

// Define keys to exclude
const excludeKeys = ['$themes'];
const excludeKeys = ["$themes"];

// Function to write data to file
const writeFile = (filePath, data) => {
const dir = path.dirname(filePath);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
const dir = path.dirname(filePath);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(data, null, 2));
};

Object.keys(jsonData).forEach(key => {
// Skip keys that are in the exclude list
if (excludeKeys.includes(key)) {
return;
}
Object.keys(jsonData).forEach((key) => {
// Skip keys that are in the exclude list
if (excludeKeys.includes(key)) {
return;
}

// Split the key into parts
let keyParts = key.split('/');
// Split the key into parts
let keyParts = key.split("/");

// Remove the first part if there are multiple parts
if (keyParts.length > 1) {
keyParts.shift();
}
// Remove the first part if there are multiple parts
if (keyParts.length > 1) {
keyParts.shift();
}

// Replace spaces in each part with hyphens
keyParts = keyParts.map(part => part.replace(/\s+/g, '-'));
// Replace spaces in each part with hyphens
keyParts = keyParts.map((part) => part.replace(/\s+/g, "-"));

// Join the remaining parts with '-' and convert to lowercase
const cleanKey = keyParts.join('-').toLowerCase();
// Join the remaining parts with '-' and convert to lowercase
const cleanKey = keyParts.join("-").toLowerCase();

const filePath = path.join(baseDir, `${cleanKey}.json`);
const filePath = path.join(baseDir, `${cleanKey}.json`);

writeFile(filePath, jsonData[key]);
writeFile(filePath, jsonData[key]);
});

console.log('JSON files have been created in the tokens directory.');
console.log("JSON files have been created in the tokens directory.");
20 changes: 10 additions & 10 deletions utils/filters.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// filters only tokens originating from semantic sets (not core, not excluded) and also check themeable or not
export const semanticFilter =
(excluded, themeable = false) =>
(token) => {
const tokenThemable = Boolean(token.attributes.themeable);
return (
themeable === tokenThemable &&
["core", ...excluded].every(
(cat) => !token.filePath.endsWith(`${cat}.json`)
)
);
};
(excluded, themeable = false) =>
(token) => {
const tokenThemable = Boolean(token.attributes.themeable);
return (
themeable === tokenThemable &&
["core", ...excluded].every(
(cat) => !token.filePath.endsWith(`${cat}.json`),
)
);
};
38 changes: 19 additions & 19 deletions utils/generateSemanticFiles.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
import { semanticFilter } from "./filters.js";

const commonFileOptions = {
format: "css/variables",
options: {
selector: ":host",
},
format: "css/variables",
options: {
selector: ":host",
},
};

export const generateSemanticFiles = (excluded, theme) => {
const filesArr = [];
// theme-specific outputs
filesArr.push({
...commonFileOptions,
filter: semanticFilter(excluded, true),
destination: `product/${theme.toLowerCase().replace(' ', '-')}.css`,
});
const filesArr = [];
// theme-specific outputs
filesArr.push({
...commonFileOptions,
filter: semanticFilter(excluded, true),
destination: `product/${theme.toLowerCase().replace(" ", "-")}.css`,
});

// not theme-specific outputs
filesArr.push({
...commonFileOptions,
filter: semanticFilter(excluded, false),
destination: `semantic.css`,
});
// not theme-specific outputs
filesArr.push({
...commonFileOptions,
filter: semanticFilter(excluded, false),
destination: `semantic.css`,
});

return filesArr;
};
return filesArr;
};
42 changes: 20 additions & 22 deletions utils/transforms/transformAttributeThemeable.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,27 @@ import { getReferences, usesReferences } from "style-dictionary/utils";
*/

export const transformAttributeThemeable = (token, themeableSets, sdTokens) => {
function isPartOfEnabledSet(token) {
const set = token.filePath
.replace(/^tokens\//g, "")
.replace(/.json$/g, "");
function isPartOfEnabledSet(token) {
const set = token.filePath.replace(/^tokens\//g, "").replace(/.json$/g, "");

return themeableSets.includes(set);
}
return themeableSets.includes(set);
}

// Set token to themeable if it's part of an enabled set
if (isPartOfEnabledSet(token)) {
return {
themeable: true,
};
}
// Set token to themeable if it's part of an enabled set
if (isPartOfEnabledSet(token)) {
return {
themeable: true,
};
}

// Set token to themeable if it's using a reference and inside the reference chain
// any one of them is from a themeable set
if (usesReferences(token.original.value)) {
const refs = getReferences(token.original.value, sdTokens);
if (refs.some((ref) => isPartOfEnabledSet(ref))) {
return {
themeable: true,
};
}
// Set token to themeable if it's using a reference and inside the reference chain
// any one of them is from a themeable set
if (usesReferences(token.original.value)) {
const refs = getReferences(token.original.value, sdTokens);
if (refs.some((ref) => isPartOfEnabledSet(ref))) {
return {
themeable: true,
};
}
}
}
};
28 changes: 14 additions & 14 deletions utils/transforms/transformRem.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,25 @@
*/

function getBasePxFontSize(options) {
return options?.basePxFontSize || 16;
return options?.basePxFontSize || 16;
}

export function transformRem(tokenValue, options) {
if (tokenValue === undefined) {
return tokenValue;
}
if (tokenValue === undefined) {
return tokenValue;
}

if (`${tokenValue}`.endsWith('rem')) {
return `${tokenValue}`;
}
if (`${tokenValue}`.endsWith("rem")) {
return `${tokenValue}`;
}

const value = parseFloat(`${tokenValue}`);
const value = parseFloat(`${tokenValue}`);

if (value === 0) {
return '0';
}
if (value === 0) {
return "0";
}

const baseFont = getBasePxFontSize(options);
const baseFont = getBasePxFontSize(options);

return `${value / baseFont}rem`;
}
return `${value / baseFont}rem`;
}

0 comments on commit 1f198e9

Please sign in to comment.