summaryrefslogtreecommitdiff
path: root/scripts/frontend/stylelint/stylelint-utils.js
blob: 2d931c1c4c23b81dda9ce8513e96cd470b99cec0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const stylelint = require('stylelint');
const md5 = require('md5');

module.exports.createPropertiesHashmap = (
  ruleRoot,
  result,
  ruleName,
  messages,
  selectorGroups,
  addSelectors,
) => {
  ruleRoot.walkRules(rule => {
    const selector = rule.selector.replace(/(?:\r\n|\r|\n)/g, ' ');

    if (
      rule &&
      rule.parent &&
      rule.parent.type != 'atrule' &&
      !(
        selector.includes('-webkit-') ||
        selector.includes('-moz-') ||
        selector.includes('-o-') ||
        selector.includes('-ms-') ||
        selector.includes(':')
      )
    ) {
      let cssArray = [];
      rule.nodes.forEach(function(property) {
        const { prop, value } = property;
        if (property && value) {
          const propval = `${prop}${value}${property.important ? '!important' : ''}`;
          cssArray.push(propval);
        }
      });

      cssArray = cssArray.sort();
      const cssContent = cssArray.toString();

      if (cssContent) {
        const hashValue = md5(cssContent);
        const selObj = selectorGroups[hashValue];

        const selectorLine = `${selector} (${
          rule.source.input.file ? rule.source.input.file + ' -' : ''
        }${rule.source.start.line}:${rule.source.start.column})`;

        if (selObj) {
          if (selectorGroups[hashValue].selectors.indexOf(selector) == -1) {
            let lastSelector =
              selectorGroups[hashValue].selectors[selectorGroups[hashValue].selectors.length - 1];

            // So we have nicer formatting if it is the same file, we remove the filename
            lastSelector = lastSelector.replace(`${rule.source.input.file} - `, '');

            if (messages) {
              stylelint.utils.report({
                result,
                ruleName,
                message: messages.expected(selector, lastSelector),
                node: rule,
                word: rule.node,
              });
            }

            if (addSelectors) {
              selectorGroups[hashValue].selectors.push(selectorLine);
            }
          }
        } else if (addSelectors) {
          selectorGroups[hashValue] = {
            selectors: [selectorLine],
          };
        }
      }
    }
  });
};