index.js 15 KB

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