summaryrefslogtreecommitdiffstats
path: root/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/balanced-listeners.js
blob: d571918909fa08e5cc7d3c41f6a48496dfe38df0 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/**
 * @fileoverview Check that there's a removeEventListener for each
 * addEventListener and an off for each on.
 * Note that for now, this rule is rather simple in that it only checks that
 * for each event name there is both an add and remove listener. It doesn't
 * check that these are called on the right objects or with the same callback.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

"use strict";

module.exports = {
  meta: {
    docs: {
      url: "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/balanced-listeners.html",
    },
    messages: {
      noCorresponding:
        "No corresponding '{{functionName}}({{type}})' was found.",
    },
    schema: [],
    type: "problem",
  },

  create(context) {
    var DICTIONARY = {
      addEventListener: "removeEventListener",
      on: "off",
    };
    // Invert this dictionary to make it easy later.
    var INVERTED_DICTIONARY = {};
    for (var i in DICTIONARY) {
      INVERTED_DICTIONARY[DICTIONARY[i]] = i;
    }

    // Collect the add/remove listeners in these 2 arrays.
    var addedListeners = [];
    var removedListeners = [];

    function addAddedListener(node) {
      var capture = false;
      let options = node.arguments[2];
      if (options) {
        if (options.type == "ObjectExpression") {
          if (
            options.properties.some(
              p => p.key.name == "once" && p.value.value === true
            )
          ) {
            // No point in adding listeners using the 'once' option.
            return;
          }
          capture = options.properties.some(
            p => p.key.name == "capture" && p.value.value === true
          );
        } else {
          capture = options.value;
        }
      }
      addedListeners.push({
        functionName: node.callee.property.name,
        type: node.arguments[0].value,
        node: node.callee.property,
        useCapture: capture,
      });
    }

    function addRemovedListener(node) {
      var capture = false;
      let options = node.arguments[2];
      if (options) {
        if (options.type == "ObjectExpression") {
          capture = options.properties.some(
            p => p.key.name == "capture" && p.value.value === true
          );
        } else {
          capture = options.value;
        }
      }
      removedListeners.push({
        functionName: node.callee.property.name,
        type: node.arguments[0].value,
        useCapture: capture,
      });
    }

    function getUnbalancedListeners() {
      var unbalanced = [];

      for (var j = 0; j < addedListeners.length; j++) {
        if (!hasRemovedListener(addedListeners[j])) {
          unbalanced.push(addedListeners[j]);
        }
      }
      addedListeners = removedListeners = [];

      return unbalanced;
    }

    function hasRemovedListener(addedListener) {
      for (var k = 0; k < removedListeners.length; k++) {
        var listener = removedListeners[k];
        if (
          DICTIONARY[addedListener.functionName] === listener.functionName &&
          addedListener.type === listener.type &&
          addedListener.useCapture === listener.useCapture
        ) {
          return true;
        }
      }

      return false;
    }

    return {
      CallExpression(node) {
        if (node.arguments.length === 0) {
          return;
        }

        if (node.callee.type === "MemberExpression") {
          var listenerMethodName = node.callee.property.name;

          if (DICTIONARY.hasOwnProperty(listenerMethodName)) {
            addAddedListener(node);
          } else if (INVERTED_DICTIONARY.hasOwnProperty(listenerMethodName)) {
            addRemovedListener(node);
          }
        }
      },

      "Program:exit": function () {
        getUnbalancedListeners().forEach(function (listener) {
          context.report({
            node: listener.node,
            messageId: "noCorresponding",
            data: {
              functionName: DICTIONARY[listener.functionName],
              type: listener.type,
            },
          });
        });
      },
    };
  },
};