list-content-styles.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env node
  2. /**
  3. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  4. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  5. */
  6. /* eslint-env node */
  7. const postcss = require( 'postcss' );
  8. module.exports = postcss.plugin( 'list-content-styles', function( options ) {
  9. const selectorStyles = options.contentRules.selector;
  10. const variables = options.contentRules.variables;
  11. return root => {
  12. root.walkRules( rule => {
  13. for ( const selector of rule.selectors ) {
  14. const data = {
  15. file: root.source.input.file,
  16. css: rule.toString()
  17. };
  18. if ( selector.match( ':root' ) ) {
  19. addDefinition( variables, data );
  20. }
  21. if ( selector.match( '.ck-content' ) ) {
  22. if ( rule.parent.name && rule.parent.params ) {
  23. const atRule = getAtRuleArray( options.contentRules.atRules, rule.parent.name, rule.parent.params );
  24. addDefinition( atRule, data );
  25. } else {
  26. addDefinition( selectorStyles, data );
  27. }
  28. }
  29. }
  30. } );
  31. };
  32. } );
  33. /**
  34. * @param {Object} collection
  35. * @param {String} name Name of an `at-rule`.
  36. * @param {String} params Parameters that describes the `at-rule`.
  37. * @returns {Array}
  38. */
  39. function getAtRuleArray( collection, name, params ) {
  40. const definition = `${ name } ${ params }`;
  41. if ( !collection[ definition ] ) {
  42. collection[ definition ] = [];
  43. }
  44. return collection[ definition ];
  45. }
  46. /**
  47. * Checks whether specified definition is duplicated in the colletion.
  48. *
  49. * @param {Array.<StyleStructure>} collection
  50. * @param {StyleStructure} def
  51. * @returns {Boolean}
  52. */
  53. function isDuplicatedDefinition( collection, def ) {
  54. for ( const item of collection ) {
  55. if ( item.file === def.file && item.css === def.css ) {
  56. return true;
  57. }
  58. }
  59. return false;
  60. }
  61. /**
  62. * Adds definition to the collection if it does not exist in the collection.
  63. *
  64. * @param {Array.<StyleStructure>} collection
  65. * @param {StyleStructure} def
  66. */
  67. function addDefinition( collection, def ) {
  68. if ( !isDuplicatedDefinition( collection, def ) ) {
  69. collection.push( def );
  70. }
  71. }
  72. /**
  73. * @typedef {Object} StyleStructure
  74. * @property {String} file An absolute path to the file where a definition is defined.
  75. * @property {String} css Definition.
  76. */