You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

364 lines
11 KiB

4 years ago
  1. var postcss = require('postcss');
  2. var Tokenizer = require('css-selector-tokenizer');
  3. function normalizeNodeArray(nodes) {
  4. var array = [];
  5. nodes.forEach(function(x) {
  6. if(Array.isArray(x)) {
  7. normalizeNodeArray(x).forEach(function(item) {
  8. array.push(item);
  9. });
  10. } else if(x) {
  11. array.push(x);
  12. }
  13. });
  14. if(array.length > 0 && array[array.length - 1].type === 'spacing') {
  15. array.pop();
  16. }
  17. return array;
  18. }
  19. function localizeNode(node, context) {
  20. if(context.ignoreNextSpacing && node.type !== 'spacing') {
  21. throw new Error('Missing whitespace after :' + context.ignoreNextSpacing);
  22. }
  23. if(context.enforceNoSpacing && node.type === 'spacing') {
  24. throw new Error('Missing whitespace before :' + context.enforceNoSpacing);
  25. }
  26. var newNodes;
  27. switch(node.type) {
  28. case 'selectors':
  29. var resultingGlobal;
  30. context.hasPureGlobals = false;
  31. newNodes = node.nodes.map(function(n) {
  32. var nContext = {
  33. global: context.global,
  34. lastWasSpacing: true,
  35. hasLocals: false,
  36. explicit: false
  37. };
  38. n = localizeNode(n, nContext);
  39. if(typeof resultingGlobal === 'undefined') {
  40. resultingGlobal = nContext.global;
  41. } else if(resultingGlobal !== nContext.global) {
  42. throw new Error('Inconsistent rule global/local result in rule "' +
  43. Tokenizer.stringify(node) + '" (multiple selectors must result in the same mode for the rule)');
  44. }
  45. if(!nContext.hasLocals) {
  46. context.hasPureGlobals = true;
  47. }
  48. return n;
  49. });
  50. context.global = resultingGlobal;
  51. node = Object.create(node);
  52. node.nodes = normalizeNodeArray(newNodes);
  53. break;
  54. case 'selector':
  55. newNodes = node.nodes.map(function(n) {
  56. return localizeNode(n, context);
  57. });
  58. node = Object.create(node);
  59. node.nodes = normalizeNodeArray(newNodes);
  60. break;
  61. case 'spacing':
  62. if(context.ignoreNextSpacing) {
  63. context.ignoreNextSpacing = false;
  64. context.lastWasSpacing = false;
  65. context.enforceNoSpacing = false;
  66. return null;
  67. }
  68. context.lastWasSpacing = true;
  69. return node;
  70. case 'pseudo-class':
  71. if(node.name === 'local' || node.name === 'global') {
  72. if(context.inside) {
  73. throw new Error('A :' + node.name + ' is not allowed inside of a :' + context.inside + '(...)');
  74. }
  75. context.ignoreNextSpacing = context.lastWasSpacing ? node.name : false;
  76. context.enforceNoSpacing = context.lastWasSpacing ? false : node.name;
  77. context.global = (node.name === 'global');
  78. context.explicit = true;
  79. return null;
  80. }
  81. break;
  82. case 'nested-pseudo-class':
  83. var subContext;
  84. if(node.name === 'local' || node.name === 'global') {
  85. if(context.inside) {
  86. throw new Error('A :' + node.name + '(...) is not allowed inside of a :' + context.inside + '(...)');
  87. }
  88. subContext = {
  89. global: (node.name === 'global'),
  90. inside: node.name,
  91. hasLocals: false,
  92. explicit: true
  93. };
  94. node = node.nodes.map(function(n) {
  95. return localizeNode(n, subContext);
  96. });
  97. // don't leak spacing
  98. node[0].before = undefined;
  99. node[node.length - 1].after = undefined;
  100. } else {
  101. subContext = {
  102. global: context.global,
  103. inside: context.inside,
  104. lastWasSpacing: true,
  105. hasLocals: false,
  106. explicit: context.explicit
  107. };
  108. newNodes = node.nodes.map(function(n) {
  109. return localizeNode(n, subContext);
  110. });
  111. node = Object.create(node);
  112. node.nodes = normalizeNodeArray(newNodes);
  113. }
  114. if(subContext.hasLocals) {
  115. context.hasLocals = true;
  116. }
  117. break;
  118. case 'id':
  119. case 'class':
  120. if(!context.global) {
  121. node = {
  122. type: 'nested-pseudo-class',
  123. name: 'local',
  124. nodes: [node]
  125. };
  126. context.hasLocals = true;
  127. }
  128. break;
  129. }
  130. // reset context
  131. context.lastWasSpacing = false;
  132. context.ignoreNextSpacing = false;
  133. context.enforceNoSpacing = false;
  134. return node;
  135. }
  136. function localizeDeclNode(node, context) {
  137. var newNode;
  138. switch(node.type) {
  139. case 'item':
  140. if(context.localizeNextItem) {
  141. newNode = Object.create(node);
  142. newNode.name = ':local(' + newNode.name + ')';
  143. context.localizeNextItem = false;
  144. return newNode;
  145. }
  146. break;
  147. case 'nested-item':
  148. var newNodes = node.nodes.map(function(n) {
  149. return localizeDeclValue(n, context);
  150. });
  151. node = Object.create(node);
  152. node.nodes = newNodes;
  153. break;
  154. case 'url':
  155. if(context.options && context.options.rewriteUrl) {
  156. newNode = Object.create(node);
  157. newNode.url = context.options.rewriteUrl(context.global, node.url);
  158. return newNode;
  159. }
  160. break;
  161. }
  162. return node;
  163. }
  164. function localizeDeclValue(valueNode, context) {
  165. var newValueNode = Object.create(valueNode);
  166. newValueNode.nodes = valueNode.nodes.map(function(node) {
  167. return localizeDeclNode(node, context);
  168. });
  169. return newValueNode;
  170. }
  171. function localizeAnimationShorthandDeclValueNodes(nodes, context) {
  172. var validIdent = validIdent = /^-?[_a-z][_a-z0-9-]*$/i;
  173. /*
  174. The spec defines some keywords that you can use to describe properties such as the timing
  175. function. These are still valid animation names, so as long as there is a property that accepts
  176. a keyword, it is given priority. Only when all the properties that can take a keyword are
  177. exhausted can the animation name be set to the keyword. I.e.
  178. animation: infinite infinite;
  179. The animation will repeat an infinite number of times from the first argument, and will have an
  180. animation name of infinite from the second.
  181. */
  182. var animationKeywords = {
  183. '$alternate': 1,
  184. '$alternate-reverse': 1,
  185. '$backwards': 1,
  186. '$both': 1,
  187. '$ease': 1,
  188. '$ease-in': 1,
  189. '$ease-in-out': 1,
  190. '$ease-out': 1,
  191. '$forwards': 1,
  192. '$infinite': 1,
  193. '$linear': 1,
  194. '$none': Infinity, // No matter how many times you write none, it will never be an animation name
  195. '$normal': 1,
  196. '$paused': 1,
  197. '$reverse': 1,
  198. '$running': 1,
  199. '$step-end': 1,
  200. '$step-start': 1,
  201. '$initial': Infinity,
  202. '$inherit': Infinity,
  203. '$unset': Infinity,
  204. };
  205. var didParseAnimationName = false;
  206. var parsedAnimationKeywords = {};
  207. return nodes.map(function(valueNode) {
  208. var value = valueNode.type === 'item'
  209. ? valueNode.name.toLowerCase()
  210. : null;
  211. var shouldParseAnimationName = false;
  212. if (!didParseAnimationName && value && validIdent.test(value)) {
  213. if ('$' + value in animationKeywords) {
  214. parsedAnimationKeywords['$' + value] = ('$' + value in parsedAnimationKeywords)
  215. ? (parsedAnimationKeywords['$' + value] + 1)
  216. : 0;
  217. shouldParseAnimationName = (parsedAnimationKeywords['$' + value] >= animationKeywords['$' + value]);
  218. } else {
  219. shouldParseAnimationName = true;
  220. }
  221. }
  222. var subContext = {
  223. options: context.options,
  224. global: context.global,
  225. localizeNextItem: shouldParseAnimationName && !context.global
  226. };
  227. return localizeDeclNode(valueNode, subContext);
  228. });
  229. }
  230. function localizeAnimationShorthandDeclValues(valuesNode, decl, context) {
  231. var newValuesNode = Object.create(valuesNode);
  232. newValuesNode.nodes = valuesNode.nodes.map(function(valueNode, index) {
  233. var newValueNode = Object.create(valueNode);
  234. newValueNode.nodes = localizeAnimationShorthandDeclValueNodes(valueNode.nodes, context);
  235. return newValueNode;
  236. });
  237. decl.value = Tokenizer.stringifyValues(newValuesNode);
  238. }
  239. function localizeDeclValues(localize, valuesNode, decl, context) {
  240. var newValuesNode = Object.create(valuesNode);
  241. newValuesNode.nodes = valuesNode.nodes.map(function(valueNode) {
  242. var subContext = {
  243. options: context.options,
  244. global: context.global,
  245. localizeNextItem: localize && !context.global
  246. };
  247. return localizeDeclValue(valueNode, subContext);
  248. });
  249. decl.value = Tokenizer.stringifyValues(newValuesNode);
  250. }
  251. function localizeDecl(decl, context) {
  252. var valuesNode = Tokenizer.parseValues(decl.value);
  253. var isAnimation = /animation?$/.test(decl.prop);
  254. if (isAnimation) return localizeAnimationShorthandDeclValues(valuesNode, decl, context);
  255. var isAnimationName = /animation(-name)?$/.test(decl.prop);
  256. if (isAnimationName) return localizeDeclValues(true, valuesNode, decl, context);
  257. return localizeDeclValues(false, valuesNode, decl, context);
  258. }
  259. module.exports = postcss.plugin('postcss-modules-local-by-default', function (options) {
  260. if (typeof options !== 'object') {
  261. options = {}; // If options is undefined or not an object the plugin fails
  262. }
  263. if(options && options.mode) {
  264. if(options.mode !== 'global' && options.mode !== 'local' && options.mode !== 'pure') {
  265. throw new Error('options.mode must be either "global", "local" or "pure" (default "local")');
  266. }
  267. }
  268. var pureMode = options && options.mode === 'pure';
  269. var globalMode = options && options.mode === 'global';
  270. return function(css) {
  271. css.walkAtRules(function(atrule) {
  272. if(/keyframes$/.test(atrule.name)) {
  273. var globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(atrule.params);
  274. var localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(atrule.params);
  275. var globalKeyframes = globalMode;
  276. if(globalMatch) {
  277. if(pureMode) {
  278. throw atrule.error('@keyframes :global(...) is not allowed in pure mode');
  279. }
  280. atrule.params = globalMatch[1];
  281. globalKeyframes = true;
  282. } else if(localMatch) {
  283. atrule.params = localMatch[0];
  284. globalKeyframes = false;
  285. } else if(!globalMode) {
  286. atrule.params = ':local(' + atrule.params + ')';
  287. }
  288. atrule.walkDecls(function(decl) {
  289. localizeDecl(decl, {
  290. options: options,
  291. global: globalKeyframes
  292. });
  293. });
  294. } else if(atrule.nodes) {
  295. atrule.nodes.forEach(function(decl) {
  296. if(decl.type === 'decl') {
  297. localizeDecl(decl, {
  298. options: options,
  299. global: globalMode
  300. });
  301. }
  302. });
  303. }
  304. });
  305. css.walkRules(function(rule) {
  306. if(rule.parent.type === 'atrule' && /keyframes$/.test(rule.parent.name)) {
  307. // ignore keyframe rules
  308. return;
  309. }
  310. var selector = Tokenizer.parse(rule.selector);
  311. var context = {
  312. options: options,
  313. global: globalMode,
  314. hasPureGlobals: false
  315. };
  316. var newSelector;
  317. try {
  318. newSelector = localizeNode(selector, context);
  319. } catch(e) {
  320. throw rule.error(e.message);
  321. }
  322. if(pureMode && context.hasPureGlobals) {
  323. throw rule.error('Selector "' + Tokenizer.stringify(selector) + '" is not pure ' +
  324. '(pure selectors must contain at least one local class or id)');
  325. }
  326. // Less-syntax mixins parse as rules with no nodes
  327. if (rule.nodes) {
  328. rule.nodes.forEach(function(decl) {
  329. localizeDecl(decl, context);
  330. });
  331. }
  332. rule.selector = Tokenizer.stringify(newSelector);
  333. });
  334. };
  335. });