|
| 1 | +const path = require('path'); |
| 2 | + |
| 3 | +const postcss = require('postcss'); |
| 4 | + |
| 5 | +const readFile = require('./utils').readFile; |
| 6 | +const parseImportPath = require('./utils').parseImportPath; |
| 7 | +const findInlineDeclarations = require('./findInlineDeclarations'); |
| 8 | +const findNestedRules = require('./findNestedRules'); |
| 9 | + |
| 10 | +const processAtRule = (onError, atRule, root, targetClass, importPath) => { |
| 11 | + const matchedDeclarations = findInlineDeclarations(root, targetClass); |
| 12 | + const nestedRules = findNestedRules(root, targetClass); |
| 13 | + |
| 14 | + if (matchedDeclarations.length === 0 && nestedRules.length === 0) { |
| 15 | + if (importPath) { |
| 16 | + onError(`Could not find class '${targetClass}' in file '${importPath}'`); |
| 17 | + } else { |
| 18 | + onError(`Could not find class '${targetClass}'`); |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + nestedRules.forEach((nestedRule) => { |
| 23 | + nestedRule.selectors = nestedRule.selectors.map((selector) => |
| 24 | + postcss.list |
| 25 | + .space(selector) |
| 26 | + .map((className) => (className === targetClass ? atRule.parent.selector : className)) |
| 27 | + .join(' '), |
| 28 | + ); |
| 29 | + root.append(nestedRule); |
| 30 | + }); |
| 31 | + |
| 32 | + atRule.replaceWith(matchedDeclarations); |
| 33 | +}; |
| 34 | + |
| 35 | +const walkAtRule = (root, result, promises) => (atRule) => { |
| 36 | + const params = postcss.list.space(atRule.params); |
| 37 | + const targetClass = params[0]; |
| 38 | + |
| 39 | + const onError = (message) => atRule.warn(result, message); |
| 40 | + |
| 41 | + if (params.length === 1) { |
| 42 | + processAtRule(onError, atRule, root, targetClass); |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + const importPath = parseImportPath(params.slice(-1)[0]); |
| 47 | + const resolvedPath = path.resolve(path.dirname(root.source.input.file), importPath); |
| 48 | + |
| 49 | + promises.push( |
| 50 | + readFile(resolvedPath) |
| 51 | + .then((rawData) => { |
| 52 | + const importedRoot = postcss.parse(rawData); |
| 53 | + processAtRule(onError, atRule, importedRoot, targetClass, importPath); |
| 54 | + }) |
| 55 | + .catch(() => { |
| 56 | + onError(`Could not find file '${importPath}'`); |
| 57 | + atRule.remove(); |
| 58 | + }), |
| 59 | + ); |
| 60 | +}; |
| 61 | + |
| 62 | +const processFile = (root, result) => (resolve) => { |
| 63 | + const promises = []; |
| 64 | + |
| 65 | + const atRuleWalker = walkAtRule(root, result, promises); |
| 66 | + |
| 67 | + root.walkRules((rule) => rule.walkAtRules('inline', atRuleWalker)); |
| 68 | + |
| 69 | + return Promise.all(promises).then(resolve).catch(resolve); |
| 70 | +}; |
| 71 | + |
| 72 | +module.exports = postcss.plugin('postcss-inline-class', () => (root, result) => |
| 73 | + new Promise(processFile(root, result)), |
| 74 | +); |
0 commit comments