Completed
Push — master ( 358145...5febcb )
by Elbert
58s
created

popup.js ➔ appsToDomTemplate   C

Complexity

Conditions 8
Paths 2

Size

Total Lines 92

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
c 2
b 0
f 0
nc 2
nop 1
dl 0
loc 92
rs 5.538

1 Function

Rating   Name   Duplication   Size   Complexity  
A popup.js ➔ ... ➔ ??? 0 5 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
/** global: chrome */
2
/** global: browser */
3
4
var func = tabs => {
5
  ( chrome || browser ).runtime.sendMessage({
6
    id: 'get_apps',
7
    tab: tabs[0],
8
    source: 'popup.js'
9
  }, response => {
10
    replaceDomWhenReady(appsToDomTemplate(response));
11
  });
12
};
13
14
try {
15
  // Chrome, Firefox
16
  browser.tabs.query({ active: true, currentWindow: true })
17
    .then(func)
18
    .catch(console.error);
19
} catch ( e ) {
20
  // Edge
21
  browser.tabs.query({ active: true, currentWindow: true }, func);
22
}
23
24
function replaceDomWhenReady(dom) {
25
  if ( /complete|interactive|loaded/.test(document.readyState) ) {
26
    replaceDom(dom);
27
  } else {
28
    document.addEventListener('DOMContentLoaded', () => {
29
      replaceDom(dom);
30
    });
31
  }
32
}
33
34
function replaceDom(domTemplate) {
35
  var container = document.getElementsByClassName('container')[0];
36
37
  while ( container.firstChild ) {
38
    container.removeChild(container.firstChild);
39
  }
40
41
  container.appendChild(jsonToDOM(domTemplate, document, {}));
42
43
  var nodes = document.querySelectorAll('[data-i18n]');
44
45
  Array.prototype.forEach.call(nodes, node => {
46
    node.childNodes[0].nodeValue = browser.i18n.getMessage(node.dataset.i18n);
47
  });
48
}
49
50
function appsToDomTemplate(response) {
51
  var
52
    appName, confidence, version, categories,
53
    template = [];
54
55
  if ( response.tabCache && Object.keys(response.tabCache.detected).length > 0 ) {
56
    const categories = {};
57
58
    // Group apps by category
59
    for ( appName in response.tabCache.detected ) {
60
      response.apps[appName].cats.forEach(cat => {
61
        categories[cat] = categories[cat] || { apps: [] };
62
63
        categories[cat].apps[appName] = appName;
64
      });
65
    }
66
67
    for ( cat in categories ) {
0 ignored issues
show
Bug introduced by
The variable cat seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.cat.
Loading history...
68
      const apps = [];
69
70
      for ( appName in categories[cat].apps ) {
71
        confidence = response.tabCache.detected[appName].confidenceTotal;
72
        version    = response.tabCache.detected[appName].version;
73
74
        apps.push(
75
          [
76
            'a', {
77
              class: 'detected__app',
78
              target: '_blank',
79
              href: 'https://wappalyzer.com/applications/' + slugify(appName)
80
            }, [
81
              'img', {
82
                class: 'detected__app-icon',
83
                src: '../images/icons/' + ( response.apps[appName].icon || 'default.svg' )
84
              },
85
            ], [
86
              'span', {
87
                class: 'detected__app-name'
88
              },
89
              appName + ( version ? ' ' + version : '' ) + ( confidence < 100 ? ' (' + confidence + '% sure)' : '' )
90
            ]
91
          ]
92
        );
93
      }
94
95
      template.push(
96
        [
97
          'div', {
98
            class: 'detected__category'
99
          }, [
100
            'a', {
101
              class: 'detected__category-link',
102
              target: '_blank',
103
              href: 'https://wappalyzer.com/categories/' + slugify(response.categories[cat].name)
104
            }, [
105
              'span', {
106
                class: 'detected__category-name'
107
              },
108
              browser.i18n.getMessage('categoryName' + cat)
109
            ]
110
          ], [
111
            'div', {
112
              class: 'detected__apps'
113
            },
114
            apps
115
          ]
116
        ]
117
      );
118
    }
119
120
    template = [
121
      'div', {
122
        class: 'detected'
123
      },
124
      template
125
    ];
126
  } else {
127
    template = [
128
      'div', {
129
        class: 'empty'
130
      },
131
      [
132
        'span', {
133
          class: 'empty__text'
134
        },
135
        browser.i18n.getMessage('noAppsDetected')
136
      ],
137
    ];
138
  }
139
140
  return template;
141
}
142
143
function slugify(string) {
144
  return string.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/--+/g, '-').replace(/(?:^-|-$)/, '');
145
}
146