-
Notifications
You must be signed in to change notification settings - Fork 7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Добавлен кастомный postcss плагин postcss-global-data #287
Merged
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
fb3b80d
feat(postcss): add custom postcss plugin - postcss-global-data
d3234ee
feat(*): remove postcss-global-data and add custom postcss-global-var…
b9bdd8a
feat(*): remove console.log
10fc6dd
feat(*): fix parse css variable and override css plugin creators
834daed
Update quick-starfishes-taste.md
VladislavNsk 53896eb
feat(*): add rootRule in rulesSelectors
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
--- | ||
'arui-scripts': minor | ||
--- | ||
|
||
Добавлен кастомный плагин postcss-global-variables, для оптимизации времени обработки глобальных переменных. | ||
@csstools/postcss-global-data *удален* | ||
|
||
Проекты, которые использовали в оверрайдах кастомные настройки для плагина @csstools/postcss-global-data, должны перейти на использование postcss-global-variables следующим образом | ||
``` | ||
postcss: (config) => { | ||
const overrideConfig = config.map((plugin) => { | ||
if (plugin.name === 'postCssGlobalVariables') { | ||
return { | ||
...plugin, | ||
options: plugin.options.concat([ | ||
// ваши файлы | ||
]) | ||
} | ||
} | ||
return plugin; | ||
}); | ||
|
||
return overrideConfig; | ||
} | ||
``` | ||
Плагин работает только с глобальными переменными, если вам надо вставить что-то другое, отличное от глобальных переменных, вам нужно будет добавить @csstools/postcss-global-data в свой проект самостоятельно |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
52 changes: 52 additions & 0 deletions
52
packages/arui-scripts/src/plugins/postcss-global-variables/postcss-global-variables.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import type { AtRule, Plugin, PluginCreator, Rule } from 'postcss'; | ||
|
||
import { insertParsedCss, parseImport, parseMediaQuery, parseVariables } from './utils/utils'; | ||
|
||
type PluginOptions = { | ||
files?: string[]; | ||
}; | ||
|
||
const postCssGlobalVariables: PluginCreator<PluginOptions> = (opts?: PluginOptions) => { | ||
const options = { | ||
files: [], | ||
...opts, | ||
}; | ||
|
||
const parsedVariables: Record<string, string> = {}; | ||
const parsedCustomMedia: Record<string, AtRule> = {}; | ||
|
||
let rulesSelectors = new Set<Rule>(); | ||
|
||
return { | ||
postcssPlugin: '@alfalab/postcss-global-variables', | ||
prepare(): Plugin { | ||
return { | ||
postcssPlugin: '@alfalab/postcss-global-variables', | ||
Once(root, postcssHelpers): void { | ||
if (!Object.keys(parsedVariables).length) { | ||
options.files.forEach((filePath) => { | ||
const importedCss = parseImport(root, postcssHelpers, filePath); | ||
|
||
parseVariables(importedCss, parsedVariables); | ||
parseMediaQuery(importedCss, parsedCustomMedia); | ||
}); | ||
} | ||
|
||
const rootRule = insertParsedCss(root, parsedVariables, parsedCustomMedia); | ||
|
||
root.append(rootRule); | ||
heymdall-legal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}, | ||
OnceExit(): void { | ||
rulesSelectors.forEach((rule) => { | ||
rule.remove(); | ||
}); | ||
rulesSelectors = new Set<Rule>(); | ||
}, | ||
}; | ||
}, | ||
}; | ||
}; | ||
|
||
postCssGlobalVariables.postcss = true; | ||
|
||
export { postCssGlobalVariables }; |
69 changes: 69 additions & 0 deletions
69
...scripts/src/plugins/postcss-global-variables/utils/__tests__/add-global-variable.tests.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import { Rule } from 'postcss'; | ||
|
||
import { addGlobalVariable } from '../utils'; | ||
|
||
describe('addGlobalVariable', () => { | ||
it('Должен добавлять переменные, найденные в cssValue, в rootSelector', () => { | ||
const mockRootSelector = new Rule({ selector: ':root' }); | ||
const parsedVariables = { | ||
'--color-primary': '#ff0000', | ||
}; | ||
|
||
addGlobalVariable('var(--color-primary)', mockRootSelector, parsedVariables); | ||
|
||
expect(mockRootSelector.nodes).toMatchObject([ | ||
{ prop: '--color-primary', value: '#ff0000' } | ||
]); | ||
}); | ||
|
||
it('Должен рекурсивно добавлять вложенные переменные', () => { | ||
const mockRootSelector = new Rule({ selector: ':root' }); | ||
const mockRootSelectorWithSpace = new Rule({ selector: ':root' }); | ||
const mockRootSelectorWithNewLine = new Rule({ selector: ':root' }); | ||
|
||
const parsedVariables = { | ||
'--color-primary': 'var(--color-secondary)', | ||
'--color-secondary': '#00ff00', | ||
}; | ||
|
||
const parsedVariablesWithSpace = { | ||
'--color-primary': 'var( --color-secondary )', | ||
'--color-secondary': '#00ff00', | ||
}; | ||
|
||
const parsedVariablesWithNewLine = { | ||
'--color-primary': 'var(\n --color-secondary\n )', | ||
'--color-secondary': '#00ff00', | ||
}; | ||
|
||
addGlobalVariable('var(--color-primary)', mockRootSelector, parsedVariables); | ||
addGlobalVariable('var(--color-primary)', mockRootSelectorWithSpace, parsedVariablesWithSpace); | ||
addGlobalVariable('var(--color-primary)', mockRootSelectorWithNewLine, parsedVariablesWithNewLine); | ||
|
||
expect(mockRootSelector.nodes).toMatchObject([ | ||
{ prop: '--color-primary', value: 'var(--color-secondary)' }, | ||
{ prop: '--color-secondary', value: '#00ff00' }, | ||
]); | ||
|
||
expect(mockRootSelectorWithSpace.nodes).toMatchObject([ | ||
{ prop: '--color-primary', value: 'var( --color-secondary )' }, | ||
{ prop: '--color-secondary', value: '#00ff00' }, | ||
]); | ||
|
||
expect(mockRootSelectorWithNewLine.nodes).toMatchObject([ | ||
{ prop: '--color-primary', value: 'var(\n --color-secondary\n )' }, | ||
{ prop: '--color-secondary', value: '#00ff00' }, | ||
]); | ||
}); | ||
|
||
it('Не должен добавлять переменные, если их нет в parsedVariables', () => { | ||
const mockRootSelector = new Rule({ selector: ':root' }); | ||
const parsedVariables = { | ||
'color-primary': '#ff0000', | ||
}; | ||
|
||
addGlobalVariable('var(--color-secondary)', mockRootSelector, parsedVariables); | ||
|
||
expect(mockRootSelector.nodes).toEqual([]); | ||
}); | ||
}); |
17 changes: 17 additions & 0 deletions
17
...cripts/src/plugins/postcss-global-variables/utils/__tests__/get-media-query-name.tests.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import type { AtRule } from 'postcss'; | ||
|
||
import { getMediaQueryName, } from '../utils'; | ||
|
||
describe('getMediaQueryName', () => { | ||
it('Должен возвращать имя медиа-запроса', () => { | ||
const rule: AtRule = { params: 'screen and (min-width: 768px)' } as AtRule; | ||
|
||
expect(getMediaQueryName(rule)).toBe('screen'); | ||
}); | ||
|
||
it('Должен возвращать пустую строку, если params пустой', () => { | ||
const rule: AtRule = { params: '' } as AtRule; | ||
|
||
expect(getMediaQueryName(rule)).toBe(''); | ||
}); | ||
}); |
29 changes: 29 additions & 0 deletions
29
...rui-scripts/src/plugins/postcss-global-variables/utils/__tests__/parse-variables.tests.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import type { Declaration,Root } from 'postcss'; | ||
|
||
import { parseVariables } from '../utils'; | ||
|
||
describe('parseVariables', () => { | ||
it('Должен корректно заполнять объект переменными на основе импортируемого файла', () => { | ||
const parsedVariables: Record<string, string> = {}; | ||
|
||
const mockImportedFile = { | ||
walkDecls: (callback: (decl: Declaration, index: number) => false | void) => { | ||
const mockDeclarations: Declaration[] = [ | ||
{ prop: '--color-primary', value: '#3498db' } as Declaration, | ||
{ prop: '--font-size', value: 'var(--gap-24)' } as Declaration, | ||
]; | ||
|
||
mockDeclarations.forEach(callback); | ||
|
||
return false; | ||
} | ||
}; | ||
|
||
parseVariables(mockImportedFile as Root, parsedVariables); | ||
|
||
expect(parsedVariables).toEqual({ | ||
'--color-primary': '#3498db', | ||
'--font-size': 'var(--gap-24)', | ||
}); | ||
}); | ||
}); |
83 changes: 83 additions & 0 deletions
83
packages/arui-scripts/src/plugins/postcss-global-variables/utils/utils.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
import fs from 'fs'; | ||
import path from 'path'; | ||
|
||
import { AtRule, Declaration, Helpers, Root, Rule } from 'postcss'; | ||
|
||
export const getMediaQueryName = (rule: AtRule) => rule.params.split(' ')[0]; | ||
|
||
export function parseImport(root: Root, postcssHelpers: Helpers, filePath: string) { | ||
let resolvedPath = ''; | ||
|
||
try { | ||
resolvedPath = path.resolve(filePath); | ||
} catch (err) { | ||
throw new Error(`Failed to read ${filePath} with error ${(err instanceof Error) ? err.message : err}`); | ||
} | ||
|
||
postcssHelpers.result.messages.push({ | ||
type: 'dependency', | ||
plugin: 'postcss-global-environments', | ||
file: resolvedPath, | ||
parent: root.source?.input?.file, | ||
}); | ||
|
||
const fileContents = fs.readFileSync(resolvedPath, 'utf8'); | ||
heymdall-legal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
return postcssHelpers.postcss.parse(fileContents, { from: resolvedPath }); | ||
} | ||
|
||
export const parseVariables = (importedFile: Root, parsedVariables: Record<string, string>) => { | ||
importedFile.walkDecls((decl) => { | ||
// eslint-disable-next-line no-param-reassign | ||
parsedVariables[decl.prop] = decl.value; | ||
}); | ||
}; | ||
|
||
export const parseMediaQuery = (importedFile: Root, parsedCustomMedia: Record<string, AtRule>) => { | ||
importedFile.walkAtRules('custom-media', (mediaRule) => { | ||
const mediaName = getMediaQueryName(mediaRule); | ||
|
||
// eslint-disable-next-line no-param-reassign | ||
parsedCustomMedia[mediaName] = mediaRule; | ||
}); | ||
}; | ||
|
||
export function addGlobalVariable(cssValue: string, rootSelector: Rule, parsedVariables: Record<string, string>) { | ||
const variableMatches = cssValue.match(/var\(\s*--([^)]+)\s*\)/g); | ||
|
||
if (variableMatches) { | ||
variableMatches.forEach((match) => { | ||
// var(--gap-24) => --gap-24 | ||
heymdall-legal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const variableName = match.slice(4, -1).trim(); | ||
|
||
if (parsedVariables[variableName]) { | ||
rootSelector.append(new Declaration({ prop: variableName, value: parsedVariables[variableName] })); | ||
|
||
// Рекурсивно проходимся по значениям css, там тоже могут использоваться переменные | ||
addGlobalVariable(parsedVariables[variableName], rootSelector, parsedVariables); | ||
} | ||
}); | ||
} | ||
} | ||
|
||
export const insertParsedCss = (root: Root, parsedVariables: Record<string, string>, parsedCustomMedia: Record<string, AtRule>): Rule => { | ||
const rootRule = new Rule({ selector: ':root' }); | ||
|
||
root.walkDecls((decl) => { | ||
addGlobalVariable(decl.value, rootRule, parsedVariables); | ||
}); | ||
|
||
root.walkAtRules('media', (rule) => { | ||
const mediaFullName = getMediaQueryName(rule); | ||
|
||
if (mediaFullName.startsWith('(--')) { | ||
const mediaName = mediaFullName.slice(1, -1); | ||
|
||
if (parsedCustomMedia[mediaName]) { | ||
root.append(parsedCustomMedia[mediaName]); | ||
} | ||
} | ||
}); | ||
|
||
return rootRule; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
К сожалению часть команд завязалась на старое название плагина, плюс они хотят передавать кастомные настройки в него. Пример можно получить поискав по гиту название плагина.
Предлагаю такой вариант:
в функции createPostcssConfig инициализировать все плагины по старому, если же pluginName === '@csstools/postcss-global-data' - использовать кастомный плагин.
На сколько помню можно передавать вместо массива [плагин, опции] сразу инициализированный плагин
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ок, поправлю
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если это сделать в createPostcssConfig, то проектам придется все равно делать изменения, тк например такая проверка уже будет не валидна в файле
arui-scripts.overrides.ts
if (Array.isArray(plugin) && plugin[0] === '@csstools/postcss-global-data')
тк вместо массива, будет функция создания плагина или объект, если инициализовать на месте плагин
Может лучше сделать это сразу после applyOverrides? Тогда уже будет применен конфиг из проекта и можно заменять на кастомный с использованием переданных новых файлов
Сделал это в последнем комите
Если есть другие мысли или я не так понял, поправлю)