css.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. /**
  2. * Copyright 2018 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. import { parse, stringify } from 'postcss';
  17. /**
  18. * Parse a textual CSS Stylesheet into a Stylesheet instance.
  19. * Stylesheet is a mutable postcss AST with format similar to CSSOM.
  20. * @see https://github.com/postcss/postcss/
  21. * @private
  22. * @param {String} stylesheet
  23. * @returns {css.Stylesheet} ast
  24. */
  25. export function parseStylesheet(stylesheet) {
  26. return parse(stylesheet);
  27. }
  28. /**
  29. * Serialize a postcss Stylesheet to a String of CSS.
  30. * @private
  31. * @param {css.Stylesheet} ast A Stylesheet to serialize, such as one returned from `parseStylesheet()`
  32. * @param {Object} options Options used by the stringify logic
  33. * @param {Boolean} [options.compress] Compress CSS output (removes comments, whitespace, etc)
  34. */
  35. export function serializeStylesheet(ast, options) {
  36. let cssStr = '';
  37. stringify(ast, (result, node, type) => {
  38. if (!options.compress) {
  39. cssStr += result;
  40. return;
  41. }
  42. // Simple minification logic
  43. if (node?.type === 'comment') return;
  44. if (node?.type === 'decl') {
  45. const prefix = node.prop + node.raws.between;
  46. cssStr += result.replace(prefix, prefix.trim());
  47. return;
  48. }
  49. if (type === 'start') {
  50. if (node.type === 'rule' && node.selectors) {
  51. cssStr += node.selectors.join(',') + '{';
  52. } else {
  53. cssStr += result.replace(/\s\{$/, '{');
  54. }
  55. return;
  56. }
  57. if (type === 'end' && result === '}' && node?.raws?.semicolon) {
  58. cssStr = cssStr.slice(0, -1);
  59. }
  60. cssStr += result.trim();
  61. });
  62. return cssStr;
  63. }
  64. /**
  65. * Converts a walkStyleRules() iterator to mark nodes with `.$$remove=true` instead of actually removing them.
  66. * This means they can be removed in a second pass, allowing the first pass to be nondestructive (eg: to preserve mirrored sheets).
  67. * @private
  68. * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node.
  69. * @returns {(rule) => void} nonDestructiveIterator
  70. */
  71. export function markOnly(predicate) {
  72. return (rule) => {
  73. const sel = rule.selectors;
  74. if (predicate(rule) === false) {
  75. rule.$$remove = true;
  76. }
  77. rule.$$markedSelectors = rule.selectors;
  78. if (rule._other) {
  79. rule._other.$$markedSelectors = rule._other.selectors;
  80. }
  81. rule.selectors = sel;
  82. };
  83. }
  84. /**
  85. * Apply filtered selectors to a rule from a previous markOnly run.
  86. * @private
  87. * @param {css.Rule} rule The Rule to apply marked selectors to (if they exist).
  88. */
  89. export function applyMarkedSelectors(rule) {
  90. if (rule.$$markedSelectors) {
  91. rule.selectors = rule.$$markedSelectors;
  92. }
  93. if (rule._other) {
  94. applyMarkedSelectors(rule._other);
  95. }
  96. }
  97. /**
  98. * Recursively walk all rules in a stylesheet.
  99. * @private
  100. * @param {css.Rule} node A Stylesheet or Rule to descend into.
  101. * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node.
  102. */
  103. export function walkStyleRules(node, iterator) {
  104. node.nodes = node.nodes.filter((rule) => {
  105. if (hasNestedRules(rule)) {
  106. walkStyleRules(rule, iterator);
  107. }
  108. rule._other = undefined;
  109. rule.filterSelectors = filterSelectors;
  110. return iterator(rule) !== false;
  111. });
  112. }
  113. /**
  114. * Recursively walk all rules in two identical stylesheets, filtering nodes into one or the other based on a predicate.
  115. * @private
  116. * @param {css.Rule} node A Stylesheet or Rule to descend into.
  117. * @param {css.Rule} node2 A second tree identical to `node`
  118. * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node from the first tree, true to remove it from the second.
  119. */
  120. export function walkStyleRulesWithReverseMirror(node, node2, iterator) {
  121. if (node2 === null) return walkStyleRules(node, iterator);
  122. [node.nodes, node2.nodes] = splitFilter(
  123. node.nodes,
  124. node2.nodes,
  125. (rule, index, rules, rules2) => {
  126. const rule2 = rules2[index];
  127. if (hasNestedRules(rule)) {
  128. walkStyleRulesWithReverseMirror(rule, rule2, iterator);
  129. }
  130. rule._other = rule2;
  131. rule.filterSelectors = filterSelectors;
  132. return iterator(rule) !== false;
  133. }
  134. );
  135. }
  136. // Checks if a node has nested rules, like @media
  137. // @keyframes are an exception since they are evaluated as a whole
  138. function hasNestedRules(rule) {
  139. return (
  140. rule.nodes &&
  141. rule.nodes.length &&
  142. rule.nodes.some((n) => n.type === 'rule' || n.type === 'atrule') &&
  143. rule.name !== 'keyframes' &&
  144. rule.name !== '-webkit-keyframes'
  145. );
  146. }
  147. // Like [].filter(), but applies the opposite filtering result to a second copy of the Array without a second pass.
  148. // This is just a quicker version of generating the compliment of the set returned from a filter operation.
  149. function splitFilter(a, b, predicate) {
  150. const aOut = [];
  151. const bOut = [];
  152. for (let index = 0; index < a.length; index++) {
  153. if (predicate(a[index], index, a, b)) {
  154. aOut.push(a[index]);
  155. } else {
  156. bOut.push(a[index]);
  157. }
  158. }
  159. return [aOut, bOut];
  160. }
  161. // can be invoked on a style rule to subset its selectors (with reverse mirroring)
  162. function filterSelectors(predicate) {
  163. if (this._other) {
  164. const [a, b] = splitFilter(
  165. this.selectors,
  166. this._other.selectors,
  167. predicate
  168. );
  169. this.selectors = a;
  170. this._other.selectors = b;
  171. } else {
  172. this.selectors = this.selectors.filter(predicate);
  173. }
  174. }