Skip to content

Commit

Permalink
fix: update color token publisher plugin (#1831)
Browse files Browse the repository at this point in the history
Co-authored-by: rzpcibot <tools+cibot@razorpay.com>
  • Loading branch information
kamleshchandnani and rzpcibot authored Nov 27, 2023
1 parent e1d6207 commit a426e3a
Show file tree
Hide file tree
Showing 26 changed files with 4,192 additions and 92 deletions.
8 changes: 6 additions & 2 deletions .github/workflows/blade-tokens-upload.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@ on:
tokens:
description: 'Token Object'
required: true
tokenType:
description: 'Token type: theme or global'
required: true

env:
GITHUB_ACCESS_TOKEN: ${{ secrets.CI_BOT_TOKEN }}
TOKENS_DATA: ${{ github.event.inputs.tokens }}
TOKEN_DATA: ${{ github.event.inputs.tokens }}
TOKEN_TYPE: ${{ github.event.inputs.tokenType }}

jobs:
token-upload:
Expand All @@ -28,6 +32,6 @@ jobs:
uses: ./.github/actions/install-dependencies
- name: Upload Tokens
working-directory: packages/blade
run: node ./scripts/uploadTokens.js '${{ env.TOKENS_DATA }}'
run: node ./scripts/uploadTokens.js '${{ env.TOKEN_DATA }}' '${{ env.TOKEN_TYPE }}'
env:
GITHUB_TOKEN: ${{ secrets.CI_BOT_TOKEN }}
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
"workspaces": {
"packages": [
"packages/blade",
"packages/token-publisher",
"packages/razorsharp",
"packages/eslint-plugin-blade"
],
Expand Down
62 changes: 29 additions & 33 deletions packages/blade/scripts/uploadTokens.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,42 +9,39 @@ const GITHUB_BOT_USERNAME = 'rzpcibot';
const uploadColorTokens = async () => {
try {
// 1. read the tokens object
const tokens = JSON.parse(process.argv[2]);
const colorTokens = JSON.parse(process.argv[2]);
const tokenType = process.argv[3];

const colorRegex = /const colors: ColorsWithModes = {(.|\n)+?};/gm;
if (tokenType === 'themeColorTokens') {
const themeColorTokensRegex = /const colors: ColorsWithModes = {(.|\n)+?};/gm;
// 2. read the bladeTheme File
const bladeThemePath = path.resolve(__dirname, '../src/tokens/theme/bladeTheme.ts');
const bladeTheme = fs.readFileSync(bladeThemePath, 'utf8');

if (tokens.paymentThemeColors) {
// 2. read the paymentTheme File
const paymentThemePath = path.resolve(__dirname, '../src/tokens/theme/paymentTheme.ts');
const paymentTheme = fs.readFileSync(paymentThemePath, 'utf8');

// 3. write the new tokens to paymentTheme file
const updatedPaymentThemeColors = JSON.stringify(tokens.paymentThemeColors.colors).replace(
/"/g,
'',
);
const updatedPaymentTheme = paymentTheme.replace(
colorRegex,
`const colors: ColorsWithModes = ${updatedPaymentThemeColors};`,
// 3. write the new tokens to bladeTheme file
const updatedbladeThemeColors = JSON.stringify(colorTokens).replace(/"/g, '');
const updatedbladeTheme = bladeTheme.replace(
themeColorTokensRegex,
`const colors: ColorsWithModes = ${updatedbladeThemeColors};`,
);
fs.writeFileSync(paymentThemePath, updatedPaymentTheme);
}
fs.writeFileSync(bladeThemePath, updatedbladeTheme);
// prettify the file
execa.commandSync('yarn prettier --write src/tokens/theme/bladeTheme.ts');
} else if (tokenType === 'globalColorTokens') {
const globalColorTokensRegex = /export const colors: Color = {(.|\n)+?};/gm;
// 2. read the bladeTheme File
const globalColorTokensPath = path.resolve(__dirname, '../src/tokens/global/colors.ts');
const globalColorTokensFile = fs.readFileSync(globalColorTokensPath, 'utf8');

if (tokens.bankingThemeColors) {
// 4. read the bankingTheme File
const bankingThemePath = path.resolve(__dirname, '../src/tokens/theme/bankingTheme.ts');
const bankingTheme = fs.readFileSync(bankingThemePath, 'utf8');

// 5. write the new tokens to bankingTheme file
const updatedBankingThemeColors = JSON.stringify(tokens.bankingThemeColors.colors).replace(
/"/g,
'',
);
const updatedBankingTheme = bankingTheme.replace(
colorRegex,
`const colors: ColorsWithModes = ${updatedBankingThemeColors};`,
// 3. write the new tokens to bladeTheme file
const updatedGlobalColorTokens = JSON.stringify(colorTokens).replace(/"/g, '');
const updatedGlobalColorTokensFile = globalColorTokensFile.replace(
globalColorTokensRegex,
`export const colors: Color = ${updatedGlobalColorTokens};`,
);
fs.writeFileSync(bankingThemePath, updatedBankingTheme);
fs.writeFileSync(globalColorTokensPath, updatedGlobalColorTokensFile);
// prettify the file
execa.commandSync('yarn prettier --write src/tokens/global/colors.ts');
}

// 6. create branch
Expand All @@ -56,14 +53,13 @@ const uploadColorTokens = async () => {
execa.commandSync(`git config user.name ${GITHUB_BOT_USERNAME}`);

// 7. Commit all changes
execa.commandSync('yarn prettier --write src/tokens/theme/*.ts');
execa.commandSync('git status');
execa.commandSync('git add -A');
execa.commandSync(`git commit -m feat(tokens):\\ add\\ new\\ tokens`, {
env: { HUSKY_SKIP_HOOKS: 1 },
});

// 8. Raise a PR
// // 8. Raise a PR
execa.commandSync(`git push origin ${branchName}`);
execa.commandSync(
`gh pr create --title feat(tokens):\\ add\\ new\\ tokens --head ${branchName} --repo razorpay/blade --body This\\ PR\\ was\\ opened\\ by\\ the\\ Token\\ Upload\\ GitHub\\ action.\\ It\\ updates\\ source\\ token\\ files\\ based\\ on\\ the\\ payload\\ from\\ Figma\\ Plugin.`,
Expand Down
File renamed without changes.
File renamed without changes.
13 changes: 13 additions & 0 deletions packages/plugin-figma-token-publisher/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "Token Publisher",
"id": "00000000",
"api": "1.0.0",
"main": "dist/plugin.js",
"ui": "dist/ui.html",
"editorType": ["figma"],
"menu": [
{ "name": "Publish Global Color Tokens", "command": "globalColorTokens" },
{ "name": "Publish Theme Color Tokens", "command": "themeColorTokens" },
{ "name": "Generate Token's Dev Names", "command": "devTokenNames" }
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"react-dom": "17.0.1"
},
"devDependencies": {
"@figma/plugin-typings": "1.19.0",
"@figma/plugin-typings": "1.81.0",
"@types/react-dom": "17.0.0",
"@types/react": "17.0.0",
"@types/set-value": "4.0.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,33 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
const GITHUB_BASE_URL = 'https://api.github.com/repos';

export type TokenType = 'themeColorTokens' | 'globalColorTokens';
type ColorTokens = Record<string, any>;

export const uploadTokens = async ({
orgName = 'razorpay',
repoName,
workflowFileName,
tokens,
personalAccessToken,
}: any): Promise<void> => {
colorTokens,
tokenType,
}: {
orgName: string;
repoName: string;
workflowFileName: string;
personalAccessToken: string;
colorTokens: ColorTokens;
tokenType?: TokenType;
}): Promise<void> => {
const API_URL = `${GITHUB_BASE_URL}/${orgName}/${repoName}/actions/workflows/${workflowFileName}/dispatches`;

const getFetchOptions = ({ themeKey, tokens }: any) => ({
const getFetchOptions = ({
colorTokens,
tokenType,
}: {
colorTokens: ColorTokens;
tokenType?: TokenType;
}) => ({
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand All @@ -22,48 +39,39 @@ export const uploadTokens = async ({
body: JSON.stringify({
ref: 'master',
inputs: {
tokens: JSON.stringify({ [themeKey]: tokens }),
tokens: JSON.stringify(colorTokens),
tokenType,
},
}),
});

try {
const responses = await Promise.all([
fetch(
API_URL,
getFetchOptions({ themeKey: 'paymentThemeColors', tokens: tokens.paymentThemeColors }),
),
fetch(
API_URL,
getFetchOptions({ themeKey: 'bankingThemeColors', tokens: tokens.bankingThemeColors }),
),
]);
const isRequestSuccess = responses.every((response) => response.status === 204);
const response = await fetch(API_URL, getFetchOptions({ colorTokens, tokenType }));

const isRequestSuccess = response.status === 204;
if (isRequestSuccess) {
// nosemgrep
parent.postMessage(
{
pluginMessage: {
type: 'success',
text: '🎉 Theme color tokens published to server',
text: '🎉 Color tokens published to server',
},
},
'*',
);
} else {
responses.forEach(async (response) => {
const responseJson = await response.json();
// nosemgrep
parent.postMessage(
{
pluginMessage: {
type: 'error',
text: `⛔️ ${responseJson.message}`,
},
const responseJson = await response.json();
// nosemgrep
parent.postMessage(
{
pluginMessage: {
type: 'error',
text: `⛔️ ${responseJson.message}`,
},
'*',
);
});
},
'*',
);
}
} catch (error: any) {
throw new Error(error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ import '../styles/ui.css';
// eslint-disable-next-line import/extensions
import 'figma-plugin-ds/dist/figma-plugin-ds.css';
import { uploadTokens } from '../api/api';
import type { TokenType } from '../api/api';

const App = (): ReactElement => {
const [themeColorTokens, setThemeColorTokens] = useState({});
const [globalColorTokens, setGlobalColorTokens] = useState({});
const [personalAccessToken, setPersonalAccessToken] = useState('');
const tokenType = React.useRef<TokenType>();

const handlePersonalAccessTokenChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
setPersonalAccessToken(event.target.value);
Expand All @@ -19,9 +22,10 @@ const App = (): ReactElement => {
repoName: 'blade',
workflowFileName: 'blade-tokens-upload.yml',
personalAccessToken,
tokens: themeColorTokens,
colorTokens: tokenType.current === 'themeColorTokens' ? themeColorTokens : globalColorTokens,
tokenType: tokenType.current,
});
}, [themeColorTokens, personalAccessToken]);
}, [themeColorTokens, globalColorTokens, personalAccessToken]);

const onCancel = React.useCallback(() => {
// nosemgrep
Expand All @@ -32,7 +36,11 @@ const App = (): ReactElement => {
window.onmessage = (event) => {
const { type, data } = event.data.pluginMessage;
if (type === 'export-theme-color-tokens') {
tokenType.current = 'themeColorTokens';
setThemeColorTokens(data);
} else if (type === 'export-global-color-tokens') {
tokenType.current = 'globalColorTokens';
setGlobalColorTokens(data);
}
};
}, []);
Expand Down
File renamed without changes.
File renamed without changes.
20 changes: 20 additions & 0 deletions packages/plugin-figma-token-publisher/src/plugin/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import makeGlobalColorTokens from './makeGlobalColorTokens';
import makeThemeColorTokens from './makeThemeColorTokens';
import makeDevTokenNames from './makeDevTokenNames';
import showNotification from './showNotification';
figma.showUI(__html__, { visible: false, width: 350, height: 250 });

console.log(figma.command);

if (figma.command === 'globalColorTokens') {
makeGlobalColorTokens();
} else if (figma.command === 'themeColorTokens') {
makeThemeColorTokens();
} else if (figma.command === 'devTokenNames') {
makeDevTokenNames();
}

figma.ui.onmessage = (message: any): void => {
showNotification({ figma, type: message.type, text: message.text });
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import showNotification from './showNotification';

const makeDevTokenNames = (): void => {
const variables = figma.variables.getLocalVariables();
variables.forEach((variable) => {
variable.setVariableCodeSyntax('WEB', variable.name.replace(/\//g, '.'));
});
showNotification({
figma,
type: 'information',
text: '✅ Dev friendly token names generated!',
});
};

export default makeDevTokenNames;
Loading

0 comments on commit a426e3a

Please sign in to comment.