map.js ➔ resetMarkerStyles   F
last analyzed

Complexity

Conditions 20

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 9
rs 0
c 0
b 0
f 0
cc 20

How to fix   Complexity   

Complexity

Complex classes like map.js ➔ resetMarkerStyles often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
define(['map/clientlayer', 'map/labellayer', 'map/button', 'leaflet', 'map/activearea'],
2
  function (ClientLayer, LabelLayer, Button, L) {
3
    'use strict';
4
5
    var options = {
6
      worldCopyJump: true,
7
      zoomControl: true,
8
      minZoom: 0
9
    };
10
11
    return function (linkScale, sidebar, buttons) {
12
      var self = this;
13
      var savedView;
14
15
      var map;
16
      var layerControl;
17
      var baseLayers = {};
18
19
      function saveView() {
20
        savedView = {
21
          center: map.getCenter(),
22
          zoom: map.getZoom()
23
        };
24
      }
25
26
      function contextMenuOpenLayerMenu() {
27
        document.querySelector('.leaflet-control-layers').classList.add('leaflet-control-layers-expanded');
28
      }
29
30
      function mapActiveArea() {
31
        map.setActiveArea({
32
          position: 'absolute',
33
          left: sidebar.getWidth() + 'px',
34
          right: 0,
35
          top: 0,
36
          bottom: 0
37
        });
38
      }
39
40
      function setActiveArea() {
41
        setTimeout(mapActiveArea, 300);
42
      }
43
44
      var el = document.createElement('div');
45
      el.classList.add('map');
46
47
      map = L.map(el, options);
48
      mapActiveArea();
49
50
      var now = new Date();
51
      config.mapLayers.forEach(function (item, i) {
52
        if ((typeof item.config.start === 'number' && item.config.start <= now.getHours()) || (typeof item.config.end === 'number' && item.config.end > now.getHours())) {
53
          item.config.order = item.config.start * -1;
54
        } else {
55
          item.config.order = i;
56
        }
57
      });
58
59
      config.mapLayers = config.mapLayers.sort(function (a, b) {
60
        return a.config.order - b.config.order;
61
      });
62
63
      var layers = config.mapLayers.map(function (d) {
64
        return {
65
          'name': d.name,
66
          'layer': L.tileLayer(d.url.replace('{format}', document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') === 0 ? 'webp' : 'png'), d.config)
67
        };
68
      });
69
70
      map.addLayer(layers[0].layer);
71
72
      layers.forEach(function (d) {
73
        baseLayers[d.name] = d.layer;
74
      });
75
76
      var button = new Button(map, buttons);
77
78
      map.on('locationfound', button.locationFound);
79
      map.on('locationerror', button.locationError);
80
      map.on('dragend', saveView);
81
      map.on('contextmenu', contextMenuOpenLayerMenu);
82
83
      if (config.geo) {
84
        [].forEach.call(config.geo, function (geo) {
85
          geo.json().then(function (result) {
86
            if (result) {
87
              L.geoJSON(result, geo.option).addTo(map);
88
            }
89
          });
90
        });
91
      }
92
93
      button.init();
94
95
      layerControl = L.control.layers(baseLayers, [], { position: 'bottomright' });
96
      layerControl.addTo(map);
97
98
      map.zoomControl.setPosition('topright');
99
100
      var clientLayer = new ClientLayer({ minZoom: config.clientZoom });
101
      clientLayer.addTo(map);
102
      clientLayer.setZIndex(5);
103
104
      var labelLayer = new LabelLayer({ minZoom: config.labelZoom });
105
      labelLayer.addTo(map);
106
      labelLayer.setZIndex(6);
107
108
      sidebar.button.addEventListener('visibility', setActiveArea);
109
110
      map.on('zoom', function () {
111
        clientLayer.redraw();
112
        labelLayer.redraw();
113
      });
114
115
      map.on('baselayerchange', function (e) {
116
        map.options.maxZoom = e.layer.options.maxZoom;
117
        clientLayer.options.maxZoom = map.options.maxZoom;
118
        labelLayer.options.maxZoom = map.options.maxZoom;
119
        if (map.getZoom() > map.options.maxZoom) {
120
          map.setZoom(map.options.maxZoom);
121
        }
122
123
        var style = document.querySelector('.css-mode:not([media="not"])');
124
        if (style && e.layer.options.mode !== '' && !style.classList.contains(e.layer.options.mode)) {
125
          style.media = 'not';
126
          labelLayer.updateLayer();
127
        }
128
        if (e.layer.options.mode) {
129
          var newStyle = document.querySelector('.css-mode.' + e.layer.options.mode);
130
          newStyle.media = '';
131
          newStyle.appendChild(document.createTextNode(''));
132
          labelLayer.updateLayer();
133
        }
134
      });
135
136
      map.on('load', function () {
137
        var inputs = document.querySelectorAll('.leaflet-control-layers-selector');
138
        [].forEach.call(inputs, function (input) {
139
          input.setAttribute('role', 'radiogroup');
140
          input.setAttribute('aria-label', input.nextSibling.innerHTML.trim());
141
        });
142
      });
143
144
      var nodeDict = {};
145
      var linkDict = {};
146
      var highlight;
147
148
      function resetMarkerStyles(nodes, links) {
149
        Object.keys(nodes).forEach(function (d) {
150
          nodes[d].resetStyle();
151
        });
152
153
        Object.keys(links).forEach(function (d) {
154
          links[d].resetStyle();
155
        });
156
      }
157
158
      function setView(bounds, zoom) {
159
        map.fitBounds(bounds, { maxZoom: (zoom ? zoom : config.nodeZoom) });
160
      }
161
162
      function goto(m) {
163
        var bounds;
164
165
        if ('getBounds' in m) {
166
          bounds = m.getBounds();
167
        } else {
168
          bounds = L.latLngBounds([m.getLatLng()]);
169
        }
170
171
        setView(bounds);
172
173
        return m;
174
      }
175
176
      function updateView(nopanzoom) {
177
        resetMarkerStyles(nodeDict, linkDict);
178
        var m;
179
180
        if (highlight !== undefined) {
181
          if (highlight.type === 'node' && nodeDict[highlight.o.node_id]) {
182
            m = nodeDict[highlight.o.node_id];
183
            m.setStyle(config.map.highlightNode);
184
          } else if (highlight.type === 'link' && linkDict[highlight.o.id]) {
185
            m = linkDict[highlight.o.id];
186
            m.setStyle(config.map.highlightLink);
187
          }
188
        }
189
190
        if (!nopanzoom) {
191
          if (m) {
192
            goto(m);
193
          } else if (savedView) {
194
            map.setView(savedView.center, savedView.zoom);
195
          } else {
196
            setView(config.fixedCenter);
197
          }
198
        }
199
      }
200
201
      self.setData = function setData(data) {
202
        nodeDict = {};
203
        linkDict = {};
204
205
        clientLayer.setData(data);
206
        labelLayer.setData(data, map, nodeDict, linkDict, linkScale);
207
208
        updateView(true);
209
      };
210
211
      self.resetView = function resetView() {
212
        button.disableTracking();
213
        highlight = undefined;
214
        updateView();
215
      };
216
217
      self.gotoNode = function gotoNode(d) {
218
        button.disableTracking();
219
        highlight = { type: 'node', o: d };
220
        updateView();
221
      };
222
223
      self.gotoLink = function gotoLink(d) {
224
        button.disableTracking();
225
        highlight = { type: 'link', o: d[0] };
226
        updateView();
227
      };
228
229
      self.gotoLocation = function gotoLocation(d) {
230
        button.disableTracking();
231
        map.setView([d.lat, d.lng], d.zoom);
232
      };
233
234
      self.destroy = function destroy() {
235
        button.clearButtons();
236
        sidebar.button.removeEventListener('visibility', setActiveArea);
237
        map.remove();
238
239
        if (el.parentNode) {
240
          el.parentNode.removeChild(el);
241
        }
242
      };
243
244
      self.render = function render(d) {
245
        d.appendChild(el);
246
        map.invalidateSize();
247
      };
248
249
      return self;
250
    };
251
  });
252