Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add support for CSS variables #11

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 83 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ const Color = require('color');
* @property {"hue"|"frequency"|null} sort
*/

/**
* @typedef {Record<string, string>} Variables
*/

/**
* @typedef {Record<string, Variables>} SelectorVariables
*/

function CssColorExtractor() {
const propertiesWithColors = [
'color',
Expand Down Expand Up @@ -158,12 +166,36 @@ function CssColorExtractor() {
return [...new Set(items)];
}

/**
* @param {postcss.Root} root
* @returns {SelectorVariables}
*/
function extractVariables(root) {
/** @type {SelectorVariables} */
const selectorVariables = {};

root.walkDecls(function(decl) {
// @ts-ignore
Copy link
Contributor

Choose a reason for hiding this comment

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

Why ts-ignore is here? Can't we do it some other way?

const selector = /** @type {string|undefined} */ (decl.parent?.selector);

if (selector && decl.prop.startsWith('--')) {
selectorVariables[selector] = {
...(selectorVariables[selector] || {}),
[decl.prop]: decl.value,
};
}
});

return selectorVariables;
}

/**
* @param {string} string
* @param {Partial<Options>} options
* @param {Variables|undefined} variables
* @returns {string[]}
*/
function extractColorsFromString(string, options) {
function extractColorsFromString(string, options, variables = undefined) {
/** @type {string[]} */
let colors = [];

Expand Down Expand Up @@ -196,6 +228,24 @@ function CssColorExtractor() {
});
});

if (variables) {
// use the variable's value if this color is a CSS variable
colors = colors
.map((value) => {
const isVariable = value.match(/^var\((--.*?)\)$/);

if (isVariable) {
const variable = isVariable[1];

if (variables[variable]) {
return variables[variable];
}
}

return value;
});
}

return colors.filter((value) => {
let color;

Expand Down Expand Up @@ -229,14 +279,32 @@ function CssColorExtractor() {
/**
* @param {postcss.Declaration} decl
* @param {Partial<Options>} options
* @param {SelectorVariables|undefined} selectorVariables
* @returns {string[]}
*/
function extractColorsFromDecl(decl, options) {
function extractColorsFromDecl(decl, options, selectorVariables = undefined) {
if (!doesPropertyAllowColor(decl.prop)) {
return [];
}

return extractColorsFromString(decl.value, options);
// @ts-ignore
const selector = /** @type {string|undefined} */ (decl.parent?.selector);

/** @type {Variables|undefined} */
let variables;

if (selectorVariables) {
variables = {
...(selectorVariables[':root'] || {}),
...(selector && selectorVariables[selector] ? selectorVariables[selector] : {}),
};
}

return extractColorsFromString(
decl.value,
options,
variables,
);
}

/**
Expand All @@ -247,21 +315,27 @@ function CssColorExtractor() {
function extractColorsFromCss(css, options) {
let colors = [];

postcss.parse(css).walkDecls(function(decl) {
colors = colors.concat(extractColorsFromDecl(decl, options));
const root = postcss.parse(css);

const selectorVariables = extractVariables(root);

root.walkDecls(function(decl) {
colors = colors.concat(extractColorsFromDecl(decl, options, selectorVariables));
});

return colors;
}

/** @type {(decl: postcss.Declaration, options: Partial<Options>) => string[]} */
this.fromDecl = (decl, options) => sortColors(extractColorsFromDecl(decl, options), options);
this.extractVariables = extractVariables;

/** @type {(decl: postcss.Declaration, options: Partial<Options>, selectorVariables?: SelectorVariables) => string[]} */
this.fromDecl = (decl, options, selectorVariables) => sortColors(extractColorsFromDecl(decl, options, selectorVariables), options);

/** @type {(css: string, options: Partial<Options>) => string[]} */
this.fromCss = (css, options) => sortColors(extractColorsFromCss(css, options), options);

/** @type {(string: string, options: Partial<Options>) => string[]} */
this.fromString = (string, options) => sortColors(extractColorsFromString(string, options), options);
/** @type {(string: string, options: Partial<Options>, variables?: Variables) => string[]} */
this.fromString = (string, options, variables) => sortColors(extractColorsFromString(string, options, variables), options);
}

module.exports = new CssColorExtractor();
18 changes: 18 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -693,4 +693,22 @@ describe('postcss-colors-only', function() {
done,
);
});

it('should read :root color variables', function(done) {
Copy link
Contributor

Choose a reason for hiding this comment

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

As i see this won't work if we gave variables in body. Example test that doesn't work:

  it('should read body color variables', function(done) {
    test(
      'body { --test-color: #0000FF; } p { color: var(--test-color); }',
      ['#0000FF'],
      null,
      done,
    );
  });

test(
':root { --test-color: #0000FF; } p { color: var(--test-color); }',
['#0000FF'],
null,
done,
);
});

it('should read color variables in the same scope', function(done) {
test(
'p { --test-color: #0000FF; color: var(--test-color); }',
['#0000FF'],
null,
done,
);
});
});