index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. 'use strict';
  2. const postcss = require('postcss');
  3. const selectorParser = require('postcss-selector-parser');
  4. const valueParser = require('postcss-value-parser');
  5. const isSpacing = node => node.type === 'combinator' && node.value === ' ';
  6. function normalizeNodeArray(nodes) {
  7. const array = [];
  8. nodes.forEach(function(x) {
  9. if (Array.isArray(x)) {
  10. normalizeNodeArray(x).forEach(function(item) {
  11. array.push(item);
  12. });
  13. } else if (x) {
  14. array.push(x);
  15. }
  16. });
  17. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  18. array.pop();
  19. }
  20. return array;
  21. }
  22. function localizeNode(rule, mode, options) {
  23. const isScopePseudo = node =>
  24. node.value === ':local' || node.value === ':global';
  25. const transform = (node, context) => {
  26. if (context.ignoreNextSpacing && !isSpacing(node)) {
  27. throw new Error('Missing whitespace after ' + context.ignoreNextSpacing);
  28. }
  29. if (context.enforceNoSpacing && isSpacing(node)) {
  30. throw new Error('Missing whitespace before ' + context.enforceNoSpacing);
  31. }
  32. let newNodes;
  33. switch (node.type) {
  34. case 'root': {
  35. let resultingGlobal;
  36. context.hasPureGlobals = false;
  37. newNodes = node.nodes.map(function(n) {
  38. const nContext = {
  39. global: context.global,
  40. lastWasSpacing: true,
  41. hasLocals: false,
  42. explicit: false,
  43. };
  44. n = transform(n, nContext);
  45. if (typeof resultingGlobal === 'undefined') {
  46. resultingGlobal = nContext.global;
  47. } else if (resultingGlobal !== nContext.global) {
  48. throw new Error(
  49. 'Inconsistent rule global/local result in rule "' +
  50. node +
  51. '" (multiple selectors must result in the same mode for the rule)'
  52. );
  53. }
  54. if (!nContext.hasLocals) {
  55. context.hasPureGlobals = true;
  56. }
  57. return n;
  58. });
  59. context.global = resultingGlobal;
  60. node.nodes = normalizeNodeArray(newNodes);
  61. break;
  62. }
  63. case 'selector': {
  64. newNodes = node.map(childNode => transform(childNode, context));
  65. node = node.clone();
  66. node.nodes = normalizeNodeArray(newNodes);
  67. break;
  68. }
  69. case 'combinator': {
  70. if (isSpacing(node)) {
  71. if (context.ignoreNextSpacing) {
  72. context.ignoreNextSpacing = false;
  73. context.lastWasSpacing = false;
  74. context.enforceNoSpacing = false;
  75. return null;
  76. }
  77. context.lastWasSpacing = true;
  78. return node;
  79. }
  80. break;
  81. }
  82. case 'pseudo': {
  83. let childContext;
  84. const isNested = !!node.length;
  85. const isScoped = isScopePseudo(node);
  86. // :local(.foo)
  87. if (isNested) {
  88. if (isScoped) {
  89. if (context.inside) {
  90. throw new Error(
  91. `A ${node.value} is not allowed inside of a ${
  92. context.inside
  93. }(...)`
  94. );
  95. }
  96. childContext = {
  97. global: node.value === ':global',
  98. inside: node.value,
  99. hasLocals: false,
  100. explicit: true,
  101. };
  102. newNodes = node
  103. .map(childNode => transform(childNode, childContext))
  104. .reduce((acc, next) => acc.concat(next.nodes), []);
  105. if (newNodes.length) {
  106. const { before, after } = node.spaces;
  107. const first = newNodes[0];
  108. const last = newNodes[newNodes.length - 1];
  109. first.spaces = { before, after: first.spaces.after };
  110. last.spaces = { before: last.spaces.before, after };
  111. }
  112. node = newNodes;
  113. break;
  114. } else {
  115. childContext = {
  116. global: context.global,
  117. inside: context.inside,
  118. lastWasSpacing: true,
  119. hasLocals: false,
  120. explicit: context.explicit,
  121. };
  122. newNodes = node.map(childNode =>
  123. transform(childNode, childContext)
  124. );
  125. node = node.clone();
  126. node.nodes = normalizeNodeArray(newNodes);
  127. if (childContext.hasLocals) {
  128. context.hasLocals = true;
  129. }
  130. }
  131. break;
  132. //:local .foo .bar
  133. } else if (isScoped) {
  134. if (context.inside) {
  135. throw new Error(
  136. `A ${node.value} is not allowed inside of a ${
  137. context.inside
  138. }(...)`
  139. );
  140. }
  141. const addBackSpacing = !!node.spaces.before;
  142. context.ignoreNextSpacing = context.lastWasSpacing
  143. ? node.value
  144. : false;
  145. context.enforceNoSpacing = context.lastWasSpacing
  146. ? false
  147. : node.value;
  148. context.global = node.value === ':global';
  149. context.explicit = true;
  150. // because this node has spacing that is lost when we remove it
  151. // we make up for it by adding an extra combinator in since adding
  152. // spacing on the parent selector doesn't work
  153. return addBackSpacing
  154. ? selectorParser.combinator({ value: ' ' })
  155. : null;
  156. }
  157. break;
  158. }
  159. case 'id':
  160. case 'class': {
  161. if (!context.global) {
  162. const innerNode = node.clone();
  163. innerNode.spaces = { before: '', after: '' };
  164. node = selectorParser.pseudo({
  165. value: ':local',
  166. nodes: [innerNode],
  167. spaces: node.spaces,
  168. });
  169. context.hasLocals = true;
  170. }
  171. break;
  172. }
  173. }
  174. context.lastWasSpacing = false;
  175. context.ignoreNextSpacing = false;
  176. context.enforceNoSpacing = false;
  177. return node;
  178. };
  179. const rootContext = {
  180. global: mode === 'global',
  181. hasPureGlobals: false,
  182. };
  183. rootContext.selector = selectorParser(root => {
  184. transform(root, rootContext);
  185. }).processSync(rule, { updateSelector: false, lossless: true });
  186. return rootContext;
  187. }
  188. function localizeDeclNode(node, context) {
  189. switch (node.type) {
  190. case 'word':
  191. if (context.localizeNextItem) {
  192. node.value = ':local(' + node.value + ')';
  193. context.localizeNextItem = false;
  194. }
  195. break;
  196. case 'function':
  197. if (
  198. context.options &&
  199. context.options.rewriteUrl &&
  200. node.value.toLowerCase() === 'url'
  201. ) {
  202. node.nodes.map(nestedNode => {
  203. if (nestedNode.type !== 'string' && nestedNode.type !== 'word') {
  204. return;
  205. }
  206. let newUrl = context.options.rewriteUrl(
  207. context.global,
  208. nestedNode.value
  209. );
  210. switch (nestedNode.type) {
  211. case 'string':
  212. if (nestedNode.quote === "'") {
  213. newUrl = newUrl.replace(/(\\)/g, '\\$1').replace(/'/g, "\\'");
  214. }
  215. if (nestedNode.quote === '"') {
  216. newUrl = newUrl.replace(/(\\)/g, '\\$1').replace(/"/g, '\\"');
  217. }
  218. break;
  219. case 'word':
  220. newUrl = newUrl.replace(/("|'|\)|\\)/g, '\\$1');
  221. break;
  222. }
  223. nestedNode.value = newUrl;
  224. });
  225. }
  226. break;
  227. }
  228. return node;
  229. }
  230. function isWordAFunctionArgument(wordNode, functionNode) {
  231. return functionNode
  232. ? functionNode.nodes.some(
  233. functionNodeChild =>
  234. functionNodeChild.sourceIndex === wordNode.sourceIndex
  235. )
  236. : false;
  237. }
  238. function localizeAnimationShorthandDeclValues(decl, context) {
  239. const validIdent = /^-?[_a-z][_a-z0-9-]*$/i;
  240. /*
  241. The spec defines some keywords that you can use to describe properties such as the timing
  242. function. These are still valid animation names, so as long as there is a property that accepts
  243. a keyword, it is given priority. Only when all the properties that can take a keyword are
  244. exhausted can the animation name be set to the keyword. I.e.
  245. animation: infinite infinite;
  246. The animation will repeat an infinite number of times from the first argument, and will have an
  247. animation name of infinite from the second.
  248. */
  249. const animationKeywords = {
  250. $alternate: 1,
  251. '$alternate-reverse': 1,
  252. $backwards: 1,
  253. $both: 1,
  254. $ease: 1,
  255. '$ease-in': 1,
  256. '$ease-in-out': 1,
  257. '$ease-out': 1,
  258. $forwards: 1,
  259. $infinite: 1,
  260. $linear: 1,
  261. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  262. $normal: 1,
  263. $paused: 1,
  264. $reverse: 1,
  265. $running: 1,
  266. '$step-end': 1,
  267. '$step-start': 1,
  268. $initial: Infinity,
  269. $inherit: Infinity,
  270. $unset: Infinity,
  271. };
  272. const didParseAnimationName = false;
  273. let parsedAnimationKeywords = {};
  274. let stepsFunctionNode = null;
  275. const valueNodes = valueParser(decl.value).walk(node => {
  276. /* If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh. */
  277. if (node.type === 'div') {
  278. parsedAnimationKeywords = {};
  279. }
  280. if (node.type === 'function' && node.value.toLowerCase() === 'steps') {
  281. stepsFunctionNode = node;
  282. }
  283. const value =
  284. node.type === 'word' && !isWordAFunctionArgument(node, stepsFunctionNode)
  285. ? node.value.toLowerCase()
  286. : null;
  287. let shouldParseAnimationName = false;
  288. if (!didParseAnimationName && value && validIdent.test(value)) {
  289. if ('$' + value in animationKeywords) {
  290. parsedAnimationKeywords['$' + value] =
  291. '$' + value in parsedAnimationKeywords
  292. ? parsedAnimationKeywords['$' + value] + 1
  293. : 0;
  294. shouldParseAnimationName =
  295. parsedAnimationKeywords['$' + value] >=
  296. animationKeywords['$' + value];
  297. } else {
  298. shouldParseAnimationName = true;
  299. }
  300. }
  301. const subContext = {
  302. options: context.options,
  303. global: context.global,
  304. localizeNextItem: shouldParseAnimationName && !context.global,
  305. };
  306. return localizeDeclNode(node, subContext);
  307. });
  308. decl.value = valueNodes.toString();
  309. }
  310. function localizeDeclValues(localize, decl, context) {
  311. const valueNodes = valueParser(decl.value);
  312. valueNodes.walk((node, index, nodes) => {
  313. const subContext = {
  314. options: context.options,
  315. global: context.global,
  316. localizeNextItem: localize && !context.global,
  317. };
  318. nodes[index] = localizeDeclNode(node, subContext);
  319. });
  320. decl.value = valueNodes.toString();
  321. }
  322. function localizeDecl(decl, context) {
  323. const isAnimation = /animation$/i.test(decl.prop);
  324. if (isAnimation) {
  325. return localizeAnimationShorthandDeclValues(decl, context);
  326. }
  327. const isAnimationName = /animation(-name)?$/i.test(decl.prop);
  328. if (isAnimationName) {
  329. return localizeDeclValues(true, decl, context);
  330. }
  331. const hasUrl = /url\(/i.test(decl.value);
  332. if (hasUrl) {
  333. return localizeDeclValues(false, decl, context);
  334. }
  335. }
  336. module.exports = postcss.plugin('postcss-modules-local-by-default', function(
  337. options
  338. ) {
  339. if (typeof options !== 'object') {
  340. options = {}; // If options is undefined or not an object the plugin fails
  341. }
  342. if (options && options.mode) {
  343. if (
  344. options.mode !== 'global' &&
  345. options.mode !== 'local' &&
  346. options.mode !== 'pure'
  347. ) {
  348. throw new Error(
  349. 'options.mode must be either "global", "local" or "pure" (default "local")'
  350. );
  351. }
  352. }
  353. const pureMode = options && options.mode === 'pure';
  354. const globalMode = options && options.mode === 'global';
  355. return function(css) {
  356. css.walkAtRules(function(atrule) {
  357. if (/keyframes$/i.test(atrule.name)) {
  358. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(atrule.params);
  359. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(atrule.params);
  360. let globalKeyframes = globalMode;
  361. if (globalMatch) {
  362. if (pureMode) {
  363. throw atrule.error(
  364. '@keyframes :global(...) is not allowed in pure mode'
  365. );
  366. }
  367. atrule.params = globalMatch[1];
  368. globalKeyframes = true;
  369. } else if (localMatch) {
  370. atrule.params = localMatch[0];
  371. globalKeyframes = false;
  372. } else if (!globalMode) {
  373. atrule.params = ':local(' + atrule.params + ')';
  374. }
  375. atrule.walkDecls(function(decl) {
  376. localizeDecl(decl, {
  377. options: options,
  378. global: globalKeyframes,
  379. });
  380. });
  381. } else if (atrule.nodes) {
  382. atrule.nodes.forEach(function(decl) {
  383. if (decl.type === 'decl') {
  384. localizeDecl(decl, {
  385. options: options,
  386. global: globalMode,
  387. });
  388. }
  389. });
  390. }
  391. });
  392. css.walkRules(function(rule) {
  393. if (
  394. rule.parent.type === 'atrule' &&
  395. /keyframes$/i.test(rule.parent.name)
  396. ) {
  397. // ignore keyframe rules
  398. return;
  399. }
  400. if (
  401. rule.nodes &&
  402. rule.selector.slice(0, 2) === '--' &&
  403. rule.selector.slice(-1) === ':'
  404. ) {
  405. // ignore custom property set
  406. return;
  407. }
  408. const context = localizeNode(rule, options.mode);
  409. context.options = options;
  410. if (pureMode && context.hasPureGlobals) {
  411. throw rule.error(
  412. 'Selector "' +
  413. rule.selector +
  414. '" is not pure ' +
  415. '(pure selectors must contain at least one local class or id)'
  416. );
  417. }
  418. rule.selector = context.selector;
  419. // Less-syntax mixins parse as rules with no nodes
  420. if (rule.nodes) {
  421. rule.nodes.forEach(decl => localizeDecl(decl, context));
  422. }
  423. });
  424. };
  425. });