From f756c56311383dfe6f6d32d718fa04c3f63cea7c Mon Sep 17 00:00:00 2001 From: Daniil Suvorov Date: Thu, 12 Jan 2023 17:39:40 +0300 Subject: [PATCH 1/2] style: add @vkontakte/prettier-config --- .eslintrc.js | 41 ++-- .github/PULL_REQUEST_TEMPLATE.md | 13 +- .github/dependabot.yml | 22 +-- .github/workflows/publish_release.yml | 4 +- .gitignore | 1 + .prettierrc | 9 - .prettierrc.js | 1 + CHANGELOG.OLD.md | 180 +++++++++-------- CONTRIBUTING.md | 118 ++++++------ README.md | 177 +++++++++-------- docs/public/index.html | 30 +-- docs/src/App.tsx | 2 +- docs/src/components/layouts/Main.tsx | 4 +- .../layouts/shared/Header/Header.tsx | 15 +- .../layouts/shared/Navigation/Navigation.tsx | 8 +- .../TokensActions/TokensActions.content.tsx | 10 +- .../Tokens/TokensActions/TokensActions.css | 4 +- .../Tokens/TokensActions/TokensActions.tsx | 33 +--- .../Tokens/TokensContent/TokensContent.css | 20 +- .../TokensContent/TokensContent.helpers.ts | 16 +- .../Tokens/TokensContent/TokensContent.tsx | 34 ++-- .../components/ColorCircle/ColorCircle.tsx | 6 +- .../components/TokensContentValue.helpers.ts | 14 +- .../components/TokensContentValue.tsx | 39 ++-- .../components/pages/Tokens/TokensHeader.tsx | 22 +-- docs/src/components/pages/Tokens/index.ts | 6 +- docs/src/index.tsx | 2 +- docs/src/pages/Tokens.tsx | 37 ++-- docs/src/shared/content/icons.ts | 2 +- docs/src/shared/utils/helpers.ts | 2 +- docs/src/shared/utils/typeGuards.ts | 8 +- docs/src/styles/index.css | 4 +- docs/tsconfig.json | 2 +- docs/webpack/webpack.client.js | 8 +- package.json | 1 + ...mpileBreakpointsCssVarsDeclaration.test.ts | 29 +-- .../compileBreakpointsCssVarsDeclaration.ts | 35 ++-- .../cssVars/helpers/accumulateValues.ts | 38 ++-- .../helpers/findViewportByAdaptivityState.ts | 12 +- .../compilers/cssVars/helpers/getVarString.ts | 2 +- .../compileGetDeclarationString.test.ts | 181 ++++++++---------- .../jsUtils/compileGetDeclarationString.ts | 20 +- .../compilers/docs/__test__/testBaseTheme.ts | 2 +- .../docs/__test__/testRecursiveReexport.ts | 2 +- .../compilers/docs/__test__/testTheme.ts | 4 +- .../compilers/docs/compileDocsJSON.test.ts | 7 +- src/build/compilers/docs/compileDocsJSON.ts | 34 +--- src/build/compilers/index.ts | 133 ++++--------- src/build/compilers/json/compileJSON.test.ts | 2 +- src/build/compilers/json/compileJSON.ts | 2 +- .../structJSON/compileStructJSON.test.ts | 2 +- .../compilers/structJSON/compileStructJSON.ts | 5 +- .../compilers/styles/compileStyles.test.ts | 65 +++---- src/build/compilers/styles/compileStyles.ts | 33 ++-- .../styles/helpers/tokenProcessors.ts | 91 +++------ .../styles/helpers/tokenRecognition.ts | 17 +- .../compilers/ts/compileTypeScript.test.ts | 5 +- src/build/compilers/ts/compileTypeScript.ts | 4 +- src/build/expandTheme.test.ts | 2 +- src/build/expandTheme.ts | 24 +-- src/build/helpers/capitalize.test.ts | 4 +- src/build/helpers/convertCamelToSnake.test.ts | 10 +- src/build/helpers/convertCamelToSnake.ts | 4 +- src/build/helpers/cssHelpers.test.ts | 2 +- src/build/helpers/cssHelpers.ts | 28 +-- src/build/helpers/flatifyTheme.test.ts | 12 +- src/build/helpers/flatifyTheme.ts | 12 +- src/build/helpers/getAllButColors.test.ts | 2 +- src/build/helpers/getAllButColors.ts | 5 +- src/build/helpers/getAllButSizes.test.ts | 2 +- src/build/helpers/getAllButSizes.ts | 5 +- .../getGradientPointsFromColor.test.ts | 2 +- .../helpers/getGradientPointsFromColor.ts | 4 +- src/build/helpers/getOnlyColors.test.ts | 2 +- src/build/helpers/getStateFunctions.test.ts | 20 +- src/build/helpers/getStateFunctions.ts | 19 +- src/build/helpers/overrideOnlyNeeded.test.ts | 14 +- src/build/helpers/overrideOnlyNeeded.ts | 7 +- src/build/helpers/replacePropDeep.test.ts | 6 +- src/build/helpers/replacePropDeep.ts | 27 ++- src/build/helpers/tokenHelpers.test.ts | 4 +- src/build/helpers/tokenHelpers.ts | 8 +- src/build/helpers/unCamelcasify.test.ts | 6 +- src/build/index.ts | 48 ++--- src/build/snapthots.test.ts | 8 +- .../createPseudoRootFromCssVars.test.ts | 50 ++--- .../createPseudoRootFromCssVars.ts | 9 +- .../customMedia/customMedia.test.ts | 23 +-- .../customMedia/customMedia.ts | 16 +- .../expandColors/expandColors.test.ts | 2 +- .../expandColors/expandColors.ts | 32 ++-- .../expandColors/mixColors.test.ts | 4 +- .../themeProcessors/expandColors/mixColors.ts | 2 +- .../expandColors/overlayColors.test.ts | 25 +-- .../expandColors/overlayColors.ts | 8 +- .../extractCssVarsStrict.test.ts | 35 +--- .../extractCssVarsStrict.ts | 6 +- .../extractGeneralTokens.test.ts | 2 +- .../extractGeneralTokens.ts | 2 +- .../extractVarsNames/extractVarsNames.test.ts | 37 ++-- .../extractVarsNames/extractVarsNames.ts | 28 ++- .../extractViewports/extractViewports.test.ts | 22 +-- .../extractViewports/extractViewports.ts | 17 +- .../pixelifyValues/pixelifyValues.test.ts | 24 +-- .../pixelifyValues/pixelifyValues.ts | 6 +- src/interfaces/general/animations/index.ts | 2 +- src/interfaces/general/colors/index.ts | 8 +- src/interfaces/general/elevation/index.ts | 2 +- src/interfaces/general/index.ts | 62 +++--- src/interfaces/general/tools/cssVars.ts | 18 +- src/interfaces/general/tools/customMedia.ts | 4 +- src/interfaces/general/tools/index.ts | 2 +- src/interfaces/general/tools/utils.ts | 11 +- src/interfaces/general/typography/index.ts | 2 +- src/interfaces/namespaces/paradigm/index.ts | 34 ++-- src/interfaces/themes/calendar/index.ts | 18 +- src/interfaces/themes/calendarDark/index.ts | 3 +- src/interfaces/themes/cloudDark/index.ts | 2 +- src/interfaces/themes/home/index.ts | 3 +- src/interfaces/themes/homeDark/index.ts | 2 +- src/interfaces/themes/media/index.ts | 15 +- src/interfaces/themes/mediaDark/index.ts | 2 +- src/interfaces/themes/mycom/index.ts | 20 +- src/interfaces/themes/octavius/index.ts | 13 +- .../themes/octaviusCompact/index.ts | 3 +- .../themes/octaviusCompactDark/index.ts | 3 +- src/interfaces/themes/otvet/index.ts | 6 +- src/interfaces/themes/otvetDark/index.ts | 2 +- src/interfaces/themes/paradigmBase/index.ts | 3 +- .../themes/paradigmBaseDark/index.ts | 3 +- src/interfaces/themes/pharma/index.ts | 12 +- src/interfaces/themes/promo/index.ts | 13 +- src/interfaces/themes/pulse/index.ts | 31 +-- src/interfaces/themes/pulseDark/index.ts | 2 +- src/interfaces/themes/search/index.ts | 9 +- src/interfaces/themes/vkBase/index.ts | 2 +- src/interfaces/themes/vkBaseDark/index.ts | 2 +- src/lint/index.test.ts | 4 +- src/lint/index.ts | 22 +-- src/lint/lint.test.ts | 2 +- src/lint/rules/alphaMismatch.test.ts | 2 +- src/lint/rules/alphaMismatch.ts | 16 +- src/lint/rules/index.ts | 4 +- src/themeDescriptions/base/paradigm.ts | 18 +- src/themeDescriptions/base/vk.ts | 42 ++-- .../common/colors/projectColors.ts | 2 +- .../common/colors/socialColors.ts | 2 +- .../common/fontSizes/index.ts | 9 +- src/themeDescriptions/common/helpers/index.ts | 2 +- src/themeDescriptions/common/index.ts | 10 +- src/themeDescriptions/descriptions.ts | 2 +- src/themeDescriptions/index.ts | 43 ++--- .../themes/calendar/index.ts | 17 +- src/themeDescriptions/themes/calls/index.ts | 11 +- src/themeDescriptions/themes/cloud/index.ts | 26 +-- src/themeDescriptions/themes/home/index.ts | 4 +- src/themeDescriptions/themes/media/index.ts | 12 +- src/themeDescriptions/themes/mycom/index.ts | 10 +- .../themes/octavius/index.ts | 87 +++------ .../themes/octaviusCompact/index.ts | 12 +- .../themes/octaviusVK/index.ts | 125 +++++------- src/themeDescriptions/themes/otvet/index.ts | 14 +- src/themeDescriptions/themes/pharma/index.ts | 6 +- src/themeDescriptions/themes/promo/index.ts | 4 +- src/themeDescriptions/themes/pulse/index.ts | 15 +- src/themeDescriptions/themes/search/index.ts | 8 +- src/themeDescriptions/themes/todo/index.ts | 8 +- .../themes/vkCom/appearance.test.ts | 2 +- .../themes/vkCom/appearance.ts | 10 +- src/themeDescriptions/themes/vkCom/index.ts | 57 ++---- src/themeDescriptions/themes/vkIOS/index.ts | 11 +- tasks/docs/mergeTokensData.test.ts | 31 ++- tasks/docs/mergeTokensData.ts | 11 +- tasks/docs/prepareTokensData.ts | 21 +- tsconfig.json | 11 +- tsconfig.publish.json | 4 +- tsconfig.tscpaths.json | 19 +- yarn.lock | 5 + 178 files changed, 1301 insertions(+), 1991 deletions(-) delete mode 100644 .prettierrc create mode 100644 .prettierrc.js diff --git a/.eslintrc.js b/.eslintrc.js index e28bbe4a..4d60f672 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,7 +1,4 @@ -const noUnusedVars = [ - 'error', - {ignoreRestSiblings: true, argsIgnorePattern: '^_.*$'}, -]; +const noUnusedVars = ['error', { ignoreRestSiblings: true, argsIgnorePattern: '^_.*$' }]; module.exports = { parser: '@typescript-eslint/parser', @@ -38,14 +35,8 @@ module.exports = { }, rules: { 'no-unused-vars': noUnusedVars, - 'max-lines': [ - 'error', - {max: 1500, skipBlankLines: true, skipComments: true}, - ], - 'max-lines-per-function': [ - 'error', - {max: 110, skipBlankLines: true, skipComments: true}, - ], + 'max-lines': ['error', { max: 1500, skipBlankLines: true, skipComments: true }], + 'max-lines-per-function': ['error', { max: 110, skipBlankLines: true, skipComments: true }], 'no-console': 'off', 'new-cap': [ 'error', @@ -53,23 +44,15 @@ module.exports = { capIsNewExceptions: ['Deferred', 'Event'], }, ], - 'spaced-comment': [ - 'error', - 'always', - {markers: ['#region'], exceptions: ['#endregion']}, - ], - 'lines-between-class-members': [ - 'error', - 'always', - {exceptAfterSingleLine: true}, - ], + 'spaced-comment': ['error', 'always', { markers: ['#region'], exceptions: ['#endregion'] }], + 'lines-between-class-members': ['error', 'always', { exceptAfterSingleLine: true }], 'no-prototype-builtins': 'off', 'no-throw-literal': 'off', 'prefer-promise-reject-errors': 'off', 'no-shadow': 'off', 'prefer-template': 'error', 'require-await': 'error', - curly: 'error', + 'curly': 'error', '@typescript-eslint/class-name-casing': 'off', 'no-useless-constructor': 'off', // see @typescript-eslint/no-useless-constructor @@ -87,9 +70,9 @@ module.exports = { '@typescript-eslint/no-var-requires': 'off', '@typescript-eslint/naming-convention': [ 'warn', - {selector: 'default', format: ['camelCase']}, + { selector: 'default', format: ['camelCase'] }, - {selector: 'variableLike', format: ['camelCase']}, + { selector: 'variableLike', format: ['camelCase'] }, { selector: 'variable', format: ['camelCase', 'UPPER_CASE', 'PascalCase'], @@ -99,7 +82,7 @@ module.exports = { format: ['camelCase'], leadingUnderscore: 'allow', }, - {selector: 'memberLike', format: ['camelCase']}, + { selector: 'memberLike', format: ['camelCase'] }, { selector: 'memberLike', modifiers: ['private'], @@ -107,13 +90,13 @@ module.exports = { leadingUnderscore: 'allow', }, - {selector: 'typeLike', format: ['PascalCase']}, - {selector: 'typeParameter', format: ['PascalCase']}, + { selector: 'typeLike', format: ['PascalCase'] }, + { selector: 'typeParameter', format: ['PascalCase'] }, { selector: 'interface', format: ['PascalCase'], - custom: {regex: '^I[A-Z]', match: false}, + custom: { regex: '^I[A-Z]', match: false }, }, ], '@typescript-eslint/interface-name-prefix': 'off', diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index bb13c072..d9b72592 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,11 +1,12 @@ Перед отправкой этого реквеста на ревью убедитесь, что: -* в вашей ветке работает сборка (`npm run build:local`), -* в вашей ветке проходят тесты (`npm test`), -* в вашей ветке проходит линтер (`npm run lint`), некоторые ошибки можно автоматически поправить с помощью `npm run lint:fix`, -* покрытие тестов не ниже минимального значения, -* если вы вносите изменения в задокументированные части библиотеки, + +- в вашей ветке работает сборка (`npm run build:local`), +- в вашей ветке проходят тесты (`npm test`), +- в вашей ветке проходит линтер (`npm run lint`), некоторые ошибки можно автоматически поправить с помощью `npm run lint:fix`, +- покрытие тестов не ниже минимального значения, +- если вы вносите изменения в задокументированные части библиотеки, ваш pull request содержит обновления документации, -* если вы вносите изменения в сами токены, вы +- если вы вносите изменения в сами токены, вы согласовали их с дизайнерами. [Подробнее о внесении изменений в репозиторий токенов](https://github.com/VKCOM/vkui-tokens/blob/master/CONTRIBUTING.md) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 03514306..61c53b85 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,20 +1,20 @@ version: 2 updates: - - package-ecosystem: "npm" - directory: "/" + - package-ecosystem: 'npm' + directory: '/' schedule: - interval: "daily" + interval: 'daily' allow: - - dependency-type: "direct" + - dependency-type: 'direct' reviewers: - - "VKCOM/vk-sec" - - "VKCOM/vkui-core" - - package-ecosystem: "github-actions" + - 'VKCOM/vk-sec' + - 'VKCOM/vkui-core' + - package-ecosystem: 'github-actions' # Workflow files stored in the # default location of `.github/workflows` - directory: "/" + directory: '/' schedule: - interval: "daily" + interval: 'daily' reviewers: - - "VKCOM/vk-sec" - - "VKCOM/vkui-core" + - 'VKCOM/vk-sec' + - 'VKCOM/vkui-core' diff --git a/.github/workflows/publish_release.yml b/.github/workflows/publish_release.yml index 44d3476c..d4855812 100644 --- a/.github/workflows/publish_release.yml +++ b/.github/workflows/publish_release.yml @@ -21,11 +21,11 @@ jobs: registry-url: https://registry.npmjs.org/ - run: yarn - run: npm run publish:latest - if: "!github.event.release.prerelease" + if: '!github.event.release.prerelease' env: NODE_AUTH_TOKEN: ${{secrets.NPMJS_PUBLISH_TOKEN}} - run: npm run publish:dist - if: "github.event.release.prerelease" + if: 'github.event.release.prerelease' env: NODE_AUTH_TOKEN: ${{secrets.NPMJS_PUBLISH_TOKEN}} diff --git a/.gitignore b/.gitignore index d668f73f..094ea066 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,7 @@ node_modules/ !/tasks/**/*.js !.eslintrc.js !jest.config.js +!.prettierrc.js .yarnclean .DS_Store .idea diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index fa381296..00000000 --- a/.prettierrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "singleQuote": true, - "trailingComma": "all", - "arrowParens": "always", - "useTabs": true, - "bracketSpacing": false, - "tabWidth": 4, - "parser": "typescript" -} diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 00000000..5efb34da --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1 @@ +module.exports = require('@vkontakte/prettier-config').createConfig(); diff --git a/CHANGELOG.OLD.md b/CHANGELOG.OLD.md index 56462077..828c0ba0 100644 --- a/CHANGELOG.OLD.md +++ b/CHANGELOG.OLD.md @@ -1,141 +1,165 @@ # **CHANGELOG (Архивная версия)** ## 4.0.0 -* **Перешли на релизы через [GitHub](https://github.com/VKCOM/vkui-tokens/releases). Все следующие релизы будут описываться там!** + +- **Перешли на релизы через [GitHub](https://github.com/VKCOM/vkui-tokens/releases). Все следующие релизы будут описываться там!** **BREAKING CHANGES** -* Провели рефакторинг дизайн-системы в рамках объединения **VKUI** и **Paradigm**: удалили ненужные, добавили новые, поменяли названия старых. + +- Провели рефакторинг дизайн-системы в рамках объединения **VKUI** и **Paradigm**: удалили ненужные, добавили новые, поменяли названия старых. Изменения можно найти в [таблице](https://docs.google.com/spreadsheets/d/10DBlAGM68KyZ1DHtr-xKy-JDDqrsWaItF67fo7-hOy4/edit#gid=314413476) - -* Изменили формат описания адаптивных токенов: теперь идём не от `viewport` (`touch`,`desktop`), а +- Изменили формат описания адаптивных токенов: теперь идём не от `viewport` (`touch`,`desktop`), а от состояний самого токена: `regular`, `compact`, `large` и т.д. Указывать состояния, отличные от `regular` нужно указывать тогда, и только тогда, когда они действительно отличаются. - + Для проектов использующих уже медиаквери и вьюпорты (paradigm-проекты) при генерации сделан маппинг с помощью переменной `breakpoints`. - -* Переписали старую генерацию `scss`, `css`, `less`, `styl` форматов с нуля. Теперь покрыли это **автотестами**: можно зайти в тесты и посмотреть как в каждом формате обробатывается каждый вид переменной - _цвет, групповая переменная (шрифты), адаптивная, медиа_ и так далее. + +- Переписали старую генерацию `scss`, `css`, `less`, `styl` форматов с нуля. Теперь покрыли это **автотестами**: можно зайти в тесты и посмотреть как в каждом формате обробатывается каждый вид переменной + _цвет, групповая переменная (шрифты), адаптивная, медиа_ и так далее. Теперь поддержка будет прозрачнее и добавление новых конструкций в процессоры не будет проблемой. - - Важно: во время переписи и из-за того, что формат адаптивных переменных сильно поменялся, то подход с ними в процессорах css тоже. + + Важно: во время переписи и из-за того, что формат адаптивных переменных сильно поменялся, то подход с ними в процессорах css тоже. Теперь везде, кроме нативного css, переменные не переопределяются автоматически через @media-query. Чтобы эту мехнику получить — нужно css файлы из `themes/${themName}/cssVars/declarations`. -* Сделали единый базовый интерфейс дизайн-системы и описали в нём тему для `paradigm` (светлый и тёмный) и `vk` (пока только светлый). -* Сделали расширение базового интерфейса для Paradigm тем и портальной специфики. -* Порефакторили подход к генерации форматов: - * Экспортируем в пакете в папку `build` все функции с помощью которых можно собрать любой вид темы. Теперь можно по описанию темы собрать её - где-то в своём проекте, а не пользоваться только готовыми отсюда - * Сделали так, чтобы любой формат темы можно было собрать хоть из одной переменной. Теперь можно легко иметь в проекте локальные переменные не связанные с дизайн-системой, но в привычном формате. -* Изменили файловую структуру при экспорте библиотеки — теперь вместо того чтобы все собранные темы попадали в `root` + +- Сделали единый базовый интерфейс дизайн-системы и описали в нём тему для `paradigm` (светлый и тёмный) и `vk` (пока только светлый). +- Сделали расширение базового интерфейса для Paradigm тем и портальной специфики. +- Порефакторили подход к генерации форматов: + - Экспортируем в пакете в папку `build` все функции с помощью которых можно собрать любой вид темы. Теперь можно по описанию темы собрать её + где-то в своём проекте, а не пользоваться только готовыми отсюда + - Сделали так, чтобы любой формат темы можно было собрать хоть из одной переменной. Теперь можно легко иметь в проекте локальные переменные не связанные с дизайн-системой, но в привычном формате. +- Изменили файловую структуру при экспорте библиотеки — теперь вместо того чтобы все собранные темы попадали в `root` , они попадают в `root/themes`. Это важно, поскольку теперь в экспорте ещё есть разные полезные функции помимо тем. - -* Поработали над тёмной темой сделали основную базовую тёмную тему и отдельно темные цвета -* Удалили `flat` темы -* Удалили `subthemes` везде -* название пакета `@vkontakte/vkui-tokens` +- Поработали над тёмной темой сделали основную базовую тёмную тему и отдельно темные цвета +- Удалили `flat` темы +- Удалили `subthemes` везде +- название пакета `@vkontakte/vkui-tokens` ## 3.2.0 -* Добавили темы `octaviusDark` и `homeDark` -* Сделали правки в типографике в `calendar` -* Добавили экспорт объявления цветов css-vars в js и в виде строки. + +- Добавили темы `octaviusDark` и `homeDark` +- Сделали правки в типографике в `calendar` +- Добавили экспорт объявления цветов css-vars в js и в виде строки. ## 3.1.0 -* Обновили тему `otvet`, добавили тёмный вариант `otvetDark` -* Аккуратно поправили вывод в генерации стилей (убрали ненужные строчки) + +- Обновили тему `otvet`, добавили тёмный вариант `otvetDark` +- Аккуратно поправили вывод в генерации стилей (убрали ненужные строчки) ## 3.0.0 -* Добавили новый вид темы `cssVars` она объявляет переменные как нативные css-custom-properties в `cssVars/${themeName}/declarations/index.css`. Там сразу сделаны изменения переменных по breakpoints, а также добавлены специальные классы для форсированного включения нужного брейкпоинта. Демо можно найти [тут](demo/example-adaptive-css-vars-theme.html); -* Также сделали компиляцию объекта темы (в `cssVars/${themeName}/theme/index`) (`ts`, `js`, `json` форматы) в где каждая переменная представлена как `{name: '--paradigm--x1', value: 'var(--paradigm--x1, 4px)'}` -* Добавили тестирование снапшотами на каждую тему (теперь любое изменение в теме вызовет падение тестов с полным дифом каждой переменной, нужно будет апрувить изменения, обновляя снапшоты (`npm t -- -u`)) -* Добавили расчёт тестового покрытия (`coverage`) в репозитории -* Для удобной миграции на `cssVars` тему в `${themeName}/cssVars/theme/fallbacks` добавлены темы, процессоров, которые ссылаются на уже нативные CSS-переменные. То есть `$size-base: 4px` -> `$size-base: var(--paradigm--size_base, 4px)` -* js,json,ts добавили поле `themeType: 'root' | 'flat' | 'pixelify' | 'cssVars'`, чтобы в runtime понимать, с каким видом темы сейчас работаем -* В `${themeName}/cssVars/declarations` помимо `index.css` есть также файлы `onlyRoot.css` (только рутовое определение переменных без, адаптивности), а также `modern.css` (используются нативные mixin ы в css (читай про @apply)) -* **BREAKING CHANGES**: удалили генерацию `css` файлов во всех (они были невалидные, поэтому врятли кто-то ими польовался), кроме `cssVars` видах тем. Теперь чистый нативный css можно заимпортить тут: `cssVars/${themeName}/declarations/index.css`. -* **BREAKING CHANGES**: в темах, в адаптивных переменных больше нет `default` состояния, вместо этого теперь там указан конкретный `viewport` (например, `touch` или `desktopS`). Это было сделано, так как default был по-сути алисом на `touch` viewport, что вызывало неконсистентые состояния, при использовании темы без `touch` брейкпоинта. Это нам дало следующие возможности: теперь можно создавать темы с любым подножеством брейкпоинтов, например: `['desktopS, 'desktopM']` - будет тема из двух десктопных брейкпоинтов. На самом деле это должно затронуть только описание тем, а также типы и `ts`, `js`, `json` форматы. Выходные файлы других форматов не изменились. `flat` темы всех форматов остались прежними. -* **BREAKING CHANGES**: подняли мажор `csstype` (единственная `prod` зависимость для `npm` у токенов). Теперь `3.0.7`. (Может вызывать нюансы в типах при обновлении). +- Добавили новый вид темы `cssVars` она объявляет переменные как нативные css-custom-properties в `cssVars/${themeName}/declarations/index.css`. Там сразу сделаны изменения переменных по breakpoints, а также добавлены специальные классы для форсированного включения нужного брейкпоинта. Демо можно найти [тут](demo/example-adaptive-css-vars-theme.html); +- Также сделали компиляцию объекта темы (в `cssVars/${themeName}/theme/index`) (`ts`, `js`, `json` форматы) в где каждая переменная представлена как `{name: '--paradigm--x1', value: 'var(--paradigm--x1, 4px)'}` +- Добавили тестирование снапшотами на каждую тему (теперь любое изменение в теме вызовет падение тестов с полным дифом каждой переменной, нужно будет апрувить изменения, обновляя снапшоты (`npm t -- -u`)) +- Добавили расчёт тестового покрытия (`coverage`) в репозитории +- Для удобной миграции на `cssVars` тему в `${themeName}/cssVars/theme/fallbacks` добавлены темы, процессоров, которые ссылаются на уже нативные CSS-переменные. То есть `$size-base: 4px` -> `$size-base: var(--paradigm--size_base, 4px)` +- js,json,ts добавили поле `themeType: 'root' | 'flat' | 'pixelify' | 'cssVars'`, чтобы в runtime понимать, с каким видом темы сейчас работаем +- В `${themeName}/cssVars/declarations` помимо `index.css` есть также файлы `onlyRoot.css` (только рутовое определение переменных без, адаптивности), а также `modern.css` (используются нативные mixin ы в css (читай про @apply)) +- **BREAKING CHANGES**: удалили генерацию `css` файлов во всех (они были невалидные, поэтому врятли кто-то ими польовался), кроме `cssVars` видах тем. Теперь чистый нативный css можно заимпортить тут: `cssVars/${themeName}/declarations/index.css`. +- **BREAKING CHANGES**: в темах, в адаптивных переменных больше нет `default` состояния, вместо этого теперь там указан конкретный `viewport` (например, `touch` или `desktopS`). Это было сделано, так как default был по-сути алисом на `touch` viewport, что вызывало неконсистентые состояния, при использовании темы без `touch` брейкпоинта. Это нам дало следующие возможности: теперь можно создавать темы с любым подножеством брейкпоинтов, например: `['desktopS, 'desktopM']` - будет тема из двух десктопных брейкпоинтов. На самом деле это должно затронуть только описание тем, а также типы и `ts`, `js`, `json` форматы. Выходные файлы других форматов не изменились. `flat` темы всех форматов остались прежними. +- **BREAKING CHANGES**: подняли мажор `csstype` (единственная `prod` зависимость для `npm` у токенов). Теперь `3.0.7`. (Может вызывать нюансы в типах при обновлении). ## 2.6.1 -* Для календарной темы обновили `thumbnailColor` + +- Для календарной темы обновили `thumbnailColor` ## 2.6.0 -* В основные темы перенесены переменные из subthemes - `colorBgPlaceholder` (цвет подложки) и `colorIconAccent` (цвет акцентированной иконки) -* Добавлен токен `colorBgPromo` для задания цвета фона промо элементов и панелей (плашек) + +- В основные темы перенесены переменные из subthemes - `colorBgPlaceholder` (цвет подложки) и `colorIconAccent` (цвет акцентированной иконки) +- Добавлен токен `colorBgPromo` для задания цвета фона промо элементов и панелей (плашек) ## 2.5.0 -* добавили переменную `sizeControlCheckBorderRadius` — _Радиус скругления чекбоксов_ -* исправили наследование `calendar` темы от octavius (больше не попадают переменные из подтем) -* удалили подтемы из календарной темы, вместо этого создали новую тему `calendarDark` с корректным интерфейсом + +- добавили переменную `sizeControlCheckBorderRadius` — _Радиус скругления чекбоксов_ +- исправили наследование `calendar` темы от octavius (больше не попадают переменные из подтем) +- удалили подтемы из календарной темы, вместо этого создали новую тему `calendarDark` с корректным интерфейсом ## 2.4.0 -* добавили тему для Облака `cloud` -* добавили переменные (и их описания) во все темы `fontFamilyAccent`, `fontWeightAccent`, `fontWeightAccentBold` -* сделали чуть более корректное наследование тем от `octavius` (чтобы не попадали в тему переменные subthemes, которые deprecated) -* Исправили генерацию customMedia (убрали перекрытие breakpoints) + +- добавили тему для Облака `cloud` +- добавили переменные (и их описания) во все темы `fontFamilyAccent`, `fontWeightAccent`, `fontWeightAccentBold` +- сделали чуть более корректное наследование тем от `octavius` (чтобы не попадали в тему переменные subthemes, которые deprecated) +- Исправили генерацию customMedia (убрали перекрытие breakpoints) ## 2.3.1 -* Изменили скругление кнопок до 8px для календарных тем + +- Изменили скругление кнопок до 8px для календарных тем ## 2.3.0 -* Добавляeтся токен "checkBoxBorderColor" для задания цвета у чекбоксов + +- Добавляeтся токен "checkBoxBorderColor" для задания цвета у чекбоксов ## 2.2.1 -* Добавляются токен "sizePromoArrowWidth" для корректного отображения стрелки в 2kit + +- Добавляются токен "sizePromoArrowWidth" для корректного отображения стрелки в 2kit ## 2.2.0 -* Добавляются токен на размер стрелки тултипа и токен для цвета новостного метатреда + +- Добавляются токен на размер стрелки тултипа и токен для цвета новостного метатреда ## 2.1.0 -* Добавляется генерация мапки со всеми переменными после миксина для SASS-файлов. + +- Добавляется генерация мапки со всеми переменными после миксина для SASS-файлов. ## 2.0.0 -* имя пакета теперь снова `@paradigm/tokens` . `@paradigm/themes` больше никогда публиковаться не будет. -* Добавлен общий интерфейс темы, от которой отнаследованы все остальные темы. -* Добавлен общий интерфейс ОПИСАНИЯ темы. (Теперь создавая тему у вас будет тип, с которым невозможно будет забыть указать что-либо). Непонятно почему недостаточно предыдущего пункта? — скорее всего вы никогда не работали в токенах. -* Процесс преобразования описания темы в полноценную тему полностью выводится из типов. И покрыт автотестами. -* Добавили и настроили линтер -* Настроили CI (проверяем линтер, jest и сборку) -* Добавили функцию хелпер `getStateFunctions`, которая добавит к теме функции, позволяющие динамически создавать `hover`, `active` состояния. + +- имя пакета теперь снова `@paradigm/tokens` . `@paradigm/themes` больше никогда публиковаться не будет. +- Добавлен общий интерфейс темы, от которой отнаследованы все остальные темы. +- Добавлен общий интерфейс ОПИСАНИЯ темы. (Теперь создавая тему у вас будет тип, с которым невозможно будет забыть указать что-либо). Непонятно почему недостаточно предыдущего пункта? — скорее всего вы никогда не работали в токенах. +- Процесс преобразования описания темы в полноценную тему полностью выводится из типов. И покрыт автотестами. +- Добавили и настроили линтер +- Настроили CI (проверяем линтер, jest и сборку) +- Добавили функцию хелпер `getStateFunctions`, которая добавит к теме функции, позволяющие динамически создавать `hover`, `active` состояния. ## 1.18.0 -* Обновили цвет вк по их брендбуку + +- Обновили цвет вк по их брендбуку ## 1.17.0 -* Добавили тему Задач Mail.ru -* Добавили темную тему для календаря + +- Добавили тему Задач Mail.ru +- Добавили темную тему для календаря ## 1.16.1 -* Поправили размеры шрифта в теме `calendar` + +- Поправили размеры шрифта в теме `calendar` ## 1.16.0 -* Добавили переменные `sizeBadge[XS|S|M|L|XL]` + +- Добавили переменные `sizeBadge[XS|S|M|L|XL]` ## 1.15.0 -* добавили переменную paddingControlSelectIcon 
 + +- добавили переменную paddingControlSelectIcon ## 1.14.0 -* добавили переменную colorButtonContrastBg 
 -* добавили переменную colorCategoryToMyself в тему октавиуса + +- добавили переменную colorButtonContrastBg +- добавили переменную colorCategoryToMyself в тему октавиуса ## 1.13.0 -* Обновили цвета с оттенками серого во всех темах -* Обновили тему `home` (Относледовали от `octavius` и добавили токенов) + +- Обновили цвета с оттенками серого во всех темах +- Обновили тему `home` (Относледовали от `octavius` и добавили токенов) ## 1.12.0 -* Добавили в тему календаря шрифт `MailSans` + +- Добавили в тему календаря шрифт `MailSans` ## 1.11.0 -* Обновили значение переменной `colorBgHighlight` `#FFF1AD` -* Настроили корректные тайпинги для этой переменной + +- Обновили значение переменной `colorBgHighlight` `#FFF1AD` +- Настроили корректные тайпинги для этой переменной ## 1.10.0 -* Добавили переменные для ширины и высоты больших кнопок ([описание](https://gitlab.corp.mail.ru/UX/paradigm.tokens/-/blob/master/themes/descriptions.ts#L858-868)) -* Добавили тему `calls` + +- Добавили переменные для ширины и высоты больших кнопок ([описание](https://gitlab.corp.mail.ru/UX/paradigm.tokens/-/blob/master/themes/descriptions.ts#L858-868)) +- Добавили тему `calls` ## 1.9.0 -* Минорное обновление цветов ошибки и саксеса. Утверждено с дизайнерами + +- Минорное обновление цветов ошибки и саксеса. Утверждено с дизайнерами ## 1.8.0 -* Добавили переменную `paddingPopupBase` ([описание](https://gitlab.corp.mail.ru/UX/paradigm.tokens/blob/master/themes/descriptions.ts#L1062)) -* Добавили переменную `paddingPopupHeader` ([описание](https://gitlab.corp.mail.ru/UX/paradigm.tokens/blob/master/themes/descriptions.ts#L1068)) -* Исправили SCSS сборку темы. Заменили классы на `mixin`, корректно обрабатывает desktop/mobile статические переменные. +- Добавили переменную `paddingPopupBase` ([описание](https://gitlab.corp.mail.ru/UX/paradigm.tokens/blob/master/themes/descriptions.ts#L1062)) +- Добавили переменную `paddingPopupHeader` ([описание](https://gitlab.corp.mail.ru/UX/paradigm.tokens/blob/master/themes/descriptions.ts#L1068)) +- Исправили SCSS сборку темы. Заменили классы на `mixin`, корректно обрабатывает desktop/mobile статические переменные. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cfc97326..75a67e21 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,18 +6,19 @@ Чтобы ваши изменения попали в основную ветку (master) нужно, чтобы ваш pull request одобрил кто-то из мейнтейнеров репозитория: -* [@vileven](https://github.com/vileven) -* [@8coon](https://github.com/8coon) -* [@warprobot](https://github.com/warprobot) +- [@vileven](https://github.com/vileven) +- [@8coon](https://github.com/8coon) +- [@warprobot](https://github.com/warprobot) Перед отправкой pull request-а на ревью убедитесь, что: -* в вашей ветке работает сборка (`npm run build:local`), -* в вашей ветке проходят тесты (`npm test`), -* в вашей ветке проходит линтер (`npm run lint`), некоторые ошибки можно автоматически поправить с помощью `npm run lint:fix`, -* покрытие тестов не ниже минимального значения, -* если вы вносите изменения в задокументированные части библиотеки, + +- в вашей ветке работает сборка (`npm run build:local`), +- в вашей ветке проходят тесты (`npm test`), +- в вашей ветке проходит линтер (`npm run lint`), некоторые ошибки можно автоматически поправить с помощью `npm run lint:fix`, +- покрытие тестов не ниже минимального значения, +- если вы вносите изменения в задокументированные части библиотеки, ваш pull request содержит обновления документации, -* если вы вносите изменения в сами токены, вы +- если вы вносите изменения в сами токены, вы согласовали их с дизайнерами. Для разработки в репозитории может понадобиться установить @@ -26,7 +27,7 @@ pull request одобрил кто-то из мейнтейнеров репоз Если вы вносили изменения в цвета, необходимо обновить [снапшоты тестов Jest](https://jestjs.io/ru/docs/snapshot-testing): -```npm test -- -u``` +`npm test -- -u` ## Версионирование @@ -37,63 +38,64 @@ pull request одобрил кто-то из мейнтейнеров репоз #### Поднимаем **патч**, если: -* локальное изменение цветов без изменения прозрачности -* локальное обратно совместимое изменение размеров +- локальное изменение цветов без изменения прозрачности +- локальное обратно совместимое изменение размеров #### Поднимаем минор, если: -* изменение прозрачности цветов (например rgb -> rgba) -* локальное изменение размеров в рамках ограниченного числа тем +- изменение прозрачности цветов (например rgb -> rgba) +- локальное изменение размеров в рамках ограниченного числа тем (в release notes обязательно указать, какие токены изменились) -* добавление нового токена или новой темы -* обратно совместимые изменения инфраструктуры +- добавление нового токена или новой темы +- обратно совместимые изменения инфраструктуры #### Поднимаем мажор, если: -* изменение размеров большого числа токенов -* удаление токена или темы -* другие обратно-несовместимые изменение +- изменение размеров большого числа токенов +- удаление токена или темы +- другие обратно-несовместимые изменение ## Структура репозитория -* src - * **interfaces** — описание интерфейса токенов - * `general` — описание общих типов и структур дизайн-системы - * `napespaces` — пространства имён тем оформления (vk, paradigm) - * `themes` — описание интерфейса каждой темы оформления - * **themeDescriptions** — описание конкретных значений переменных тем оформления - * _base_ — значения переменных базовых тем - * _themes_ — значения переменных продуктовых тем - * _common_ — вспомогательный код и общие для всех тем значения - * **build** — инструменты сборки - * **lint** — инструменты линтинга токенов +- src + - **interfaces** — описание интерфейса токенов + - `general` — описание общих типов и структур дизайн-системы + - `napespaces` — пространства имён тем оформления (vk, paradigm) + - `themes` — описание интерфейса каждой темы оформления + - **themeDescriptions** — описание конкретных значений переменных тем оформления + - _base_ — значения переменных базовых тем + - _themes_ — значения переменных продуктовых тем + - _common_ — вспомогательный код и общие для всех тем значения + - **build** — инструменты сборки + - **lint** — инструменты линтинга токенов ### Структура наследования тем -* _vkBase_ - * vkBaseDark - * vkCom - * vkIOS -* _paradigmBase_ - * paradigmBaseDark - * calendar - * calendarDark - * calls - * cloud - * home - * homeDark - * media - * mediaDark - * mycom - * octavius - * octaviusCompact - * octaviusCompactDark - * octaviusDark - * octaviusVK - * octaviusVKDark - * octaviusWhite - * otvet - * otvetDark - * pharma - * promo - * pulse - * pulseDark + +- _vkBase_ + - vkBaseDark + - vkCom + - vkIOS +- _paradigmBase_ + - paradigmBaseDark + - calendar + - calendarDark + - calls + - cloud + - home + - homeDark + - media + - mediaDark + - mycom + - octavius + - octaviusCompact + - octaviusCompactDark + - octaviusDark + - octaviusVK + - octaviusVKDark + - octaviusWhite + - otvet + - otvetDark + - pharma + - promo + - pulse + - pulseDark diff --git a/README.md b/README.md index 2fa1be9b..29ea795e 100644 --- a/README.md +++ b/README.md @@ -14,19 +14,19 @@ # Содержание -* [Использование](#использование) - * [Использование CSS-переменных темы напрямую из пакета](#использование-css-переменных-темы-напрямую-из-пакета) - * [Подключение темы на страницу](#подключение-темы-на-страницу) - * [Использование переменных в вёрстке](#использование-переменных-в-вёрстке) - * [Использование базовой темы напрямую из пакета](#использование-базовой-темы-напрямую-из-пакета) -* [Инструменты](#инструменты) - * [Локальная сборка своих тем инструментами библиотеки](#локальная-сборка-своих-тем-инструментами-библиотеки) - * [Наследование от существующей темы](#наследование-от-существующей-темы) - * [Создание собственной темы "с нуля"](#создание-собственной-темы-с-нуля) -* [Roadmap](#roadmap) -* [Полезные ссылки](#полезные-ссылки) -* [Информация для внесения изменений](CONTRIBUTING.md) -* [Changelog (архивная версия)](CHANGELOG.OLD.md) +- [Использование](#использование) + - [Использование CSS-переменных темы напрямую из пакета](#использование-css-переменных-темы-напрямую-из-пакета) + - [Подключение темы на страницу](#подключение-темы-на-страницу) + - [Использование переменных в вёрстке](#использование-переменных-в-вёрстке) + - [Использование базовой темы напрямую из пакета](#использование-базовой-темы-напрямую-из-пакета) +- [Инструменты](#инструменты) + - [Локальная сборка своих тем инструментами библиотеки](#локальная-сборка-своих-тем-инструментами-библиотеки) + - [Наследование от существующей темы](#наследование-от-существующей-темы) + - [Создание собственной темы "с нуля"](#создание-собственной-темы-с-нуля) +- [Roadmap](#roadmap) +- [Полезные ссылки](#полезные-ссылки) +- [Информация для внесения изменений](CONTRIBUTING.md) +- [Changelog (архивная версия)](CHANGELOG.OLD.md) Актуальный changelog находится на странице [релизов в GitHub](https://github.com/VKCOM/vkui-tokens/releases)! @@ -34,19 +34,25 @@ # Использование Устанавливаем npm-пакет `@vkontakte/vkui-tokens`: + ```bash npm i --save @vkontakte/vkui-tokens@latest ``` + ## Использование CSS-переменных темы напрямую из пакета + ### Подключение темы на страницу В любом CSS-файле подключаем файл темы со значениями переменных: + ```css -@import "@vkontakte/vkui-tokens/themes/vkBase/cssVars/declarations/index.css"; +@import '@vkontakte/vkui-tokens/themes/vkBase/cssVars/declarations/index.css'; ``` ### Использование переменных в вёрстке + #### Использование в CSS + ```postcss .myAwesomeClass:hover { background-color: var(--vkui--color_background--hover); @@ -54,33 +60,38 @@ npm i --save @vkontakte/vkui-tokens@latest ``` #### Использование CSS-переменных через объект в JavaScript (TypeScript) + ```typescript import baseTheme from '@vkontakte/vkui-tokens/themes/vkBase/cssVars/theme'; // Собствено имя CSS-переменной (название токена) -console.log(baseTheme.colorBackground.hover.name) // --vkui--color_background--hover; +console.log(baseTheme.colorBackground.hover.name); // --vkui--color_background--hover; // Сниппет для использования CSS-переменной -console.log(baseTheme.colorBackground.hover.value) // var(--vkui--color_background--hover, #F5F5F7) +console.log(baseTheme.colorBackground.hover.value); // var(--vkui--color_background--hover, #F5F5F7) // Динамически (с учётом возможных переопределений) // узнаём, чему равно значение переменной внутри myElement: -getComputedStyle(myElement).getPropertyValue(baseTheme.colorBackground.hover.name) +getComputedStyle(myElement).getPropertyValue(baseTheme.colorBackground.hover.name); ``` #### Принудительное использование токенов определённого размера -Чтобы принудительно включить тот или иной вид темы у конкретного -поддерева элементов, нужно воспользоваться классами + +Чтобы принудительно включить тот или иной вид темы у конкретного +поддерева элементов, нужно воспользоваться классами `.vkui--force-${auto | regular | compact | large | largeX ...}`. -Смотри [демо](demo/example-adaptive-css-vars-theme.html) работы +Смотри [демо](demo/example-adaptive-css-vars-theme.html) работы адаптивных переменных и спец. классов. -Также можно просто использовать переменную конкретного брейкпоинта -(ex. --vkui--size_field_height--**_compact_**), они все тоже +Также можно просто использовать переменную конкретного брейкпоинта +(ex. --vkui--size*field_height--\*\*\_compact*\*\*), они все тоже попадают в `:root`) ## Использование базовой темы напрямую из пакета + ### js/ts/json + Импортируем необходимую тему в файле и используем: + ```ts import baseTheme from '@vkontakte/vkui-tokens/themes/vkBase'; @@ -88,9 +99,11 @@ import baseTheme from '@vkontakte/vkui-tokens/themes/vkBase'; ``` ### Используем в scss/styl/less root темы из пакета + Импортируем файл с необходимой темой и используем переменные от туда (снизу синтаксис SCSS) + ```scss -@import "~@vkontakte/vkui-tokens/themes/vkBase/index"; +@import '~@vkontakte/vkui-tokens/themes/vkBase/index'; .myAwesomeClass { background-color: $color-bg; @@ -101,67 +114,69 @@ import baseTheme from '@vkontakte/vkui-tokens/themes/vkBase'; } ``` -### Используем pcss формат темы из пакета +### Используем pcss формат темы из пакета -1. Заходим в файл, где хотим использовать тему, и импортируем её: +1. Заходим в файл, где хотим использовать тему, и импортируем её: @import "@vkontakte/vkui-tokens/themes/vkBase"; -2. Заходим в файл темы, смотрим какие там есть переменные и юзаем их, например: +2. Заходим в файл темы, смотрим какие там есть переменные и юзаем их, например: width: var(--size-content-block-width); -3. Просто так ничего не заработает, нужно поставить postcss: +3. Просто так ничего не заработает, нужно поставить postcss: - npm i --save-dev postcss + npm i --save-dev postcss - Для запуска у postcss есть командная строка, которую тоже надо установить: + Для запуска у postcss есть командная строка, которую тоже надо установить: - npm i --save-dev postcss-cli + npm i --save-dev postcss-cli -4. Создаем конфиг postcss. Для этого создаем файл postcss.config.js (можно в любом месте проекта, но лучше в корне) и пишем в него необходимые плагины: +4. Создаем конфиг postcss. Для этого создаем файл postcss.config.js (можно в любом месте проекта, но лучше в корне) и пишем в него необходимые плагины: - ```javascript - const postcssPresetEnv = require('postcss-preset-env'); + ```javascript + const postcssPresetEnv = require('postcss-preset-env'); - module.exports = { - plugins: [ - require('postcss-import'), - require('precss'), - require('postcss-css-variables'), - require('postcss-custom-media'), - require('postcss-media-minmax'), - require('postcss-extend-rule'), - postcssPresetEnv({ - stage: 0, - }), - require('postcss-color-mix'), - require('cssnano') - ], - }; - ``` - Возможно, вам не понадобятся все эти плагины, поэтому лучше почитать, что делает каждый из них (https://www.postcss.parts/). - Нужно посмотреть файл вашей темы и ваш css (scss и др.), чтобы понять, что вам необходимо. + module.exports = { + plugins: [ + require('postcss-import'), + require('precss'), + require('postcss-css-variables'), + require('postcss-custom-media'), + require('postcss-media-minmax'), + require('postcss-extend-rule'), + postcssPresetEnv({ + stage: 0, + }), + require('postcss-color-mix'), + require('cssnano'), + ], + }; + ``` -5. Устанавливаем все необходимые плагины, которые написали в конфиге, например: + Возможно, вам не понадобятся все эти плагины, поэтому лучше почитать, что делает каждый из них (https://www.postcss.parts/). + Нужно посмотреть файл вашей темы и ваш css (scss и др.), чтобы понять, что вам необходимо. + +5. Устанавливаем все необходимые плагины, которые написали в конфиге, например: npm i --save-dev postcss-import -6. Настраиваем сборку postcss. +6. Настраиваем сборку postcss. - Сборка производится командой postcss через командную строку с необходимым параметрами. - Про них подробнее тут https://github.com/postcss/postcss-cli + Сборка производится командой postcss через командную строку с необходимым параметрами. + Про них подробнее тут https://github.com/postcss/postcss-cli - Пример команды: + Пример команды: - postcss src/main.css -c ./ --dir public + postcss src/main.css -c ./ --dir public - Такая команда прогонит файл src/main.css с помощью конфига из текущей папки и положит результат в папку public. + Такая команда прогонит файл src/main.css с помощью конфига из текущей папки и положит результат в папку public. # Инструменты + ## Локальная сборка своих тем инструментами библиотеки -Библиотека предоставляет интерфейсы и темы, от которых можно +Библиотека предоставляет интерфейсы и темы, от которых можно наследоваться. Помимо этого, библиотека предоставляет набор функций, которые позволяют @@ -171,14 +186,15 @@ import baseTheme from '@vkontakte/vkui-tokens/themes/vkBase'; состояний (hover, active), округление и "пикселизация" значений и т.д. ### Наследование от существующей темы + Пример: ```typescript -import type {ThemeDescription} from '@vkontakte/vkui-tokens/interfaces/general'; -import type {Adaptive} from '@vkontakte/vkui-tokens/interfaces/general/tools'; -import {lightTheme as baseTheme} from '@vkontakte/vkui-tokens/themeDescriptions/base/vk'; -import {expandAll} from '@vkontakte/vkui-tokens/build/expandTheme'; -import {compileStyles} from '@vkontakte/vkui-tokens/build/compilers/styles/compileStyles'; +import type { ThemeDescription } from '@vkontakte/vkui-tokens/interfaces/general'; +import type { Adaptive } from '@vkontakte/vkui-tokens/interfaces/general/tools'; +import { lightTheme as baseTheme } from '@vkontakte/vkui-tokens/themeDescriptions/base/vk'; +import { expandAll } from '@vkontakte/vkui-tokens/build/expandTheme'; +import { compileStyles } from '@vkontakte/vkui-tokens/build/compilers/styles/compileStyles'; interface MyNewAwesomeThemeDescription extends ThemeDescription { myNewAwesomeToken: Adaptive; @@ -193,7 +209,7 @@ const myNewAwesomeTheme: MyNewAwesomeThemeDescription = { }; // получаем разные типы тем на основе описания -const {theme, pixelifyTheme, cssVarsTheme} = expandAll(myNewAwesomeTheme); +const { theme, pixelifyTheme, cssVarsTheme } = expandAll(myNewAwesomeTheme); // получаем CSS-строку со всеми переменными темы, // которую можно вставить в DOM или сохранить в файл @@ -201,16 +217,17 @@ const cssString = compileStyles('css', pixelifyTheme); ``` ### Создание собственной темы "с нуля" + В некоторых случаях нет необходимости наследоваться от одной из -базовых тем. Библиотека позволяет сгенерировать свою тему из +базовых тем. Библиотека позволяет сгенерировать свою тему из произвольного количества уникальных переменных. Пример: ```typescript -import type {Adaptive} from '@vkontakte/vkui-tokens/interfaces/general/tools'; -import {expandAll} from '@vkontakte/vkui-tokens/build/expandTheme'; -import {compileStyles} from '@vkontakte/vkui-tokens/build/compilers/styles/compileStyles'; +import type { Adaptive } from '@vkontakte/vkui-tokens/interfaces/general/tools'; +import { expandAll } from '@vkontakte/vkui-tokens/build/expandTheme'; +import { compileStyles } from '@vkontakte/vkui-tokens/build/compilers/styles/compileStyles'; interface MyNewAwesomeThemeDescription { myNewAwesomeToken: Adaptive; @@ -224,7 +241,7 @@ const myNewAwesomeTheme: MyNewAwesomeThemeDescription = { }; // получаем разные типы тем на основе описания -const {theme, pixelifyTheme, cssVarsTheme} = expandAll(myNewAwesomeTheme); +const { theme, pixelifyTheme, cssVarsTheme } = expandAll(myNewAwesomeTheme); // получаем CSS-строку со всеми переменными темы, // которую можно вставить в DOM или сохранить в файл @@ -239,17 +256,19 @@ const cssString = compileStyles('css', pixelifyTheme); ``` # Roadmap -* [ ] Добавить более умную генерацию active, hover состояний цвета. - При генерации нужно учитывать тёмный и светлый вариант тем, а также - сам цвет, для которого генерируется состояние. - (решаем проблему, что цвет наведения, сгенерированный от синего, - плохо виден на большинстве мониторов). -* [ ] Генерация цветов по заранее определённой палитре. -* [ ] Текстовое описание семантики каждого токена. -* [ ] Более подробная документация. -* [ ] Сайт с примерами и описанием. + +- [ ] Добавить более умную генерацию active, hover состояний цвета. + При генерации нужно учитывать тёмный и светлый вариант тем, а также + сам цвет, для которого генерируется состояние. + (решаем проблему, что цвет наведения, сгенерированный от синего, + плохо виден на большинстве мониторов). +- [ ] Генерация цветов по заранее определённой палитре. +- [ ] Текстовое описание семантики каждого токена. +- [ ] Более подробная документация. +- [ ] Сайт с примерами и описанием. # Полезные ссылки + 1. [Доклад](https://youtu.be/0rHgqQvl0NQ?t=1858) про дизайн-системы на фронтенде: там рассказывается, зачем нужны дизайн-токены, причём тут UI-kit и как делать темизацию. 2. Серия видеороликов на youtube, где показано использование этой библиотеки (но со старым названием, не пугайтесь), как ядра дизайн-системы на практике: [первый](https://www.youtube.com/watch?v=RKCsrPOxYWE), [второй](https://www.youtube.com/watch?v=ZhiH4jFL-kU), [третий](https://www.youtube.com/watch?v=ZXOmmkyxrwk) 3. Opensource библиотека компонентов (UI-kit) [VKUI](https://github.com/VKCOM/VKUI), которая использует токены. diff --git a/docs/public/index.html b/docs/public/index.html index d9efbc44..104bb926 100644 --- a/docs/public/index.html +++ b/docs/public/index.html @@ -1,18 +1,18 @@ - - - - - - - - VKUI Tokens documentation - - -
- + + + + + + + + VKUI Tokens documentation + + +
+ diff --git a/docs/src/App.tsx b/docs/src/App.tsx index 8ffcb9c9..fecd3050 100644 --- a/docs/src/App.tsx +++ b/docs/src/App.tsx @@ -3,7 +3,7 @@ import '@vkontakte/vkui/dist/vkui.css'; import '@vkontakte/vkui/dist/unstable.css'; import './styles/index.css'; -import React, {FC} from 'react'; +import React, { FC } from 'react'; import Main from '@/components/layouts/Main'; import Tokens from '@/pages/Tokens'; diff --git a/docs/src/components/layouts/Main.tsx b/docs/src/components/layouts/Main.tsx index 7f90a725..125ab2b9 100644 --- a/docs/src/components/layouts/Main.tsx +++ b/docs/src/components/layouts/Main.tsx @@ -7,7 +7,7 @@ import { View, WebviewType, } from '@vkontakte/vkui'; -import React, {FC} from 'react'; +import React, { FC } from 'react'; import Header from './shared/Header/Header'; @@ -15,7 +15,7 @@ type Props = { children: React.ReactNode; }; -const Main: FC = ({children}) => ( +const Main: FC = ({ children }) => ( diff --git a/docs/src/components/layouts/shared/Header/Header.tsx b/docs/src/components/layouts/shared/Header/Header.tsx index 3c85b835..2ecd7629 100644 --- a/docs/src/components/layouts/shared/Header/Header.tsx +++ b/docs/src/components/layouts/shared/Header/Header.tsx @@ -1,13 +1,13 @@ -import {Card, PanelHeader, useAdaptivity} from '@vkontakte/vkui'; +import { Card, PanelHeader, useAdaptivity } from '@vkontakte/vkui'; import clsx from 'clsx'; -import React, {FC, useState} from 'react'; +import React, { FC, useState } from 'react'; -import {LogoIcon} from '@/shared/content/icons'; +import { LogoIcon } from '@/shared/content/icons'; import Navigation from '../Navigation/Navigation'; const Header: FC = () => { - const {viewWidth} = useAdaptivity(); + const { viewWidth } = useAdaptivity(); const isTablet = viewWidth > 3; const [mobileMenuOpen, setMobileMenuOpen] = useState(false); @@ -19,12 +19,7 @@ const Header: FC = () => { return ( -
+
diff --git a/docs/src/components/layouts/shared/Navigation/Navigation.tsx b/docs/src/components/layouts/shared/Navigation/Navigation.tsx index 1cf25f5b..a57ff662 100644 --- a/docs/src/components/layouts/shared/Navigation/Navigation.tsx +++ b/docs/src/components/layouts/shared/Navigation/Navigation.tsx @@ -1,7 +1,7 @@ -import {Button} from '@vkontakte/vkui'; -import React, {FC} from 'react'; +import { Button } from '@vkontakte/vkui'; +import React, { FC } from 'react'; -import {navigation} from './Navigation.content'; +import { navigation } from './Navigation.content'; type Props = { isTablet: boolean; @@ -16,7 +16,7 @@ const styles = { }, }; -const Navigation: FC = ({isTablet}) => { +const Navigation: FC = ({ isTablet }) => { if (!isTablet) { return null; } diff --git a/docs/src/components/pages/Tokens/TokensActions/TokensActions.content.tsx b/docs/src/components/pages/Tokens/TokensActions/TokensActions.content.tsx index ee7563df..9f6b306e 100644 --- a/docs/src/components/pages/Tokens/TokensActions/TokensActions.content.tsx +++ b/docs/src/components/pages/Tokens/TokensActions/TokensActions.content.tsx @@ -1,15 +1,15 @@ -import {Icon20ComputerOutline, Icon20SmartphoneOutline} from '@vkontakte/icons'; +import { Icon20ComputerOutline, Icon20SmartphoneOutline } from '@vkontakte/icons'; import React from 'react'; export const valueTypes = [ { - label:
- } - {...searchProps} - /> + } {...searchProps} />
); diff --git a/docs/src/components/pages/Tokens/TokensContent/TokensContent.css b/docs/src/components/pages/Tokens/TokensContent/TokensContent.css index ee036696..8aeebdb2 100644 --- a/docs/src/components/pages/Tokens/TokensContent/TokensContent.css +++ b/docs/src/components/pages/Tokens/TokensContent/TokensContent.css @@ -1,4 +1,5 @@ -.tokens-content-header, .tokens-content-item { +.tokens-content-header, +.tokens-content-item { display: flex; } @@ -14,20 +15,25 @@ overflow: auto; } -.tokens-content-header > div:nth-child(1), .tokens-content-header > div:nth-child(2), -.tokens-content-item > div:nth-child(1), .tokens-content-item > div:nth-child(2){ +.tokens-content-header > div:nth-child(1), +.tokens-content-header > div:nth-child(2), +.tokens-content-item > div:nth-child(1), +.tokens-content-item > div:nth-child(2) { padding-right: 20px; } -.tokens-content-header > div:nth-child(1), .tokens-content-item > div:nth-child(1) { +.tokens-content-header > div:nth-child(1), +.tokens-content-item > div:nth-child(1) { flex-basis: 35%; } -.tokens-content-header > div:nth-child(2), .tokens-content-item > div:nth-child(2) { +.tokens-content-header > div:nth-child(2), +.tokens-content-item > div:nth-child(2) { flex-basis: 25%; } -.tokens-content-header > div:nth-child(3), .tokens-content-item > div:nth-child(3) { +.tokens-content-header > div:nth-child(3), +.tokens-content-item > div:nth-child(3) { flex-basis: 40%; } @@ -49,7 +55,7 @@ } .token-name-btn_hover { - background-color: #FFEABD; + background-color: #ffeabd; } .token-name-btn_hover .vkuiButton__content { diff --git a/docs/src/components/pages/Tokens/TokensContent/TokensContent.helpers.ts b/docs/src/components/pages/Tokens/TokensContent/TokensContent.helpers.ts index 2e46bfd8..83616c92 100644 --- a/docs/src/components/pages/Tokens/TokensContent/TokensContent.helpers.ts +++ b/docs/src/components/pages/Tokens/TokensContent/TokensContent.helpers.ts @@ -1,9 +1,6 @@ -import {TokenItem, TokenItemValue} from '@/shared/types'; +import { TokenItem, TokenItemValue } from '@/shared/types'; -export function filterByTags( - selectedTags: Array, - token: TokenItem, -): boolean { +export function filterByTags(selectedTags: Array, token: TokenItem): boolean { // Исключаем legacy-токены по умолчанию, если не запросили явно if (!selectedTags.includes('legacy') && token.tags.includes('legacy')) { return false; @@ -21,9 +18,7 @@ function containsInDesc(haystack: string, needle: string): boolean { } function containsInValue(haystack: TokenItemValue, needle: string): boolean { - const haystackNorm = JSON.stringify(haystack) - .toLowerCase() - .replace(/\s/g, ''); + const haystackNorm = JSON.stringify(haystack).toLowerCase().replace(/\s/g, ''); return haystackNorm.includes(needle.replace(/\s/g, '')); } @@ -35,8 +30,5 @@ export function filterByDesc(searchValue: string, token: TokenItem): boolean { const needle = searchValue.toLowerCase(); - return ( - containsInDesc(token.desc, needle) || - containsInValue(token.value, needle) - ); + return containsInDesc(token.desc, needle) || containsInValue(token.value, needle); } diff --git a/docs/src/components/pages/Tokens/TokensContent/TokensContent.tsx b/docs/src/components/pages/Tokens/TokensContent/TokensContent.tsx index a772c16d..5d1802b8 100644 --- a/docs/src/components/pages/Tokens/TokensContent/TokensContent.tsx +++ b/docs/src/components/pages/Tokens/TokensContent/TokensContent.tsx @@ -1,14 +1,14 @@ import './TokensContent.css'; -import {Icon20CopyOutline} from '@vkontakte/icons'; -import {copyTextToClipboard} from '@vkontakte/vkjs'; -import {Button, Paragraph, Separator, useAdaptivity} from '@vkontakte/vkui'; -import React, {FC, useMemo} from 'react'; +import { Icon20CopyOutline } from '@vkontakte/icons'; +import { copyTextToClipboard } from '@vkontakte/vkjs'; +import { Button, Paragraph, Separator, useAdaptivity } from '@vkontakte/vkui'; +import React, { FC, useMemo } from 'react'; -import {Tokens, ValueType} from '@/shared/types'; +import { Tokens, ValueType } from '@/shared/types'; import TokensContentValue from './components/TokensContentValue'; -import {filterByDesc, filterByTags} from './TokensContent.helpers'; +import { filterByDesc, filterByTags } from './TokensContent.helpers'; type Props = { tokens: Tokens; @@ -17,13 +17,8 @@ type Props = { searchValue: string; }; -const TokensContent: FC = ({ - tokens, - selectedTags, - selectedValueType, - searchValue, -}) => { - const {viewWidth} = useAdaptivity(); +const TokensContent: FC = ({ tokens, selectedTags, selectedValueType, searchValue }) => { + const { viewWidth } = useAdaptivity(); const isTablet = viewWidth > 3; const tokensKeys = useMemo( @@ -36,10 +31,7 @@ const TokensContent: FC = ({ return (
-
+
Название токена
@@ -54,9 +46,7 @@ const TokensContent: FC = ({
{tokensKeys.map((token, index) => ( - {index !== 0 && ( - - )} + {index !== 0 && }
{isTablet && (
- - {tokens[token].desc || '-'} - + {tokens[token].desc || '-'}
)} {!isTablet && !!tokens[token].desc && ( diff --git a/docs/src/components/pages/Tokens/TokensContent/components/ColorCircle/ColorCircle.tsx b/docs/src/components/pages/Tokens/TokensContent/components/ColorCircle/ColorCircle.tsx index 7c782c7e..35c04b78 100644 --- a/docs/src/components/pages/Tokens/TokensContent/components/ColorCircle/ColorCircle.tsx +++ b/docs/src/components/pages/Tokens/TokensContent/components/ColorCircle/ColorCircle.tsx @@ -1,17 +1,17 @@ import './ColorCircle.css'; -import React, {FC} from 'react'; +import React, { FC } from 'react'; type Props = { content: string; style?: React.CSSProperties; }; -const ColorCircle: FC = ({content, style}) => ( +const ColorCircle: FC = ({ content, style }) => (
diff --git a/docs/src/components/pages/Tokens/TokensContent/components/TokensContentValue.helpers.ts b/docs/src/components/pages/Tokens/TokensContent/components/TokensContentValue.helpers.ts index fe58271c..e485d1f5 100644 --- a/docs/src/components/pages/Tokens/TokensContent/components/TokensContentValue.helpers.ts +++ b/docs/src/components/pages/Tokens/TokensContent/components/TokensContentValue.helpers.ts @@ -1,10 +1,5 @@ -import {TokenItemValue, ValueType} from '@/shared/types'; -import { - isNumber, - isRegularCompactObj, - isRegularObj, - isString, -} from '@/shared/utils'; +import { TokenItemValue, ValueType } from '@/shared/types'; +import { isNumber, isRegularCompactObj, isRegularObj, isString } from '@/shared/utils'; export function oneLineRenderCondition(contentValue: TokenItemValue): boolean { return ( @@ -15,10 +10,7 @@ export function oneLineRenderCondition(contentValue: TokenItemValue): boolean { ); } -export function getOneLineContent( - value: TokenItemValue, - valueType: ValueType, -): string | number { +export function getOneLineContent(value: TokenItemValue, valueType: ValueType): string | number { if (isString(value) || isNumber(value)) { return value; } diff --git a/docs/src/components/pages/Tokens/TokensContent/components/TokensContentValue.tsx b/docs/src/components/pages/Tokens/TokensContent/components/TokensContentValue.tsx index 2496bad5..0470421b 100644 --- a/docs/src/components/pages/Tokens/TokensContent/components/TokensContentValue.tsx +++ b/docs/src/components/pages/Tokens/TokensContent/components/TokensContentValue.tsx @@ -1,32 +1,26 @@ -import {Paragraph} from '@vkontakte/vkui'; +import { Paragraph } from '@vkontakte/vkui'; import clsx from 'clsx'; -import React, {FC} from 'react'; +import React, { FC } from 'react'; -import {TokenItemValue, ValueType} from '@/shared/types'; -import {isColor, isRegularCompactObj} from '@/shared/utils'; +import { TokenItemValue, ValueType } from '@/shared/types'; +import { isColor, isRegularCompactObj } from '@/shared/utils'; import ColorCircle from './ColorCircle/ColorCircle'; -import { - getOneLineContent, - oneLineRenderCondition, -} from './TokensContentValue.helpers'; +import { getOneLineContent, oneLineRenderCondition } from './TokensContentValue.helpers'; type Props = { contentValue: TokenItemValue; selectedValueType: ValueType; }; -const TokensContentValue: FC = ({contentValue, selectedValueType}) => { +const TokensContentValue: FC = ({ contentValue, selectedValueType }) => { if (oneLineRenderCondition(contentValue)) { const content = getOneLineContent(contentValue, selectedValueType); return (
{content} {isColor(content) && ( - + )}
); @@ -39,24 +33,13 @@ const TokensContentValue: FC = ({contentValue, selectedValueType}) => { const nestedValue = contentValue[key]; if (oneLineRenderCondition(nestedValue)) { - const content = getOneLineContent( - nestedValue, - selectedValueType, - ); + const content = getOneLineContent(nestedValue, selectedValueType); return ( -
+
{key}:  {content} {isColor(content) && ( - + )}
); @@ -65,7 +48,7 @@ const TokensContentValue: FC = ({contentValue, selectedValueType}) => { return ( {key}:  - + {JSON.stringify(nestedValue, null, 4)} diff --git a/docs/src/components/pages/Tokens/TokensHeader.tsx b/docs/src/components/pages/Tokens/TokensHeader.tsx index aba4a64c..0285e2b7 100644 --- a/docs/src/components/pages/Tokens/TokensHeader.tsx +++ b/docs/src/components/pages/Tokens/TokensHeader.tsx @@ -1,7 +1,7 @@ -import {Icon16Linked} from '@vkontakte/icons'; -import {Link, Title, useAdaptivity} from '@vkontakte/vkui'; +import { Icon16Linked } from '@vkontakte/icons'; +import { Link, Title, useAdaptivity } from '@vkontakte/vkui'; import clsx from 'clsx'; -import React, {FC} from 'react'; +import React, { FC } from 'react'; import packageJson from '@/../../package.json'; @@ -20,22 +20,19 @@ const styles = { }; const TokensHeader: FC = () => { - const {viewWidth} = useAdaptivity(); + const { viewWidth } = useAdaptivity(); const isTablet = viewWidth > 3; return (
VKUI Tokens
@@ -43,11 +40,8 @@ const TokensHeader: FC = () => {
- - + + Github
diff --git a/docs/src/components/pages/Tokens/index.ts b/docs/src/components/pages/Tokens/index.ts index 96900368..bd9933f9 100644 --- a/docs/src/components/pages/Tokens/index.ts +++ b/docs/src/components/pages/Tokens/index.ts @@ -1,3 +1,3 @@ -export {default as TokensActions} from './TokensActions/TokensActions'; -export {default as TokensContent} from './TokensContent/TokensContent'; -export {default as TokensHeader} from './TokensHeader'; +export { default as TokensActions } from './TokensActions/TokensActions'; +export { default as TokensContent } from './TokensContent/TokensContent'; +export { default as TokensHeader } from './TokensHeader'; diff --git a/docs/src/index.tsx b/docs/src/index.tsx index ce0a7782..c9af1381 100644 --- a/docs/src/index.tsx +++ b/docs/src/index.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import {createRoot} from 'react-dom/client'; +import { createRoot } from 'react-dom/client'; import App from './App'; diff --git a/docs/src/pages/Tokens.tsx b/docs/src/pages/Tokens.tsx index 25d7e21f..e6e2b693 100644 --- a/docs/src/pages/Tokens.tsx +++ b/docs/src/pages/Tokens.tsx @@ -1,14 +1,10 @@ -import {useAdaptivity} from '@vkontakte/vkui'; -import React, {FC, useMemo, useState} from 'react'; +import { useAdaptivity } from '@vkontakte/vkui'; +import React, { FC, useMemo, useState } from 'react'; -import { - TokensActions, - TokensContent, - TokensHeader, -} from '@/components/pages/Tokens'; +import { TokensActions, TokensContent, TokensHeader } from '@/components/pages/Tokens'; import tokensData from '@/public/static/data/tokensData.json'; -import {useDebounce} from '@/shared/hooks/useDebounce'; -import {ChipOption, Tokens as TokensType, ValueType} from '@/shared/types'; +import { useDebounce } from '@/shared/hooks/useDebounce'; +import { ChipOption, Tokens as TokensType, ValueType } from '@/shared/types'; const themes = Object.keys(tokensData); @@ -18,10 +14,7 @@ function transformTags(tokens: TokensType) { const flatTags = tags.reduce((acc, curr) => acc.concat(curr), []); const sortedTagsWithQuantity = flatTags .reduce( - (acc, curr, i, arr) => - acc.concat([ - [curr, arr.filter((curr1) => curr1 === curr).length], - ]), + (acc, curr, i, arr) => acc.concat([[curr, arr.filter((curr1) => curr1 === curr).length]]), [], ) .sort((a, b) => b[1] - a[1]); @@ -48,26 +41,21 @@ function findThemeTags(themeNames: string[]): string[] { } const Tokens: FC = () => { - const {viewWidth} = useAdaptivity(); + const { viewWidth } = useAdaptivity(); const isTablet = viewWidth > 3; const themeTags = useMemo(() => findThemeTags(themes), [themes]); const [selectedTags, setSelectedTags] = useState>([]); const [selectedTheme, setSelectedTheme] = useState(themes[0]); - const [selectedValueType, setSelectedValueType] = - useState('regular'); + const [selectedValueType, setSelectedValueType] = useState('regular'); const [searchValue, setSearchValue] = useState(''); const searchValueDebounced = useDebounce(searchValue, 500); - const searchChangeHandler = ( - event: React.ChangeEvent, - ) => { + const searchChangeHandler = (event: React.ChangeEvent) => { setSearchValue(event.target.value); }; - const changeThemeHandler = ( - event: React.ChangeEvent, - ) => { + const changeThemeHandler = (event: React.ChangeEvent) => { setSelectedTheme(event.target.value); }; @@ -100,10 +88,7 @@ const Tokens: FC = () => { - selectedTags.map((tagOption) => - String(tagOption.value), - ), + () => selectedTags.map((tagOption) => String(tagOption.value)), [selectedTags.join(' ')], )} selectedValueType={selectedValueType} diff --git a/docs/src/shared/content/icons.ts b/docs/src/shared/content/icons.ts index 3a7ec831..edcfa25a 100644 --- a/docs/src/shared/content/icons.ts +++ b/docs/src/shared/content/icons.ts @@ -1,3 +1,3 @@ import LogoIcon from '@/public/static/svg/logo.svg'; -export {LogoIcon}; +export { LogoIcon }; diff --git a/docs/src/shared/utils/helpers.ts b/docs/src/shared/utils/helpers.ts index 8a80881f..94a5cd41 100644 --- a/docs/src/shared/utils/helpers.ts +++ b/docs/src/shared/utils/helpers.ts @@ -1,4 +1,4 @@ -import {TokenItemValue} from '@/shared/types'; +import { TokenItemValue } from '@/shared/types'; export function isExist(obj: unknown, key: string): boolean { return Object.prototype.hasOwnProperty.call(obj, key); diff --git a/docs/src/shared/utils/typeGuards.ts b/docs/src/shared/utils/typeGuards.ts index ee9a7b9a..4bb8a6e0 100644 --- a/docs/src/shared/utils/typeGuards.ts +++ b/docs/src/shared/utils/typeGuards.ts @@ -1,6 +1,6 @@ -import {RegularCompactObj} from '@/shared/types'; +import { RegularCompactObj } from '@/shared/types'; -import {isExist} from './helpers'; +import { isExist } from './helpers'; export function isString(value: unknown): value is string { return typeof value === 'string'; @@ -16,8 +16,6 @@ export function isRegularObj( return isExist(value, 'regular'); } -export function isRegularCompactObj( - value: unknown, -): value is Required { +export function isRegularCompactObj(value: unknown): value is Required { return isExist(value, 'regular') && isExist(value, 'compact'); } diff --git a/docs/src/styles/index.css b/docs/src/styles/index.css index 8562ca50..67f2a997 100644 --- a/docs/src/styles/index.css +++ b/docs/src/styles/index.css @@ -1,5 +1,5 @@ -@import "flex.css"; -@import "space.css"; +@import 'flex.css'; +@import 'space.css'; .container { max-width: 1144px; diff --git a/docs/tsconfig.json b/docs/tsconfig.json index d519bad4..7430e647 100644 --- a/docs/tsconfig.json +++ b/docs/tsconfig.json @@ -16,6 +16,6 @@ "paths": { "@/public/*": ["./public/*"], "@/*": ["./src/*"] - }, + } } } diff --git a/docs/webpack/webpack.client.js b/docs/webpack/webpack.client.js index 8d3d281e..21d5ed62 100644 --- a/docs/webpack/webpack.client.js +++ b/docs/webpack/webpack.client.js @@ -2,7 +2,7 @@ const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const WebpackNotifierPlugin = require('webpack-notifier'); const TerserPlugin = require('terser-webpack-plugin'); -const {CleanWebpackPlugin} = require('clean-webpack-plugin'); +const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const webpackConfig = require('./webpack.config'); @@ -43,9 +43,7 @@ module.exports = function (env, argv) { }, output: { path: path.resolve(__dirname, '../dist'), - filename: watchMode - ? 'assets/[name].[hash].js' - : 'assets/[name].[chunkhash].js', + filename: watchMode ? 'assets/[name].[hash].js' : 'assets/[name].[chunkhash].js', publicPath: 'auto', }, module: { @@ -59,7 +57,7 @@ module.exports = function (env, argv) { new HtmlWebpackPlugin({ template: './public/index.html', }), - new WebpackNotifierPlugin({alwaysNotify: false}), + new WebpackNotifierPlugin({ alwaysNotify: false }), new CopyWebpackPlugin({ patterns: [ { diff --git a/package.json b/package.json index 480fa6d0..a387e0d6 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,7 @@ "@typescript-eslint/parser": "4.33.0", "@vkontakte/appearance": "https://github.com/VKCOM/Appearance#v9.51.4", "@vkontakte/icons": "2.3.0", + "@vkontakte/prettier-config": "0.1.0", "@vkontakte/vk-bridge": "2.7.2", "@vkontakte/vkui": "4.40.0", "babel-jest": "29.3.1", diff --git a/src/build/compilers/cssVars/declarations/compileBreakpointsCssVarsDeclaration.test.ts b/src/build/compilers/cssVars/declarations/compileBreakpointsCssVarsDeclaration.test.ts index 3f4452b5..e7c438e3 100644 --- a/src/build/compilers/cssVars/declarations/compileBreakpointsCssVarsDeclaration.test.ts +++ b/src/build/compilers/cssVars/declarations/compileBreakpointsCssVarsDeclaration.test.ts @@ -1,16 +1,14 @@ -import {stripIndent} from 'common-tags'; +import { stripIndent } from 'common-tags'; -import {ThemeCssVarsWide} from '@/interfaces/general'; -import {ParadigmThemeCssVarsWide} from '@/interfaces/namespaces/paradigm'; +import { ThemeCssVarsWide } from '@/interfaces/general'; +import { ParadigmThemeCssVarsWide } from '@/interfaces/namespaces/paradigm'; -import {compileBreakpointsCssVarsDeclaration} from './compileBreakpointsCssVarsDeclaration'; +import { compileBreakpointsCssVarsDeclaration } from './compileBreakpointsCssVarsDeclaration'; describe('compileBreakpointsCssVarsDeclaration', () => { it('should not work without breakpoints', () => { const theme = {}; - expect( - compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide), - ).toBe(null); + expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide)).toBe(null); }); it('should work with breakpoints and empty vals', () => { @@ -26,9 +24,7 @@ describe('compileBreakpointsCssVarsDeclaration', () => { }, }, }; - expect( - compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide), - ).toBe(null); + expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide)).toBe(null); }); it('should work with non adaptive values', () => { @@ -49,9 +45,7 @@ describe('compileBreakpointsCssVarsDeclaration', () => { originalValue: '4px', }, }; - expect( - compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide), - ).toBe(null); + expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide)).toBe(null); }); it('should work with flat adaptive values and several breakpotins', () => { @@ -83,8 +77,7 @@ describe('compileBreakpointsCssVarsDeclaration', () => { }, }, }; - expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide)) - .toBe(stripIndent` + expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide)).toBe(stripIndent` :root { --vkui--size_popup_base_padding: var(--vkui--size_popup_base_padding--regular); } @@ -135,8 +128,7 @@ describe('compileBreakpointsCssVarsDeclaration', () => { }, }, }; - expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide)) - .toBe(stripIndent` + expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide)).toBe(stripIndent` :root { --vkui--size_popup_base_padding: 20px; } @@ -188,8 +180,7 @@ describe('compileBreakpointsCssVarsDeclaration', () => { }, }; - expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide)) - .toBe(stripIndent` + expect(compileBreakpointsCssVarsDeclaration(theme as ThemeCssVarsWide)).toBe(stripIndent` :root { --vkui--font_h1--font_size: var(--vkui--font_h1--font_size--regular); --vkui--font_h1--line_height: var(--vkui--font_h1--line_height--regular); diff --git a/src/build/compilers/cssVars/declarations/compileBreakpointsCssVarsDeclaration.ts b/src/build/compilers/cssVars/declarations/compileBreakpointsCssVarsDeclaration.ts index e758d0dc..04e001d4 100644 --- a/src/build/compilers/cssVars/declarations/compileBreakpointsCssVarsDeclaration.ts +++ b/src/build/compilers/cssVars/declarations/compileBreakpointsCssVarsDeclaration.ts @@ -1,15 +1,15 @@ -import {stripIndent, stripIndents} from 'common-tags'; +import { stripIndent, stripIndents } from 'common-tags'; -import {findViewportByAdaptivityState} from '@/build/compilers/cssVars/helpers/findViewportByAdaptivityState'; -import {capitalize} from '@/build/helpers/capitalize'; -import {convertCamelToSnake} from '@/build/helpers/convertCamelToSnake'; -import {getOnlyColors} from '@/build/helpers/getOnlyColors'; -import {processCustomMedia} from '@/build/themeProcessors/customMedia/customMedia'; -import {Theme, ThemeCssVarsWide} from '@/interfaces/general'; -import {Adaptive, Breakpoints} from '@/interfaces/general/tools'; +import { findViewportByAdaptivityState } from '@/build/compilers/cssVars/helpers/findViewportByAdaptivityState'; +import { capitalize } from '@/build/helpers/capitalize'; +import { convertCamelToSnake } from '@/build/helpers/convertCamelToSnake'; +import { getOnlyColors } from '@/build/helpers/getOnlyColors'; +import { processCustomMedia } from '@/build/themeProcessors/customMedia/customMedia'; +import { Theme, ThemeCssVarsWide } from '@/interfaces/general'; +import { Adaptive, Breakpoints } from '@/interfaces/general/tools'; -import {accumulateValues} from '../helpers/accumulateValues'; -import {getVarString} from '../helpers/getVarString'; +import { accumulateValues } from '../helpers/accumulateValues'; +import { getVarString } from '../helpers/getVarString'; export type DeclarationType = 'default' | 'onlyRoot' | 'modern' | 'onlyColors'; @@ -26,14 +26,13 @@ export function compileBreakpointsCssVarsDeclaration( if (!('breakpoints' in sourceTheme)) { return null; } - const breakpoints: Partial = - sourceTheme['breakpoints']; + const breakpoints: Partial = sourceTheme['breakpoints']; const customMedia = processCustomMedia(sourceTheme as any); const theme: ThemeCssVarsWide = type === 'onlyColors' ? getOnlyColors(sourceTheme) : sourceTheme; - const {adaptiveValues} = accumulateValues({ + const { adaptiveValues } = accumulateValues({ theme, }); @@ -45,7 +44,7 @@ export function compileBreakpointsCssVarsDeclaration( result += stripIndent` :root { -${getVarString({valuesObject: adaptiveValues.auto, prefix: '\t\t'})} +${getVarString({ valuesObject: adaptiveValues.auto, prefix: '\t\t' })} }`; const adaptivityStatesLength = Object.keys(adaptiveValues).length; @@ -86,12 +85,8 @@ ${getVarString({valuesObject: adaptiveValues.auto, prefix: '\t\t'})} return; } - const regularName = name.replace( - new RegExp(`${adaptivityState}$`), - 'regular', - ); - const regularValue = - adaptiveValues.regular[regularName]; + const regularName = name.replace(new RegExp(`${adaptivityState}$`), 'regular'); + const regularValue = adaptiveValues.regular[regularName]; if (regularValue) { regularValues += `${regularName}: ${regularValue};\n`; } diff --git a/src/build/compilers/cssVars/helpers/accumulateValues.ts b/src/build/compilers/cssVars/helpers/accumulateValues.ts index 10a70dcd..6fa6b7fc 100644 --- a/src/build/compilers/cssVars/helpers/accumulateValues.ts +++ b/src/build/compilers/cssVars/helpers/accumulateValues.ts @@ -1,6 +1,6 @@ -import {Theme} from '@/interfaces/general'; -import {Adaptive, adaptiveKeys} from '@/interfaces/general/tools'; -import {WideCssVarValue} from '@/interfaces/general/tools/cssVars'; +import { Theme } from '@/interfaces/general'; +import { Adaptive, adaptiveKeys } from '@/interfaces/general/tools'; +import { WideCssVarValue } from '@/interfaces/general/tools/cssVars'; export type FlatValuesObject = { [key: string]: string | number; @@ -26,18 +26,10 @@ const passOriginalValue = ({ toValue, fromValue, }: { - toValue: - | WideCssVarValue - | Record>; - fromValue: - | WideCssVarValue - | Record>; + toValue: WideCssVarValue | Record>; + fromValue: WideCssVarValue | Record>; }): void => { - if ( - typeof toValue === 'object' && - 'name' in toValue && - typeof toValue.name === 'string' - ) { + if (typeof toValue === 'object' && 'name' in toValue && typeof toValue.name === 'string') { toValue.originalValue = fromValue.originalValue; return; } @@ -78,20 +70,12 @@ const fillValues = ({ manyAdaptiveStates, }: { destination: FlatValuesObject; - value: - | WideCssVarValue - | Record>; + value: WideCssVarValue | Record>; adaptiveDestination?: AdaptiveValuesObject; - autoValue?: - | WideCssVarValue - | Record>; + autoValue?: WideCssVarValue | Record>; manyAdaptiveStates: boolean; }) => { - if ( - typeof value === 'object' && - 'name' in value && - typeof value.name === 'string' - ) { + if (typeof value === 'object' && 'name' in value && typeof value.name === 'string') { constructSourceVal({ destination, value: value as WideCssVarValue, @@ -144,7 +128,7 @@ const fillValues = ({ }); }; -export function accumulateValues({theme}: Params): ReturnValues { +export function accumulateValues({ theme }: Params): ReturnValues { const flatValues: FlatValuesObject = {}; const adaptiveValues: AdaptiveValuesObject = { auto: {}, @@ -165,5 +149,5 @@ export function accumulateValues({theme}: Params): ReturnValues { }); }); - return {flatValues, adaptiveValues}; + return { flatValues, adaptiveValues }; } diff --git a/src/build/compilers/cssVars/helpers/findViewportByAdaptivityState.ts b/src/build/compilers/cssVars/helpers/findViewportByAdaptivityState.ts index 4991106b..daddbce7 100644 --- a/src/build/compilers/cssVars/helpers/findViewportByAdaptivityState.ts +++ b/src/build/compilers/cssVars/helpers/findViewportByAdaptivityState.ts @@ -1,13 +1,7 @@ -import {Adaptive, Breakpoints} from '@/interfaces/general/tools'; -import { - DefaultViewports, - Viewports, - ViewportsTuple, -} from '@/interfaces/general/tools/viewports'; +import { Adaptive, Breakpoints } from '@/interfaces/general/tools'; +import { DefaultViewports, Viewports, ViewportsTuple } from '@/interfaces/general/tools/viewports'; -export function findViewportByAdaptivityState< - Vt extends ViewportsTuple = DefaultViewports, ->( +export function findViewportByAdaptivityState( breakpoints: Partial['breakpoints']>, adaptivityState: keyof Adaptive, ): Viewports { diff --git a/src/build/compilers/cssVars/helpers/getVarString.ts b/src/build/compilers/cssVars/helpers/getVarString.ts index e291c0a9..3ab163c9 100644 --- a/src/build/compilers/cssVars/helpers/getVarString.ts +++ b/src/build/compilers/cssVars/helpers/getVarString.ts @@ -1,4 +1,4 @@ -import {FlatValuesObject} from './accumulateValues'; +import { FlatValuesObject } from './accumulateValues'; interface GetVarStringParams { valuesObject: FlatValuesObject; diff --git a/src/build/compilers/cssVars/jsUtils/compileGetDeclarationString.test.ts b/src/build/compilers/cssVars/jsUtils/compileGetDeclarationString.test.ts index 2b5e7ff3..4ac38be6 100644 --- a/src/build/compilers/cssVars/jsUtils/compileGetDeclarationString.test.ts +++ b/src/build/compilers/cssVars/jsUtils/compileGetDeclarationString.test.ts @@ -1,8 +1,8 @@ -import {stripIndent} from 'common-tags'; +import { stripIndent } from 'common-tags'; -import {compileGetDeclarationString} from '@/build/compilers/cssVars/jsUtils/compileGetDeclarationString'; -import {ThemeCssVarsWide} from '@/interfaces/general'; -import {ParadigmThemeCssVarsWide} from '@/interfaces/namespaces/paradigm'; +import { compileGetDeclarationString } from '@/build/compilers/cssVars/jsUtils/compileGetDeclarationString'; +import { ThemeCssVarsWide } from '@/interfaces/general'; +import { ParadigmThemeCssVarsWide } from '@/interfaces/namespaces/paradigm'; describe('compileGetDeclarationString', () => { it('should work with empty', () => { @@ -23,55 +23,51 @@ describe('compileGetDeclarationString', () => { }); it('should work with any values', () => { - const theme: Pick< - ParadigmThemeCssVarsWide, - 'x1' | 'sizePopupBasePadding' | 'colorTextAccent' - > = { - x1: { - name: '--paradigm--x1', - value: 'val(--paradigm--x1, 4px)', - originalValue: '4px', - }, - - sizePopupBasePadding: { - auto: { - name: '--vkui--size_popup_base_padding', - value: 'var(--vkui--size_popup_base_padding)', + const theme: Pick = + { + x1: { + name: '--paradigm--x1', + value: 'val(--paradigm--x1, 4px)', + originalValue: '4px', }, - compact: { - name: '--vkui--size_popup_base_padding--compact', - value: 'var(--vkui--size_popup_base_padding--compact, 16px)', - originalValue: '16px', - }, - regular: { - name: '--vkui--size_popup_base_padding--regular', - value: 'var(--vkui--size_popup_base_padding--regular, 20px)', - originalValue: '20px', - }, - }, - colorTextAccent: { - normal: { - name: '--vkui--color_text_accent', - value: 'val(--vkui--color_text_accent, white)', - originalValue: 'white', - }, - hover: { - name: '--vkui--color_text_accent--hover', - value: 'val(--vkui--color_text_accent--hover, black)', - originalValue: 'black', + sizePopupBasePadding: { + auto: { + name: '--vkui--size_popup_base_padding', + value: 'var(--vkui--size_popup_base_padding)', + }, + compact: { + name: '--vkui--size_popup_base_padding--compact', + value: 'var(--vkui--size_popup_base_padding--compact, 16px)', + originalValue: '16px', + }, + regular: { + name: '--vkui--size_popup_base_padding--regular', + value: 'var(--vkui--size_popup_base_padding--regular, 20px)', + originalValue: '20px', + }, }, - active: { - name: '--vkui--color_text_accent--active', - value: 'val(--vkui--color_text_accent--active, red)', - originalValue: 'red', + + colorTextAccent: { + normal: { + name: '--vkui--color_text_accent', + value: 'val(--vkui--color_text_accent, white)', + originalValue: 'white', + }, + hover: { + name: '--vkui--color_text_accent--hover', + value: 'val(--vkui--color_text_accent--hover, black)', + originalValue: 'black', + }, + active: { + name: '--vkui--color_text_accent--active', + value: 'val(--vkui--color_text_accent--active, red)', + originalValue: 'red', + }, }, - }, - }; + }; - expect( - compileGetDeclarationString(theme as ParadigmThemeCssVarsWide), - ).toBe( + expect(compileGetDeclarationString(theme as ParadigmThemeCssVarsWide)).toBe( stripIndent` import {Properties} from 'csstype'; @@ -87,58 +83,51 @@ describe('compileGetDeclarationString', () => { }); it('should work onlyColorsMode', () => { - const theme: Pick< - ParadigmThemeCssVarsWide, - 'x1' | 'sizePopupBasePadding' | 'colorTextAccent' - > = { - x1: { - name: '--paradigm--x1', - value: 'val(--paradigm--x1, 4px)', - originalValue: '4px', - }, - - sizePopupBasePadding: { - auto: { - name: '--vkui--size_popup_base_padding', - value: 'var(--vkui--size_popup_base_padding)', - }, - compact: { - name: '--vkui--size_popup_base_padding--compact', - value: 'var(--vkui--size_popup_base_padding--compact, 16px)', - originalValue: '16px', + const theme: Pick = + { + x1: { + name: '--paradigm--x1', + value: 'val(--paradigm--x1, 4px)', + originalValue: '4px', }, - regular: { - name: '--vkui--size_popup_base_padding--regular', - value: 'var(--vkui--size_popup_base_padding--regular, 20px)', - originalValue: '20px', - }, - }, - colorTextAccent: { - normal: { - name: '--vkui--color_text_accent', - value: 'val(--vkui--color_text_accent, white)', - originalValue: 'white', - }, - hover: { - name: '--vkui--color_text_accent--hover', - value: 'val(--vkui--color_text_accent--hover, black)', - originalValue: 'black', + sizePopupBasePadding: { + auto: { + name: '--vkui--size_popup_base_padding', + value: 'var(--vkui--size_popup_base_padding)', + }, + compact: { + name: '--vkui--size_popup_base_padding--compact', + value: 'var(--vkui--size_popup_base_padding--compact, 16px)', + originalValue: '16px', + }, + regular: { + name: '--vkui--size_popup_base_padding--regular', + value: 'var(--vkui--size_popup_base_padding--regular, 20px)', + originalValue: '20px', + }, }, - active: { - name: '--vkui--color_text_accent--active', - value: 'val(--vkui--color_text_accent--active, red)', - originalValue: 'red', + + colorTextAccent: { + normal: { + name: '--vkui--color_text_accent', + value: 'val(--vkui--color_text_accent, white)', + originalValue: 'white', + }, + hover: { + name: '--vkui--color_text_accent--hover', + value: 'val(--vkui--color_text_accent--hover, black)', + originalValue: 'black', + }, + active: { + name: '--vkui--color_text_accent--active', + value: 'val(--vkui--color_text_accent--active, red)', + originalValue: 'red', + }, }, - }, - }; - - expect( - compileGetDeclarationString( - theme as ParadigmThemeCssVarsWide, - 'onlyColors', - ), - ).toBe( + }; + + expect(compileGetDeclarationString(theme as ParadigmThemeCssVarsWide, 'onlyColors')).toBe( stripIndent` import {Properties} from 'csstype'; diff --git a/src/build/compilers/cssVars/jsUtils/compileGetDeclarationString.ts b/src/build/compilers/cssVars/jsUtils/compileGetDeclarationString.ts index f5947b52..803d4592 100644 --- a/src/build/compilers/cssVars/jsUtils/compileGetDeclarationString.ts +++ b/src/build/compilers/cssVars/jsUtils/compileGetDeclarationString.ts @@ -1,9 +1,9 @@ -import {stripIndent} from 'common-tags'; +import { stripIndent } from 'common-tags'; -import {accumulateValues} from '@/build/compilers/cssVars/helpers/accumulateValues'; -import {getVarString} from '@/build/compilers/cssVars/helpers/getVarString'; -import {getOnlyColors} from '@/build/helpers/getOnlyColors'; -import {Theme, ThemeCssVarsWide} from '@/interfaces/general'; +import { accumulateValues } from '@/build/compilers/cssVars/helpers/accumulateValues'; +import { getVarString } from '@/build/compilers/cssVars/helpers/getVarString'; +import { getOnlyColors } from '@/build/helpers/getOnlyColors'; +import { Theme, ThemeCssVarsWide } from '@/interfaces/general'; export type DeclarationType = 'default' | 'onlyColors'; @@ -14,16 +14,14 @@ export function compileGetDeclarationString( const theme: ThemeCssVarsWide = type === 'onlyColors' ? getOnlyColors(sourceTheme) : sourceTheme; - const {flatValues} = accumulateValues({ + const { flatValues } = accumulateValues({ theme, }); return stripIndent` import {Properties} from 'csstype'; - export function getDeclarationVar${ - type === 'onlyColors' ? 'Colors' : '' - }String(): string { + export function getDeclarationVar${type === 'onlyColors' ? 'Colors' : ''}String(): string { return \`${getVarString({ valuesObject: flatValues, prefix: '', @@ -31,9 +29,7 @@ export function compileGetDeclarationString( })}\`; } - export function getDeclarationVar${ - type === 'onlyColors' ? 'Colors' : '' - }Object(): Properties { + export function getDeclarationVar${type === 'onlyColors' ? 'Colors' : ''}Object(): Properties { return ${JSON.stringify(flatValues)} as Properties; } `; diff --git a/src/build/compilers/docs/__test__/testBaseTheme.ts b/src/build/compilers/docs/__test__/testBaseTheme.ts index 0a3f2b40..5766b0ae 100644 --- a/src/build/compilers/docs/__test__/testBaseTheme.ts +++ b/src/build/compilers/docs/__test__/testBaseTheme.ts @@ -1 +1 @@ -export {BaseTheme as BaseTheme1} from './testBaseForBase'; +export { BaseTheme as BaseTheme1 } from './testBaseForBase'; diff --git a/src/build/compilers/docs/__test__/testRecursiveReexport.ts b/src/build/compilers/docs/__test__/testRecursiveReexport.ts index 8bb071f9..8d7d0fcf 100644 --- a/src/build/compilers/docs/__test__/testRecursiveReexport.ts +++ b/src/build/compilers/docs/__test__/testRecursiveReexport.ts @@ -1 +1 @@ -export {BaseTheme1 as BaseTheme} from './testBaseTheme'; +export { BaseTheme1 as BaseTheme } from './testBaseTheme'; diff --git a/src/build/compilers/docs/__test__/testTheme.ts b/src/build/compilers/docs/__test__/testTheme.ts index 1065edf0..064cd3c5 100644 --- a/src/build/compilers/docs/__test__/testTheme.ts +++ b/src/build/compilers/docs/__test__/testTheme.ts @@ -1,5 +1,5 @@ -import {EmptyTheme} from '@/build/compilers/docs/__test__/emptyTheme'; -import {BaseTheme1} from '@/build/compilers/docs/__test__/testBaseTheme'; +import { EmptyTheme } from '@/build/compilers/docs/__test__/emptyTheme'; +import { BaseTheme1 } from '@/build/compilers/docs/__test__/testBaseTheme'; export interface BaseTheme2 { /** diff --git a/src/build/compilers/docs/compileDocsJSON.test.ts b/src/build/compilers/docs/compileDocsJSON.test.ts index c9aeba22..e29470c8 100644 --- a/src/build/compilers/docs/compileDocsJSON.test.ts +++ b/src/build/compilers/docs/compileDocsJSON.test.ts @@ -1,4 +1,4 @@ -import {getTypeDocs} from './compileDocsJSON'; +import { getTypeDocs } from './compileDocsJSON'; describe('compileDocsJSON', () => { it('should correct compile documentation with reexported interface', () => { @@ -16,10 +16,7 @@ describe('compileDocsJSON', () => { }); it('should correct compile documentation with imports', () => { - const docs = getTypeDocs( - 'src/build/compilers/docs/__test__/testTheme.ts', - 'ThemeTest', - ); + const docs = getTypeDocs('src/build/compilers/docs/__test__/testTheme.ts', 'ThemeTest'); expect(docs).toEqual({ prop: { diff --git a/src/build/compilers/docs/compileDocsJSON.ts b/src/build/compilers/docs/compileDocsJSON.ts index f6d0bc61..6b13d829 100644 --- a/src/build/compilers/docs/compileDocsJSON.ts +++ b/src/build/compilers/docs/compileDocsJSON.ts @@ -1,8 +1,8 @@ import path from 'path'; -import {JSDocTagInfo, Node, Project, SourceFile} from 'ts-morph'; +import { JSDocTagInfo, Node, Project, SourceFile } from 'ts-morph'; -import {capitalize} from '@/build/helpers/capitalize'; -import {SpecialTokens, Theme} from '@/interfaces/general'; +import { capitalize } from '@/build/helpers/capitalize'; +import { SpecialTokens, Theme } from '@/interfaces/general'; export interface ThemePropertyDoc { tags: string[]; @@ -23,10 +23,7 @@ function getTagText(tag: JSDocTagInfo): string { function resolveDeclaration(declaration: Node): Node[] { if (Node.isExportSpecifier(declaration)) { // export { A as B } from 'path/to/module.ts' - const declarations = declaration - .getNameNode() - .getSymbol() - .getDeclarations(); + const declarations = declaration.getNameNode().getSymbol().getDeclarations(); return resolveDeclarations(declarations); } @@ -39,10 +36,7 @@ function resolveDeclarations(declarations: Node[]): Node[] { }, []); } -function getExportedTypeDeclarations( - file: SourceFile, - typeName: string, -): Node[] { +function getExportedTypeDeclarations(file: SourceFile, typeName: string): Node[] { const exportSymbol = file.getExportSymbols().find((symbol) => { return symbol.getName() === typeName; }); @@ -51,9 +45,7 @@ function getExportedTypeDeclarations( return resolveDeclarations(declarations); } -function mapJsDocTagsToThemePropertyDoc( - tags: JSDocTagInfo[], -): ThemePropertyDoc { +function mapJsDocTagsToThemePropertyDoc(tags: JSDocTagInfo[]): ThemePropertyDoc { const doc: ThemePropertyDoc = { tags: [], desc: '', @@ -87,14 +79,12 @@ export function getTypeDocs(filePath: string, name: string): ThemeDocs { const properties = declaration.getType().getApparentProperties(); const docs = properties.reduce((all, prop) => { - all[prop.getName()] = mapJsDocTagsToThemePropertyDoc( - prop.getJsDocTags(), - ); + all[prop.getName()] = mapJsDocTagsToThemePropertyDoc(prop.getJsDocTags()); return all; }, {}); - return {...all, ...docs}; + return { ...all, ...docs }; }, {}); } @@ -125,12 +115,8 @@ export function getTypeDocs(filePath: string, name: string): ThemeDocs { * export interface MyDarkTheme extends MyTheme, BaseTheme, AnotherBaseTheme * - export { BaseTheme as MyTheme } from 'path/to/baseTheme.ts' */ -export function compileDocsJSON( - theme: T, -): string { - const themeFilePath = path.resolve( - `src/interfaces/themes/${theme.themeName}/index.ts`, - ); +export function compileDocsJSON(theme: T): string { + const themeFilePath = path.resolve(`src/interfaces/themes/${theme.themeName}/index.ts`); const themeInterfaceName = `Theme${capitalize(theme.themeName)}`; const docs = getTypeDocs(themeFilePath, themeInterfaceName); diff --git a/src/build/compilers/index.ts b/src/build/compilers/index.ts index 3fe55cf6..3a041c74 100644 --- a/src/build/compilers/index.ts +++ b/src/build/compilers/index.ts @@ -1,31 +1,18 @@ import fs from 'fs-extra'; import path from 'path'; -import {compileGetDeclarationString} from '@/build/compilers/cssVars/jsUtils/compileGetDeclarationString'; -import {compileDocsJSON} from '@/build/compilers/docs/compileDocsJSON'; -import {compileJSON} from '@/build/compilers/json/compileJSON'; -import { - compileStyles, - CompileStylesMode, -} from '@/build/compilers/styles/compileStyles'; -import {compileTypeScript} from '@/build/compilers/ts/compileTypeScript'; -import {capitalize} from '@/build/helpers/capitalize'; -import { - PixelifyTheme, - SpecialTokens, - Theme, - ThemeCssVarsWide, -} from '@/interfaces/general'; - -import {compileBreakpointsCssVarsDeclaration} from './cssVars/declarations/compileBreakpointsCssVarsDeclaration'; -import {compileStructJSON} from './structJSON/compileStructJSON'; - -type ThemeBuildType = - | 'root' - | 'subtheme' - | 'flat' - | 'cssVars' - | 'cssVarsPseudoRoot'; +import { compileGetDeclarationString } from '@/build/compilers/cssVars/jsUtils/compileGetDeclarationString'; +import { compileDocsJSON } from '@/build/compilers/docs/compileDocsJSON'; +import { compileJSON } from '@/build/compilers/json/compileJSON'; +import { compileStyles, CompileStylesMode } from '@/build/compilers/styles/compileStyles'; +import { compileTypeScript } from '@/build/compilers/ts/compileTypeScript'; +import { capitalize } from '@/build/helpers/capitalize'; +import { PixelifyTheme, SpecialTokens, Theme, ThemeCssVarsWide } from '@/interfaces/general'; + +import { compileBreakpointsCssVarsDeclaration } from './cssVars/declarations/compileBreakpointsCssVarsDeclaration'; +import { compileStructJSON } from './structJSON/compileStructJSON'; + +type ThemeBuildType = 'root' | 'subtheme' | 'flat' | 'cssVars' | 'cssVarsPseudoRoot'; interface CssModeConfig { mode: CompileStylesMode; @@ -34,24 +21,20 @@ interface CssModeConfig { } const cssModes: CssModeConfig[] = [ - {mode: 'default', fileName: 'index.css'}, - {mode: 'onlyVariables', fileName: 'onlyVariables.css'}, - {mode: 'onlyVariablesLocal', fileName: 'onlyVariablesLocal.css'}, + { mode: 'default', fileName: 'index.css' }, + { mode: 'onlyVariables', fileName: 'onlyVariables.css' }, + { mode: 'onlyVariablesLocal', fileName: 'onlyVariablesLocal.css' }, { mode: 'onlyVariablesLocalIncremental', fileName: 'onlyVariablesLocalIncremental.css', }, - {mode: 'onlyColors', fileName: 'onlyColors.css'}, - {mode: 'onlyAdaptiveGroups', fileName: 'onlyAdaptiveGroups.css'}, - {mode: 'noSizes', fileName: 'noSizes.css'}, - {mode: 'noColors', fileName: 'noColors.css'}, + { mode: 'onlyColors', fileName: 'onlyColors.css' }, + { mode: 'onlyAdaptiveGroups', fileName: 'onlyAdaptiveGroups.css' }, + { mode: 'noSizes', fileName: 'noSizes.css' }, + { mode: 'noColors', fileName: 'noColors.css' }, ]; -function writeStructJsonFile( - themePath: string, - theme: T, - _?: ThemeBuildType, -): void { +function writeStructJsonFile(themePath: string, theme: T, _?: ThemeBuildType): void { console.log(`компилируем структурный json...`); const fileName = `struct.json`; const filePath = path.resolve(themePath, fileName); @@ -63,11 +46,7 @@ function writeStructJsonFile( console.log(`успешно записали файл ${fileName}`); } -function writeJsonFile( - themePath: string, - theme: T, - _?: ThemeBuildType, -): void { +function writeJsonFile(themePath: string, theme: T, _?: ThemeBuildType): void { console.log(`компилируем json...`); const fileName = `index.json`; const filePath = path.resolve(themePath, fileName); @@ -96,50 +75,27 @@ function writeTsFile( switch (type) { case 'flat': content = sourceContent - .replace( - /\$\$InterfaceName\$\$/g, - `Theme${capitalize(theme.themeName)}Flat`, - ) - .replace( - /\$\$InterfaceURL\$\$/g, - `@/interfaces/themes/${theme.themeName}`, - ); + .replace(/\$\$InterfaceName\$\$/g, `Theme${capitalize(theme.themeName)}Flat`) + .replace(/\$\$InterfaceURL\$\$/g, `@/interfaces/themes/${theme.themeName}`); break; case 'subtheme': content = sourceContent - .replace( - /\$\$InterfaceName\$\$/g, - `SubTheme${capitalize((theme as any).parentThemeName)}`, - ) + .replace(/\$\$InterfaceName\$\$/g, `SubTheme${capitalize((theme as any).parentThemeName)}`) .replace( /\$\$InterfaceURL\$\$/g, - `@/interfaces/themes/${ - (theme as any).parentThemeName - }/subthemes`, + `@/interfaces/themes/${(theme as any).parentThemeName}/subthemes`, ); break; case 'cssVars': content = sourceContent - .replace( - /\$\$InterfaceName\$\$/g, - `Theme${capitalize(themeName)}CssVars`, - ) - .replace( - /\$\$InterfaceURL\$\$/g, - `@/interfaces/themes/${themeName}`, - ); + .replace(/\$\$InterfaceName\$\$/g, `Theme${capitalize(themeName)}CssVars`) + .replace(/\$\$InterfaceURL\$\$/g, `@/interfaces/themes/${themeName}`); break; case 'root': default: content = sourceContent - .replace( - /\$\$InterfaceName\$\$/g, - `Theme${capitalize(theme.themeName)}`, - ) - .replace( - /\$\$InterfaceURL\$\$/g, - `@/interfaces/themes/${theme.themeName}`, - ); + .replace(/\$\$InterfaceName\$\$/g, `Theme${capitalize(theme.themeName)}`) + .replace(/\$\$InterfaceURL\$\$/g, `@/interfaces/themes/${theme.themeName}`); } fs.writeFileSync(filePath, content); @@ -181,19 +137,13 @@ function writeCssVarsSourceFile( const compiledVars = compileStyles( 'css', theme, - modeConfig.mode === 'default' - ? 'withAdaptiveGroups' - : modeConfig.mode, + modeConfig.mode === 'default' ? 'withAdaptiveGroups' : modeConfig.mode, themeBase, ); const compiledBreakpoints = modeConfig.mode === 'default' - ? `\n\n${ - compileBreakpointsCssVarsDeclaration( - cssVarsTheme as any, - ) ?? '' - }` + ? `\n\n${compileBreakpointsCssVarsDeclaration(cssVarsTheme as any) ?? ''}` : ''; if (compiledBreakpoints.includes('null')) { @@ -208,10 +158,7 @@ function writeCssVarsSourceFile( } } -function writeCssVarsSourceMediaFile( - themePath: string, - theme: T, -): void { +function writeCssVarsSourceMediaFile(themePath: string, theme: T): void { console.log(`компилируем медиа переменные для css vars тем...`); const fileName = 'onlyMedia.css'; @@ -226,18 +173,15 @@ function writeCssVarsSourceMediaFile( } } -function writeCssVarsJsUtils( - themePath: string, - theme: ThemeCssVarsWide, -): void { +function writeCssVarsJsUtils(themePath: string, theme: ThemeCssVarsWide): void { console.log(`компилируем утилиты для js для css vars тем...`); ( [ - {mode: 'default', fileName: 'onlyVariables.ts'}, - {mode: 'onlyColors', fileName: 'onlyColors.ts'}, + { mode: 'default', fileName: 'onlyVariables.ts' }, + { mode: 'onlyColors', fileName: 'onlyColors.ts' }, ] as const - ).forEach(({mode, fileName}) => { + ).forEach(({ mode, fileName }) => { const filePath = path.resolve(themePath, fileName); const content = compileGetDeclarationString(theme, mode); @@ -248,10 +192,7 @@ function writeCssVarsJsUtils( }); } -function writeDocsFiles( - themePath: string, - theme: T, -): void { +function writeDocsFiles(themePath: string, theme: T): void { console.log(`компилируем документацию...`); const fileName = `docs.json`; const filePath = path.resolve(themePath, fileName); diff --git a/src/build/compilers/json/compileJSON.test.ts b/src/build/compilers/json/compileJSON.test.ts index c5d2101b..09405481 100644 --- a/src/build/compilers/json/compileJSON.test.ts +++ b/src/build/compilers/json/compileJSON.test.ts @@ -1,4 +1,4 @@ -import {compileJSON} from './compileJSON'; +import { compileJSON } from './compileJSON'; describe('compileJSON', () => { it('should correct stringify', () => { diff --git a/src/build/compilers/json/compileJSON.ts b/src/build/compilers/json/compileJSON.ts index 7f7c78a8..3f3d31ee 100644 --- a/src/build/compilers/json/compileJSON.ts +++ b/src/build/compilers/json/compileJSON.ts @@ -1,4 +1,4 @@ -import {Theme} from '@/interfaces/general'; +import { Theme } from '@/interfaces/general'; /** * Компилирует json с темой diff --git a/src/build/compilers/structJSON/compileStructJSON.test.ts b/src/build/compilers/structJSON/compileStructJSON.test.ts index 8df1e310..4ff68463 100644 --- a/src/build/compilers/structJSON/compileStructJSON.test.ts +++ b/src/build/compilers/structJSON/compileStructJSON.test.ts @@ -1,4 +1,4 @@ -import {compileStructJSON} from './compileStructJSON'; +import { compileStructJSON } from './compileStructJSON'; describe('compileJSON', () => { it('should correct stringify', () => { diff --git a/src/build/compilers/structJSON/compileStructJSON.ts b/src/build/compilers/structJSON/compileStructJSON.ts index 2ca25234..6e1b031a 100644 --- a/src/build/compilers/structJSON/compileStructJSON.ts +++ b/src/build/compilers/structJSON/compileStructJSON.ts @@ -1,4 +1,4 @@ -import type {Theme} from '@/interfaces/general'; +import type { Theme } from '@/interfaces/general'; export type ValuesOf = T[number]; @@ -25,8 +25,7 @@ export const compileStructJSON = (theme: T): string => { const structTheme = {}; Object.keys(theme).forEach((key) => { - const group = - groups.find((predicate) => key.startsWith(predicate)) || 'other'; + const group = groups.find((predicate) => key.startsWith(predicate)) || 'other'; if (!structTheme[group]) { structTheme[group] = {}; diff --git a/src/build/compilers/styles/compileStyles.test.ts b/src/build/compilers/styles/compileStyles.test.ts index ec0a219a..3b2ace21 100644 --- a/src/build/compilers/styles/compileStyles.test.ts +++ b/src/build/compilers/styles/compileStyles.test.ts @@ -1,10 +1,10 @@ -import {stripIndent} from 'common-tags'; +import { stripIndent } from 'common-tags'; -import {PixelifyTheme} from '@/interfaces/general'; -import {ParadigmTheme} from '@/interfaces/namespaces/paradigm'; +import { PixelifyTheme } from '@/interfaces/general'; +import { ParadigmTheme } from '@/interfaces/namespaces/paradigm'; -import {compileStyles, CompileStylesMode} from './compileStyles'; -import {EStyleTypes, Formats} from './helpers/tokenProcessors'; +import { compileStyles, CompileStylesMode } from './compileStyles'; +import { EStyleTypes, Formats } from './helpers/tokenProcessors'; type DescriptionTheme = Partial> & Pick; @@ -479,29 +479,27 @@ describe('compileStyles', () => { }); }); - test.each(formats)( - '%s: should compile adaptive class variables with onlyAdaptiveGroups', - (f) => { - runTest(f, { - descriptionTheme: { - themeName: 'testTheme', - colorsScheme: 'light', - fontText: { - regular: { - fontSize: '15px', - lineHeight: '20px', - fontFamily: 'Arial', - fontWeight: 500, - }, - compact: { - fontSize: '16px', - lineHeight: '24px', - }, + test.each(formats)('%s: should compile adaptive class variables with onlyAdaptiveGroups', (f) => { + runTest(f, { + descriptionTheme: { + themeName: 'testTheme', + colorsScheme: 'light', + fontText: { + regular: { + fontSize: '15px', + lineHeight: '20px', + fontFamily: 'Arial', + fontWeight: 500, + }, + compact: { + fontSize: '16px', + lineHeight: '24px', }, }, - mode: 'onlyAdaptiveGroups', - result: { - css: stripIndent` + }, + mode: 'onlyAdaptiveGroups', + result: { + css: stripIndent` .vkui--font_text { font-size: var(--vkui--font_text--font_size); line-height: var(--vkui--font_text--line_height); @@ -509,15 +507,14 @@ describe('compileStyles', () => { font-weight: var(--vkui--font_text--font_weight); } `, - scss: stripIndent``, - pcss: stripIndent``, - less: stripIndent``, + scss: stripIndent``, + pcss: stripIndent``, + less: stripIndent``, - styl: stripIndent``, - }, - }); - }, - ); + styl: stripIndent``, + }, + }); + }); test.each(formats)( '%s: should compile adaptive class variables with mode=withAdaptiveGroups', diff --git a/src/build/compilers/styles/compileStyles.ts b/src/build/compilers/styles/compileStyles.ts index 54d22a91..8b2783a9 100644 --- a/src/build/compilers/styles/compileStyles.ts +++ b/src/build/compilers/styles/compileStyles.ts @@ -1,13 +1,13 @@ import 'css.escape'; -import {deepStrictEqual} from 'assert'; -import {stripIndent} from 'common-tags'; +import { deepStrictEqual } from 'assert'; +import { stripIndent } from 'common-tags'; -import {getAllButColors} from '@/build/helpers/getAllButColors'; -import {getAllButSizes} from '@/build/helpers/getAllButSizes'; -import {getOnlyColors} from '@/build/helpers/getOnlyColors'; -import {unCamelcasify} from '@/build/helpers/unCamelcasify'; -import {PixelifyTheme} from '@/interfaces/general'; +import { getAllButColors } from '@/build/helpers/getAllButColors'; +import { getAllButSizes } from '@/build/helpers/getAllButSizes'; +import { getOnlyColors } from '@/build/helpers/getOnlyColors'; +import { unCamelcasify } from '@/build/helpers/unCamelcasify'; +import { PixelifyTheme } from '@/interfaces/general'; import { customMediaDeclaration, @@ -42,10 +42,7 @@ function isClassicCssType(format: Formats): boolean { return format === EStyleTypes.CSS || format === EStyleTypes.PCSS; } -export function getPrefix( - format: Formats, - theme: PT, -): string { +export function getPrefix(format: Formats, theme: PT): string { let prefix = theme.prefix ? `${theme.prefix}-` : ''; if (isClassicCssType(format) && prefix) { @@ -83,9 +80,7 @@ export function getRootSelector( return ':root'; } - return `.${getPrefix(EStyleTypes.CSS, theme)}${getThemeNameBase(theme)}--${ - theme.colorsScheme - }`; + return `.${getPrefix(EStyleTypes.CSS, theme)}${getThemeNameBase(theme)}--${theme.colorsScheme}`; } function isDeepEqual(actual: unknown, expected: unknown): boolean { @@ -149,10 +144,7 @@ export const compileStyles = ( // если переменная — строка (например, имя темы) if (isString(token, key)) { - variables += getVariableStatement( - getDeclaration(key, prefix), - `'${CSS.escape(token)}'`, - ); + variables += getVariableStatement(getDeclaration(key, prefix), `'${CSS.escape(token)}'`); return; } @@ -193,10 +185,7 @@ export const compileStyles = ( variables += getVariableStatement( getDeclaration(key, prefix), value, - `--${unCamelcasify( - adaptivivityState, - classicCssType ? '_' : '-', - )}`, + `--${unCamelcasify(adaptivivityState, classicCssType ? '_' : '-')}`, ); }); return; diff --git a/src/build/compilers/styles/helpers/tokenProcessors.ts b/src/build/compilers/styles/helpers/tokenProcessors.ts index 26ef7005..2f19d583 100644 --- a/src/build/compilers/styles/helpers/tokenProcessors.ts +++ b/src/build/compilers/styles/helpers/tokenProcessors.ts @@ -1,7 +1,7 @@ -import {stripIndent} from 'common-tags'; +import { stripIndent } from 'common-tags'; -import {unCamelcasify} from '@/build/helpers/unCamelcasify'; -import {Adaptive} from '@/interfaces/general/tools'; +import { unCamelcasify } from '@/build/helpers/unCamelcasify'; +import { Adaptive } from '@/interfaces/general/tools'; export const EStyleTypes = { CSS: 'css', @@ -14,29 +14,19 @@ export const EStyleTypes = { export type Formats = typeof EStyleTypes[keyof typeof EStyleTypes]; export const varDeclarations = { - [EStyleTypes.CSS]: (prop, prefix = '') => - `--${prefix}${unCamelcasify(prop, '_')}`, - [EStyleTypes.PCSS]: (prop, prefix = '_') => - `--${prefix}${unCamelcasify(prop)}`, - [EStyleTypes.SCSS]: (prop, prefix = '') => - `$${prefix}${unCamelcasify(prop)}`, - [EStyleTypes.LESS]: (prop, prefix = '') => - `@${prefix}${unCamelcasify(prop)}`, - [EStyleTypes.STYL]: (prop, prefix = '') => - `$${prefix}${unCamelcasify(prop)}`, + [EStyleTypes.CSS]: (prop, prefix = '') => `--${prefix}${unCamelcasify(prop, '_')}`, + [EStyleTypes.PCSS]: (prop, prefix = '_') => `--${prefix}${unCamelcasify(prop)}`, + [EStyleTypes.SCSS]: (prop, prefix = '') => `$${prefix}${unCamelcasify(prop)}`, + [EStyleTypes.LESS]: (prop, prefix = '') => `@${prefix}${unCamelcasify(prop)}`, + [EStyleTypes.STYL]: (prop, prefix = '') => `$${prefix}${unCamelcasify(prop)}`, } as const; export const variablesStatementDeclaration = { - [EStyleTypes.CSS]: (key, token, postfix = '') => - `\t${key}${postfix}: ${token};\n`, - [EStyleTypes.PCSS]: (key, token, postfix = '') => - `\t${key}${postfix}: ${token};\n`, - [EStyleTypes.SCSS]: (key, token, postfix = '') => - `${key}${postfix}: ${token};\n`, - [EStyleTypes.LESS]: (key, token, postfix = '') => - `${key}${postfix}: ${token};\n`, - [EStyleTypes.STYL]: (key, token, postfix = '') => - `${key}${postfix} = ${token};\n`, + [EStyleTypes.CSS]: (key, token, postfix = '') => `\t${key}${postfix}: ${token};\n`, + [EStyleTypes.PCSS]: (key, token, postfix = '') => `\t${key}${postfix}: ${token};\n`, + [EStyleTypes.SCSS]: (key, token, postfix = '') => `${key}${postfix}: ${token};\n`, + [EStyleTypes.LESS]: (key, token, postfix = '') => `${key}${postfix}: ${token};\n`, + [EStyleTypes.STYL]: (key, token, postfix = '') => `${key}${postfix} = ${token};\n`, } as const; export const mixinDeclaration = { @@ -79,9 +69,7 @@ export const customMediaDeclaration = { interface ProcessGroupTokenParams { format: Formats; - token: - | Adaptive> - | Record; + token: Adaptive> | Record; key: string; prefix: string; adaptiveMode?: 'none' | 'onlyAdaptiveGroups' | 'withAdaptiveGroups'; @@ -103,25 +91,18 @@ export function processGroupToken({ key, prefix, adaptiveMode = 'none', -}: ProcessGroupTokenParams): {variables: string; groupTokens: string} { +}: ProcessGroupTokenParams): { variables: string; groupTokens: string } { const needUpdateVariables = format === EStyleTypes.CSS; const needMap = format === EStyleTypes.SCSS; const needAddAdaptiveClasses = - (adaptiveMode === 'withAdaptiveGroups' || - adaptiveMode === 'onlyAdaptiveGroups') && + (adaptiveMode === 'withAdaptiveGroups' || adaptiveMode === 'onlyAdaptiveGroups') && format === EStyleTypes.CSS; - const defineStyleProperty = ( - subKey: string, - subToken: string, - varName?: string, - ) => { + const defineStyleProperty = (subKey: string, subToken: string, varName?: string) => { let result = `\t${unCamelcasify(subKey)}: ${subToken};\n`; if (needUpdateVariables) { - result += `\t${unCamelcasify( - subKey, - )}: var(${varName}, ${subToken});\n`; + result += `\t${unCamelcasify(subKey)}: var(${varName}, ${subToken});\n`; } return result; @@ -147,9 +128,7 @@ export function processGroupToken({ } if (needMap) { - map += `${varDeclarations.scss(key, prefix)}--${unCamelcasify( - adaptivityState, - )}--map: (\n`; + map += `${varDeclarations.scss(key, prefix)}--${unCamelcasify(adaptivityState)}--map: (\n`; } Object.entries({ @@ -159,32 +138,21 @@ export function processGroupToken({ let varName = ''; if (needUpdateVariables) { - const reallyNewToken = - token[adaptivityState][subKey] !== undefined; - - varName = `${varDeclarations.css( - key, - prefix, - )}--${unCamelcasify(subKey, '_')}--${ - reallyNewToken - ? unCamelcasify(adaptivityState, '_') - : 'regular' + const reallyNewToken = token[adaptivityState][subKey] !== undefined; + + varName = `${varDeclarations.css(key, prefix)}--${unCamelcasify(subKey, '_')}--${ + reallyNewToken ? unCamelcasify(adaptivityState, '_') : 'regular' }`; if (reallyNewToken) { - variables += variablesStatementDeclaration.css( - varName, - subValue, - ); + variables += variablesStatementDeclaration.css(varName, subValue); } } groupTokens += defineStyleProperty(subKey, subValue, varName); if (needAddAdaptiveClasses && !addedAdaptiveGroup) { - adaptiveGroup += `\t${unCamelcasify( - subKey, - )}: var(${varName.replace( + adaptiveGroup += `\t${unCamelcasify(subKey)}: var(${varName.replace( new RegExp(`--(regular|${adaptivityState})$`), '', )});\n`; @@ -213,7 +181,7 @@ export function processGroupToken({ groupTokens = adaptiveGroup; } - return {variables, groupTokens}; + return { variables, groupTokens }; } // неадаптивная группа @@ -227,10 +195,7 @@ export function processGroupToken({ let varName = ''; if (needUpdateVariables) { - varName = `${varDeclarations.css(key, prefix)}--${unCamelcasify( - subKey, - '_', - )}`; + varName = `${varDeclarations.css(key, prefix)}--${unCamelcasify(subKey, '_')}`; variables += variablesStatementDeclaration.css(varName, subValue); } @@ -247,5 +212,5 @@ export function processGroupToken({ groupTokens += map; } - return {variables, groupTokens}; + return { variables, groupTokens }; } diff --git a/src/build/compilers/styles/helpers/tokenRecognition.ts b/src/build/compilers/styles/helpers/tokenRecognition.ts index 0622764a..95f4cd79 100644 --- a/src/build/compilers/styles/helpers/tokenRecognition.ts +++ b/src/build/compilers/styles/helpers/tokenRecognition.ts @@ -1,11 +1,8 @@ -import {processCustomMedia} from '@/build/themeProcessors/customMedia/customMedia'; -import {ColorWithStates} from '@/interfaces/general/colors'; -import {Adaptive} from '@/interfaces/general/tools'; -import {CustomMediaByViewportUnion} from '@/interfaces/general/tools/customMedia'; -import { - ViewportsOrdered, - ViewportsTuple, -} from '@/interfaces/general/tools/viewports'; +import { processCustomMedia } from '@/build/themeProcessors/customMedia/customMedia'; +import { ColorWithStates } from '@/interfaces/general/colors'; +import { Adaptive } from '@/interfaces/general/tools'; +import { CustomMediaByViewportUnion } from '@/interfaces/general/tools/customMedia'; +import { ViewportsOrdered, ViewportsTuple } from '@/interfaces/general/tools/viewports'; const stringKeys = ['themeName', 'themeNameBase', 'themeInheritsFrom']; @@ -72,8 +69,6 @@ const allCustomMediaKeys = Object.keys( }), ); -export function isCustomMediaToken( - key: any, -): key is CustomMediaByViewportUnion { +export function isCustomMediaToken(key: any): key is CustomMediaByViewportUnion { return typeof key === 'string' && allCustomMediaKeys.includes(key); } diff --git a/src/build/compilers/ts/compileTypeScript.test.ts b/src/build/compilers/ts/compileTypeScript.test.ts index a2209390..4cc8f41b 100644 --- a/src/build/compilers/ts/compileTypeScript.test.ts +++ b/src/build/compilers/ts/compileTypeScript.test.ts @@ -1,4 +1,4 @@ -import {compileTypeScript} from '@/build/compilers/ts/compileTypeScript'; +import { compileTypeScript } from '@/build/compilers/ts/compileTypeScript'; describe('compileTypeScript', () => { const testData = { @@ -6,8 +6,7 @@ describe('compileTypeScript', () => { }; it('should work', () => { - expect(compileTypeScript(testData)) - .toBe(`import { $$InterfaceName$$ } from '$$InterfaceURL$$'; + expect(compileTypeScript(testData)).toBe(`import { $$InterfaceName$$ } from '$$InterfaceURL$$'; const theme: $$InterfaceName$$ = { "themeName": "base" diff --git a/src/build/compilers/ts/compileTypeScript.ts b/src/build/compilers/ts/compileTypeScript.ts index bf463bbb..27f63955 100644 --- a/src/build/compilers/ts/compileTypeScript.ts +++ b/src/build/compilers/ts/compileTypeScript.ts @@ -1,5 +1,5 @@ -import {compileJSON} from '@/build/compilers/json/compileJSON'; -import {Theme} from '@/interfaces/general'; +import { compileJSON } from '@/build/compilers/json/compileJSON'; +import { Theme } from '@/interfaces/general'; /** * Компилирует строку с ts видом темы diff --git a/src/build/expandTheme.test.ts b/src/build/expandTheme.test.ts index 0bb354fd..fb83f442 100644 --- a/src/build/expandTheme.test.ts +++ b/src/build/expandTheme.test.ts @@ -1,4 +1,4 @@ -import {expandAll, expandRootTheme} from '@/build/expandTheme'; +import { expandAll, expandRootTheme } from '@/build/expandTheme'; describe('expandTheme', () => { describe('expandRootTheme', () => { diff --git a/src/build/expandTheme.ts b/src/build/expandTheme.ts index 1659d4a1..5f72df3d 100644 --- a/src/build/expandTheme.ts +++ b/src/build/expandTheme.ts @@ -1,10 +1,10 @@ -import {createPseudoRootFromCssVars} from '@/build/themeProcessors/createPseudoRootFromCssVars/createPseudoRootFromCssVars'; -import {processCustomMedia} from '@/build/themeProcessors/customMedia/customMedia'; -import {getExpandedThemeColors} from '@/build/themeProcessors/expandColors/expandColors'; -import {extractCssVarsStrict} from '@/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict'; -import {extractGeneralTokens} from '@/build/themeProcessors/extractGeneralTokens/extractGeneralTokens'; -import {extractVarsNames} from '@/build/themeProcessors/extractVarsNames/extractVarsNames'; -import {pixelifyValues} from '@/build/themeProcessors/pixelifyValues/pixelifyValues'; +import { createPseudoRootFromCssVars } from '@/build/themeProcessors/createPseudoRootFromCssVars/createPseudoRootFromCssVars'; +import { processCustomMedia } from '@/build/themeProcessors/customMedia/customMedia'; +import { getExpandedThemeColors } from '@/build/themeProcessors/expandColors/expandColors'; +import { extractCssVarsStrict } from '@/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict'; +import { extractGeneralTokens } from '@/build/themeProcessors/extractGeneralTokens/extractGeneralTokens'; +import { extractVarsNames } from '@/build/themeProcessors/extractVarsNames/extractVarsNames'; +import { pixelifyValues } from '@/build/themeProcessors/pixelifyValues/pixelifyValues'; import { PixelifyTheme, Theme, @@ -12,7 +12,7 @@ import { ThemeCssVarsWide, ThemeDescription, } from '@/interfaces/general'; -import {StaticTokens} from '@/interfaces/general/tools/tokenValue'; +import { StaticTokens } from '@/interfaces/general/tools/tokenValue'; export interface ExpandedThemeObject { theme: StaticTokens; @@ -51,13 +51,9 @@ export function expandAll( const pixelifyTheme = pixelifyValues(theme); const cssVarsThemeWide = extractVarsNames>(theme); - const cssVarsTheme = - extractCssVarsStrict>(cssVarsThemeWide); + const cssVarsTheme = extractCssVarsStrict>(cssVarsThemeWide); - const pseudoThemeCssVars = createPseudoRootFromCssVars>( - theme, - cssVarsThemeWide, - ); + const pseudoThemeCssVars = createPseudoRootFromCssVars>(theme, cssVarsThemeWide); return { theme, diff --git a/src/build/helpers/capitalize.test.ts b/src/build/helpers/capitalize.test.ts index 8cf51015..980ac9d2 100644 --- a/src/build/helpers/capitalize.test.ts +++ b/src/build/helpers/capitalize.test.ts @@ -1,6 +1,6 @@ -import {expect} from '@jest/globals'; +import { expect } from '@jest/globals'; -import {capitalize} from './capitalize'; +import { capitalize } from './capitalize'; describe('capitalize', () => { it('should work without letters', () => { diff --git a/src/build/helpers/convertCamelToSnake.test.ts b/src/build/helpers/convertCamelToSnake.test.ts index 054b1a4a..adfec0ae 100644 --- a/src/build/helpers/convertCamelToSnake.test.ts +++ b/src/build/helpers/convertCamelToSnake.test.ts @@ -1,4 +1,4 @@ -import {convertCamelToSnake} from './convertCamelToSnake'; +import { convertCamelToSnake } from './convertCamelToSnake'; describe('convertCamelToSnake', () => { it('should correctly work with empty string', () => { @@ -18,14 +18,10 @@ describe('convertCamelToSnake', () => { }); it('should convert many words string', () => { - expect(convertCamelToSnake('helloWorldMyFriend')).toBe( - 'hello_world_my_friend', - ); + expect(convertCamelToSnake('helloWorldMyFriend')).toBe('hello_world_my_friend'); }); it('should convert special case 1', () => { - expect(convertCamelToSnake('octaviusShadowLetterList')).toBe( - 'octavius_shadow_letter_list', - ); + expect(convertCamelToSnake('octaviusShadowLetterList')).toBe('octavius_shadow_letter_list'); }); }); diff --git a/src/build/helpers/convertCamelToSnake.ts b/src/build/helpers/convertCamelToSnake.ts index ed7b21a4..0219e414 100644 --- a/src/build/helpers/convertCamelToSnake.ts +++ b/src/build/helpers/convertCamelToSnake.ts @@ -2,7 +2,5 @@ * camelCase -> snake_case */ export function convertCamelToSnake(str: string): string { - return str - .replace(/([A-Z])/g, (letter) => `_${letter.toLowerCase()}`) - .replace(/^_/, ''); + return str.replace(/([A-Z])/g, (letter) => `_${letter.toLowerCase()}`).replace(/^_/, ''); } diff --git a/src/build/helpers/cssHelpers.test.ts b/src/build/helpers/cssHelpers.test.ts index 1f95c640..fd8d3737 100644 --- a/src/build/helpers/cssHelpers.test.ts +++ b/src/build/helpers/cssHelpers.test.ts @@ -1,4 +1,4 @@ -import {getRGBA, toneOpacity} from './cssHelpers'; +import { getRGBA, toneOpacity } from './cssHelpers'; describe('cssHelpers', () => { describe('getRGBA', () => { diff --git a/src/build/helpers/cssHelpers.ts b/src/build/helpers/cssHelpers.ts index 09e50382..8525e822 100644 --- a/src/build/helpers/cssHelpers.ts +++ b/src/build/helpers/cssHelpers.ts @@ -8,10 +8,7 @@ import { const hexToRgb = (hex: string) => { const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result - ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt( - result[3], - 16, - )}` + ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}` : ''; }; @@ -25,15 +22,11 @@ export function isColorWithStates(value: unknown): value is ColorWithStates { ); } -export function isColorDescriptionCallable( - value: unknown, -): value is ColorDescriptionCallable { +export function isColorDescriptionCallable(value: unknown): value is ColorDescriptionCallable { return typeof value === 'function'; } -export function isColorDescriptionStatic( - value: unknown, -): value is ColorDescriptionStatic { +export function isColorDescriptionStatic(value: unknown): value is ColorDescriptionStatic { return typeof value === 'string' || isColorWithStates(value); } @@ -42,10 +35,7 @@ export function isColorDescriptionStatic( * @use toneOpacity * TODO: remove */ -export function getRGBA( - color: ColorDescription, - opacity: number, -): ColorDescription { +export function getRGBA(color: ColorDescription, opacity: number): ColorDescription { if (isColorDescriptionStatic(color)) { if (isColorWithStates(color)) { return `rgba(${hexToRgb(color.normal)}, ${opacity})`; @@ -60,13 +50,7 @@ export function getRGBA( } export function toneOpacity(color: string, opacity: number): string; -export function toneOpacity( - color: ColorDescription, - opacity: number, -): ColorDescription; -export function toneOpacity( - color: ColorDescription, - opacity: number, -): ColorDescription { +export function toneOpacity(color: ColorDescription, opacity: number): ColorDescription; +export function toneOpacity(color: ColorDescription, opacity: number): ColorDescription { return getRGBA(color, opacity); } diff --git a/src/build/helpers/flatifyTheme.test.ts b/src/build/helpers/flatifyTheme.test.ts index 2c80f907..c063a735 100644 --- a/src/build/helpers/flatifyTheme.test.ts +++ b/src/build/helpers/flatifyTheme.test.ts @@ -1,5 +1,5 @@ -import {flatifyTheme} from '@/build/helpers/flatifyTheme'; -import {ThemeDescription} from '@/interfaces/general'; +import { flatifyTheme } from '@/build/helpers/flatifyTheme'; +import { ThemeDescription } from '@/interfaces/general'; describe('flatifyTheme', () => { it('should return new object', () => { @@ -15,18 +15,18 @@ describe('flatifyTheme', () => { }); it('should not touch flat vars', () => { - const theme: Partial = {opacityDisable: 0.5}; + const theme: Partial = { opacityDisable: 0.5 }; - expect(flatifyTheme(theme)).toStrictEqual({opacityDisable: 0.5}); + expect(flatifyTheme(theme)).toStrictEqual({ opacityDisable: 0.5 }); }); it('should not touch colors', () => { const theme: Partial = { - colors: {colorTextPrimary: 'blue'} as any, + colors: { colorTextPrimary: 'blue' } as any, }; expect(flatifyTheme(theme)).toStrictEqual({ - colors: {colorTextPrimary: 'blue'}, + colors: { colorTextPrimary: 'blue' }, }); }); diff --git a/src/build/helpers/flatifyTheme.ts b/src/build/helpers/flatifyTheme.ts index fca5d660..2b445f8d 100644 --- a/src/build/helpers/flatifyTheme.ts +++ b/src/build/helpers/flatifyTheme.ts @@ -1,15 +1,9 @@ -import {ThemeDescription} from '@/interfaces/general'; -import {Adaptive} from '@/interfaces/general/tools'; +import { ThemeDescription } from '@/interfaces/general'; +import { Adaptive } from '@/interfaces/general/tools'; export function flatifyTheme( theme: T, - removeStates: (keyof Adaptive)[] = [ - 'compactX', - 'compact', - 'large', - 'largeX', - 'largeXX', - ], + removeStates: (keyof Adaptive)[] = ['compactX', 'compact', 'large', 'largeX', 'largeXX'], ): T { return Object.entries(theme).reduce((acc, [themeKey, themeValue]) => { if (typeof themeValue === 'object') { diff --git a/src/build/helpers/getAllButColors.test.ts b/src/build/helpers/getAllButColors.test.ts index 3e8d16a2..7ba82388 100644 --- a/src/build/helpers/getAllButColors.test.ts +++ b/src/build/helpers/getAllButColors.test.ts @@ -1,4 +1,4 @@ -import {getAllButColors} from '@/build/helpers/getAllButColors'; +import { getAllButColors } from '@/build/helpers/getAllButColors'; describe('getAllButColors', () => { it('should filter out tokens that start with "color"', () => { diff --git a/src/build/helpers/getAllButColors.ts b/src/build/helpers/getAllButColors.ts index fa2caff2..cb6f9112 100644 --- a/src/build/helpers/getAllButColors.ts +++ b/src/build/helpers/getAllButColors.ts @@ -1,9 +1,6 @@ const regexSize = /^color/i; -export function getAllButColors( - theme: Record, - themeNameBase?: unknown, -): any { +export function getAllButColors(theme: Record, themeNameBase?: unknown): any { return Object.keys(theme).reduce>((acc, key) => { const value = theme[key]; diff --git a/src/build/helpers/getAllButSizes.test.ts b/src/build/helpers/getAllButSizes.test.ts index fe57e69b..65dee649 100644 --- a/src/build/helpers/getAllButSizes.test.ts +++ b/src/build/helpers/getAllButSizes.test.ts @@ -1,4 +1,4 @@ -import {getAllButSizes} from '@/build/helpers/getAllButSizes'; +import { getAllButSizes } from '@/build/helpers/getAllButSizes'; describe('getAllButSizes', () => { it('should filter out tokens that start with "size", "font" or are a size helper', () => { diff --git a/src/build/helpers/getAllButSizes.ts b/src/build/helpers/getAllButSizes.ts index f8bf35c6..484f182d 100644 --- a/src/build/helpers/getAllButSizes.ts +++ b/src/build/helpers/getAllButSizes.ts @@ -1,9 +1,6 @@ const regexSize = /^(size|font|x\d+)/i; -export function getAllButSizes( - theme: Record, - themeNameBase?: unknown, -): any { +export function getAllButSizes(theme: Record, themeNameBase?: unknown): any { return Object.keys(theme).reduce>((acc, key) => { const value = theme[key]; diff --git a/src/build/helpers/getGradientPointsFromColor.test.ts b/src/build/helpers/getGradientPointsFromColor.test.ts index 6ad606a7..38a0641f 100644 --- a/src/build/helpers/getGradientPointsFromColor.test.ts +++ b/src/build/helpers/getGradientPointsFromColor.test.ts @@ -1,4 +1,4 @@ -import {getGradientPointsFromColor} from '@/build/helpers/getGradientPointsFromColor'; +import { getGradientPointsFromColor } from '@/build/helpers/getGradientPointsFromColor'; describe('getGradientPointsFromColor', () => { it('should generate gradient from color', () => { diff --git a/src/build/helpers/getGradientPointsFromColor.ts b/src/build/helpers/getGradientPointsFromColor.ts index f92fdc69..d800bc3e 100644 --- a/src/build/helpers/getGradientPointsFromColor.ts +++ b/src/build/helpers/getGradientPointsFromColor.ts @@ -1,7 +1,7 @@ import color from 'color'; -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {GradientPoints} from '@/interfaces/general/gradients'; +import { GradientPoints } from '@/interfaces/general/gradients'; type OpacityMap = Array<[number, number]>; diff --git a/src/build/helpers/getOnlyColors.test.ts b/src/build/helpers/getOnlyColors.test.ts index dcfc6856..51ff9c61 100644 --- a/src/build/helpers/getOnlyColors.test.ts +++ b/src/build/helpers/getOnlyColors.test.ts @@ -1,4 +1,4 @@ -import {getOnlyColors} from '@/build/helpers/getOnlyColors'; +import { getOnlyColors } from '@/build/helpers/getOnlyColors'; describe('getOnlyColors', () => { it('should filter out tokens that do not look like a color', () => { diff --git a/src/build/helpers/getStateFunctions.test.ts b/src/build/helpers/getStateFunctions.test.ts index 04f0e32d..8294e553 100644 --- a/src/build/helpers/getStateFunctions.test.ts +++ b/src/build/helpers/getStateFunctions.test.ts @@ -1,6 +1,6 @@ -import {expect} from '@jest/globals'; +import { expect } from '@jest/globals'; -import {getStateFunctions} from './getStateFunctions'; +import { getStateFunctions } from './getStateFunctions'; describe('getStateFunctions', () => { const testThemeData = { @@ -29,9 +29,7 @@ describe('getStateFunctions', () => { describe('stateHover', () => { it('should correctly work with transparent', () => { - expect(testStateFunctions.stateHover('transparent')).toBe( - 'rgba(#00103D,0.04)', - ); + expect(testStateFunctions.stateHover('transparent')).toBe('rgba(#00103D,0.04)'); }); it('should correct create stateHover with custom color', () => { @@ -41,9 +39,7 @@ describe('getStateFunctions', () => { describe('stateActive', () => { it('should correctly work with transparent', () => { - expect(testStateFunctions.stateActive('transparent')).toBe( - 'rgba(#00103D,0.08)', - ); + expect(testStateFunctions.stateActive('transparent')).toBe('rgba(#00103D,0.08)'); }); it('should correct create stateActive with custom color', () => { @@ -53,9 +49,7 @@ describe('getStateFunctions', () => { describe('stateFocus', () => { it('should correctly work with transparent', () => { - expect(testStateFunctions.stateFocus('transparent')).toBe( - 'rgba(#00103D,0.08)', - ); + expect(testStateFunctions.stateFocus('transparent')).toBe('rgba(#00103D,0.08)'); }); it('should correct create stateFocus with custom color', () => { @@ -65,9 +59,7 @@ describe('getStateFunctions', () => { describe('stateDisabled', () => { it('should correct create stateDisabled with custom color', () => { - expect(testStateFunctions.stateDisabled('#f00')).toBe( - 'rgba(255, 0, 0, 0.48)', - ); + expect(testStateFunctions.stateDisabled('#f00')).toBe('rgba(255, 0, 0, 0.48)'); }); }); }); diff --git a/src/build/helpers/getStateFunctions.ts b/src/build/helpers/getStateFunctions.ts index 5cf71a8b..2d6a2c0e 100644 --- a/src/build/helpers/getStateFunctions.ts +++ b/src/build/helpers/getStateFunctions.ts @@ -1,6 +1,6 @@ import color from 'color'; -import {colorStateMap} from '@/build/themeProcessors/expandColors/expandColors'; +import { colorStateMap } from '@/build/themeProcessors/expandColors/expandColors'; type ColorStateObject = { colorsScheme: 'light' | 'dark'; @@ -24,31 +24,22 @@ export function getStateFunctions(theme: ColorStateObject): StateFunctions { if (colorHover === 'transparent') { return `rgba(${colorState},${theme.toneValueHover})`; } - return color(colorHover) - .mix(color(colorState), theme.toneValueHover) - .hex(); + return color(colorHover).mix(color(colorState), theme.toneValueHover).hex(); }, stateActive(colorActive: string) { if (colorActive === 'transparent') { return `rgba(${colorState},${theme.toneValueActive})`; } - return color(colorActive) - .mix(color(colorState), theme.toneValueActive) - .hex(); + return color(colorActive).mix(color(colorState), theme.toneValueActive).hex(); }, stateFocus(colorFocus: string) { if (colorFocus === 'transparent') { return `rgba(${colorState},${theme.toneValueFocus})`; } - return color(colorFocus) - .mix(color(colorState), theme.toneValueFocus) - .hex(); + return color(colorFocus).mix(color(colorState), theme.toneValueFocus).hex(); }, stateDisabled(colorDisabled: string) { - return color(colorDisabled) - .alpha(theme.opacityDisable) - .rgb() - .string(); + return color(colorDisabled).alpha(theme.opacityDisable).rgb().string(); }, }; } diff --git a/src/build/helpers/overrideOnlyNeeded.test.ts b/src/build/helpers/overrideOnlyNeeded.test.ts index 466f1e88..75307c3a 100644 --- a/src/build/helpers/overrideOnlyNeeded.test.ts +++ b/src/build/helpers/overrideOnlyNeeded.test.ts @@ -1,16 +1,16 @@ -import {overrideOnlyNeeded} from './overrideOnlyNeeded'; +import { overrideOnlyNeeded } from './overrideOnlyNeeded'; describe('overrideOnlyNeeded', () => { it('should return new object', () => { - const target = {a: 2, b: 3}; + const target = { a: 2, b: 3 }; expect(overrideOnlyNeeded(target, {})).not.toBe(target); expect(overrideOnlyNeeded(target, {})).toStrictEqual(target); }); it('should not add new properties', () => { - const target = {a: 2, b: 3}; - const override = {c: 5}; + const target = { a: 2, b: 3 }; + const override = { c: 5 }; const result = overrideOnlyNeeded(target, override); @@ -19,12 +19,12 @@ describe('overrideOnlyNeeded', () => { }); it('should override props', () => { - const target = {a: 2, b: 3}; - const override = {a: 32}; + const target = { a: 2, b: 3 }; + const override = { a: 32 }; const result = overrideOnlyNeeded(target, override); expect(result.a).toBe(32); - expect(result).toStrictEqual({a: 32, b: 3}); + expect(result).toStrictEqual({ a: 32, b: 3 }); }); }); diff --git a/src/build/helpers/overrideOnlyNeeded.ts b/src/build/helpers/overrideOnlyNeeded.ts index 0bd08d2d..9adcf37e 100644 --- a/src/build/helpers/overrideOnlyNeeded.ts +++ b/src/build/helpers/overrideOnlyNeeded.ts @@ -1,6 +1,7 @@ -export function overrideOnlyNeeded< - T extends Record = Record, ->(targetObject: T, overrideObject: Record): T { +export function overrideOnlyNeeded = Record>( + targetObject: T, + overrideObject: Record, +): T { const targetCopy = JSON.parse(JSON.stringify(targetObject)); return Object.keys(targetObject).reduce((target, key) => { if (key in overrideObject) { diff --git a/src/build/helpers/replacePropDeep.test.ts b/src/build/helpers/replacePropDeep.test.ts index c8466eb6..de20622c 100644 --- a/src/build/helpers/replacePropDeep.test.ts +++ b/src/build/helpers/replacePropDeep.test.ts @@ -1,4 +1,4 @@ -import {replacePropDeep} from '@/build/helpers/replacePropDeep'; +import { replacePropDeep } from '@/build/helpers/replacePropDeep'; describe('replacePropDeep', () => { const mapReplace = { @@ -19,7 +19,7 @@ describe('replacePropDeep', () => { }); it('should not touch other vars', () => { - const object = {opacityDisable: 0.5}; + const object = { opacityDisable: 0.5 }; expect(replacePropDeep(object, mapReplace)).toStrictEqual({ opacityDisable: 0.5, @@ -27,7 +27,7 @@ describe('replacePropDeep', () => { }); it('should replace flat values', () => { - const object = {fontFamily: 'kek'}; + const object = { fontFamily: 'kek' }; expect(replacePropDeep(object, mapReplace)).toStrictEqual({ fontFamily: 'lol', diff --git a/src/build/helpers/replacePropDeep.ts b/src/build/helpers/replacePropDeep.ts index 765ce3b9..819d4d73 100644 --- a/src/build/helpers/replacePropDeep.ts +++ b/src/build/helpers/replacePropDeep.ts @@ -6,20 +6,17 @@ export function replacePropDeep>( object: T, mapReplace: MapReplace, ): T { - return Object.entries(object).reduce( - (acc, [key, value]: [keyof T, any]) => { - if (typeof value === 'object' && !(key in mapReplace)) { - acc[key] = replacePropDeep(value, mapReplace); - return acc; - } - - if (key in mapReplace) { - acc[key] = mapReplace[key as any]; - } else { - acc[key] = value; - } + return Object.entries(object).reduce((acc, [key, value]: [keyof T, any]) => { + if (typeof value === 'object' && !(key in mapReplace)) { + acc[key] = replacePropDeep(value, mapReplace); return acc; - }, - {} as T, - ); + } + + if (key in mapReplace) { + acc[key] = mapReplace[key as any]; + } else { + acc[key] = value; + } + return acc; + }, {} as T); } diff --git a/src/build/helpers/tokenHelpers.test.ts b/src/build/helpers/tokenHelpers.test.ts index 2b98f61b..8168a52e 100644 --- a/src/build/helpers/tokenHelpers.test.ts +++ b/src/build/helpers/tokenHelpers.test.ts @@ -1,9 +1,9 @@ -import {alias, staticRef} from '@/build/helpers/tokenHelpers'; +import { alias, staticRef } from '@/build/helpers/tokenHelpers'; describe('tokenHelpers', () => { describe('alias', () => { test('maps token to another token', () => { - expect(alias('sizeArrow')({sizeArrow: {regular: 10}})).toEqual({ + expect(alias('sizeArrow')({ sizeArrow: { regular: 10 } })).toEqual({ regular: 10, }); }); diff --git a/src/build/helpers/tokenHelpers.ts b/src/build/helpers/tokenHelpers.ts index 989d820c..8f520a7c 100644 --- a/src/build/helpers/tokenHelpers.ts +++ b/src/build/helpers/tokenHelpers.ts @@ -1,9 +1,7 @@ -import {ThemeGeneral} from '@/interfaces/general'; -import {Token} from '@/interfaces/general/tools/tokenValue'; +import { ThemeGeneral } from '@/interfaces/general'; +import { Token } from '@/interfaces/general/tools/tokenValue'; -export function alias( - token: string, -): (theme: Partial) => Token { +export function alias(token: string): (theme: Partial) => Token { return (theme) => theme[token]; } diff --git a/src/build/helpers/unCamelcasify.test.ts b/src/build/helpers/unCamelcasify.test.ts index 632d5e48..ac24cd3b 100644 --- a/src/build/helpers/unCamelcasify.test.ts +++ b/src/build/helpers/unCamelcasify.test.ts @@ -1,4 +1,4 @@ -import {unCamelcasify} from './unCamelcasify'; +import { unCamelcasify } from './unCamelcasify'; describe('unCamelcasify', () => { it('should correctly work with empty string', () => { @@ -14,8 +14,6 @@ describe('unCamelcasify', () => { }); it('should convert many words string', () => { - expect(unCamelcasify('helloWorldMyFriend')).toBe( - 'hello-world-my-friend', - ); + expect(unCamelcasify('helloWorldMyFriend')).toBe('hello-world-my-friend'); }); }); diff --git a/src/build/index.ts b/src/build/index.ts index 0a0e5104..a0422704 100644 --- a/src/build/index.ts +++ b/src/build/index.ts @@ -11,16 +11,16 @@ import { writeStyleFiles, writeTsFile, } from '@/build/compilers'; -import {expandAll} from '@/build/expandTheme'; -import {themes} from '@/themeDescriptions'; +import { expandAll } from '@/build/expandTheme'; +import { themes } from '@/themeDescriptions'; -import {processCustomMedia} from './themeProcessors/customMedia/customMedia'; +import { processCustomMedia } from './themeProcessors/customMedia/customMedia'; const ROOT_DIR = path.resolve(__dirname, '../..'); console.log('Удаляем папку dist...'); export const DIST_PATH = `${ROOT_DIR}/dist`; -export const rmDist = (): void => fs.rmdirSync(DIST_PATH, {recursive: true}); +export const rmDist = (): void => fs.rmdirSync(DIST_PATH, { recursive: true }); rmDist(); @@ -44,8 +44,7 @@ const expandedThemes = themes.map(expandAll); const expandedThemesMap: Record = {}; for (const expandedThemeObject of expandedThemes) { - expandedThemesMap[expandedThemeObject.theme.themeName] = - expandedThemeObject; + expandedThemesMap[expandedThemeObject.theme.themeName] = expandedThemeObject; } console.log('Успешно сформировали объекты тем на основе описания тем\n'); @@ -54,20 +53,13 @@ console.log('Успешно сформировали объекты тем на expandedThemes.forEach((expandedThemeObject) => { console.log('\n----------\n'); - const { - theme, - pixelifyTheme, - cssVarsThemeWide, - cssVarsTheme, - pseudoThemeCssVars, - } = expandedThemeObject; + const { theme, pixelifyTheme, cssVarsThemeWide, cssVarsTheme, pseudoThemeCssVars } = + expandedThemeObject; - const {themeName, themeInheritsFrom} = theme; + const { themeName, themeInheritsFrom } = theme; const themeObjectBase = - themeName === themeInheritsFrom - ? undefined - : expandedThemesMap[themeInheritsFrom]; + themeName === themeInheritsFrom ? undefined : expandedThemesMap[themeInheritsFrom]; const pixelifyThemeBase = themeObjectBase?.pixelifyTheme; @@ -105,9 +97,7 @@ expandedThemes.forEach((expandedThemeObject) => { writeCssVarsJsUtils(cssVarsDeclarationsPath, cssVarsThemeWide); writeCssVarsSourceMediaFile(cssVarsDeclarationsPath, cssVarsThemeWide); - console.log( - 'начинаем компиляцию объектов темы использующих css переменные', - ); + console.log('начинаем компиляцию объектов темы использующих css переменные'); const cssVarsThemesPath = path.resolve(cssVarsPath, 'theme'); fs.mkdirSync(cssVarsThemesPath); @@ -115,10 +105,7 @@ expandedThemes.forEach((expandedThemeObject) => { writeJsonFile(cssVarsThemesPath, cssVarsTheme as any, 'cssVars'); writeTsFile(cssVarsThemesPath, cssVarsTheme as any, 'cssVars', themeName); - const cssVarsThemesPathFallbacks = path.resolve( - cssVarsThemesPath, - 'fallbacks', - ); + const cssVarsThemesPathFallbacks = path.resolve(cssVarsThemesPath, 'fallbacks'); fs.mkdirSync(cssVarsThemesPathFallbacks); const pseudoForStyles = { ...JSON.parse(JSON.stringify(pseudoThemeCssVars)), @@ -140,10 +127,10 @@ fs.mkdirSync(path.resolve(DIST_PATH, 'build/helpers')); fs.mkdirSync(path.resolve(DIST_PATH, 'build/compilers')); [ - {in: '.npmignore'}, - {in: '.gitignore'}, - {in: '.npmrc'}, - {in: 'README.md'}, + { in: '.npmignore' }, + { in: '.gitignore' }, + { in: '.npmrc' }, + { in: 'README.md' }, { in: 'assets', }, @@ -195,10 +182,7 @@ fs.mkdirSync(path.resolve(DIST_PATH, 'build/compilers')); const contentSource = fs.readFileSync(fileSourcePath, 'utf-8'); - const contentDest = contentSource.replace( - /@\/themeDescriptions\/common/g, - `@/utils/common`, - ); + const contentDest = contentSource.replace(/@\/themeDescriptions\/common/g, `@/utils/common`); fs.writeFileSync(fileDestPath, contentDest); } else { diff --git a/src/build/snapthots.test.ts b/src/build/snapthots.test.ts index 1cde7706..89963445 100644 --- a/src/build/snapthots.test.ts +++ b/src/build/snapthots.test.ts @@ -1,6 +1,6 @@ -import {themes} from '@/themeDescriptions'; +import { themes } from '@/themeDescriptions'; -import {expandAll} from './expandTheme'; +import { expandAll } from './expandTheme'; describe('shapshots', () => { themes.forEach((theme) => { @@ -20,9 +20,7 @@ describe('shapshots', () => { }); it('should match pseudo theme from CssVars', () => { - expect( - expandedThemeObject.pseudoThemeCssVars, - ).toMatchSnapshot(); + expect(expandedThemeObject.pseudoThemeCssVars).toMatchSnapshot(); }); }); }); diff --git a/src/build/themeProcessors/createPseudoRootFromCssVars/createPseudoRootFromCssVars.test.ts b/src/build/themeProcessors/createPseudoRootFromCssVars/createPseudoRootFromCssVars.test.ts index 84249c53..a3d40258 100644 --- a/src/build/themeProcessors/createPseudoRootFromCssVars/createPseudoRootFromCssVars.test.ts +++ b/src/build/themeProcessors/createPseudoRootFromCssVars/createPseudoRootFromCssVars.test.ts @@ -1,28 +1,20 @@ -import { - PixelifyTheme, - Theme, - ThemeCssVars, - ThemeCssVarsWide, -} from '@/interfaces/general'; +import { PixelifyTheme, Theme, ThemeCssVars, ThemeCssVarsWide } from '@/interfaces/general'; import { ParadigmTheme, ParadigmThemeCssVars, ParadigmThemeCssVarsWide, } from '@/interfaces/namespaces/paradigm'; -import {createPseudoRootFromCssVars} from './createPseudoRootFromCssVars'; +import { createPseudoRootFromCssVars } from './createPseudoRootFromCssVars'; describe('createPseudoRootFromCssVars', () => { it('should return new object', () => { const theme = {}; const cssVarsTheme = {}; - expect( - createPseudoRootFromCssVars( - theme as Theme, - cssVarsTheme as ThemeCssVarsWide, - ), - ).not.toBe(theme); + expect(createPseudoRootFromCssVars(theme as Theme, cssVarsTheme as ThemeCssVarsWide)).not.toBe( + theme, + ); }); it('should change type', () => { @@ -35,12 +27,9 @@ describe('createPseudoRootFromCssVars', () => { themeType: 'cssVars', }; - expect( - createPseudoRootFromCssVars( - theme as Theme, - cssVarsTheme as ThemeCssVars, - ), - ).toStrictEqual({themeType: 'pixelify'}); + expect(createPseudoRootFromCssVars(theme as Theme, cssVarsTheme as ThemeCssVars)).toStrictEqual( + { themeType: 'pixelify' }, + ); }); it('should expand flat values', () => { @@ -67,12 +56,9 @@ describe('createPseudoRootFromCssVars', () => { x2: 'var(--paradigm--x2, 8px)', }; - expect( - createPseudoRootFromCssVars( - theme, - cssVarsTheme as ParadigmThemeCssVars, - ), - ).toStrictEqual(expectedResult); + expect(createPseudoRootFromCssVars(theme, cssVarsTheme as ParadigmThemeCssVars)).toStrictEqual( + expectedResult, + ); }); it('should expand adaptive values', () => { @@ -109,9 +95,7 @@ describe('createPseudoRootFromCssVars', () => { }, }; - expect( - createPseudoRootFromCssVars(theme, cssVarsTheme as any), - ).toStrictEqual(expectedResult); + expect(createPseudoRootFromCssVars(theme, cssVarsTheme as any)).toStrictEqual(expectedResult); }); it('should expand adaptive complex values', () => { @@ -183,10 +167,7 @@ describe('createPseudoRootFromCssVars', () => { }; expect( - createPseudoRootFromCssVars( - theme, - cssVarsTheme as ParadigmThemeCssVarsWide, - ), + createPseudoRootFromCssVars(theme, cssVarsTheme as ParadigmThemeCssVarsWide), ).toStrictEqual(expectedResult); }); @@ -215,10 +196,7 @@ describe('createPseudoRootFromCssVars', () => { }; expect( - createPseudoRootFromCssVars( - theme as ParadigmTheme, - cssVarsTheme as any, - ), + createPseudoRootFromCssVars(theme as ParadigmTheme, cssVarsTheme as any), ).toStrictEqual(expectedResult); }); }); diff --git a/src/build/themeProcessors/createPseudoRootFromCssVars/createPseudoRootFromCssVars.ts b/src/build/themeProcessors/createPseudoRootFromCssVars/createPseudoRootFromCssVars.ts index 9b7e8076..686c755e 100644 --- a/src/build/themeProcessors/createPseudoRootFromCssVars/createPseudoRootFromCssVars.ts +++ b/src/build/themeProcessors/createPseudoRootFromCssVars/createPseudoRootFromCssVars.ts @@ -1,9 +1,4 @@ -import { - PixelifyTheme, - Theme, - ThemeCssVars, - ThemeCssVarsWide, -} from '@/interfaces/general'; +import { PixelifyTheme, Theme, ThemeCssVars, ThemeCssVarsWide } from '@/interfaces/general'; function fillNewValues({ objectTo, @@ -46,7 +41,7 @@ export function createPseudoRootFromCssVars( const theme: PixelifyTheme = JSON.parse(JSON.stringify(pseudoTheme)); Object.keys(theme).forEach((key) => { - fillNewValues({objectTo: theme, objectFrom: cssVarsTheme, key}); + fillNewValues({ objectTo: theme, objectFrom: cssVarsTheme, key }); }); return theme; diff --git a/src/build/themeProcessors/customMedia/customMedia.test.ts b/src/build/themeProcessors/customMedia/customMedia.test.ts index 2c02618c..6664ed0b 100644 --- a/src/build/themeProcessors/customMedia/customMedia.test.ts +++ b/src/build/themeProcessors/customMedia/customMedia.test.ts @@ -1,12 +1,8 @@ -import {Breakpoints} from '@/interfaces/general/tools'; -import {CustomMediaByViewport} from '@/interfaces/general/tools/customMedia'; -import {ViewportsOrdered} from '@/interfaces/general/tools/viewports'; +import { Breakpoints } from '@/interfaces/general/tools'; +import { CustomMediaByViewport } from '@/interfaces/general/tools/customMedia'; +import { ViewportsOrdered } from '@/interfaces/general/tools/viewports'; -import { - getCustomMediaKey, - getUsingViewports, - processCustomMedia, -} from './customMedia'; +import { getCustomMediaKey, getUsingViewports, processCustomMedia } from './customMedia'; describe('customMedia', () => { describe('getCustomMediaKey', () => { @@ -37,10 +33,7 @@ describe('customMedia', () => { }, }; - expect(getUsingViewports(breakpoints)).toStrictEqual([ - 'touch', - 'desktopS', - ]); + expect(getUsingViewports(breakpoints)).toStrictEqual(['touch', 'desktopS']); }); it('should sort breakpoints', () => { @@ -86,15 +79,13 @@ describe('customMedia', () => { const testData: Breakpoints = { breakpoints: { - desktopS: {breakpoint: 0, adaptiveValue: 'regular'}, + desktopS: { breakpoint: 0, adaptiveValue: 'regular' }, }, }; const expectedResult: CustomMediaByViewport = {}; - expect(processCustomMedia(testData)).toStrictEqual( - expectedResult, - ); + expect(processCustomMedia(testData)).toStrictEqual(expectedResult); }); it('should correctly work with single breakpoint', () => { diff --git a/src/build/themeProcessors/customMedia/customMedia.ts b/src/build/themeProcessors/customMedia/customMedia.ts index 53e60077..4030e87f 100644 --- a/src/build/themeProcessors/customMedia/customMedia.ts +++ b/src/build/themeProcessors/customMedia/customMedia.ts @@ -1,5 +1,5 @@ -import {capitalize} from '@/build/helpers/capitalize'; -import {Breakpoints} from '@/interfaces/general/tools'; +import { capitalize } from '@/build/helpers/capitalize'; +import { Breakpoints } from '@/interfaces/general/tools'; import { CustomMediaByViewport, CustomMediaByViewportUnion, @@ -31,9 +31,7 @@ export const getCustomMediaKey = ( layoutName, )}` as any as CustomMediaByViewportUnion; -export function processCustomMedia< - Vt extends ViewportsTuple = DefaultViewports, ->({ +export function processCustomMedia({ breakpoints, }: Pick, 'breakpoints'>): CustomMediaByViewport { if (!breakpoints || Object.keys(breakpoints).length === 1) { @@ -55,9 +53,7 @@ export function processCustomMedia< // между текущим и следущим брейкпоинтом result[getCustomMediaKey(viewport)] = `(min-width: ${ breakpoints[viewport].breakpoint - }px) and (max-width: ${ - breakpoints[array[index + 1]]?.breakpoint - 1 - }px)`; + }px) and (max-width: ${breakpoints[array[index + 1]]?.breakpoint - 1}px)`; } if (viewport === 'touch') { @@ -78,9 +74,7 @@ export function processCustomMedia< if (isLastKey) { // больше текущего - result[ - getCustomMediaKey(viewport) - ] = `(min-width: ${breakpoints[viewport].breakpoint}px)`; + result[getCustomMediaKey(viewport)] = `(min-width: ${breakpoints[viewport].breakpoint}px)`; } }); diff --git a/src/build/themeProcessors/expandColors/expandColors.test.ts b/src/build/themeProcessors/expandColors/expandColors.test.ts index 79cf2ac4..045b2a5d 100644 --- a/src/build/themeProcessors/expandColors/expandColors.test.ts +++ b/src/build/themeProcessors/expandColors/expandColors.test.ts @@ -1,4 +1,4 @@ -import {getExpandedThemeColors} from './expandColors'; +import { getExpandedThemeColors } from './expandColors'; describe('expandColors', () => { it('should return null if colors not specified', () => { diff --git a/src/build/themeProcessors/expandColors/expandColors.ts b/src/build/themeProcessors/expandColors/expandColors.ts index e4231d2e..9890e3ce 100644 --- a/src/build/themeProcessors/expandColors/expandColors.ts +++ b/src/build/themeProcessors/expandColors/expandColors.ts @@ -1,10 +1,7 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import { - isColorDescriptionCallable, - isColorWithStates, -} from '@/build/helpers/cssHelpers'; -import {ColorsDescription, ColorsFinal} from '@/interfaces/general'; +import { isColorDescriptionCallable, isColorWithStates } from '@/build/helpers/cssHelpers'; +import { ColorsDescription, ColorsFinal } from '@/interfaces/general'; import { ColorDescription, ColorDescriptionStatic, @@ -12,7 +9,7 @@ import { ColorWithStates, } from '@/interfaces/general/colors'; -import {mixColors} from './mixColors'; +import { mixColors } from './mixColors'; export const colorStateMap = { light: '#00103D', @@ -54,7 +51,7 @@ const getColorWithStates = ({ }; }; -function expandCallableColor( +function expandCallableColor( color: ColorDescription, theme: Partial>, ): ColorDescriptionStatic { @@ -67,11 +64,8 @@ function expandCallableColor( } export function expandColor< - T extends {[key in keyof T]: ColorDescription} = ColorsDescriptionStruct, ->( - color: ColorDescription, - theme: Partial>, -): ColorWithStates { + T extends { [key in keyof T]: ColorDescription } = ColorsDescriptionStruct, +>(color: ColorDescription, theme: Partial>): ColorWithStates { color = expandCallableColor(color, theme); if (isColorWithStates(color)) { @@ -95,9 +89,9 @@ export function expandColor< * (и добавляет эти состояния только тем цветам, которые там действительно нужны) */ export function getExpandedThemeColors< - T extends {[key in keyof T]: ColorDescription} = ColorsDescriptionStruct, + T extends { [key in keyof T]: ColorDescription } = ColorsDescriptionStruct, >(colorsDescription: Partial>): ColorsFinal { - const {colorsScheme, colors} = colorsDescription; + const { colorsScheme, colors } = colorsDescription; if (!colorsScheme || !colors) { return null; @@ -107,11 +101,9 @@ export function getExpandedThemeColors< colorsScheme, }; - Object.entries(colors).forEach( - ([key, colorValue]: [keyof ColorsDescription, Property.Color]) => { - theme[key] = expandColor(colorValue, colorsDescription); - }, - ); + Object.entries(colors).forEach(([key, colorValue]: [keyof ColorsDescription, Property.Color]) => { + theme[key] = expandColor(colorValue, colorsDescription); + }); return theme as ColorsFinal; } diff --git a/src/build/themeProcessors/expandColors/mixColors.test.ts b/src/build/themeProcessors/expandColors/mixColors.test.ts index f67ea034..b06f33e4 100644 --- a/src/build/themeProcessors/expandColors/mixColors.test.ts +++ b/src/build/themeProcessors/expandColors/mixColors.test.ts @@ -1,6 +1,6 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {mixColors} from './mixColors'; +import { mixColors } from './mixColors'; describe('mixColors', () => { const colorState: Property.Color = '#000000'; diff --git a/src/build/themeProcessors/expandColors/mixColors.ts b/src/build/themeProcessors/expandColors/mixColors.ts index ad9165dc..cac2bbf7 100644 --- a/src/build/themeProcessors/expandColors/mixColors.ts +++ b/src/build/themeProcessors/expandColors/mixColors.ts @@ -1,5 +1,5 @@ import color from 'color'; -import {Property} from 'csstype'; +import { Property } from 'csstype'; export const mixColors = ( colorArg: Property.Color, diff --git a/src/build/themeProcessors/expandColors/overlayColors.test.ts b/src/build/themeProcessors/expandColors/overlayColors.test.ts index 04fa91d4..69046171 100644 --- a/src/build/themeProcessors/expandColors/overlayColors.test.ts +++ b/src/build/themeProcessors/expandColors/overlayColors.test.ts @@ -1,13 +1,8 @@ -import {overlayColors} from '@/build/themeProcessors/expandColors/overlayColors'; +import { overlayColors } from '@/build/themeProcessors/expandColors/overlayColors'; describe('overlayColors', () => { test('overlay transparent on opaque in light color scheme', () => { - expect( - overlayColors( - 'rgb(0,0,0)', - 'rgba(255,255,255,.5)', - )({colorsScheme: 'light'}), - ).toEqual({ + expect(overlayColors('rgb(0,0,0)', 'rgba(255,255,255,.5)')({ colorsScheme: 'light' })).toEqual({ normal: '#404040', hover: '#4D4D4D', active: '#5C5C5C', @@ -15,12 +10,7 @@ describe('overlayColors', () => { }); test('overlay transparent on opaque in dark color scheme', () => { - expect( - overlayColors( - 'rgb(0,0,0)', - 'rgba(255,255,255,.5)', - )({colorsScheme: 'dark'}), - ).toEqual({ + expect(overlayColors('rgb(0,0,0)', 'rgba(255,255,255,.5)')({ colorsScheme: 'dark' })).toEqual({ normal: '#404040', hover: '#4D4D4D', active: '#5C5C5C', @@ -28,12 +18,7 @@ describe('overlayColors', () => { }); test('overlay opaque on opaque', () => { - expect( - overlayColors( - 'rgb(0,0,0)', - 'rgb(255,255,255)', - )({colorsScheme: 'light'}), - ).toEqual({ + expect(overlayColors('rgb(0,0,0)', 'rgb(255,255,255)')({ colorsScheme: 'light' })).toEqual({ normal: '#FFFFFF', hover: '#F5F5F7', active: '#EBECEF', @@ -46,7 +31,7 @@ describe('overlayColors', () => { normal: 'rgba(255,255,255,.5)', hover: 'rgba(255,255,255,.5)', active: 'rgba(255,255,255,.5)', - })({colorsScheme: 'light'}), + })({ colorsScheme: 'light' }), ).toEqual({ normal: '#404040', hover: '#404040', diff --git a/src/build/themeProcessors/expandColors/overlayColors.ts b/src/build/themeProcessors/expandColors/overlayColors.ts index 5e668c9d..b1266630 100644 --- a/src/build/themeProcessors/expandColors/overlayColors.ts +++ b/src/build/themeProcessors/expandColors/overlayColors.ts @@ -1,8 +1,8 @@ import color from 'color'; -import {expandColor} from '@/build/themeProcessors/expandColors/expandColors'; -import {mixColors} from '@/build/themeProcessors/expandColors/mixColors'; -import {ColorsDescription} from '@/interfaces/general'; +import { expandColor } from '@/build/themeProcessors/expandColors/expandColors'; +import { mixColors } from '@/build/themeProcessors/expandColors/mixColors'; +import { ColorsDescription } from '@/interfaces/general'; import { ColorDescription, ColorDescriptionCallable, @@ -10,7 +10,7 @@ import { } from '@/interfaces/general/colors'; export function overlayColors< - T extends {[key in keyof T]: ColorDescription} = ColorsDescriptionStruct, + T extends { [key in keyof T]: ColorDescription } = ColorsDescriptionStruct, >( background: ColorDescription, foreground: ColorDescription, diff --git a/src/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict.test.ts b/src/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict.test.ts index 1912d25e..5cf59831 100644 --- a/src/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict.test.ts +++ b/src/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict.test.ts @@ -1,16 +1,11 @@ -import {extractCssVarsStrict} from '@/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict'; -import {ThemeCssVars, ThemeCssVarsWide} from '@/interfaces/general'; -import { - ParadigmThemeCssVars, - ParadigmThemeCssVarsWide, -} from '@/interfaces/namespaces/paradigm'; +import { extractCssVarsStrict } from '@/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict'; +import { ThemeCssVars, ThemeCssVarsWide } from '@/interfaces/general'; +import { ParadigmThemeCssVars, ParadigmThemeCssVarsWide } from '@/interfaces/namespaces/paradigm'; describe('extractCssVarsStrict', () => { it('should work with empty object', () => { const testData = {}; - expect( - extractCssVarsStrict(testData as ThemeCssVarsWide), - ).toStrictEqual({}); + expect(extractCssVarsStrict(testData as ThemeCssVarsWide)).toStrictEqual({}); }); it('should not do anything with breakpoints', () => { @@ -38,11 +33,9 @@ describe('extractCssVarsStrict', () => { }, }; - const expectedData = {...{breakpoints: {...theme.breakpoints}}}; + const expectedData = { ...{ breakpoints: { ...theme.breakpoints } } }; - expect( - extractCssVarsStrict(theme as ThemeCssVarsWide), - ).toStrictEqual(expectedData); + expect(extractCssVarsStrict(theme as ThemeCssVarsWide)).toStrictEqual(expectedData); }); it('should change type', () => { @@ -56,9 +49,7 @@ describe('extractCssVarsStrict', () => { themeType: 'cssVars', }; - expect(extractCssVarsStrict(theme as ThemeCssVarsWide)).toStrictEqual( - expectResult, - ); + expect(extractCssVarsStrict(theme as ThemeCssVarsWide)).toStrictEqual(expectResult); }); it('should work with flat values', () => { @@ -79,9 +70,7 @@ describe('extractCssVarsStrict', () => { }, }; - expect( - extractCssVarsStrict(theme as ParadigmThemeCssVarsWide), - ).toStrictEqual(expectResult); + expect(extractCssVarsStrict(theme as ParadigmThemeCssVarsWide)).toStrictEqual(expectResult); }); it('should work with adaprive breakpoints values', () => { @@ -120,9 +109,7 @@ describe('extractCssVarsStrict', () => { }, }; - expect( - extractCssVarsStrict(theme as ParadigmThemeCssVarsWide), - ).toStrictEqual(expectedResult); + expect(extractCssVarsStrict(theme as ParadigmThemeCssVarsWide)).toStrictEqual(expectedResult); }); it('should with flat and adaptive values together', () => { @@ -169,8 +156,6 @@ describe('extractCssVarsStrict', () => { }, }; - expect( - extractCssVarsStrict(theme as ParadigmThemeCssVarsWide), - ).toStrictEqual(expectedResult); + expect(extractCssVarsStrict(theme as ParadigmThemeCssVarsWide)).toStrictEqual(expectedResult); }); }); diff --git a/src/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict.ts b/src/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict.ts index e6a3418f..057bdabe 100644 --- a/src/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict.ts +++ b/src/build/themeProcessors/extractCssVarsStrict/extractCssVarsStrict.ts @@ -1,4 +1,4 @@ -import {Theme, ThemeCssVars, ThemeCssVarsWide} from '@/interfaces/general'; +import { Theme, ThemeCssVars, ThemeCssVarsWide } from '@/interfaces/general'; function removeOriginValue(object: Record) { if (typeof object === 'object') { @@ -18,9 +18,7 @@ function removeOriginValue(object: Record) { } } -export function extractCssVarsStrict( - sourceTheme: ThemeCssVarsWide, -): ThemeCssVars { +export function extractCssVarsStrict(sourceTheme: ThemeCssVarsWide): ThemeCssVars { const theme = JSON.parse(JSON.stringify(sourceTheme)); removeOriginValue(theme); diff --git a/src/build/themeProcessors/extractGeneralTokens/extractGeneralTokens.test.ts b/src/build/themeProcessors/extractGeneralTokens/extractGeneralTokens.test.ts index bb86c9cf..81d190b7 100644 --- a/src/build/themeProcessors/extractGeneralTokens/extractGeneralTokens.test.ts +++ b/src/build/themeProcessors/extractGeneralTokens/extractGeneralTokens.test.ts @@ -1,4 +1,4 @@ -import {extractGeneralTokens} from './extractGeneralTokens'; +import { extractGeneralTokens } from './extractGeneralTokens'; describe('mixColors', () => { it('should return new object', () => { diff --git a/src/build/themeProcessors/extractGeneralTokens/extractGeneralTokens.ts b/src/build/themeProcessors/extractGeneralTokens/extractGeneralTokens.ts index 2037da98..112ceba0 100644 --- a/src/build/themeProcessors/extractGeneralTokens/extractGeneralTokens.ts +++ b/src/build/themeProcessors/extractGeneralTokens/extractGeneralTokens.ts @@ -1,4 +1,4 @@ -import {ThemeDescription, ThemeGeneral} from '@/interfaces/general'; +import { ThemeDescription, ThemeGeneral } from '@/interfaces/general'; /** * Процессор, который возвращает новый объект на основе описания темы (ThemeDescription), diff --git a/src/build/themeProcessors/extractVarsNames/extractVarsNames.test.ts b/src/build/themeProcessors/extractVarsNames/extractVarsNames.test.ts index 4576123d..ea42c0c4 100644 --- a/src/build/themeProcessors/extractVarsNames/extractVarsNames.test.ts +++ b/src/build/themeProcessors/extractVarsNames/extractVarsNames.test.ts @@ -1,23 +1,18 @@ -import {Breakpoints} from '@/interfaces/general/tools'; -import { - ParadigmTheme, - ParadigmThemeCssVarsWide, -} from '@/interfaces/namespaces/paradigm'; +import { Breakpoints } from '@/interfaces/general/tools'; +import { ParadigmTheme, ParadigmThemeCssVarsWide } from '@/interfaces/namespaces/paradigm'; -import {extractVarsNames, getVariableName} from './extractVarsNames'; +import { extractVarsNames, getVariableName } from './extractVarsNames'; describe('extractVarsNames', () => { describe('getVariableName', () => { it('should work only with key param', () => { - expect(getVariableName({key: 'paddingBase'})).toBe( - '--vkui--padding_base', - ); + expect(getVariableName({ key: 'paddingBase' })).toBe('--vkui--padding_base'); }); it('shoud work with custom prefix', () => { - expect( - getVariableName({key: 'paddingBase', prefix: 'myParadigm'}), - ).toBe('--my_paradigm--padding_base'); + expect(getVariableName({ key: 'paddingBase', prefix: 'myParadigm' })).toBe( + '--my_paradigm--padding_base', + ); }); it('should work with custom prefix with double hyphen', () => { @@ -30,21 +25,19 @@ describe('extractVarsNames', () => { }); it('shoud work with auto mode', () => { - expect(getVariableName({key: 'paddingBase', mode: 'auto'})).toBe( - '--vkui--padding_base', - ); + expect(getVariableName({ key: 'paddingBase', mode: 'auto' })).toBe('--vkui--padding_base'); }); it('should work with nocamel mode', () => { - expect(getVariableName({key: 'paddingBase', mode: 'touch'})).toBe( + expect(getVariableName({ key: 'paddingBase', mode: 'touch' })).toBe( '--vkui--padding_base--touch', ); }); it('should work with camel mode', () => { - expect( - getVariableName({key: 'paddingBase', mode: 'desktopS'}), - ).toBe('--vkui--padding_base--desktop_s'); + expect(getVariableName({ key: 'paddingBase', mode: 'desktopS' })).toBe( + '--vkui--padding_base--desktop_s', + ); }); }); @@ -79,7 +72,7 @@ describe('extractVarsNames', () => { }, }; - const expectedData = {...{breakpoints: {...theme.breakpoints}}}; + const expectedData = { ...{ breakpoints: { ...theme.breakpoints } } }; expect(extractVarsNames(theme)).toStrictEqual(expectedData); }); @@ -361,8 +354,6 @@ describe('extractVarsNames', () => { // eslint-disable-next-line unicorn/consistent-function-scoping const valueConstruct = (_: string, value: string) => value; - expect(extractVarsNames(theme, {valueConstruct})).toStrictEqual( - expectedData, - ); + expect(extractVarsNames(theme, { valueConstruct })).toStrictEqual(expectedData); }); }); diff --git a/src/build/themeProcessors/extractVarsNames/extractVarsNames.ts b/src/build/themeProcessors/extractVarsNames/extractVarsNames.ts index 882bc398..d3503263 100644 --- a/src/build/themeProcessors/extractVarsNames/extractVarsNames.ts +++ b/src/build/themeProcessors/extractVarsNames/extractVarsNames.ts @@ -1,11 +1,11 @@ -import {convertCamelToSnake} from '@/build/helpers/convertCamelToSnake'; -import {staticRef} from '@/build/helpers/tokenHelpers'; -import {Theme, ThemeCssVarsWide} from '@/interfaces/general'; -import {Adaptive} from '@/interfaces/general/tools'; -import {CustomMediaByViewport} from '@/interfaces/general/tools/customMedia'; +import { convertCamelToSnake } from '@/build/helpers/convertCamelToSnake'; +import { staticRef } from '@/build/helpers/tokenHelpers'; +import { Theme, ThemeCssVarsWide } from '@/interfaces/general'; +import { Adaptive } from '@/interfaces/general/tools'; +import { CustomMediaByViewport } from '@/interfaces/general/tools/customMedia'; -import {processCustomMedia} from '../customMedia/customMedia'; -import {pixelifyValues} from '../pixelifyValues/pixelifyValues'; +import { processCustomMedia } from '../customMedia/customMedia'; +import { pixelifyValues } from '../pixelifyValues/pixelifyValues'; export function getVariableName({ key, @@ -22,9 +22,7 @@ export function getVariableName({ } return `--${convertCamelToSnake(prefix)}--${convertCamelToSnake(key)}${ - mode !== undefined && mode !== 'auto' - ? `--${convertCamelToSnake(mode)}` - : '' + mode !== undefined && mode !== 'auto' ? `--${convertCamelToSnake(mode)}` : '' }`; } @@ -76,7 +74,7 @@ function processVarNaming({ // если это адаптивный объект (например шрифты) if (typeof value.regular === 'object') { result[key] = (['auto', ...states] as const).reduce< - Partial<{[key in keyof Adaptive | 'auto']: any}> + Partial<{ [key in keyof Adaptive | 'auto']: any }> >((acc, mode: keyof Adaptive | 'auto') => { acc[mode] = processVarNaming({ object: value[mode] ?? value.regular, @@ -93,17 +91,17 @@ function processVarNaming({ // обычная адаптивная переменная, нужно сформировать объект result[key] = (['auto', ...states] as const).reduce< - Partial<{[key in keyof Adaptive | 'auto']: any}> + Partial<{ [key in keyof Adaptive | 'auto']: any }> >((acc, mode) => { if (mode === 'auto') { - const name = getVariableName({key, prefix, mode: 'auto'}); + const name = getVariableName({ key, prefix, mode: 'auto' }); acc[mode] = { name, value: valueConstruct(name), }; } else { - const name = getVariableName({key, prefix, mode}); + const name = getVariableName({ key, prefix, mode }); const originalValue = value[mode]; acc[mode] = { name, @@ -132,7 +130,7 @@ function processVarNaming({ value = JSON.stringify(value); } - const name = getVariableName({key, prefix, mode}); + const name = getVariableName({ key, prefix, mode }); result[key] = mode !== 'auto' ? ({ diff --git a/src/build/themeProcessors/extractViewports/extractViewports.test.ts b/src/build/themeProcessors/extractViewports/extractViewports.test.ts index 8383fdab..4ae9a4ee 100644 --- a/src/build/themeProcessors/extractViewports/extractViewports.test.ts +++ b/src/build/themeProcessors/extractViewports/extractViewports.test.ts @@ -1,6 +1,6 @@ -import {extractViewports} from '@/build/themeProcessors/extractViewports/extractViewports'; -import {Breakpoints} from '@/interfaces/general/tools'; -import {DefaultViewports} from '@/interfaces/general/tools/viewports'; +import { extractViewports } from '@/build/themeProcessors/extractViewports/extractViewports'; +import { Breakpoints } from '@/interfaces/general/tools'; +import { DefaultViewports } from '@/interfaces/general/tools/viewports'; describe('extractViewports', () => { it('should work without breakpoints: touch', () => { @@ -16,9 +16,7 @@ describe('extractViewports', () => { }; expect( - extractViewports>( - testBreakpoints, - ), + extractViewports>(testBreakpoints), ).toStrictEqual(['touch']); }); @@ -35,9 +33,7 @@ describe('extractViewports', () => { }; expect( - extractViewports>( - testBreakpoints, - ), + extractViewports>(testBreakpoints), ).toStrictEqual(['desktopM']); }); @@ -58,9 +54,7 @@ describe('extractViewports', () => { }; expect( - extractViewports>( - testBreakpoints, - ), + extractViewports>(testBreakpoints), ).toStrictEqual(['touch', 'desktopS']); }); @@ -89,9 +83,7 @@ describe('extractViewports', () => { }; expect( - extractViewports>( - testBreakpoints, - ), + extractViewports>(testBreakpoints), ).toStrictEqual(['touch', 'desktopS', 'desktopM', 'desktopL']); }); }); diff --git a/src/build/themeProcessors/extractViewports/extractViewports.ts b/src/build/themeProcessors/extractViewports/extractViewports.ts index c76d2a75..102031f7 100644 --- a/src/build/themeProcessors/extractViewports/extractViewports.ts +++ b/src/build/themeProcessors/extractViewports/extractViewports.ts @@ -1,17 +1,10 @@ -import {Breakpoints} from '@/interfaces/general/tools'; -import { - DefaultViewports, - ViewportsTuple, -} from '@/interfaces/general/tools/viewports'; -import {ParadigmTheme} from '@/interfaces/namespaces/paradigm'; +import { Breakpoints } from '@/interfaces/general/tools'; +import { DefaultViewports, ViewportsTuple } from '@/interfaces/general/tools/viewports'; +import { ParadigmTheme } from '@/interfaces/namespaces/paradigm'; export function extractViewports< V extends ViewportsTuple = DefaultViewports, T extends Breakpoints = ParadigmTheme, ->({breakpoints}: T): ViewportsTuple { - return [ - ...(Object.keys( - breakpoints, - ) as (keyof Breakpoints['breakpoints'])[]), - ]; +>({ breakpoints }: T): ViewportsTuple { + return [...(Object.keys(breakpoints) as (keyof Breakpoints['breakpoints'])[])]; } diff --git a/src/build/themeProcessors/pixelifyValues/pixelifyValues.test.ts b/src/build/themeProcessors/pixelifyValues/pixelifyValues.test.ts index 249ca601..3b9784e8 100644 --- a/src/build/themeProcessors/pixelifyValues/pixelifyValues.test.ts +++ b/src/build/themeProcessors/pixelifyValues/pixelifyValues.test.ts @@ -1,7 +1,7 @@ -import {PixelifyTheme, Theme} from '@/interfaces/general'; -import {ParadigmTheme} from '@/interfaces/namespaces/paradigm'; +import { PixelifyTheme, Theme } from '@/interfaces/general'; +import { ParadigmTheme } from '@/interfaces/namespaces/paradigm'; -import {pixelifyValues} from './pixelifyValues'; +import { pixelifyValues } from './pixelifyValues'; describe('pixelifyValues', () => { describe('general', () => { @@ -14,9 +14,7 @@ describe('pixelifyValues', () => { themeType: 'pixelify', }; - expect( - pixelifyValues(theme) as Partial, - ).toStrictEqual(pixelifyTheme); + expect(pixelifyValues(theme) as Partial).toStrictEqual(pixelifyTheme); }); it('should pixelify flat numbers', () => { @@ -30,9 +28,7 @@ describe('pixelifyValues', () => { x2: '8px', }; - expect( - pixelifyValues(theme) as Partial, - ).toStrictEqual(pixelifyTheme); + expect(pixelifyValues(theme) as Partial).toStrictEqual(pixelifyTheme); }); it('should pixelify viewport values', () => { @@ -50,9 +46,7 @@ describe('pixelifyValues', () => { }, }; - expect( - pixelifyValues(theme) as Partial, - ).toStrictEqual(pixelifyTheme); + expect(pixelifyValues(theme) as Partial).toStrictEqual(pixelifyTheme); }); it('should correctly pixelify fonts (exclude weight)', () => { @@ -94,13 +88,11 @@ describe('pixelifyValues', () => { }, }; - expect( - pixelifyValues(theme) as Partial, - ).toStrictEqual(pixelifyTheme); + expect(pixelifyValues(theme) as Partial).toStrictEqual(pixelifyTheme); }); it('should correctly pixelify custom fontWeight tokens', () => { - expect(pixelifyValues({fontWeightAccent1: 700})).toEqual({ + expect(pixelifyValues({ fontWeightAccent1: 700 })).toEqual({ fontWeightAccent1: 700, }); }); diff --git a/src/build/themeProcessors/pixelifyValues/pixelifyValues.ts b/src/build/themeProcessors/pixelifyValues/pixelifyValues.ts index 812d5c42..6bf3028c 100644 --- a/src/build/themeProcessors/pixelifyValues/pixelifyValues.ts +++ b/src/build/themeProcessors/pixelifyValues/pixelifyValues.ts @@ -1,4 +1,4 @@ -import {PixelifyTheme, Theme} from '@/interfaces/general'; +import { PixelifyTheme, Theme } from '@/interfaces/general'; const numericCSSProperties = /^(breakpoints$|fontWeight|zIndex)/i; @@ -7,9 +7,7 @@ const numericCSSProperties = /^(breakpoints$|fontWeight|zIndex)/i; * пример fontSize: 14 -> fontSize: "14px" */ export function pixelifyValues(sourceTheme: T): PixelifyTheme { - const theme: Partial = JSON.parse( - JSON.stringify(sourceTheme), - ); + const theme: Partial = JSON.parse(JSON.stringify(sourceTheme)); Object.entries(theme).forEach(([key, value]) => { if (numericCSSProperties.test(key)) { diff --git a/src/interfaces/general/animations/index.ts b/src/interfaces/general/animations/index.ts index 0b039208..0c7b0dc1 100644 --- a/src/interfaces/general/animations/index.ts +++ b/src/interfaces/general/animations/index.ts @@ -1,4 +1,4 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; /** * Переменные отвечающие за параметры анимаций diff --git a/src/interfaces/general/colors/index.ts b/src/interfaces/general/colors/index.ts index 292c03e5..2b7abd0e 100644 --- a/src/interfaces/general/colors/index.ts +++ b/src/interfaces/general/colors/index.ts @@ -1,6 +1,6 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {ColorsDescription, ColorsScheme} from '@/interfaces/general'; +import { ColorsDescription, ColorsScheme } from '@/interfaces/general'; /** * Интерфейс всех цветов на выходе @@ -15,7 +15,7 @@ export type ColorDescriptionStatic = Property.Color | ColorWithStates; export type ColorDescriptionCallable< // eslint-disable-next-line no-use-before-define - T extends {[key in keyof T]: ColorDescription} = ColorsDescriptionStruct, + T extends { [key in keyof T]: ColorDescription } = ColorsDescriptionStruct, > = ( theme: Partial>, // eslint-disable-next-line no-use-before-define @@ -23,7 +23,7 @@ export type ColorDescriptionCallable< export type ColorDescription< // eslint-disable-next-line no-use-before-define - T extends {[key in keyof T]: ColorDescription} = ColorsDescriptionStruct, + T extends { [key in keyof T]: ColorDescription } = ColorsDescriptionStruct, > = ColorDescriptionStatic | ColorDescriptionCallable; /** diff --git a/src/interfaces/general/elevation/index.ts b/src/interfaces/general/elevation/index.ts index 1a2e252f..b1ccb4f6 100644 --- a/src/interfaces/general/elevation/index.ts +++ b/src/interfaces/general/elevation/index.ts @@ -1,4 +1,4 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; export interface Elevation { /** diff --git a/src/interfaces/general/index.ts b/src/interfaces/general/index.ts index 39dc5484..1eb7ff2d 100644 --- a/src/interfaces/general/index.ts +++ b/src/interfaces/general/index.ts @@ -1,25 +1,23 @@ -import {Property} from 'csstype'; - -import {Animations} from './animations'; -import {ColorDescription, Colors, ColorsDescriptionStruct} from './colors'; -import {Elevation} from './elevation'; -import {Sizes} from './geometry'; -import {Gradients} from './gradients'; -import {ToneValues} from './toneValues'; -import {Adaptive} from './tools'; -import {NamifyObject} from './tools/cssVars'; -import {StringifyObject} from './tools/utils'; -import {Fonts, TypographyBaseProps} from './typography'; -import {ZIndex} from './zIndex'; +import { Property } from 'csstype'; + +import { Animations } from './animations'; +import { ColorDescription, Colors, ColorsDescriptionStruct } from './colors'; +import { Elevation } from './elevation'; +import { Sizes } from './geometry'; +import { Gradients } from './gradients'; +import { ToneValues } from './toneValues'; +import { Adaptive } from './tools'; +import { NamifyObject } from './tools/cssVars'; +import { StringifyObject } from './tools/utils'; +import { Fonts, TypographyBaseProps } from './typography'; +import { ZIndex } from './zIndex'; import ColorScheme = Property.ColorScheme; -import {StaticTokens, Tokens} from '@/interfaces/general/tools/tokenValue'; +import { StaticTokens, Tokens } from '@/interfaces/general/tools/tokenValue'; interface AdaptiveInterfaceValues extends Sizes, Fonts {} type AdaptiveTokens = { - [key in keyof AdaptiveInterfaceValues]: Adaptive< - AdaptiveInterfaceValues[key] - >; + [key in keyof AdaptiveInterfaceValues]: Adaptive; }; export interface ColorsScheme { @@ -32,7 +30,7 @@ export interface ColorsScheme { } export interface ColorsDescription< - T extends {[key in keyof T]: ColorDescription} = ColorsDescriptionStruct, + T extends { [key in keyof T]: ColorDescription } = ColorsDescriptionStruct, > extends ColorsScheme { colors: T; } @@ -85,9 +83,7 @@ export interface ThemeGeneral /** * Интерфейс описания Темы (в этом типе описываются все темы дизайн-системы) */ -export interface ThemeDescription - extends Tokens, - ColorsDescription {} +export interface ThemeDescription extends Tokens, ColorsDescription {} /** * Основной интерфейс темы @@ -104,25 +100,21 @@ export interface Theme extends ThemeGeneral, ColorsFinal { * Тема, в которой все значения пикселизированы. Т.е. 16 -> '16px' */ // eslint-disable-next-line @typescript-eslint/ban-types -export type PixelifyTheme< - T extends Partial> = StaticTokens, -> = StringifyObject> & - Pick> & { - themeType: 'pixelify'; - themeName: string; - colorScheme: ColorScheme; - }; +export type PixelifyTheme> = StaticTokens> = + StringifyObject> & + Pick> & { + themeType: 'pixelify'; + themeName: string; + colorScheme: ColorScheme; + }; /** * Тема, которая каждой переменной даёт name и value в виде названия * соответствующей css-переменной и ссылки на неё */ export type ThemeCssVars = { - [K in keyof Omit]: NamifyObject< - StringifyObject[K], - true - >; -} & Pick & {themeType: 'cssVars'}; + [K in keyof Omit]: NamifyObject[K], true>; +} & Pick & { themeType: 'cssVars' }; /** * Тоже самое, что и ThemeCssVars, только у переменных есть ещё originValue @@ -130,4 +122,4 @@ export type ThemeCssVars = { */ export type ThemeCssVarsWide = { [K in keyof Omit]: NamifyObject[K]>; -} & Pick & {themeType: 'cssVarsWide'}; +} & Pick & { themeType: 'cssVarsWide' }; diff --git a/src/interfaces/general/tools/cssVars.ts b/src/interfaces/general/tools/cssVars.ts index 8d042188..793386d0 100644 --- a/src/interfaces/general/tools/cssVars.ts +++ b/src/interfaces/general/tools/cssVars.ts @@ -1,7 +1,7 @@ /** * Структура переменной в CssVars теме */ -import {Adaptive} from '.'; +import { Adaptive } from '.'; export interface CssVarValue { /** @@ -19,22 +19,16 @@ export interface WideCssVarValue extends CssVarValue { originalValue: T; } -type Valuefy< - T, - WithoutValue extends boolean = false, -> = WithoutValue extends true ? CssVarValue : WideCssVarValue; +type Valuefy = WithoutValue extends true + ? CssVarValue + : WideCssVarValue; -export type NamifyObject = T extends Adaptive< - T[keyof T] -> +export type NamifyObject = T extends Adaptive ? { auto: NamifyObject; regular: NamifyObject; } & { - [key in Exclude]?: NamifyObject< - Partial, - W - >; + [key in Exclude]?: NamifyObject, W>; } : T extends Record ? { diff --git a/src/interfaces/general/tools/customMedia.ts b/src/interfaces/general/tools/customMedia.ts index d3c93067..db7f6323 100644 --- a/src/interfaces/general/tools/customMedia.ts +++ b/src/interfaces/general/tools/customMedia.ts @@ -1,5 +1,5 @@ -import {GetLast, GetLength} from './utils'; -import {ViewportsTuple} from './viewports'; +import { GetLast, GetLength } from './utils'; +import { ViewportsTuple } from './viewports'; export type CustomMediaByViewportUnion = | `width${Capitalize extends 1 ? never : Vt[number]>}` diff --git a/src/interfaces/general/tools/index.ts b/src/interfaces/general/tools/index.ts index 30e219d0..90b6510e 100644 --- a/src/interfaces/general/tools/index.ts +++ b/src/interfaces/general/tools/index.ts @@ -1,4 +1,4 @@ -import {DefaultViewports, ViewportsTuple} from './viewports'; +import { DefaultViewports, ViewportsTuple } from './viewports'; /** * Cтруктура адаптивной переменной. diff --git a/src/interfaces/general/tools/utils.ts b/src/interfaces/general/tools/utils.ts index 7ca8f9b3..42f009db 100644 --- a/src/interfaces/general/tools/utils.ts +++ b/src/interfaces/general/tools/utils.ts @@ -11,18 +11,17 @@ export type GetLength = T['length']; /** * Получить кортеж БЕЗ первого элемента */ -export type DropFirstInTuple = (( - ...args: T -) => any) extends (arg: any, ...rest: infer U) => any +export type DropFirstInTuple = ((...args: T) => any) extends ( + arg: any, + ...rest: infer U +) => any ? U : T; /** * Тип, позволяющий получить последний кортежа */ -export type GetLast = T[GetLength< - DropFirstInTuple ->]; +export type GetLast = T[GetLength>]; /** * Тип который может deep изменять свойства number -> number | string diff --git a/src/interfaces/general/typography/index.ts b/src/interfaces/general/typography/index.ts index 0e55f3c1..20dced56 100644 --- a/src/interfaces/general/typography/index.ts +++ b/src/interfaces/general/typography/index.ts @@ -1,4 +1,4 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; type TLength = string | 0; diff --git a/src/interfaces/namespaces/paradigm/index.ts b/src/interfaces/namespaces/paradigm/index.ts index dbb25bc1..5d4deac4 100644 --- a/src/interfaces/namespaces/paradigm/index.ts +++ b/src/interfaces/namespaces/paradigm/index.ts @@ -1,23 +1,15 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import { - Theme, - ThemeCssVars, - ThemeCssVarsWide, - ThemeDescription, -} from '@/interfaces/general'; +import { Theme, ThemeCssVars, ThemeCssVarsWide, ThemeDescription } from '@/interfaces/general'; import { ColorDescription, ColorsDescriptionStruct, ColorWithStates, } from '@/interfaces/general/colors'; -import {Adaptive, Breakpoints} from '@/interfaces/general/tools'; -import {CustomMediaByViewport} from '@/interfaces/general/tools/customMedia'; -import { - DefaultViewports, - ViewportsTuple, -} from '@/interfaces/general/tools/viewports'; -import {Font} from '@/interfaces/general/typography'; +import { Adaptive, Breakpoints } from '@/interfaces/general/tools'; +import { CustomMediaByViewport } from '@/interfaces/general/tools/customMedia'; +import { DefaultViewports, ViewportsTuple } from '@/interfaces/general/tools/viewports'; +import { Font } from '@/interfaces/general/typography'; export interface LocalParadigmColorsDescriptionStruct { /** @@ -704,9 +696,8 @@ type ParadigmAdaptiveTokens = { [key in keyof AdaptiveValues]: Adaptive; }; -export interface ParadigmThemeDescription< - Vt extends ViewportsTuple = DefaultViewports, -> extends ThemeDescription, +export interface ParadigmThemeDescription + extends ThemeDescription, ParadigmAdaptiveTokens, ParadigmToneValues, ParadigmBorders, @@ -724,12 +715,11 @@ interface ParadigmThemeStatic ParadigmHelpers, ParadigmLocalColors {} -export type ParadigmTheme = - ParadigmThemeStatic & CustomMediaByViewport; +export type ParadigmTheme = ParadigmThemeStatic & + CustomMediaByViewport; -export type ParadigmThemeCssVarsWide< - Vt extends ViewportsTuple = DefaultViewports, -> = ThemeCssVarsWide, 'breakpoints'>; +export type ParadigmThemeCssVarsWide = + ThemeCssVarsWide, 'breakpoints'>; export type ParadigmThemeCssVars< Vt extends ViewportsTuple = DefaultViewports, diff --git a/src/interfaces/themes/calendar/index.ts b/src/interfaces/themes/calendar/index.ts index 4034e15a..e8614755 100644 --- a/src/interfaces/themes/calendar/index.ts +++ b/src/interfaces/themes/calendar/index.ts @@ -1,18 +1,15 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {ThemeCssVars} from '@/interfaces/general'; +import { ThemeCssVars } from '@/interfaces/general'; import { ColorDescription, ColorsDescriptionStruct, ColorWithStates, } from '@/interfaces/general/colors'; -import {Adaptive} from '@/interfaces/general/tools'; -import {Font} from '@/interfaces/general/typography'; -import {LocalParadigmColorsDescriptionStruct} from '@/interfaces/namespaces/paradigm'; -import { - ThemeParadigmBase, - ThemeParadigmBaseDescription, -} from '@/interfaces/themes/paradigmBase'; +import { Adaptive } from '@/interfaces/general/tools'; +import { Font } from '@/interfaces/general/typography'; +import { LocalParadigmColorsDescriptionStruct } from '@/interfaces/namespaces/paradigm'; +import { ThemeParadigmBase, ThemeParadigmBaseDescription } from '@/interfaces/themes/paradigmBase'; export interface ThemeCalendarOverValues { calendarFontTextEvent: Adaptive; @@ -112,5 +109,4 @@ export interface ThemeCalendarDescription ColorsDescriptionStruct; } -export interface ThemeCalendarCssVars - extends ThemeCssVars {} +export interface ThemeCalendarCssVars extends ThemeCssVars {} diff --git a/src/interfaces/themes/calendarDark/index.ts b/src/interfaces/themes/calendarDark/index.ts index 824d6d9e..92c5bea8 100644 --- a/src/interfaces/themes/calendarDark/index.ts +++ b/src/interfaces/themes/calendarDark/index.ts @@ -5,6 +5,5 @@ import { } from '@/interfaces/themes/calendar'; export interface ThemeCalendarDark extends ThemeCalendar {} -export interface ThemeCalendarDarkDescription - extends ThemeCalendarDescription {} +export interface ThemeCalendarDarkDescription extends ThemeCalendarDescription {} export interface ThemeCalendarDarkCssVars extends ThemeCalendarCssVars {} diff --git a/src/interfaces/themes/cloudDark/index.ts b/src/interfaces/themes/cloudDark/index.ts index 63cbf21e..ddc4968b 100644 --- a/src/interfaces/themes/cloudDark/index.ts +++ b/src/interfaces/themes/cloudDark/index.ts @@ -1,4 +1,4 @@ -import {ThemeCloud, ThemeCloudCssVars, ThemeCloudDescription} from '../cloud'; +import { ThemeCloud, ThemeCloudCssVars, ThemeCloudDescription } from '../cloud'; export type ThemeCloudDark = ThemeCloud; export type ThemeCloudDarkDescription = ThemeCloudDescription; diff --git a/src/interfaces/themes/home/index.ts b/src/interfaces/themes/home/index.ts index 23c3d833..2b65fa7e 100644 --- a/src/interfaces/themes/home/index.ts +++ b/src/interfaces/themes/home/index.ts @@ -44,5 +44,4 @@ export interface ThemeHomeDescription } // Интерфейс ниже не используем в коде, но нужен для сборки -export interface ThemeHomeCssVars - extends ParadigmThemeCssVars {} +export interface ThemeHomeCssVars extends ParadigmThemeCssVars {} diff --git a/src/interfaces/themes/homeDark/index.ts b/src/interfaces/themes/homeDark/index.ts index afa62258..4bf43145 100644 --- a/src/interfaces/themes/homeDark/index.ts +++ b/src/interfaces/themes/homeDark/index.ts @@ -1,4 +1,4 @@ -import {ThemeHome, ThemeHomeCssVars, ThemeHomeDescription} from '../home'; +import { ThemeHome, ThemeHomeCssVars, ThemeHomeDescription } from '../home'; export type ThemeHomeDark = ThemeHome; export type ThemeHomeDarkDescription = ThemeHomeDescription; diff --git a/src/interfaces/themes/media/index.ts b/src/interfaces/themes/media/index.ts index 9c9fbb55..a5a4eea0 100644 --- a/src/interfaces/themes/media/index.ts +++ b/src/interfaces/themes/media/index.ts @@ -1,8 +1,8 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {ColorDescription, ColorWithStates} from '@/interfaces/general/colors'; -import {Adaptive} from '@/interfaces/general/tools'; -import {Font} from '@/interfaces/general/typography'; +import { ColorDescription, ColorWithStates } from '@/interfaces/general/colors'; +import { Adaptive } from '@/interfaces/general/tools'; +import { Font } from '@/interfaces/general/typography'; import { ParadigmTheme, ParadigmThemeCssVars, @@ -86,10 +86,7 @@ export interface ThemeMedia export interface ThemeMediaDescription extends ParadigmThemeDescription, MediaUniqTokens { - colors: ParadigmThemeDescription['colors'] & - ProjectColorsDescriptions & - SocialColorsDescriptions; + colors: ParadigmThemeDescription['colors'] & ProjectColorsDescriptions & SocialColorsDescriptions; } -export interface ThemeMediaCssVars - extends ParadigmThemeCssVars {} +export interface ThemeMediaCssVars extends ParadigmThemeCssVars {} diff --git a/src/interfaces/themes/mediaDark/index.ts b/src/interfaces/themes/mediaDark/index.ts index d453cae7..5c96c568 100644 --- a/src/interfaces/themes/mediaDark/index.ts +++ b/src/interfaces/themes/mediaDark/index.ts @@ -1,4 +1,4 @@ -import {ThemeMedia, ThemeMediaCssVars, ThemeMediaDescription} from '../media'; +import { ThemeMedia, ThemeMediaCssVars, ThemeMediaDescription } from '../media'; export type ThemeMediaDark = ThemeMedia; export type ThemeMediaDarkDescription = ThemeMediaDescription; diff --git a/src/interfaces/themes/mycom/index.ts b/src/interfaces/themes/mycom/index.ts index 5b004411..6eb95a7a 100644 --- a/src/interfaces/themes/mycom/index.ts +++ b/src/interfaces/themes/mycom/index.ts @@ -1,23 +1,17 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {ColorWithStates} from '@/interfaces/general/colors'; -import {ParadigmThemeCssVars} from '@/interfaces/namespaces/paradigm'; -import { - MediaViewportsTuple, - ThemeMedia, - ThemeMediaDescription, -} from '@/interfaces/themes/media'; +import { ColorWithStates } from '@/interfaces/general/colors'; +import { ParadigmThemeCssVars } from '@/interfaces/namespaces/paradigm'; +import { MediaViewportsTuple, ThemeMedia, ThemeMediaDescription } from '@/interfaces/themes/media'; export interface ThemeMycom extends Omit { colorSale: ColorWithStates; fontFamily: Property.FontFamily; } -export interface ThemeMycomDescription - extends Omit { +export interface ThemeMycomDescription extends Omit { fontFamily: Property.FontFamily; - colors: ThemeMediaDescription['colors'] & {colorSale: Property.Color}; + colors: ThemeMediaDescription['colors'] & { colorSale: Property.Color }; } -export interface ThemeMycomCssVars - extends ParadigmThemeCssVars {} +export interface ThemeMycomCssVars extends ParadigmThemeCssVars {} diff --git a/src/interfaces/themes/octavius/index.ts b/src/interfaces/themes/octavius/index.ts index 384ab7ce..95ced4e3 100644 --- a/src/interfaces/themes/octavius/index.ts +++ b/src/interfaces/themes/octavius/index.ts @@ -1,12 +1,12 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {ThemeCssVars} from '@/interfaces/general'; +import { ThemeCssVars } from '@/interfaces/general'; import { ColorDescription, ColorsDescriptionStruct, ColorWithStates, } from '@/interfaces/general/colors'; -import {Adaptive} from '@/interfaces/general/tools'; +import { Adaptive } from '@/interfaces/general/tools'; import { LocalParadigmColorsDescriptionStruct, ParadigmTheme, @@ -58,9 +58,7 @@ export interface ThemeOctaviusLocalSizes { } type ThemeOctaviusAdaptiveTokens = { - [key in keyof ThemeOctaviusLocalSizes]: Adaptive< - ThemeOctaviusLocalSizes[key] - >; + [key in keyof ThemeOctaviusLocalSizes]: Adaptive; }; export interface LocalOctaviusColorsDescriptionStruct { @@ -274,5 +272,4 @@ export interface ThemeOctavius OctaviusLocalColors, ThemeOctaviusAdaptiveTokens {} -export interface ThemeOctaviusCssVars - extends ThemeCssVars {} +export interface ThemeOctaviusCssVars extends ThemeCssVars {} diff --git a/src/interfaces/themes/octaviusCompact/index.ts b/src/interfaces/themes/octaviusCompact/index.ts index 08f8e2f3..45a876f4 100644 --- a/src/interfaces/themes/octaviusCompact/index.ts +++ b/src/interfaces/themes/octaviusCompact/index.ts @@ -5,6 +5,5 @@ import { } from '@/interfaces/themes/octavius'; export interface ThemeOctaviusCompact extends ThemeOctavius {} -export interface ThemeOctaviusCompactDescription - extends ThemeOctaviusDescription {} +export interface ThemeOctaviusCompactDescription extends ThemeOctaviusDescription {} export interface ThemeOctaviusCompactCssVars extends ThemeOctaviusCssVars {} diff --git a/src/interfaces/themes/octaviusCompactDark/index.ts b/src/interfaces/themes/octaviusCompactDark/index.ts index 78201b37..167be7d4 100644 --- a/src/interfaces/themes/octaviusCompactDark/index.ts +++ b/src/interfaces/themes/octaviusCompactDark/index.ts @@ -5,6 +5,5 @@ import { } from '@/interfaces/themes/octavius'; export interface ThemeOctaviusCompactDark extends ThemeOctavius {} -export interface ThemeOctaviusCompacDarkDescription - extends ThemeOctaviusDescription {} +export interface ThemeOctaviusCompacDarkDescription extends ThemeOctaviusDescription {} export interface ThemeOctaviusCompactDarkCssVars extends ThemeOctaviusCssVars {} diff --git a/src/interfaces/themes/otvet/index.ts b/src/interfaces/themes/otvet/index.ts index 7786a684..7f39aa1a 100644 --- a/src/interfaces/themes/otvet/index.ts +++ b/src/interfaces/themes/otvet/index.ts @@ -6,7 +6,5 @@ import { type OtvetViewports = ['desktopS']; export interface ThemeOtvet extends ParadigmTheme {} -export interface ThemeOtvetDescription - extends ParadigmThemeDescription {} -export interface ThemeOtvetCssVars - extends ParadigmThemeCssVars {} +export interface ThemeOtvetDescription extends ParadigmThemeDescription {} +export interface ThemeOtvetCssVars extends ParadigmThemeCssVars {} diff --git a/src/interfaces/themes/otvetDark/index.ts b/src/interfaces/themes/otvetDark/index.ts index 651f53ea..e8482b90 100644 --- a/src/interfaces/themes/otvetDark/index.ts +++ b/src/interfaces/themes/otvetDark/index.ts @@ -1,4 +1,4 @@ -import {ThemeOtvet, ThemeOtvetCssVars, ThemeOtvetDescription} from '../otvet'; +import { ThemeOtvet, ThemeOtvetCssVars, ThemeOtvetDescription } from '../otvet'; export type ThemeOtvetDark = ThemeOtvet; export type ThemeOtvetDarkDescription = ThemeOtvetDescription; diff --git a/src/interfaces/themes/paradigmBase/index.ts b/src/interfaces/themes/paradigmBase/index.ts index a33044ab..75e0a451 100644 --- a/src/interfaces/themes/paradigmBase/index.ts +++ b/src/interfaces/themes/paradigmBase/index.ts @@ -4,7 +4,6 @@ import { ParadigmThemeDescription, } from '@/interfaces/namespaces/paradigm'; -export interface ThemeParadigmBaseDescription - extends ParadigmThemeDescription {} +export interface ThemeParadigmBaseDescription extends ParadigmThemeDescription {} export interface ThemeParadigmBase extends ParadigmTheme {} export interface ThemeParadigmBaseCssVars extends ParadigmThemeCssVars {} diff --git a/src/interfaces/themes/paradigmBaseDark/index.ts b/src/interfaces/themes/paradigmBaseDark/index.ts index fb4b3bd5..efcc62ed 100644 --- a/src/interfaces/themes/paradigmBaseDark/index.ts +++ b/src/interfaces/themes/paradigmBaseDark/index.ts @@ -4,7 +4,6 @@ import { ParadigmThemeDescription, } from '@/interfaces/namespaces/paradigm'; -export interface ThemeParadigmBaseDarkDescription - extends ParadigmThemeDescription {} +export interface ThemeParadigmBaseDarkDescription extends ParadigmThemeDescription {} export interface ThemeParadigmBaseDark extends ParadigmTheme {} export interface ThemeParadigmBaseDarkCssVars extends ParadigmThemeCssVars {} diff --git a/src/interfaces/themes/pharma/index.ts b/src/interfaces/themes/pharma/index.ts index 23c86f85..231baa02 100644 --- a/src/interfaces/themes/pharma/index.ts +++ b/src/interfaces/themes/pharma/index.ts @@ -1,17 +1,13 @@ -import {ColorDescription, ColorWithStates} from '@/interfaces/general/colors'; -import {ParadigmThemeCssVars} from '@/interfaces/namespaces/paradigm'; -import { - MediaViewportsTuple, - ThemeMedia, - ThemeMediaDescription, -} from '@/interfaces/themes/media'; +import { ColorDescription, ColorWithStates } from '@/interfaces/general/colors'; +import { ParadigmThemeCssVars } from '@/interfaces/namespaces/paradigm'; +import { MediaViewportsTuple, ThemeMedia, ThemeMediaDescription } from '@/interfaces/themes/media'; export interface ThemePharma extends ThemeMedia { colorSale: ColorWithStates; } export interface ThemePharmaDescription extends ThemeMediaDescription { - colors: ThemeMediaDescription['colors'] & {colorSale: ColorDescription}; + colors: ThemeMediaDescription['colors'] & { colorSale: ColorDescription }; } export interface ThemePharmaCssVars diff --git a/src/interfaces/themes/promo/index.ts b/src/interfaces/themes/promo/index.ts index fa1918a3..899f741d 100644 --- a/src/interfaces/themes/promo/index.ts +++ b/src/interfaces/themes/promo/index.ts @@ -1,7 +1,7 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {Adaptive} from '@/interfaces/general/tools'; -import {ViewportsOrdered} from '@/interfaces/general/tools/viewports'; +import { Adaptive } from '@/interfaces/general/tools'; +import { ViewportsOrdered } from '@/interfaces/general/tools/viewports'; import { ParadigmTheme, ParadigmThemeCssVars, @@ -44,13 +44,10 @@ type PromoSpecificTokens = { sizeMarginL: Adaptive; }; -export interface ThemePromo - extends ParadigmTheme, - PromoSpecificTokens {} +export interface ThemePromo extends ParadigmTheme, PromoSpecificTokens {} export interface ThemePromoDescription extends ParadigmThemeDescription, PromoSpecificTokens {} -export interface ThemePromoCssVars - extends ParadigmThemeCssVars {} +export interface ThemePromoCssVars extends ParadigmThemeCssVars {} diff --git a/src/interfaces/themes/pulse/index.ts b/src/interfaces/themes/pulse/index.ts index 78358c56..150cfebe 100644 --- a/src/interfaces/themes/pulse/index.ts +++ b/src/interfaces/themes/pulse/index.ts @@ -1,18 +1,11 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import { - ColorsDescription, - ThemeCssVars, - ThemeDescription, -} from '@/interfaces/general'; -import {ColorDescription, ColorWithStates} from '@/interfaces/general/colors'; -import {GradientPoints} from '@/interfaces/general/gradients'; -import {Adaptive} from '@/interfaces/general/tools'; -import {Font} from '@/interfaces/general/typography'; -import { - ParadigmTheme, - ParadigmThemeDescription, -} from '@/interfaces/namespaces/paradigm'; +import { ColorsDescription, ThemeCssVars, ThemeDescription } from '@/interfaces/general'; +import { ColorDescription, ColorWithStates } from '@/interfaces/general/colors'; +import { GradientPoints } from '@/interfaces/general/gradients'; +import { Adaptive } from '@/interfaces/general/tools'; +import { Font } from '@/interfaces/general/typography'; +import { ParadigmTheme, ParadigmThemeDescription } from '@/interfaces/namespaces/paradigm'; type AllowedParadigmTokens = /* Special */ @@ -226,16 +219,10 @@ type ThemePulseColorsWithState = { type AllowedParadigmThemeTokens = Pick< ParadigmTheme, - | 'themeType' - | 'colorsScheme' - | AllowedParadigmTokens - | AllowedParadigmColorTokens + 'themeType' | 'colorsScheme' | AllowedParadigmTokens | AllowedParadigmColorTokens >; -type AllowedParadigmTokensDescription = Pick< - ThemeDescription, - AllowedParadigmTokens ->; +type AllowedParadigmTokensDescription = Pick; export interface ThemePulse extends AllowedParadigmThemeTokens, diff --git a/src/interfaces/themes/pulseDark/index.ts b/src/interfaces/themes/pulseDark/index.ts index d059cc96..9115f33d 100644 --- a/src/interfaces/themes/pulseDark/index.ts +++ b/src/interfaces/themes/pulseDark/index.ts @@ -1,4 +1,4 @@ -import {ThemePulse, ThemePulseCssVars, ThemePulseDescription} from '../pulse'; +import { ThemePulse, ThemePulseCssVars, ThemePulseDescription } from '../pulse'; export interface ThemePulseDark extends ThemePulse {} export interface ThemePulseDarkDescription extends ThemePulseDescription {} diff --git a/src/interfaces/themes/search/index.ts b/src/interfaces/themes/search/index.ts index 21fd32ed..ae8c5b64 100644 --- a/src/interfaces/themes/search/index.ts +++ b/src/interfaces/themes/search/index.ts @@ -1,12 +1,12 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; import { ColorDescription, ColorsDescriptionStruct, ColorWithStates, } from '@/interfaces/general/colors'; -import {Adaptive} from '@/interfaces/general/tools'; -import {Font} from '@/interfaces/general/typography'; +import { Adaptive } from '@/interfaces/general/tools'; +import { Font } from '@/interfaces/general/typography'; import { LocalParadigmColorsDescriptionStruct, ParadigmTheme, @@ -78,5 +78,4 @@ export interface ThemeSearchDescription } // Интерфейс ниже не используем в коде, но нужен для сборки -export interface ThemeSearchCssVars - extends ParadigmThemeCssVars {} +export interface ThemeSearchCssVars extends ParadigmThemeCssVars {} diff --git a/src/interfaces/themes/vkBase/index.ts b/src/interfaces/themes/vkBase/index.ts index 4fa85510..994843c8 100644 --- a/src/interfaces/themes/vkBase/index.ts +++ b/src/interfaces/themes/vkBase/index.ts @@ -1,4 +1,4 @@ -import {Theme, ThemeCssVars, ThemeDescription} from '@/interfaces/general'; +import { Theme, ThemeCssVars, ThemeDescription } from '@/interfaces/general'; export interface ThemeVkBase extends Theme {} export interface ThemeVkBaseDescription extends ThemeDescription {} diff --git a/src/interfaces/themes/vkBaseDark/index.ts b/src/interfaces/themes/vkBaseDark/index.ts index 0ed75557..b79b5c96 100644 --- a/src/interfaces/themes/vkBaseDark/index.ts +++ b/src/interfaces/themes/vkBaseDark/index.ts @@ -1,4 +1,4 @@ -import {Theme, ThemeCssVars, ThemeDescription} from '@/interfaces/general'; +import { Theme, ThemeCssVars, ThemeDescription } from '@/interfaces/general'; export interface ThemeVkBaseDark extends Theme {} export interface ThemeVkBaseDarkDescription extends ThemeDescription {} diff --git a/src/lint/index.test.ts b/src/lint/index.test.ts index 2487cbc5..a65aa617 100644 --- a/src/lint/index.test.ts +++ b/src/lint/index.test.ts @@ -1,4 +1,4 @@ -import {lint} from '@/lint/index'; +import { lint } from '@/lint/index'; describe('lint unit', () => { test('shows no warnings if everything is ok', () => { @@ -39,7 +39,7 @@ describe('lint unit', () => { expect( lint([ { - colors: {colorBg: 'transparent'}, + colors: { colorBg: 'transparent' }, }, ]), ).toEqual([ diff --git a/src/lint/index.ts b/src/lint/index.ts index b0d27767..98268abc 100644 --- a/src/lint/index.ts +++ b/src/lint/index.ts @@ -1,11 +1,8 @@ -import { - isColorDescriptionCallable, - isColorDescriptionStatic, -} from '@/build/helpers/cssHelpers'; -import {expandColor} from '@/build/themeProcessors/expandColors/expandColors'; -import {ColorsDescription} from '@/interfaces/general'; -import {checkAllRules} from '@/lint/rules'; -import {themes} from '@/themeDescriptions'; +import { isColorDescriptionCallable, isColorDescriptionStatic } from '@/build/helpers/cssHelpers'; +import { expandColor } from '@/build/themeProcessors/expandColors/expandColors'; +import { ColorsDescription } from '@/interfaces/general'; +import { checkAllRules } from '@/lint/rules'; +import { themes } from '@/themeDescriptions'; function lintThemeObject( object: Record, @@ -18,17 +15,12 @@ function lintThemeObject( const tokenValue = object[token]; if (tokenValue && typeof tokenValue === 'object') { - lintThemeObject(tokenValue as any, theme, (message) => - emit(`${token}.${message}`), - ); + lintThemeObject(tokenValue as any, theme, (message) => emit(`${token}.${message}`)); } const childEmit = (message) => emit(`${token} error: ${message}`); - if ( - token.startsWith('color') && - isColorDescriptionCallable(tokenValue) - ) { + if (token.startsWith('color') && isColorDescriptionCallable(tokenValue)) { checkAllRules(token, expandColor(tokenValue, theme), childEmit); } else if (isColorDescriptionStatic(tokenValue)) { checkAllRules(token, tokenValue, childEmit); diff --git a/src/lint/lint.test.ts b/src/lint/lint.test.ts index 90302713..347f84bd 100644 --- a/src/lint/lint.test.ts +++ b/src/lint/lint.test.ts @@ -1,4 +1,4 @@ -import {lint} from '@/lint/index'; +import { lint } from '@/lint/index'; describe('lint', () => { test('snapshot', () => { diff --git a/src/lint/rules/alphaMismatch.test.ts b/src/lint/rules/alphaMismatch.test.ts index b90f5db1..427d19db 100644 --- a/src/lint/rules/alphaMismatch.test.ts +++ b/src/lint/rules/alphaMismatch.test.ts @@ -1,4 +1,4 @@ -import {checkAlphaMismatch} from '@/lint/rules/alphaMismatch'; +import { checkAlphaMismatch } from '@/lint/rules/alphaMismatch'; describe('lint rules | alphaMismatch', () => { const emit = jest.fn(); diff --git a/src/lint/rules/alphaMismatch.ts b/src/lint/rules/alphaMismatch.ts index 0da3744e..6f7c7c62 100644 --- a/src/lint/rules/alphaMismatch.ts +++ b/src/lint/rules/alphaMismatch.ts @@ -1,13 +1,9 @@ -import {isColorWithStates} from '@/build/helpers/cssHelpers'; -import {ColorDescriptionStatic} from '@/interfaces/general/colors'; +import { isColorWithStates } from '@/build/helpers/cssHelpers'; +import { ColorDescriptionStatic } from '@/interfaces/general/colors'; function isAlphaColor(color: ColorDescriptionStatic): boolean { if (isColorWithStates(color)) { - return ( - isAlphaColor(color.normal) && - isAlphaColor(color.hover) && - isAlphaColor(color.active) - ); + return isAlphaColor(color.normal) && isAlphaColor(color.hover) && isAlphaColor(color.active); } return color === 'transparent' || /^rgba\(/i.test(color); @@ -27,9 +23,9 @@ export function checkAlphaMismatch( if (isAlphaName !== isAlphaValue) { emit( - `Color token type mismatch: ${ - isAlphaName ? 'alpha' : 'opaque' - } token name but ${isAlphaValue ? 'alpha' : 'opaque'} value`, + `Color token type mismatch: ${isAlphaName ? 'alpha' : 'opaque'} token name but ${ + isAlphaValue ? 'alpha' : 'opaque' + } value`, ); } } diff --git a/src/lint/rules/index.ts b/src/lint/rules/index.ts index 1cefda67..f26a203f 100644 --- a/src/lint/rules/index.ts +++ b/src/lint/rules/index.ts @@ -1,5 +1,5 @@ -import {ColorDescriptionStatic} from '@/interfaces/general/colors'; -import {checkAlphaMismatch} from '@/lint/rules/alphaMismatch'; +import { ColorDescriptionStatic } from '@/interfaces/general/colors'; +import { checkAlphaMismatch } from '@/lint/rules/alphaMismatch'; // Тут перечислены все проверки export function checkAllRules( diff --git a/src/themeDescriptions/base/paradigm.ts b/src/themeDescriptions/base/paradigm.ts index a468a441..7421b53b 100644 --- a/src/themeDescriptions/base/paradigm.ts +++ b/src/themeDescriptions/base/paradigm.ts @@ -1,12 +1,12 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {getGradientPointsFromColor} from '@/build/helpers/getGradientPointsFromColor'; -import {alias, staticRef} from '@/build/helpers/tokenHelpers'; -import {overlayColors} from '@/build/themeProcessors/expandColors/overlayColors'; -import {ColorsDescription, ThemeDescription} from '@/interfaces/general'; -import {Elevation} from '@/interfaces/general/elevation'; -import {ParadigmThemeDescription} from '@/interfaces/namespaces/paradigm'; -import {helpers} from '@/themeDescriptions/common'; +import { getGradientPointsFromColor } from '@/build/helpers/getGradientPointsFromColor'; +import { alias, staticRef } from '@/build/helpers/tokenHelpers'; +import { overlayColors } from '@/build/themeProcessors/expandColors/overlayColors'; +import { ColorsDescription, ThemeDescription } from '@/interfaces/general'; +import { Elevation } from '@/interfaces/general/elevation'; +import { ParadigmThemeDescription } from '@/interfaces/namespaces/paradigm'; +import { helpers } from '@/themeDescriptions/common'; const fontFamilyAccent = 'MailSans, Helvetica, Arial, sans-serif'; const fontFamilyBase = 'Helvetica, Arial, sans-serif'; @@ -674,7 +674,7 @@ export const lightThemeBase: ThemeDescription = { zIndexPopout: 100, }; -const {x05, x1, x2, x3, x4, x5, x6, x8, x10} = helpers; +const { x05, x1, x2, x3, x4, x5, x6, x8, x10 } = helpers; export const lightTheme: ParadigmThemeDescription = { ...lightThemeBase, diff --git a/src/themeDescriptions/base/vk.ts b/src/themeDescriptions/base/vk.ts index e59a322d..443766ab 100644 --- a/src/themeDescriptions/base/vk.ts +++ b/src/themeDescriptions/base/vk.ts @@ -1,10 +1,10 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {getGradientPointsFromColor} from '@/build/helpers/getGradientPointsFromColor'; -import {alias} from '@/build/helpers/tokenHelpers'; -import {ColorsDescription, ThemeDescription} from '@/interfaces/general'; -import {Elevation} from '@/interfaces/general/elevation'; -import {Gradients} from '@/interfaces/general/gradients'; +import { getGradientPointsFromColor } from '@/build/helpers/getGradientPointsFromColor'; +import { alias } from '@/build/helpers/tokenHelpers'; +import { ColorsDescription, ThemeDescription } from '@/interfaces/general'; +import { Elevation } from '@/interfaces/general/elevation'; +import { Gradients } from '@/interfaces/general/gradients'; const FONT_FAMILY_DEFAULT = 'VK Sans Text'; @@ -150,16 +150,11 @@ export const lightGradient: Gradients = { }; export const lightElevation: Elevation = { - elevation1: - '0px 0px 2px rgba(0, 0, 0, 0.03), 0px 2px 2px rgba(0, 0, 0, 0.06)', - elevation1InvertY: - '0px 0px 2px rgba(0, 0, 0, 0.03), 0px -2px 2px rgba(0, 0, 0, 0.06)', - elevation2: - '0px 4px 8px rgba(0, 0, 0, 0.04), 0px 0px 4px rgba(0, 0, 0, 0.06)', - elevation3: - '0px 0px 2px rgba(0, 0, 0, 0.08), 0px 4px 16px rgba(0, 0, 0, 0.08)', - elevation4: - '0px 0px 8px rgba(0, 0, 0, 0.12), 0px 16px 16px rgba(0, 0, 0, 0.16)', + elevation1: '0px 0px 2px rgba(0, 0, 0, 0.03), 0px 2px 2px rgba(0, 0, 0, 0.06)', + elevation1InvertY: '0px 0px 2px rgba(0, 0, 0, 0.03), 0px -2px 2px rgba(0, 0, 0, 0.06)', + elevation2: '0px 4px 8px rgba(0, 0, 0, 0.04), 0px 0px 4px rgba(0, 0, 0, 0.06)', + elevation3: '0px 0px 2px rgba(0, 0, 0, 0.08), 0px 4px 16px rgba(0, 0, 0, 0.08)', + elevation4: '0px 0px 8px rgba(0, 0, 0, 0.12), 0px 16px 16px rgba(0, 0, 0, 0.16)', }; export const darkColors: ColorsDescription = { @@ -289,16 +284,11 @@ export const darkGradient: Gradients = { export const darkElevation: Elevation = { // TODO: Тени (Поправить для Dark) - elevation1: - '0px 0px 2px rgba(0, 0, 0, 0.03), 0px 2px 2px rgba(0, 0, 0, 0.06)', - elevation1InvertY: - '0px 0px 2px rgba(0, 0, 0, 0.03), 0px -2px 2px rgba(0, 0, 0, 0.06)', - elevation2: - '0px 4px 8px rgba(0, 0, 0, 0.04), 0px 0px 4px rgba(0, 0, 0, 0.06)', - elevation3: - '0px 0px 2px rgba(0, 0, 0, 0.08), 0px 4px 16px rgba(0, 0, 0, 0.08)', - elevation4: - '0px 0px 8px rgba(0, 0, 0, 0.12), 0px 16px 16px rgba(0, 0, 0, 0.16)', + elevation1: '0px 0px 2px rgba(0, 0, 0, 0.03), 0px 2px 2px rgba(0, 0, 0, 0.06)', + elevation1InvertY: '0px 0px 2px rgba(0, 0, 0, 0.03), 0px -2px 2px rgba(0, 0, 0, 0.06)', + elevation2: '0px 4px 8px rgba(0, 0, 0, 0.04), 0px 0px 4px rgba(0, 0, 0, 0.06)', + elevation3: '0px 0px 2px rgba(0, 0, 0, 0.08), 0px 4px 16px rgba(0, 0, 0, 0.08)', + elevation4: '0px 0px 8px rgba(0, 0, 0, 0.12), 0px 16px 16px rgba(0, 0, 0, 0.16)', }; export const lightTheme: ThemeDescription = { diff --git a/src/themeDescriptions/common/colors/projectColors.ts b/src/themeDescriptions/common/colors/projectColors.ts index 9767458e..a6b5e470 100644 --- a/src/themeDescriptions/common/colors/projectColors.ts +++ b/src/themeDescriptions/common/colors/projectColors.ts @@ -1,4 +1,4 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; export type ProjectColors = { colorPrimaryAuto: Property.Color; diff --git a/src/themeDescriptions/common/colors/socialColors.ts b/src/themeDescriptions/common/colors/socialColors.ts index cf127819..2d18c926 100644 --- a/src/themeDescriptions/common/colors/socialColors.ts +++ b/src/themeDescriptions/common/colors/socialColors.ts @@ -1,4 +1,4 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; export type SocialColors = { colorSocialVk: Property.Color; diff --git a/src/themeDescriptions/common/fontSizes/index.ts b/src/themeDescriptions/common/fontSizes/index.ts index e76c17fd..4701171c 100644 --- a/src/themeDescriptions/common/fontSizes/index.ts +++ b/src/themeDescriptions/common/fontSizes/index.ts @@ -1,12 +1,11 @@ -import {Font, TypographyBaseProps} from '@/interfaces/general/typography'; +import { Font, TypographyBaseProps } from '@/interfaces/general/typography'; -import {helpers} from '../helpers'; +import { helpers } from '../helpers'; -const {sizeBase} = helpers; +const { sizeBase } = helpers; // базовые параметры шрифта -export const fontFamily: TypographyBaseProps['fontFamilyBase'] = - 'Helvetica, Arial, sans-serif'; +export const fontFamily: TypographyBaseProps['fontFamilyBase'] = 'Helvetica, Arial, sans-serif'; export const fontFamilyAccent: TypographyBaseProps['fontFamilyAccent'] = 'MailSans, Helvetica, Arial, sans-serif'; export const fontWeight: TypographyBaseProps['fontWeightBase1'] = 400; diff --git a/src/themeDescriptions/common/helpers/index.ts b/src/themeDescriptions/common/helpers/index.ts index 8ed99575..ea783c90 100644 --- a/src/themeDescriptions/common/helpers/index.ts +++ b/src/themeDescriptions/common/helpers/index.ts @@ -1,4 +1,4 @@ -import {ParadigmHelpers} from '@/interfaces/namespaces/paradigm'; +import { ParadigmHelpers } from '@/interfaces/namespaces/paradigm'; const sizeBase = 4; const x0 = 0; diff --git a/src/themeDescriptions/common/index.ts b/src/themeDescriptions/common/index.ts index 696ae03f..fcf97bc8 100644 --- a/src/themeDescriptions/common/index.ts +++ b/src/themeDescriptions/common/index.ts @@ -1,6 +1,6 @@ -import {projectColors} from './colors/projectColors'; -import {socialColors} from './colors/socialColors'; -import {fontSizes} from './fontSizes'; -import {helpers} from './helpers'; +import { projectColors } from './colors/projectColors'; +import { socialColors } from './colors/socialColors'; +import { fontSizes } from './fontSizes'; +import { helpers } from './helpers'; -export {fontSizes, helpers, projectColors, socialColors}; +export { fontSizes, helpers, projectColors, socialColors }; diff --git a/src/themeDescriptions/descriptions.ts b/src/themeDescriptions/descriptions.ts index b51b58f3..0f9aa4df 100644 --- a/src/themeDescriptions/descriptions.ts +++ b/src/themeDescriptions/descriptions.ts @@ -1,4 +1,4 @@ -import {Theme} from '@/interfaces/general'; +import { Theme } from '@/interfaces/general'; export type Description = { category: string; diff --git a/src/themeDescriptions/index.ts b/src/themeDescriptions/index.ts index 5d67f997..e8e0dee8 100644 --- a/src/themeDescriptions/index.ts +++ b/src/themeDescriptions/index.ts @@ -1,12 +1,9 @@ -import { - calendarDarkTheme, - calendarTheme, -} from '@/themeDescriptions/themes/calendar'; -import {callsTheme} from '@/themeDescriptions/themes/calls'; -import {cloudDarkTheme, cloudTheme} from '@/themeDescriptions/themes/cloud'; -import {homeDarkTheme, homeTheme} from '@/themeDescriptions/themes/home'; -import {mediaDarkTheme, mediaTheme} from '@/themeDescriptions/themes/media'; -import {mycomTheme} from '@/themeDescriptions/themes/mycom'; +import { calendarDarkTheme, calendarTheme } from '@/themeDescriptions/themes/calendar'; +import { callsTheme } from '@/themeDescriptions/themes/calls'; +import { cloudDarkTheme, cloudTheme } from '@/themeDescriptions/themes/cloud'; +import { homeDarkTheme, homeTheme } from '@/themeDescriptions/themes/home'; +import { mediaDarkTheme, mediaTheme } from '@/themeDescriptions/themes/media'; +import { mycomTheme } from '@/themeDescriptions/themes/mycom'; import { octaviusDarkTheme, octaviusTheme, @@ -16,24 +13,18 @@ import { octaviusCompactDarkTheme, octaviusCompactTheme, } from '@/themeDescriptions/themes/octaviusCompact'; -import { - octaviusVKDarkTheme, - octaviusVKTheme, -} from '@/themeDescriptions/themes/octaviusVK'; -import {otvetDarkTheme, otvetTheme} from '@/themeDescriptions/themes/otvet'; -import {pharmaTheme} from '@/themeDescriptions/themes/pharma'; -import {promoTheme} from '@/themeDescriptions/themes/promo'; -import {pulseTheme, pulseThemeDark} from '@/themeDescriptions/themes/pulse'; -import {searchTheme} from '@/themeDescriptions/themes/search'; -import {todoTheme} from '@/themeDescriptions/themes/todo'; -import {vkComTheme, vkComThemeDark} from '@/themeDescriptions/themes/vkCom'; -import {vkIOSTheme, vkIOSThemeDark} from '@/themeDescriptions/themes/vkIOS'; +import { octaviusVKDarkTheme, octaviusVKTheme } from '@/themeDescriptions/themes/octaviusVK'; +import { otvetDarkTheme, otvetTheme } from '@/themeDescriptions/themes/otvet'; +import { pharmaTheme } from '@/themeDescriptions/themes/pharma'; +import { promoTheme } from '@/themeDescriptions/themes/promo'; +import { pulseTheme, pulseThemeDark } from '@/themeDescriptions/themes/pulse'; +import { searchTheme } from '@/themeDescriptions/themes/search'; +import { todoTheme } from '@/themeDescriptions/themes/todo'; +import { vkComTheme, vkComThemeDark } from '@/themeDescriptions/themes/vkCom'; +import { vkIOSTheme, vkIOSThemeDark } from '@/themeDescriptions/themes/vkIOS'; -import { - darkThemeExport as paradigmBaseDark, - lightTheme as paradigmBase, -} from './base/paradigm'; -import {darkTheme as vkBaseDark, lightTheme as vkBase} from './base/vk'; +import { darkThemeExport as paradigmBaseDark, lightTheme as paradigmBase } from './base/paradigm'; +import { darkTheme as vkBaseDark, lightTheme as vkBase } from './base/vk'; export const themes = [ // ==== Базовые темы новой дизайн-системы ==== diff --git a/src/themeDescriptions/themes/calendar/index.ts b/src/themeDescriptions/themes/calendar/index.ts index 511d69aa..2962add1 100644 --- a/src/themeDescriptions/themes/calendar/index.ts +++ b/src/themeDescriptions/themes/calendar/index.ts @@ -1,16 +1,15 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {ThemeCalendarDescription} from '@/interfaces/themes/calendar'; -import {ThemeCalendarDarkDescription} from '@/interfaces/themes/calendarDark'; -import {fontWeight} from '@/themeDescriptions/common/fontSizes'; +import { ThemeCalendarDescription } from '@/interfaces/themes/calendar'; +import { ThemeCalendarDarkDescription } from '@/interfaces/themes/calendarDark'; +import { fontWeight } from '@/themeDescriptions/common/fontSizes'; -import {darkTheme, darkThemeElevation, lightTheme} from '../../base/paradigm'; -import {fontSizes, helpers} from '../../common'; +import { darkTheme, darkThemeElevation, lightTheme } from '../../base/paradigm'; +import { fontSizes, helpers } from '../../common'; -const {x2, x4, x5} = helpers; +const { x2, x4, x5 } = helpers; -export const fontFamily: Property.FontFamily = - 'MailSans, Helvetica, Arial, sans-serif'; +export const fontFamily: Property.FontFamily = 'MailSans, Helvetica, Arial, sans-serif'; const fontSize2 = { ...fontSizes.fontSize2, diff --git a/src/themeDescriptions/themes/calls/index.ts b/src/themeDescriptions/themes/calls/index.ts index a022a1fa..ca7c4761 100644 --- a/src/themeDescriptions/themes/calls/index.ts +++ b/src/themeDescriptions/themes/calls/index.ts @@ -1,12 +1,11 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {ThemeCallsDescription} from '@/interfaces/themes/calls'; +import { ThemeCallsDescription } from '@/interfaces/themes/calls'; -import {darkTheme} from '../../base/paradigm'; -import {fontSizes} from '../../common'; +import { darkTheme } from '../../base/paradigm'; +import { fontSizes } from '../../common'; -export const fontFamily: Property.FontFamily = - 'MailSans, Helvetica, Arial, sans-serif'; +export const fontFamily: Property.FontFamily = 'MailSans, Helvetica, Arial, sans-serif'; const fontSize1 = { ...fontSizes.fontSize1, diff --git a/src/themeDescriptions/themes/cloud/index.ts b/src/themeDescriptions/themes/cloud/index.ts index ba9ccc33..2e65b3e4 100644 --- a/src/themeDescriptions/themes/cloud/index.ts +++ b/src/themeDescriptions/themes/cloud/index.ts @@ -1,14 +1,14 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; -import {staticRef} from '@/build/helpers/tokenHelpers'; -import {Font} from '@/interfaces/general/typography'; -import {ThemeCloudDescription} from '@/interfaces/themes/cloud'; -import {ThemeCloudDarkDescription} from '@/interfaces/themes/cloudDark'; +import { staticRef } from '@/build/helpers/tokenHelpers'; +import { Font } from '@/interfaces/general/typography'; +import { ThemeCloudDescription } from '@/interfaces/themes/cloud'; +import { ThemeCloudDarkDescription } from '@/interfaces/themes/cloudDark'; -import {darkTheme, darkThemeElevation, lightTheme} from '../../base/paradigm'; -import {helpers} from '../../common'; +import { darkTheme, darkThemeElevation, lightTheme } from '../../base/paradigm'; +import { helpers } from '../../common'; -const {x2, x4, x5} = helpers; +const { x2, x4, x5 } = helpers; // шрифты не наследуются от fonSize потому что // мы хотим обновить шрифтовую шкалу и проще начать с этого проекта @@ -16,14 +16,8 @@ type FontAccentAtributes = { fontFamily: Property.FontFamily; fontWeight: Property.FontWeight; }; -const fontFamilyBase: Property.FontFamily = - 'Inter, Helvetica, Arial, sans-serif'; -const { - fontFamilyAccent, - fontWeightBase3, - fontWeightAccent1, - fontWeightAccent2, -} = lightTheme; +const fontFamilyBase: Property.FontFamily = 'Inter, Helvetica, Arial, sans-serif'; +const { fontFamilyAccent, fontWeightBase3, fontWeightAccent1, fontWeightAccent2 } = lightTheme; const fontAccentBoldAtributes: FontAccentAtributes = { fontFamily: staticRef(fontFamilyAccent), diff --git a/src/themeDescriptions/themes/home/index.ts b/src/themeDescriptions/themes/home/index.ts index b7cca87e..2beaadb3 100644 --- a/src/themeDescriptions/themes/home/index.ts +++ b/src/themeDescriptions/themes/home/index.ts @@ -3,8 +3,8 @@ import { ThemeHomeDescription, ThemeHomeOverValues, } from '@/interfaces/themes/home'; -import {ThemeHomeDarkDescription} from '@/interfaces/themes/homeDark'; -import {darkTheme, lightTheme} from '@/themeDescriptions/base/paradigm'; +import { ThemeHomeDarkDescription } from '@/interfaces/themes/homeDark'; +import { darkTheme, lightTheme } from '@/themeDescriptions/base/paradigm'; const localHomeColors: LocalHomeColorsDescriptionStruct = { homeColorSocialVk: '#2787F5', diff --git a/src/themeDescriptions/themes/media/index.ts b/src/themeDescriptions/themes/media/index.ts index 4f4d5bbc..03ad2a7a 100644 --- a/src/themeDescriptions/themes/media/index.ts +++ b/src/themeDescriptions/themes/media/index.ts @@ -1,11 +1,11 @@ -import {replacePropDeep} from '@/build/helpers/replacePropDeep'; -import {staticRef} from '@/build/helpers/tokenHelpers'; -import {ThemeMediaDescription} from '@/interfaces/themes/media'; -import {helpers, projectColors, socialColors} from '@/themeDescriptions/common'; +import { replacePropDeep } from '@/build/helpers/replacePropDeep'; +import { staticRef } from '@/build/helpers/tokenHelpers'; +import { ThemeMediaDescription } from '@/interfaces/themes/media'; +import { helpers, projectColors, socialColors } from '@/themeDescriptions/common'; -import {darkTheme, lightTheme} from '../../base/paradigm'; +import { darkTheme, lightTheme } from '../../base/paradigm'; -const {x0, x05, x2, x3, x4, x5, x6, x8, x10, x12} = helpers; +const { x0, x05, x2, x3, x4, x5, x6, x8, x10, x12 } = helpers; const fontFamilyAccent = 'MailSans, Inter, Helvetica, Arial, sans-serif'; const fontFamilyArticle = 'Georgia, serif'; diff --git a/src/themeDescriptions/themes/mycom/index.ts b/src/themeDescriptions/themes/mycom/index.ts index 65791006..2d2aeb78 100644 --- a/src/themeDescriptions/themes/mycom/index.ts +++ b/src/themeDescriptions/themes/mycom/index.ts @@ -1,9 +1,9 @@ -import {replacePropDeep} from '@/build/helpers/replacePropDeep'; -import {ThemeMediaDescription} from '@/interfaces/themes/media'; -import {ThemeMycomDescription} from '@/interfaces/themes/mycom'; -import {projectColors} from '@/themeDescriptions/common/colors/projectColors'; +import { replacePropDeep } from '@/build/helpers/replacePropDeep'; +import { ThemeMediaDescription } from '@/interfaces/themes/media'; +import { ThemeMycomDescription } from '@/interfaces/themes/mycom'; +import { projectColors } from '@/themeDescriptions/common/colors/projectColors'; -import {mediaTheme} from '../media'; +import { mediaTheme } from '../media'; const fontFamily = 'Proxima Nova, Arial, sans-serif'; const themeWithFontFamily: ThemeMediaDescription = replacePropDeep(mediaTheme, { diff --git a/src/themeDescriptions/themes/octavius/index.ts b/src/themeDescriptions/themes/octavius/index.ts index 5c4da99b..b836aa23 100644 --- a/src/themeDescriptions/themes/octavius/index.ts +++ b/src/themeDescriptions/themes/octavius/index.ts @@ -1,12 +1,12 @@ -import {getRGBA, toneOpacity} from '@/build/helpers/cssHelpers'; -import {ThemeOctaviusDescription} from '@/interfaces/themes/octavius'; +import { getRGBA, toneOpacity } from '@/build/helpers/cssHelpers'; +import { ThemeOctaviusDescription } from '@/interfaces/themes/octavius'; import { darkTheme, darkThemeElevation, lightColors, lightTheme, } from '@/themeDescriptions/base/paradigm'; -import {socialColors} from '@/themeDescriptions/common'; +import { socialColors } from '@/themeDescriptions/common'; export const octaviusTheme: ThemeOctaviusDescription = { ...lightTheme, @@ -87,22 +87,18 @@ export const octaviusTheme: ThemeOctaviusDescription = { octaviusColorHeaderIconAttach: lightTheme.colors.colorIconContrast, octaviusColorHeaderTextSecondary: '#93969b', octaviusColorHeaderSearchIcon: '#b6b8be', - octaviusColorHeaderSearchChipBackground: - lightTheme.colors.colorBackgroundSecondary, + octaviusColorHeaderSearchChipBackground: lightTheme.colors.colorBackgroundSecondary, octaviusColorHeaderSearchChipBackgroundEditable: '#ffffff', - octaviusColorHeaderSearchChipBorderEditableAlpha: - lightTheme.colors.colorFieldBorderAlpha, + octaviusColorHeaderSearchChipBorderEditableAlpha: lightTheme.colors.colorFieldBorderAlpha, octaviusColorHeaderSearchBackground: '#ffffff', octaviusColorHeaderSearchBackgroundCollapsed: '#ffffff', octaviusColorHeaderSearchText: lightTheme.colors.colorTextPrimary, - octaviusColorHeaderSearchTextCollapsed: - lightTheme.colors.colorTextSecondary, + octaviusColorHeaderSearchTextCollapsed: lightTheme.colors.colorTextSecondary, octaviusColorHeaderFilterTextAlpha: 'rgba(255, 255, 255, .48)', - octaviusColorHeaderProgress: - lightTheme.colors.colorBackgroundAccentAlternative, + octaviusColorHeaderProgress: lightTheme.colors.colorBackgroundAccentAlternative, octaviusColorPortalMenuBackground: lightTheme.colors.colorBackground, @@ -114,11 +110,9 @@ export const octaviusTheme: ThemeOctaviusDescription = { octaviusColorSidebarButtonText: lightTheme.colors.colorTextPrimary, octaviusColorSidebarButtonBackground: '#FFFFFF', - octaviusColorSidebarCounterBackgroundAlpha: - lightTheme.colors.colorTransparent, + octaviusColorSidebarCounterBackgroundAlpha: lightTheme.colors.colorTransparent, octaviusColorSidebarCounterText: lightTheme.colors.colorTextPrimary, - octaviusColorSidebarItemBackgroundAlpha: - lightTheme.colors.colorTransparent, + octaviusColorSidebarItemBackgroundAlpha: lightTheme.colors.colorTransparent, octaviusColorSidebarScrollbarAlpha: 'rgba(0, 16, 61, 0.08)', octaviusColorSidebarItemIcon: '#333333', octaviusColorSidebarItemText: '#333333', @@ -128,14 +122,10 @@ export const octaviusTheme: ThemeOctaviusDescription = { octaviusColorSidebarShortItemIcon: '#333333', octaviusColorSidebarShortItemText: '#333333', - octaviusColorSidebarShortItemTextActive: - lightTheme.colors.colorTextPrimary, - octaviusColorSidebarShortItemIconActive: - lightTheme.colors.colorIconPrimary, - octaviusColorSidebarShortItemIconSecondary: - lightTheme.colors.colorIconSecondary, - octaviusColorSidebarShortItemTextSecondary: - lightTheme.colors.colorTextSecondary, + octaviusColorSidebarShortItemTextActive: lightTheme.colors.colorTextPrimary, + octaviusColorSidebarShortItemIconActive: lightTheme.colors.colorIconPrimary, + octaviusColorSidebarShortItemIconSecondary: lightTheme.colors.colorIconSecondary, + octaviusColorSidebarShortItemTextSecondary: lightTheme.colors.colorTextSecondary, octaviusColorSidebarComposeButtonBackground: '#ffffff', octaviusColorSidebarComposeButtonText: '#2c2d2e', @@ -173,23 +163,19 @@ export const octaviusTheme: ThemeOctaviusDescription = { octaviusColorListTextUnread: lightTheme.colors.colorTextPrimary, octaviusColorListTextPrimary: lightTheme.colors.colorTextPrimary, octaviusColorListIconPrimary: lightTheme.colors.colorIconPrimary, - octaviusColorListLetterSeparatorAlpha: - lightTheme.colors.colorSeparatorPrimaryAlpha, + octaviusColorListLetterSeparatorAlpha: lightTheme.colors.colorSeparatorPrimaryAlpha, octaviusColorListLetterAdvBackground: '#F0F5FF', octaviusColorListBackgroundPositiveAlpha: 'rgba(13, 194, 104, 0.08)', octaviusColorListBackgroundPositiveTagsOutline: '#F2FAF4', octaviusColorLetterListTextUnread: '#2c2d2e', - octaviusColorDatasetBackground: - lightTheme.colors.colorBackgroundContent, + octaviusColorDatasetBackground: lightTheme.colors.colorBackgroundContent, octaviusColorEmptyStateText: '#333333', octaviusColorButtonEmptyStateText: '#2C2D2E', octaviusColorButtonEmptyStateBackgroundAlpha: 'rgba(0, 16, 61, 0.06)', - octaviusColorLayoutBorderAlpha: - lightTheme.colors.colorSeparatorPrimaryAlpha, - octaviusColorLayoutLetterBorderAlpha: - lightTheme.colors.colorSeparatorPrimaryAlpha, + octaviusColorLayoutBorderAlpha: lightTheme.colors.colorSeparatorPrimaryAlpha, + octaviusColorLayoutLetterBorderAlpha: lightTheme.colors.colorSeparatorPrimaryAlpha, octaviusColorEmptyStateTextLink: '#005bd1', octaviusColorLetterContactBackgroundAlpha: { normal: 'transparent', @@ -232,8 +218,7 @@ export const octaviusTheme: ThemeOctaviusDescription = { octaviusFontFamilyDefault: 'HelveticaNeue, Helvetica, Arial, sans-serif', - octaviusFontFamilyMailSans: - 'MailSans, HelveticaNeue, Helvetica, Arial, sans-serif', + octaviusFontFamilyMailSans: 'MailSans, HelveticaNeue, Helvetica, Arial, sans-serif', octaviusFontFamilyGlobal: 'Arial, Tahoma, Verdana, sans-serif', octaviusFontFamilyMac: 'Helvetica, Arial, Tahoma, Verdana, sans-serif', @@ -295,19 +280,15 @@ export const octaviusDarkTheme: ThemeOctaviusDescription = { octaviusColorHeaderIconUnread: darkTheme.colors.colorIconContrast, octaviusColorHeaderIconFavorite: darkTheme.colors.colorIconContrast, octaviusColorHeaderIconAttach: darkTheme.colors.colorIconContrast, - octaviusColorHeaderProgress: - darkTheme.colors.colorBackgroundAccentAlternative, + octaviusColorHeaderProgress: darkTheme.colors.colorBackgroundAccentAlternative, octaviusColorHeaderSearchBackground: '#303030', - octaviusColorHeaderSearchBackgroundCollapsed: - darkTheme.colors.colorBackgroundModal, + octaviusColorHeaderSearchBackgroundCollapsed: darkTheme.colors.colorBackgroundModal, octaviusColorHeaderSearchChipBackground: '#404040', octaviusColorHeaderSearchChipBackgroundEditable: '#3e3e3e', - octaviusColorHeaderSearchChipBorderEditableAlpha: - 'rgba(255, 255, 255, .48)', + octaviusColorHeaderSearchChipBorderEditableAlpha: 'rgba(255, 255, 255, .48)', octaviusColorHeaderSearchText: darkTheme.colors.colorTextPrimary, - octaviusColorHeaderSearchTextCollapsed: - darkTheme.colors.colorTextSecondary, + octaviusColorHeaderSearchTextCollapsed: darkTheme.colors.colorTextSecondary, octaviusColorSidebarItemIconPrimary: '#E7E8EA', @@ -322,10 +303,8 @@ export const octaviusDarkTheme: ThemeOctaviusDescription = { octaviusColorSidebarShortItemText: '#E7E8EA', octaviusColorSidebarShortItemTextActive: '#ffffff', octaviusColorSidebarShortItemIconActive: '#ffffff', - octaviusColorSidebarShortItemTextSecondary: - darkTheme.colors.colorTextSecondary, - octaviusColorSidebarShortItemIconSecondary: - darkTheme.colors.colorIconSecondary, + octaviusColorSidebarShortItemTextSecondary: darkTheme.colors.colorTextSecondary, + octaviusColorSidebarShortItemIconSecondary: darkTheme.colors.colorIconSecondary, octaviusColorHeaderButtonBackgroundAlpha: { normal: 'transparent', @@ -345,8 +324,7 @@ export const octaviusDarkTheme: ThemeOctaviusDescription = { octaviusColorSidebarButtonText: lightTheme.colors.colorTextPrimary, octaviusColorSidebarButtonBackground: '#FFFFFF', - octaviusColorSidebarCounterBackgroundAlpha: - darkTheme.colors.colorTransparent, + octaviusColorSidebarCounterBackgroundAlpha: darkTheme.colors.colorTransparent, octaviusColorSidebarCounterText: darkTheme.colors.colorTextPrimary, octaviusColorSidebarScrollbarAlpha: 'rgba(255, 255, 255, 0.12)', @@ -380,10 +358,8 @@ export const octaviusDarkTheme: ThemeOctaviusDescription = { octaviusColorSidebarIconEvent: '#3BBAFE', octaviusColorSidebarIconFees: '#EE3C3C', - octaviusColorListLetterBackground: - darkTheme.colors.colorBackgroundContent, - octaviusColorListLetterSeparatorAlpha: - darkTheme.colors.colorSeparatorPrimaryAlpha, + octaviusColorListLetterBackground: darkTheme.colors.colorBackgroundContent, + octaviusColorListLetterSeparatorAlpha: darkTheme.colors.colorSeparatorPrimaryAlpha, octaviusColorListLetterAdvBackground: '#151515', octaviusColorListBackgroundPositiveAlpha: 'rgba(13, 194, 104, 0.08)', octaviusColorListBackgroundPositiveTagsOutline: '#272F2A', @@ -391,8 +367,7 @@ export const octaviusDarkTheme: ThemeOctaviusDescription = { octaviusColorDatasetBackground: darkTheme.colors.colorBackgroundContent, octaviusColorEmptyStateText: darkTheme.colors.colorTextPrimary, octaviusColorButtonEmptyStateText: '#E7E8EA', - octaviusColorButtonEmptyStateBackgroundAlpha: - 'rgba(255, 255, 255, 0.12)', + octaviusColorButtonEmptyStateBackgroundAlpha: 'rgba(255, 255, 255, 0.12)', octaviusColorLayoutBorderAlpha: 'transparent', octaviusColorLayoutLetterBorderAlpha: 'rgba(0, 0, 0, 0.4)', octaviusColorEmptyStateTextLink: '#E7E8EA', @@ -441,11 +416,9 @@ export const octaviusWhiteTheme: ThemeOctaviusDescription = { hover: 'rgba(255, 255, 255, 0.64)', active: 'rgba(255, 255, 255, 0.4)', }, - octaviusColorHeaderFilterTextAlpha: - lightColors.colors.colorIconMediumAlpha, + octaviusColorHeaderFilterTextAlpha: lightColors.colors.colorIconMediumAlpha, octaviusColorHeaderSearchChipBackgroundEditable: '#ffffff', - octaviusColorHeaderSearchChipBorderEditableAlpha: - lightTheme.colors.colorFieldBorderAlpha, + octaviusColorHeaderSearchChipBorderEditableAlpha: lightTheme.colors.colorFieldBorderAlpha, octaviusColorHeaderButtonBackgroundAlpha: { normal: 'transparent', hover: 'rgba(255, 255, 255, 0.64)', diff --git a/src/themeDescriptions/themes/octaviusCompact/index.ts b/src/themeDescriptions/themes/octaviusCompact/index.ts index ac1f0112..b2a3301d 100644 --- a/src/themeDescriptions/themes/octaviusCompact/index.ts +++ b/src/themeDescriptions/themes/octaviusCompact/index.ts @@ -1,10 +1,10 @@ -import {staticRef} from '@/build/helpers/tokenHelpers'; -import {ThemeOctaviusCompactDescription} from '@/interfaces/themes/octaviusCompact'; +import { staticRef } from '@/build/helpers/tokenHelpers'; +import { ThemeOctaviusCompactDescription } from '@/interfaces/themes/octaviusCompact'; -import {fontSizes} from '../../common'; -import {octaviusDarkTheme, octaviusTheme} from '../octavius'; +import { fontSizes } from '../../common'; +import { octaviusDarkTheme, octaviusTheme } from '../octavius'; -const {fontSize2} = fontSizes; +const { fontSize2 } = fontSizes; export const octaviusCompactTheme: ThemeOctaviusCompactDescription = { ...octaviusTheme, @@ -12,7 +12,7 @@ export const octaviusCompactTheme: ThemeOctaviusCompactDescription = { fontText: { compact: staticRef(octaviusTheme.fontText).compact, - regular: {...fontSize2}, + regular: { ...fontSize2 }, }, sizeFieldHeight: { diff --git a/src/themeDescriptions/themes/octaviusVK/index.ts b/src/themeDescriptions/themes/octaviusVK/index.ts index 389d2333..f5f6cb76 100644 --- a/src/themeDescriptions/themes/octaviusVK/index.ts +++ b/src/themeDescriptions/themes/octaviusVK/index.ts @@ -1,12 +1,12 @@ -import {toneOpacity} from '@/build/helpers/cssHelpers'; -import {staticRef} from '@/build/helpers/tokenHelpers'; -import {ThemeOctaviusDescription} from '@/interfaces/themes/octavius'; +import { toneOpacity } from '@/build/helpers/cssHelpers'; +import { staticRef } from '@/build/helpers/tokenHelpers'; +import { ThemeOctaviusDescription } from '@/interfaces/themes/octavius'; import { darkColors as vkDarkColors, lightColors as vkLightColors, lightTheme as vkLightTheme, } from '@/themeDescriptions/base/vk'; -import {octaviusTheme} from '@/themeDescriptions/themes/octavius'; +import { octaviusTheme } from '@/themeDescriptions/themes/octavius'; const fontFamilyAccent = 'VKSansDisplay, Helvetica, Arial, sans-serif'; const fontFamilyBase = 'VKSansText, Helvetica, Arial, sans-serif'; @@ -38,8 +38,7 @@ const octaviusVKThemeBase: ThemeOctaviusDescription = { }, colorThumbErrorBackgroundAlpha: `rgba(230, 70, 70, 0.12)`, - colorBackgroundAccentAlternative: - vkLightColors.colors.colorBackgroundAccent, + colorBackgroundAccentAlternative: vkLightColors.colors.colorBackgroundAccent, octaviusColorBackground: '#EDEEF0', octaviusColorBackgroundAccentTonedAlpha: toneOpacity( @@ -71,40 +70,27 @@ const octaviusVKThemeBase: ThemeOctaviusDescription = { }, octaviusColorHeaderButtonText: '#000000', octaviusColorHeaderIcon: vkLightColors.colors.colorIconAccent, - octaviusColorHeaderTextSecondary: - vkLightColors.colors.colorTextSecondary, + octaviusColorHeaderTextSecondary: vkLightColors.colors.colorTextSecondary, octaviusColorHeaderProgress: vkLightColors.colors.colorBackgroundAccent, - octaviusColorHeaderFilterTextAlpha: - vkLightColors.colors.colorIconMediumAlpha, + octaviusColorHeaderFilterTextAlpha: vkLightColors.colors.colorIconMediumAlpha, octaviusColorSidebarItemText: '#333333', octaviusColorSidebarItemIcon: '#3F8AE0', octaviusColorSidebarShortItemText: '#333333', - octaviusColorSidebarShortItemIcon: - vkLightColors.colors.colorIconPrimary, - - octaviusColorSidebarItemTextActive: - vkLightColors.colors.colorTextPrimary, - octaviusColorSidebarItemIconActive: - vkLightColors.colors.colorIconPrimary, - octaviusColorSidebarItemTextSecondary: - vkLightColors.colors.colorTextSecondary, - octaviusColorSidebarItemIconSecondary: - vkLightColors.colors.colorIconAccent, - - octaviusColorSidebarShortItemTextActive: - vkLightColors.colors.colorTextPrimary, - octaviusColorSidebarShortItemIconActive: - vkLightColors.colors.colorIconPrimary, - octaviusColorSidebarShortItemTextSecondary: - vkLightColors.colors.colorTextSecondary, - octaviusColorSidebarShortItemIconSecondary: - vkLightColors.colors.colorIconSecondary, - - octaviusColorHeaderSearchBackground: - vkLightColors.colors.colorBackground, - octaviusColorHeaderSearchBackgroundCollapsed: - vkLightColors.colors.colorBackground, + octaviusColorSidebarShortItemIcon: vkLightColors.colors.colorIconPrimary, + + octaviusColorSidebarItemTextActive: vkLightColors.colors.colorTextPrimary, + octaviusColorSidebarItemIconActive: vkLightColors.colors.colorIconPrimary, + octaviusColorSidebarItemTextSecondary: vkLightColors.colors.colorTextSecondary, + octaviusColorSidebarItemIconSecondary: vkLightColors.colors.colorIconAccent, + + octaviusColorSidebarShortItemTextActive: vkLightColors.colors.colorTextPrimary, + octaviusColorSidebarShortItemIconActive: vkLightColors.colors.colorIconPrimary, + octaviusColorSidebarShortItemTextSecondary: vkLightColors.colors.colorTextSecondary, + octaviusColorSidebarShortItemIconSecondary: vkLightColors.colors.colorIconSecondary, + + octaviusColorHeaderSearchBackground: vkLightColors.colors.colorBackground, + octaviusColorHeaderSearchBackgroundCollapsed: vkLightColors.colors.colorBackground, octaviusColorHeaderSearchChipBackground: { normal: '#FFFFFF', hover: 'rgba(255, 255, 255, 0.64)', @@ -117,28 +103,22 @@ const octaviusVKThemeBase: ThemeOctaviusDescription = { }, octaviusColorHeaderSearchIcon: '#b6b8be', octaviusColorHeaderSearchText: vkLightColors.colors.colorTextPrimary, - octaviusColorHeaderSearchTextCollapsed: - vkLightColors.colors.colorTextSecondary, + octaviusColorHeaderSearchTextCollapsed: vkLightColors.colors.colorTextSecondary, octaviusColorSidebarItemBackgroundAlpha: { normal: 'transparent', hover: 'rgba(0, 16, 61, 0.04)', active: 'rgba(0, 16, 61, 0.08)', }, - octaviusColorSidebarItemIconPrimary: - vkLightColors.colors.colorIconAccent, - octaviusColorSidebarCounterBackgroundAlpha: - vkLightColors.colors.colorIconTertiaryAlpha, + octaviusColorSidebarItemIconPrimary: vkLightColors.colors.colorIconAccent, + octaviusColorSidebarCounterBackgroundAlpha: vkLightColors.colors.colorIconTertiaryAlpha, octaviusColorSidebarCounterText: '#FFFFFF', octaviusColorSidebarScrollbarAlpha: 'rgba(0, 16, 61, 0.08)', - octaviusColorContentScrollbarAlpha: - vkLightColors.colors.colorIconTertiaryAlpha, + octaviusColorContentScrollbarAlpha: vkLightColors.colors.colorIconTertiaryAlpha, - octaviusColorDatasetBackground: - octaviusTheme.colors.colorBackgroundContent, - octaviusColorListLetterSeparatorAlpha: - vkLightColors.colors.colorSeparatorPrimaryAlpha, + octaviusColorDatasetBackground: octaviusTheme.colors.colorBackgroundContent, + octaviusColorListLetterSeparatorAlpha: vkLightColors.colors.colorSeparatorPrimaryAlpha, octaviusColorListLetterBackground: { normal: '#ffffff', hover: '#E4E5E9', @@ -379,8 +359,7 @@ export const octaviusVKDarkTheme: ThemeOctaviusDescription = { active: 'rgba(255, 255, 255, 0.2)', }, - colorBackgroundAccentAlternative: - vkDarkColors.colors.colorBackgroundAccent, + colorBackgroundAccentAlternative: vkDarkColors.colors.colorBackgroundAccent, octaviusColorBackground: '#000000', octaviusColorBackgroundAccentTonedAlpha: toneOpacity( @@ -400,23 +379,17 @@ export const octaviusVKDarkTheme: ThemeOctaviusDescription = { octaviusColorPortalMenuBackground: 'rgb(31, 31, 31)', octaviusColorHeaderButtonText: vkDarkColors.colors.colorTextPrimary, octaviusColorHeaderIcon: vkDarkColors.colors.colorIconAccent, - octaviusColorHeaderTextSecondary: - vkDarkColors.colors.colorTextSecondary, + octaviusColorHeaderTextSecondary: vkDarkColors.colors.colorTextSecondary, octaviusColorHeaderProgress: vkDarkColors.colors.colorBackgroundAccent, - octaviusColorHeaderSearchBackground: - vkDarkColors.colors.colorBackground, - octaviusColorHeaderSearchBackgroundCollapsed: - vkDarkColors.colors.colorBackground, - octaviusColorHeaderSearchChipBackground: - vkDarkColors.colors.colorBackgroundModal, + octaviusColorHeaderSearchBackground: vkDarkColors.colors.colorBackground, + octaviusColorHeaderSearchBackgroundCollapsed: vkDarkColors.colors.colorBackground, + octaviusColorHeaderSearchChipBackground: vkDarkColors.colors.colorBackgroundModal, octaviusColorHeaderSearchChipBackgroundEditable: '#313131', - octaviusColorHeaderSearchChipBorderEditableAlpha: - 'rgba(255, 255, 255, .48)', + octaviusColorHeaderSearchChipBorderEditableAlpha: 'rgba(255, 255, 255, .48)', octaviusColorHeaderSearchIcon: vkDarkColors.colors.colorIconSecondary, octaviusColorHeaderSearchText: vkDarkColors.colors.colorTextSecondary, - octaviusColorHeaderSearchTextCollapsed: - vkDarkColors.colors.colorTextSecondary, + octaviusColorHeaderSearchTextCollapsed: vkDarkColors.colors.colorTextSecondary, octaviusColorHeaderFilterTextAlpha: 'rgba(255, 255, 255, 0.48)', octaviusColorSidebarItemBackgroundAlpha: { @@ -431,19 +404,15 @@ export const octaviusVKDarkTheme: ThemeOctaviusDescription = { active: 'rgba(255, 255, 255, 0.24)', }, - octaviusColorSidebarItemIconPrimary: - vkDarkColors.colors.colorIconPrimary, - octaviusColorSidebarCounterBackgroundAlpha: - vkDarkColors.colors.colorIconTertiaryAlpha, + octaviusColorSidebarItemIconPrimary: vkDarkColors.colors.colorIconPrimary, + octaviusColorSidebarCounterBackgroundAlpha: vkDarkColors.colors.colorIconTertiaryAlpha, octaviusColorSidebarCounterText: '#e1e3e6', octaviusColorSidebarScrollbarAlpha: 'rgba(255, 255, 255, 0.12)', octaviusColorContentScrollbarAlpha: 'rgba(255, 255, 255, 0.2)', - octaviusColorDatasetBackground: - vkDarkColors.colors.colorBackgroundContent, - octaviusColorListLetterSeparatorAlpha: - vkDarkColors.colors.colorSeparatorPrimaryAlpha, + octaviusColorDatasetBackground: vkDarkColors.colors.colorBackgroundContent, + octaviusColorListLetterSeparatorAlpha: vkDarkColors.colors.colorSeparatorPrimaryAlpha, octaviusColorListLetterBackground: { normal: '#19191A', hover: '#2B2B2C', @@ -460,10 +429,8 @@ export const octaviusVKDarkTheme: ThemeOctaviusDescription = { octaviusColorSidebarItemTextActive: '#ffffff', octaviusColorSidebarItemIconActive: '#ffffff', - octaviusColorSidebarShortItemTextActive: - vkDarkColors.colors.colorTextPrimary, - octaviusColorSidebarShortItemIconActive: - vkDarkColors.colors.colorIconPrimary, + octaviusColorSidebarShortItemTextActive: vkDarkColors.colors.colorTextPrimary, + octaviusColorSidebarShortItemIconActive: vkDarkColors.colors.colorIconPrimary, octaviusColorButtonText: '#E7E8EA', octaviusColorButtonIcon: '#E7E8EA', @@ -479,14 +446,10 @@ export const octaviusVKDarkTheme: ThemeOctaviusDescription = { active: 'rgba(255, 255, 255, 0.2)', }, - octaviusColorSidebarItemTextSecondary: - vkDarkColors.colors.colorTextSecondary, - octaviusColorSidebarItemIconSecondary: - vkDarkColors.colors.colorIconSecondary, - octaviusColorSidebarShortItemTextSecondary: - vkDarkColors.colors.colorTextSecondary, - octaviusColorSidebarShortItemIconSecondary: - vkDarkColors.colors.colorIconSecondary, + octaviusColorSidebarItemTextSecondary: vkDarkColors.colors.colorTextSecondary, + octaviusColorSidebarItemIconSecondary: vkDarkColors.colors.colorIconSecondary, + octaviusColorSidebarShortItemTextSecondary: vkDarkColors.colors.colorTextSecondary, + octaviusColorSidebarShortItemIconSecondary: vkDarkColors.colors.colorIconSecondary, octaviusColorLayoutBorderAlpha: 'transparent', octaviusColorLayoutLetterBorderAlpha: 'rgba(0, 0, 0, 0.4)', diff --git a/src/themeDescriptions/themes/otvet/index.ts b/src/themeDescriptions/themes/otvet/index.ts index 27f43eb1..9b8ff222 100644 --- a/src/themeDescriptions/themes/otvet/index.ts +++ b/src/themeDescriptions/themes/otvet/index.ts @@ -1,12 +1,12 @@ -import {ThemeOtvetDescription} from '@/interfaces/themes/otvet'; -import {ThemeOtvetDarkDescription} from '@/interfaces/themes/otvetDark'; +import { ThemeOtvetDescription } from '@/interfaces/themes/otvet'; +import { ThemeOtvetDarkDescription } from '@/interfaces/themes/otvetDark'; -import {flatifyTheme} from '../../../build/helpers/flatifyTheme'; -import {darkTheme, lightTheme} from '../../base/paradigm'; -import {fontSizes, helpers} from '../../common'; +import { flatifyTheme } from '../../../build/helpers/flatifyTheme'; +import { darkTheme, lightTheme } from '../../base/paradigm'; +import { fontSizes, helpers } from '../../common'; -const {x05, x3, x4, x5, x10} = helpers; -const {fontSize4, fontSize5, fontSize6, fontSize7, fontSize8} = fontSizes; +const { x05, x3, x4, x5, x10 } = helpers; +const { fontSize4, fontSize5, fontSize6, fontSize7, fontSize8 } = fontSizes; const octaviusThemeRegular = flatifyTheme(lightTheme); diff --git a/src/themeDescriptions/themes/pharma/index.ts b/src/themeDescriptions/themes/pharma/index.ts index df80cb5e..c1df8c99 100644 --- a/src/themeDescriptions/themes/pharma/index.ts +++ b/src/themeDescriptions/themes/pharma/index.ts @@ -1,7 +1,7 @@ -import {ThemePharmaDescription} from '@/interfaces/themes/pharma'; +import { ThemePharmaDescription } from '@/interfaces/themes/pharma'; -import {projectColors} from '../../common'; -import {mediaTheme} from '../media'; +import { projectColors } from '../../common'; +import { mediaTheme } from '../media'; export const pharmaTheme: ThemePharmaDescription = { ...mediaTheme, diff --git a/src/themeDescriptions/themes/promo/index.ts b/src/themeDescriptions/themes/promo/index.ts index 5ba97c8e..33d7d8ad 100644 --- a/src/themeDescriptions/themes/promo/index.ts +++ b/src/themeDescriptions/themes/promo/index.ts @@ -1,6 +1,6 @@ -import {ThemePromoDescription} from '@/interfaces/themes/promo'; +import { ThemePromoDescription } from '@/interfaces/themes/promo'; -import {lightTheme} from '../../base/paradigm'; +import { lightTheme } from '../../base/paradigm'; const fontWeight = 300; diff --git a/src/themeDescriptions/themes/pulse/index.ts b/src/themeDescriptions/themes/pulse/index.ts index 735db641..bc0fc87b 100644 --- a/src/themeDescriptions/themes/pulse/index.ts +++ b/src/themeDescriptions/themes/pulse/index.ts @@ -1,15 +1,15 @@ -import {Property} from 'csstype'; +import { Property } from 'csstype'; import { AllowedParadigmColorDescriptions, AllowedParadigmColorTokens, ThemePulseDescription, } from '@/interfaces/themes/pulse'; -import {ThemePulseDarkDescription} from '@/interfaces/themes/pulseDark'; -import {darkColors, lightThemeBase} from '@/themeDescriptions/base/paradigm'; -import {helpers} from '@/themeDescriptions/common'; +import { ThemePulseDarkDescription } from '@/interfaces/themes/pulseDark'; +import { darkColors, lightThemeBase } from '@/themeDescriptions/base/paradigm'; +import { helpers } from '@/themeDescriptions/common'; -const {x3, x4, x5} = helpers; +const { x3, x4, x5 } = helpers; const allowedParadigmColors: AllowedParadigmColorTokens[] = [ 'colorTextPrimary', @@ -92,10 +92,7 @@ const allowedParadigmColors: AllowedParadigmColorTokens[] = [ 'colorAvatarOverlay', ]; -const pick = ( - colors, - keys: AllowedParadigmColorTokens[], -): AllowedParadigmColorDescriptions => +const pick = (colors, keys: AllowedParadigmColorTokens[]): AllowedParadigmColorDescriptions => keys .filter((key) => key in colors) .reduce((res, key) => { diff --git a/src/themeDescriptions/themes/search/index.ts b/src/themeDescriptions/themes/search/index.ts index a52d683b..777360f2 100644 --- a/src/themeDescriptions/themes/search/index.ts +++ b/src/themeDescriptions/themes/search/index.ts @@ -1,7 +1,7 @@ -import {Adaptive} from '@/interfaces/general/tools'; -import {Font} from '@/interfaces/general/typography'; -import {ThemeSearchDescription} from '@/interfaces/themes/search'; -import {lightTheme} from '@/themeDescriptions/base/paradigm'; +import { Adaptive } from '@/interfaces/general/tools'; +import { Font } from '@/interfaces/general/typography'; +import { ThemeSearchDescription } from '@/interfaces/themes/search'; +import { lightTheme } from '@/themeDescriptions/base/paradigm'; export const searchTheme: ThemeSearchDescription = { ...lightTheme, diff --git a/src/themeDescriptions/themes/todo/index.ts b/src/themeDescriptions/themes/todo/index.ts index bff8a525..8d2e8932 100644 --- a/src/themeDescriptions/themes/todo/index.ts +++ b/src/themeDescriptions/themes/todo/index.ts @@ -1,9 +1,9 @@ -import {ThemeTodoDescription} from '@/interfaces/themes/todo'; +import { ThemeTodoDescription } from '@/interfaces/themes/todo'; -import {lightTheme} from '../../base/paradigm'; -import {helpers} from '../../common/helpers'; +import { lightTheme } from '../../base/paradigm'; +import { helpers } from '../../common/helpers'; -const {x12, x10} = helpers; +const { x12, x10 } = helpers; export const todoTheme: ThemeTodoDescription = { ...lightTheme, diff --git a/src/themeDescriptions/themes/vkCom/appearance.test.ts b/src/themeDescriptions/themes/vkCom/appearance.test.ts index d3c9bb90..5fd59a85 100644 --- a/src/themeDescriptions/themes/vkCom/appearance.test.ts +++ b/src/themeDescriptions/themes/vkCom/appearance.test.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import {resolveColor} from './appearance'; +import { resolveColor } from './appearance'; describe('vkCom/appearance', () => { test('white', () => { diff --git a/src/themeDescriptions/themes/vkCom/appearance.ts b/src/themeDescriptions/themes/vkCom/appearance.ts index ed185a29..0a2f031a 100644 --- a/src/themeDescriptions/themes/vkCom/appearance.ts +++ b/src/themeDescriptions/themes/vkCom/appearance.ts @@ -9,9 +9,7 @@ interface ClusterData { export function resolveColor(clusterData: ClusterData): string { const color = palette[clusterData.color_identifier] as string; - const alphaMultiplier = clusterData.alpha_multiplier - ? Number(clusterData.alpha_multiplier) - : 1; + const alphaMultiplier = clusterData.alpha_multiplier ? Number(clusterData.alpha_multiplier) : 1; if (!color) { console.error('Missing color:', clusterData.color_identifier); @@ -33,8 +31,8 @@ function ahex2rgba(ahex: string, multiplier = 1): string { } function opacify(hex: string, opacity: number): string { - return `rgba(${parseInt(hex.slice(0, 2), 16)}, ${parseInt( - hex.slice(2, 4), + return `rgba(${parseInt(hex.slice(0, 2), 16)}, ${parseInt(hex.slice(2, 4), 16)}, ${parseInt( + hex.slice(4), 16, - )}, ${parseInt(hex.slice(4), 16)}, ${opacity.toFixed(2)})`; + )}, ${opacity.toFixed(2)})`; } diff --git a/src/themeDescriptions/themes/vkCom/index.ts b/src/themeDescriptions/themes/vkCom/index.ts index 8fd98d58..cde3b9b8 100644 --- a/src/themeDescriptions/themes/vkCom/index.ts +++ b/src/themeDescriptions/themes/vkCom/index.ts @@ -1,11 +1,8 @@ -import { - vkcom_dark, - vkcom_light, -} from '@vkontakte/appearance/main.valette/scheme_web.json'; +import { vkcom_dark, vkcom_light } from '@vkontakte/appearance/main.valette/scheme_web.json'; -import {ColorsDescription} from '@/interfaces/general'; -import {ThemeVkComDescription} from '@/interfaces/themes/vkCom'; -import {ThemeVkComDarkDescription} from '@/interfaces/themes/vkComDark'; +import { ColorsDescription } from '@/interfaces/general'; +import { ThemeVkComDescription } from '@/interfaces/themes/vkCom'; +import { ThemeVkComDarkDescription } from '@/interfaces/themes/vkComDark'; import { darkColors, darkElevation, @@ -14,21 +11,17 @@ import { lightTheme, } from '@/themeDescriptions/base/vk'; -import {resolveColor} from './appearance'; +import { resolveColor } from './appearance'; const vkComColors = (theme: typeof vkcom_light) => ({ // Background colorBackgroundAccent: resolveColor(theme.colors.accent), - colorBackgroundAccentThemed: resolveColor( - theme.colors.button_primary_background, - ), + colorBackgroundAccentThemed: resolveColor(theme.colors.button_primary_background), // colorBackgroundAccentTint: '#5a9eff', colorBackgroundAccentAlternative: resolveColor(theme.colors.accent), colorBackground: resolveColor(theme.colors.background_page), colorBackgroundContent: resolveColor(theme.colors.background_content), - colorBackgroundSecondary: resolveColor( - theme.colors.content_tint_background, - ), + colorBackgroundSecondary: resolveColor(theme.colors.content_tint_background), // colorBackgroundSecondaryAlpha: { // normal: 'rgba(255, 255, 255, 0.04)', // hover: 'rgba(255, 255, 255, 0.08)', @@ -38,26 +31,16 @@ const vkComColors = (theme: typeof vkcom_light) => ({ // theme.colors.button_secondary_background, // ), colorBackgroundTertiary: resolveColor(theme.colors.background_light), - colorBackgroundContrast: resolveColor( - theme.colors.media_overlay_button_background, - ), + colorBackgroundContrast: resolveColor(theme.colors.media_overlay_button_background), // colorBackgroundContrastSecondaryAlpha: 'rgba(255, 255, 255, 0.20)', - colorBackgroundContrastInverse: resolveColor( - theme.colors.media_overlay_button_foreground, - ), + colorBackgroundContrastInverse: resolveColor(theme.colors.media_overlay_button_foreground), colorBackgroundModal: resolveColor(theme.colors.background_suggestions), - colorBackgroundModalInverse: resolveColor( - theme.colors.modal_card_header_close, - ), + colorBackgroundModalInverse: resolveColor(theme.colors.modal_card_header_close), // colorBackgroundWarning: resolveColor( // theme.colors.content_warning_background, // ), - colorBackgroundPositive: resolveColor( - theme.colors.button_commerce_background, - ), - colorBackgroundNegative: resolveColor( - theme.colors.button_secondary_destructive_foreground, - ), + colorBackgroundPositive: resolveColor(theme.colors.button_commerce_background), + colorBackgroundNegative: resolveColor(theme.colors.button_secondary_destructive_foreground), // colorBackgroundNegativeTint: resolveColor( // theme.colors.field_error_background, // ), @@ -69,9 +52,7 @@ const vkComColors = (theme: typeof vkcom_light) => ({ colorTextAccent: resolveColor(theme.colors.accent), colorTextAccentThemed: resolveColor(theme.colors.button_primary_background), colorTextPrimary: resolveColor(theme.colors.text_primary), - colorTextPrimaryInvariably: resolveColor( - theme.colors.media_overlay_button_foreground, - ), + colorTextPrimaryInvariably: resolveColor(theme.colors.media_overlay_button_foreground), colorTextSecondary: resolveColor(theme.colors.content_placeholder_text), colorTextSubhead: resolveColor(theme.colors.text_subhead), colorTextTertiary: resolveColor(theme.colors.text_tertiary), @@ -89,9 +70,7 @@ const vkComColors = (theme: typeof vkcom_light) => ({ colorIconAccent: resolveColor(theme.colors.accent), colorIconAccentThemed: resolveColor(theme.colors.button_primary_background), // colorIconPrimary: '#E1E3E6', - colorIconPrimaryInvariably: resolveColor( - theme.colors.media_overlay_button_foreground, - ), + colorIconPrimaryInvariably: resolveColor(theme.colors.media_overlay_button_foreground), colorIconMedium: resolveColor(theme.colors.icon_medium), colorIconMediumAlpha: resolveColor(theme.colors.icon_medium_alpha), colorIconSecondary: resolveColor(theme.colors.icon_secondary), @@ -106,9 +85,7 @@ const vkComColors = (theme: typeof vkcom_light) => ({ // Stroke colorStrokeAccent: resolveColor(theme.colors.accent), - colorStrokeAccentThemed: resolveColor( - theme.colors.button_primary_background, - ), + colorStrokeAccentThemed: resolveColor(theme.colors.button_primary_background), // colorSeparatorPrimary: '#363738', // resolveColor(theme.colors.separator_common), // colorSeparatorPrimary2x: '#444546', // colorSeparatorPrimary3x: '#505253', @@ -149,9 +126,7 @@ const vkComColors = (theme: typeof vkcom_light) => ({ // colorActionSheetText: '#529EF4', colorTrackBackground: resolveColor(theme.colors.loader_track_fill), colorTrackBuffer: resolveColor(theme.colors.loader_track_value_fill), - colorSearchFieldBackground: resolveColor( - theme.colors.search_bar_field_background, - ), + colorSearchFieldBackground: resolveColor(theme.colors.search_bar_field_background), colorPanelHeaderIcon: resolveColor(theme.colors.accent), // colorSegmentedControl: resolveColor( // theme.colors.segmented_control_bar_background, diff --git a/src/themeDescriptions/themes/vkIOS/index.ts b/src/themeDescriptions/themes/vkIOS/index.ts index 3d048516..2bd30e35 100644 --- a/src/themeDescriptions/themes/vkIOS/index.ts +++ b/src/themeDescriptions/themes/vkIOS/index.ts @@ -1,11 +1,6 @@ -import {ThemeVkIOSDescription} from '@/interfaces/themes/vkIOS'; -import {ThemeVkIOSDarkDescription} from '@/interfaces/themes/vkIOSDark'; -import { - darkColors, - darkElevation, - darkGradient, - lightTheme, -} from '@/themeDescriptions/base/vk'; +import { ThemeVkIOSDescription } from '@/interfaces/themes/vkIOS'; +import { ThemeVkIOSDarkDescription } from '@/interfaces/themes/vkIOSDark'; +import { darkColors, darkElevation, darkGradient, lightTheme } from '@/themeDescriptions/base/vk'; export const vkIOSTheme: ThemeVkIOSDescription = { ...lightTheme, diff --git a/tasks/docs/mergeTokensData.test.ts b/tasks/docs/mergeTokensData.test.ts index 6801cf2c..c00eb2a5 100644 --- a/tasks/docs/mergeTokensData.test.ts +++ b/tasks/docs/mergeTokensData.test.ts @@ -1,4 +1,4 @@ -import {mergeTokensData} from './mergeTokensData'; +import { mergeTokensData } from './mergeTokensData'; const fontFamily = 'MailSans, Helvetica, Arial, sans-serif'; @@ -146,35 +146,26 @@ const content = { describe('mergeTokensData', () => { it('should merge 2 object token with simple token value', () => { - expect( - mergeTokensData(content.simple.docs, content.simple.tokens), - ).toEqual(content.simple.result); + expect(mergeTokensData(content.simple.docs, content.simple.tokens)).toEqual( + content.simple.result, + ); }); it('should merge 2 object token with regular/compact token value', () => { - expect( - mergeTokensData( - content.regularCompact.docs, - content.regularCompact.tokens, - ), - ).toEqual(content.regularCompact.result); + expect(mergeTokensData(content.regularCompact.docs, content.regularCompact.tokens)).toEqual( + content.regularCompact.result, + ); }); it('should merge 2 object token with only regular token value', () => { - expect( - mergeTokensData( - content.onlyRegular.docs, - content.onlyRegular.tokens, - ), - ).toEqual(content.onlyRegular.result); + expect(mergeTokensData(content.onlyRegular.docs, content.onlyRegular.tokens)).toEqual( + content.onlyRegular.result, + ); }); it('should merge 2 object token with not regular/compact token value', () => { expect( - mergeTokensData( - content.notRegularCompact.docs, - content.notRegularCompact.tokens, - ), + mergeTokensData(content.notRegularCompact.docs, content.notRegularCompact.tokens), ).toEqual(content.notRegularCompact.result); }); }); diff --git a/tasks/docs/mergeTokensData.ts b/tasks/docs/mergeTokensData.ts index 25d9252d..90eb36dd 100644 --- a/tasks/docs/mergeTokensData.ts +++ b/tasks/docs/mergeTokensData.ts @@ -1,4 +1,4 @@ -import {RegularCompactObj, StrNum, Token, Tokens} from './prepareTokensData'; +import { RegularCompactObj, StrNum, Token, Tokens } from './prepareTokensData'; const isObject = (value: unknown): value is Record => Object.prototype.toString.call(value) === '[object Object]' && @@ -36,9 +36,7 @@ export function mergeTokensData( docs: Record>, tokens: Record< string, - | StrNum - | RegularCompactObj> - | Record + StrNum | RegularCompactObj> | Record >, ): Tokens { const result: Record = {}; @@ -54,10 +52,7 @@ export function mergeTokensData( value, }; - if ( - isObject(value) && - (isObject(value.regular) || isObject(value.compact)) - ) { + if (isObject(value) && (isObject(value.regular) || isObject(value.compact))) { result[docsKey].value = transformRegularCompactObj(value); } }); diff --git a/tasks/docs/prepareTokensData.ts b/tasks/docs/prepareTokensData.ts index 08d3debd..3dbd69ee 100644 --- a/tasks/docs/prepareTokensData.ts +++ b/tasks/docs/prepareTokensData.ts @@ -1,4 +1,4 @@ -import {mergeTokensData} from './mergeTokensData'; +import { mergeTokensData } from './mergeTokensData'; const path = require('path'); const fs = require('fs-extra'); @@ -26,10 +26,7 @@ type TokensData = Record; function prepareTokensData() { const ROOT_DIR = path.resolve(__dirname, '../..'); const THEMES_DIR = path.resolve(ROOT_DIR, './dist/themes'); - const RESULT_DATA_FILE = path.resolve( - ROOT_DIR, - './docs/public/static/data/tokensData.json', - ); + const RESULT_DATA_FILE = path.resolve(ROOT_DIR, './docs/public/static/data/tokensData.json'); if (fs.existsSync(RESULT_DATA_FILE)) { fs.removeSync(RESULT_DATA_FILE); @@ -37,12 +34,8 @@ function prepareTokensData() { const tokensData: TokensData = {}; fs.readdirSync(THEMES_DIR).forEach((dir) => { - const docsRaw = fs.readFileSync( - path.resolve(THEMES_DIR, `./${dir}/docs.json`), - ); - const tokensRaw = fs.readFileSync( - path.resolve(THEMES_DIR, `./${dir}/index.json`), - ); + const docsRaw = fs.readFileSync(path.resolve(THEMES_DIR, `./${dir}/docs.json`)); + const tokensRaw = fs.readFileSync(path.resolve(THEMES_DIR, `./${dir}/index.json`)); const docs = JSON.parse(docsRaw); const tokens = JSON.parse(tokensRaw); @@ -50,11 +43,7 @@ function prepareTokensData() { }); fs.createFileSync(RESULT_DATA_FILE); - fs.writeFileSync( - RESULT_DATA_FILE, - JSON.stringify(tokensData, null, ' '), - 'utf-8', - ); + fs.writeFileSync(RESULT_DATA_FILE, JSON.stringify(tokensData, null, ' '), 'utf-8'); } prepareTokensData(); diff --git a/tsconfig.json b/tsconfig.json index ee3973c5..c59e756f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,13 +15,6 @@ }, "resolveJsonModule": true }, - "include": [ - "**/*.ts" - ], - "exclude": [ - "node_modules/", - "src/themeDescriptions/", - "src/generators/", - "./index.ts" - ] + "include": ["**/*.ts"], + "exclude": ["node_modules/", "src/themeDescriptions/", "src/generators/", "./index.ts"] } diff --git a/tsconfig.publish.json b/tsconfig.publish.json index e1dda908..8e387160 100644 --- a/tsconfig.publish.json +++ b/tsconfig.publish.json @@ -10,7 +10,5 @@ "lib": ["ES6", "DOM", "ES2017"], "declaration": true }, - "include": [ - "dist/**/*.ts" - ] + "include": ["dist/**/*.ts"] } diff --git a/tsconfig.tscpaths.json b/tsconfig.tscpaths.json index 8087489d..0b63ca3d 100644 --- a/tsconfig.tscpaths.json +++ b/tsconfig.tscpaths.json @@ -12,25 +12,12 @@ "noImplicitAny": false, "noUnusedLocals": false, "jsx": "react", - "lib": [ - "dom", - "es2015", - "es2016", - "es2017", - "es2018" - ], - "typeRoots": [ - "node_modules/@types", - "src/types" - ], + "lib": ["dom", "es2015", "es2016", "es2017", "es2018"], + "typeRoots": ["node_modules/@types", "src/types"], "baseUrl": "dist", "paths": { "@/*": ["*"] } }, - "exclude": [ - "yoda", - "src/**/*stories.tsx", - "src/stories" - ] + "exclude": ["yoda", "src/**/*stories.tsx", "src/stories"] } diff --git a/yarn.lock b/yarn.lock index a1f9ee94..68103aaf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2011,6 +2011,11 @@ dependencies: svg-baker-runtime "1.4.7" +"@vkontakte/prettier-config@0.1.0": + version "0.1.0" + resolved "https://registry.yarnpkg.com/@vkontakte/prettier-config/-/prettier-config-0.1.0.tgz#4bb288d12a4a3f38cab1827bf7b94b10888773a9" + integrity sha512-Ec0V5C4IUUZm/7cxHX1AowXRdK3lBEoXXCDxZ8Ii6N3MPhYOXDfegen3ld40mmtQA1jMpJdiqpH+E8e8st/zTg== + "@vkontakte/vk-bridge@2.7.2": version "2.7.2" resolved "https://registry.yarnpkg.com/@vkontakte/vk-bridge/-/vk-bridge-2.7.2.tgz#284380d3d5f54774741e6a2e67cce9fbe62e2072" From 0ea7dab49ccbbee06bbf14789e7d06752c39e310 Mon Sep 17 00:00:00 2001 From: Daniil Suvorov Date: Thu, 12 Jan 2023 17:50:37 +0300 Subject: [PATCH 2/2] chore: add .git-blame-ignore-revs --- .git-blame-ignore-revs | 2 ++ CONTRIBUTING.md | 7 +++++++ 2 files changed, 9 insertions(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000..cd295c95 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# style: add @vkontakte/prettier-config +f756c56311383dfe6f6d32d718fa04c3f63cea7c \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 75a67e21..6df36b6c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,6 +29,13 @@ pull request одобрил кто-то из мейнтейнеров репоз `npm test -- -u` +(Необязательно) Для игнорирование коммитов в `git blame`, связанные с +изменениями стиля кода, необходимо запустить следующую команду: + +```sh +git config --local blame.ignoreRevsFile .git-blame-ignore-revs +``` + ## Версионирование В целом версионирование vkui-tokens придерживается