Skip to content

Instantly share code, notes, and snippets.

@rushkeldon
Created May 21, 2024 15:14
Show Gist options
  • Save rushkeldon/50d8b366f75ea0103e7bef63d4b738fa to your computer and use it in GitHub Desktop.
Save rushkeldon/50d8b366f75ea0103e7bef63d4b738fa to your computer and use it in GitHub Desktop.
CSS Glean

GleanCSS

A utility to extract and pretty-print specific CSS classes which contain rules for properties which match the propsToGlean array members.

Table of Contents

Installation

Include the following code snippet in your React component where you want to run the CSS gleaning:

useEffect(() => {
  const propsToGlean = [
    'font',
    'text',
    'letter',
    'white-space',
    'line-height',
  ];

  function gleanCSS() {
    const stylesheets = Array.from(document.styleSheets);
    const classRules = {};

    for (const stylesheet of stylesheets) {
      try {
        for (const rule of stylesheet.cssRules) {
          if (rule instanceof CSSStyleRule) {
            const [selector, rules] = rule.cssText.split('{');
            const cleanedRules = rules.replace('}', '').trim();
            const propertiesArray = cleanedRules.split(';').filter(Boolean);
            for (const property of propertiesArray) {
              const [propertyName, propertyValue] = property.split(':');
              for (const prop of propsToGlean) {
                if (propertyName.trim().includes(prop)) {
                  classRules[rule.selectorText] = prettyPrintCss(rule.cssText);
                }
              }
            }
          }
        }
      } catch (e) {
        console.log('gleanCSS error', e);
      }
    }
    logReport(classRules);
  }

  function prettyPrintCss(cssRule) {
    const [selector, properties] = cssRule.split('{');
    const propertiesArray = properties.replace('}', '').split(';');
    const formattedProperties = propertiesArray
      .filter((property) => property.trim() !== '') // filter out empty strings
      .map((property) => `  ${property.trim()};`)
      .join('\n');
    return `${selector.trim()} {\n${formattedProperties}\n}\n`;
  }

  function logReport(report) {
    let str = '/* CSS Gleaned */\n\n';
    for (const cssClass in report) {
      str += report[cssClass];
    }
    console.log(str);
  }
  gleanCSS();
}, []);

Usage

  1. Add the above code to a React component within a useEffect hook to run the CSS gleaning process when the component mounts.
  2. Modify the propsToGlean array to specify which CSS properties you want to extract.
  3. The script will log the gleaned CSS rules to the console in a pretty-printed format.

Properties to Glean

The propsToGlean array specifies which CSS properties to extract. By default, it includes:

  • font
  • text
  • letter
  • white-space
  • line-height

You can customize this array to include any properties you need.

Functions

gleanCSS

This function iterates through all stylesheets and their rules in the document, extracting rules that contain the specified properties.

prettyPrintCss

Formats the CSS rule into a readable string with proper indentation and newlines.

logReport

Logs the gleaned CSS rules to the console in a pretty-printed format.

Example Output

When executed, the script will log something like the following to the console:

/* CSS Gleaned */

.className {
  font-size: 16px;
  line-height: 1.5;
}

.anotherClass {
  text-align: center;
  white-space: nowrap;
}

This output helps you see all the CSS rules containing the specified properties in a neat and organized manner.

useEffect(() => {
const propsToGlean = [
'font',
'text',
'letter',
'white-space',
'line-height',
];
function gleanCSS() {
const stylesheets = Array.from(document.styleSheets);
const classRules = {};
for (const stylesheet of stylesheets) {
try {
for (const rule of stylesheet.cssRules) {
if (rule instanceof CSSStyleRule) {
const [selector, rules] = rule.cssText.split('{');
const cleanedRules = rules.replace('}', '').trim();
const propertiesArray = cleanedRules.split(';').filter(Boolean);
for (const property of propertiesArray) {
const [propertyName, propertyValue] = property.split(':');
for (const prop of propsToGlean) {
if (propertyName.trim().includes(prop)) {
classRules[rule.selectorText] = prettyPrintCss(
rule.cssText
);
}
}
}
}
}
} catch (e) {
console.log('gleanCSS error', e);
}
}
logReport(classRules);
}
function prettyPrintCss(cssRule) {
const [selector, properties] = cssRule.split('{');
const propertiesArray = properties.replace('}', '').split(';');
const formattedProperties = propertiesArray
.filter((property) => property.trim() !== '') // filter out empty strings
.map((property) => ` ${property.trim()};`)
.join('\n');
return `${selector.trim()} {\n${formattedProperties}\n}\n`;
}
function logReport(report) {
let str = '/* CSS Gleaned */\n\n';
for (const cssClass in report) {
str += report[cssClass];
}
console.log(str);
}
gleanCSS();
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment