index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var cssParser = require('css');
  2. var extractClassesFromRules = require('./extract-classes-from-rules');
  3. var extractIdsFromRules = require('./extract-ids-from-rules');
  4. /**
  5. * Extract the class names from the selectors found
  6. * in the specified code. Class order is not guaranteed.
  7. * @param {string} code the CSS code to parse
  8. * @return {Array.<string>} the list of class names
  9. */
  10. function extractClasses(code) {
  11. var ast = cssParser.parse(code);
  12. return extractClassesFromRules(ast.stylesheet.rules);
  13. }
  14. /**
  15. * Extract the ids from the selectors found
  16. * in the specified code. Id order is not guaranteed.
  17. * @param {string} code the CSS code to parse
  18. * @return {Array.<string>} the list of ids
  19. */
  20. function extractIds(code) {
  21. var ast = cssParser.parse(code);
  22. return extractIdsFromRules(ast.stylesheet.rules);
  23. }
  24. var extractMethods = {
  25. extractClassesFromRules: extractClassesFromRules,
  26. extractIdsFromRules: extractIdsFromRules
  27. };
  28. function capitalize(string) {
  29. return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
  30. }
  31. /**
  32. * Extract the specified features from a given code
  33. * @param {string[]} features
  34. * @param {string} code
  35. * @return {Object.<string, string[]>} For each feature, a list of matches
  36. */
  37. function extract(features, code) {
  38. var ast = cssParser.parse(code);
  39. var rules = ast.stylesheet.rules;
  40. var method, methodName, feature;
  41. var result = {};
  42. var i = 0;
  43. while (!!(feature = features[i++])) {
  44. methodName = 'extract' + capitalize(feature) + 'FromRules';
  45. method = extractMethods[methodName];
  46. if (method) {
  47. result[feature] = method(rules);
  48. } else {
  49. throw new Error('Unsupported feature ' + feature);
  50. }
  51. }
  52. return result;
  53. }
  54. extract.extractClasses = extractClasses;
  55. extract.extractIds = extractIds;
  56. module.exports = extract;