Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: export svg only #2

Merged
merged 2 commits into from
Mar 13, 2024
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
1,528 changes: 1,392 additions & 136 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@
]
},
"devDependencies": {
"@auto-it/conventional-commits": "10.37.1",
"@auto-it/npm": "10.37.1",
"@auto-it/conventional-commits": "11.1.1",
"@auto-it/npm": "11.1.1",
"@commitlint/cli": "17.0.2",
"@commitlint/config-conventional": "17.0.2",
"auto": "10.37.1",
"auto": "11.1.1",
"husky": "8.0.1",
"lerna": "5.0.0",
"lint-staged": "10.5.4",
Expand Down
64 changes: 10 additions & 54 deletions packages/icon-export-ui/src/app/components/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import prettier from 'prettier/standalone';
import type { Options } from 'prettier';

import { FilesPayloadResponse, IconComponents, IconPayload } from '../../types';
import { getIconAsset, getIconComponent, getIconSource, getIndexSource, getIconCategories } from '../../source';
import { getIconCategories, getIconSvg } from '../../source';
import { getFilesSource } from '../api/githubFilesFetcher';

const prettierSetting: Options = {
Expand All @@ -22,90 +22,46 @@ const prettierSetting: Options = {

export const prettify = (source: string) => prettier.format(source, prettierSetting);

// Эскпортируем svg и информацию по категориям
export const getFilesPath = (iconName?: string, iconSize?: number) => ({
iconSourceExport: 'packages/plasma-icons/src/scalable/index.ts',
iconSourceComponent: 'packages/plasma-icons/src/scalable/Icon.tsx',
iconSourceImport16: 'packages/plasma-icons/src/scalable/Icon.assets.16/index.ts',
iconSourceImport24: 'packages/plasma-icons/src/scalable/Icon.assets.24/index.ts',
iconSourceImport36: 'packages/plasma-icons/src/scalable/Icon.assets.36/index.ts',
iconAsset: `packages/plasma-icons/src/scalable/Icon.assets.${iconSize}/${iconName}.tsx`,
iconComponent: `packages/plasma-icons/src/scalable/Icons/Icon${iconName}.tsx`,
iconSvgAsset: `packages/plasma-icons/src/scalable/Icon.svg.${iconSize}/${iconName}.svg`,
});

export const getFilesPayload = (iconsMetaData: IconPayload[], ...args: string[]): FilesPayloadResponse => {
let [iconSourceExport, iconSourceComponent, iconSourceImport16, iconSourceImport24, iconSourceImport36] = args;
let [iconSourceComponent] = args;

const iconsComponents = iconsMetaData.map(({ size, name = 'IconName', category, svg }) => {
iconSourceExport = getIndexSource(iconSourceExport, name);

if (size === 16) {
iconSourceImport16 = getIconSource(iconSourceImport16, name);
}
if (size === 24) {
iconSourceImport24 = getIconSource(iconSourceImport24, name);
}
if (size === 36) {
iconSourceImport36 = getIconSource(iconSourceImport36, name);
}

iconSourceComponent = getIconCategories(iconSourceComponent, name, size, category);
iconSourceComponent = getIconCategories(iconSourceComponent, name, category);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а точно не надо разбивать на размеры? Пока что у нас только в 24 доступны, но в будущем (насколько я понимаю) будут и остальные. Как они в таком случае будут генериться?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а здесь это уже не нужно. У нас получается теперь так, что есть 3 папки(в данный момент только 1 с 24 размером), куда добавляются иконки в формате svg. Это внутри getFlatIconFiles через size как раз происходит


return {
iconSize: size,
iconName: name,
iconAsset: prettify(getIconAsset(svg, name)),
iconComponent: prettify(getIconComponent(name)),
iconSvgAsset: getIconSvg(svg),
};
});

return {
iconsComponents,
iconSourceExport,
iconSourceComponent,
iconSourceImport16,
iconSourceImport24,
iconSourceImport36,
};
};

export const getGitHubData = async (token?: string, owner = 'salute-developers', repo = 'plasma') =>
getFilesSource(
owner,
repo,
[
getFilesPath().iconSourceExport,
getFilesPath().iconSourceComponent,
getFilesPath().iconSourceImport16,
getFilesPath().iconSourceImport24,
getFilesPath().iconSourceImport36,
],
token,
);
getFilesSource(owner, repo, [getFilesPath().iconSourceComponent], token);

export const getFlatIconFiles = (iconsComponents: IconComponents[]) =>
iconsComponents.reduce((acc: Record<string, string>, { iconAsset, iconComponent, iconName, iconSize }) => {
acc[getFilesPath(iconName).iconComponent] = iconComponent;
acc[getFilesPath(iconName, iconSize).iconAsset] = iconAsset;
iconsComponents.reduce((acc: Record<string, string>, { iconSvgAsset, iconName, iconSize }) => {
acc[getFilesPath(iconName, iconSize).iconSvgAsset] = iconSvgAsset;

return acc;
}, {});

export const getFilesTree = ({
iconSourceExport,
iconSourceComponent,
iconSourceImport16,
iconSourceImport24,
iconSourceImport36,
iconsComponents,
}: FilesPayloadResponse) => {
export const getFilesTree = ({ iconSourceComponent, iconsComponents }: FilesPayloadResponse) => {
const iconFiles = getFlatIconFiles(iconsComponents);

return {
[getFilesPath().iconSourceExport]: iconSourceExport,
[getFilesPath().iconSourceComponent]: iconSourceComponent,
[getFilesPath().iconSourceImport16]: iconSourceImport16,
[getFilesPath().iconSourceImport24]: iconSourceImport24,
[getFilesPath().iconSourceImport36]: iconSourceImport36,
...iconFiles,
};
};
2 changes: 1 addition & 1 deletion packages/icon-export-ui/src/app/hooks/useGithubAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const FETCH_DELAY = 1_500;
* onGetToken - метод для получения токена
*/
export const useGithubAuth = () => {
const [token, setToken] = useState<string | undefined>();
const [token, setToken] = useState<string | undefined>(); // сюда можно вставить свой собтвенный токен

const onSetToken = useCallback((value?: string) => setToken(value), []);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export const useRunGithubPRProcess = ({ owner, repo, branchName }: RunProcessGit

const withMetaData = saveMetaData(octokit, owner, repo);

// закомментить 0, 6, 7 step для добавления в существующую ветку
if (branchName !== 'master' && branchName !== 'dev') {
setStep(0);
await withMetaData(createBranch)(branchName);
Expand Down
50 changes: 0 additions & 50 deletions packages/icon-export-ui/src/source/iconAsset.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,3 @@
import { camelize, compose, removeLineBreak } from '../utils';

const getSvgContent = (source: string) => (/<svg(.*?)>(.*?)<\/svg>/gm.exec(source) || [])[2];

const getViewBox = (source: string) => (/viewBox="(.*?)"/gm.exec(source) || [])[1];

const removeFillOpacity = (source: string) => source.replace(/fill-opacity="(.*?)"/gm, '');

const setFillCurrentColor = (source: string) => source.replace(/fill="(.*?)"/gm, 'fill="currentColor"');

const convertCSSProperty = (source: string) =>
source.replace(
/([a-zA-Z-]*):(.*)/g,
(...match) => `${camelize(match[1])}: ${Number.isNaN(Number(match[2])) ? `'${match[2]}'` : match[2]}`,
);

const getCSSProperties = (source: string) => source.split(';').map(convertCSSProperty).join(',');

const convertInlineStyleToObject = (source: string) =>
source.replace(/style="(.*?)"/gm, (_, group) => `style={{ ${getCSSProperties(group)} }}`);

const camelizeAttributes = (source: string) => source.replace(/([\w-]+)=/g, camelize);

/**
* Здесь экспортируется svg иконки.
*/
Expand All @@ -31,30 +8,3 @@ export const getExportSvg = async (selection: SceneNode) => {

return String.fromCharCode.apply(null, Array.from(svgSource));
};

/**
* Функция генерации файла `/Icon.assets/<Name>.tsx`. Здесь экспортируется иконка из figma
* и возвращается svg компонент иконки.
*/
export default (source: string, iconName: string) => {
const viewBox = getViewBox(source);
const svgContent = compose(
removeLineBreak,
getSvgContent,
setFillCurrentColor,
removeFillOpacity,
convertInlineStyleToObject,
camelizeAttributes,
)(source);

return `import React from 'react';

import { IconProps } from '../IconRoot';

export const ${iconName}: React.FC<IconProps> = (props) => (
<svg width="100%" viewBox="${viewBox}" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
${svgContent}
</svg>
);
`;
};
13 changes: 4 additions & 9 deletions packages/icon-export-ui/src/source/iconCategories.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { insertString, lowerFirstLetter } from '../utils';

const EXPORT_ICON_SET_OBJECT_LINE = 'interface Props';
const CATEGORIES_OBJECT_LINE = 'export const iconSectionsSet = {';

const getStartIndex = (source: string, text: string) => source.search(text);
Expand All @@ -10,7 +9,7 @@ const getEndIndex = (source: string, index: number) => source.substring(index).s
const getCategoryEndIndex = (source: string, index: number) => source.substring(index).search(' },');

const addToIconCategory = (source: string, index: number, iconName: string) =>
insertString(source, index, ` ${lowerFirstLetter(iconName)}: ${iconName},\n`);
insertString(source, index, ` ${lowerFirstLetter(iconName)}: '${iconName}',\n`);

const addToCategories = (source: string, start: number, iconName: string, category: string) => {
let newSource = source;
Expand All @@ -35,20 +34,16 @@ const createIconCategories = (source: string, index: number) =>
const createIconCategory = (source: string, index: number, category: string) =>
insertString(source, index, ` ${category}: {\n },\n`);

const getIconImport = (iconName: string, size: number) =>
`import { ${iconName} } from './Icon.assets.${size}/${iconName}';\n`;

/**
* Функция модификации файла `/Icon.tsx`. Здесь вставляется сгенерированный импорт иконки,
* и добавляется её компонент в список иконок по категориям
*/
export default (source: string, iconName: string, size: number, category: string) => {
if (source.includes(`{ ${iconName} }`)) {
export default (source: string, iconName: string, category: string) => {
if (source.includes(`'${iconName}'`)) {
return source;
}

const index = source.search(EXPORT_ICON_SET_OBJECT_LINE) - 1;
let newSource = insertString(source, index, getIconImport(iconName, size));
let newSource = source;

let startIndexCategories = getStartIndex(newSource, CATEGORIES_OBJECT_LINE);
if (startIndexCategories === -1) {
Expand Down
14 changes: 0 additions & 14 deletions packages/icon-export-ui/src/source/iconComponent.ts

This file was deleted.

30 changes: 0 additions & 30 deletions packages/icon-export-ui/src/source/iconSource.ts

This file was deleted.

7 changes: 7 additions & 0 deletions packages/icon-export-ui/src/source/iconSvg.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* Функция генерации файла `/Icon.svg.24/<Name>.svg`. Здесь экспортируется иконка из figma
* и возвращается svg компонент иконки.
*/
export default (source: string) => {
return `${source}`;
};
5 changes: 1 addition & 4 deletions packages/icon-export-ui/src/source/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
export { default as getIconSource } from './iconSource';
export { default as getIndexSource } from './indexSource';
export { default as getIconAsset } from './iconAsset';
export { default as getIconComponent } from './iconComponent';
export { default as getIconSvg } from './iconSvg';
export { default as getIconCategories } from './iconCategories';
18 changes: 0 additions & 18 deletions packages/icon-export-ui/src/source/indexSource.ts

This file was deleted.

7 changes: 1 addition & 6 deletions packages/icon-export-ui/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,13 @@ export interface TokenPayloadRequest {
export type TokenPayloadResponse = TokenPayloadRequest;

export interface IconComponents {
iconAsset: string;
iconComponent: string;
iconName: string;
iconSize: number;
iconSvgAsset: string;
}

export interface FilesPayloadResponse {
iconSourceExport: string;
iconSourceComponent: string;
iconSourceImport16: string;
iconSourceImport24: string;
iconSourceImport36: string;
iconsComponents: IconComponents[];
}

Expand Down
Loading