UNPKG

12.3 kBJavaScriptView Raw
1/*! Clusterize.js - v0.16.0 - 2016-03-12
2* http://NeXTs.github.com/Clusterize.js/
3* Copyright (c) 2015 Denis Lukov; Licensed GPLv3 */
4
5;(function(name, definition) {
6 if (typeof module != 'undefined') module.exports = definition();
7 else if (typeof define == 'function' && typeof define.amd == 'object') define(definition);
8 else this[name] = definition();
9}('Clusterize', function() {
10 "use strict"
11
12 // detect ie9 and lower
13 // https://gist.github.com/padolsey/527683#comment-786682
14 var ie = (function(){
15 for( var v = 3,
16 el = document.createElement('b'),
17 all = el.all || [];
18 el.innerHTML = '<!--[if gt IE ' + (++v) + ']><i><![endif]-->',
19 all[0];
20 ){}
21 return v > 4 ? v : document.documentMode;
22 }()),
23 is_mac = navigator.platform.toLowerCase().indexOf('mac') + 1;
24 var Clusterize = function(data) {
25 if( ! (this instanceof Clusterize))
26 return new Clusterize(data);
27 var self = this;
28
29 var defaults = {
30 item_height: 0,
31 block_height: 0,
32 rows_in_block: 50,
33 rows_in_cluster: 0,
34 cluster_height: 0,
35 blocks_in_cluster: 4,
36 tag: null,
37 content_tag: null,
38 show_no_data_row: true,
39 no_data_class: 'clusterize-no-data',
40 no_data_text: 'No data',
41 keep_parity: true,
42 callbacks: {},
43 scroll_top: 0
44 }
45
46 // public parameters
47 self.options = {};
48 var options = ['rows_in_block', 'blocks_in_cluster', 'show_no_data_row', 'no_data_class', 'no_data_text', 'keep_parity', 'tag', 'callbacks'];
49 for(var i = 0, option; option = options[i]; i++) {
50 self.options[option] = typeof data[option] != 'undefined' && data[option] != null
51 ? data[option]
52 : defaults[option];
53 }
54
55 var elems = ['scroll', 'content'];
56 for(var i = 0, elem; elem = elems[i]; i++) {
57 self[elem + '_elem'] = data[elem + 'Id']
58 ? document.getElementById(data[elem + 'Id'])
59 : data[elem + 'Elem'];
60 if( ! self[elem + '_elem'])
61 throw new Error("Error! Could not find " + elem + " element");
62 }
63
64 // tabindex forces the browser to keep focus on the scrolling list, fixes #11
65 if( ! self.content_elem.hasAttribute('tabindex'))
66 self.content_elem.setAttribute('tabindex', 0);
67
68 // private parameters
69 var rows = isArray(data.rows)
70 ? data.rows
71 : self.fetchMarkup(),
72 cache = {data: '', bottom: 0},
73 scroll_top = self.scroll_elem.scrollTop;
74
75 // get row height
76 self.exploreEnvironment(rows);
77
78 // append initial data
79 self.insertToDOM(rows, cache);
80
81 // restore the scroll position
82 self.scroll_elem.scrollTop = scroll_top;
83
84 // adding scroll handler
85 var last_cluster = false,
86 scroll_debounce = 0,
87 pointer_events_set = false,
88 scrollEv = function() {
89 // fixes scrolling issue on Mac #3
90 if (is_mac) {
91 if( ! pointer_events_set) self.content_elem.style.pointerEvents = 'none';
92 pointer_events_set = true;
93 clearTimeout(scroll_debounce);
94 scroll_debounce = setTimeout(function () {
95 self.content_elem.style.pointerEvents = 'auto';
96 pointer_events_set = false;
97 }, 50);
98 }
99 if (last_cluster != (last_cluster = self.getClusterNum()))
100 self.insertToDOM(rows, cache);
101 if (self.options.callbacks.scrollingProgress)
102 self.options.callbacks.scrollingProgress(self.getScrollProgress());
103 },
104 resize_debounce = 0,
105 resizeEv = function() {
106 clearTimeout(resize_debounce);
107 resize_debounce = setTimeout(self.refresh, 100);
108 }
109 on('scroll', self.scroll_elem, scrollEv);
110 on('resize', window, resizeEv);
111
112 // public methods
113 self.destroy = function(clean) {
114 off('scroll', self.scroll_elem, scrollEv);
115 off('resize', window, resizeEv);
116 self.html((clean ? self.generateEmptyRow() : rows).join(''));
117 }
118 self.refresh = function() {
119 self.getRowsHeight(rows) && self.update(rows);
120 }
121 self.update = function(new_rows) {
122 rows = isArray(new_rows)
123 ? new_rows
124 : [];
125 var scroll_top = self.scroll_elem.scrollTop;
126 // fixes #39
127 if(rows.length * self.options.item_height < scroll_top) {
128 self.scroll_elem.scrollTop = 0;
129 last_cluster = 0;
130 }
131 self.insertToDOM(rows, cache);
132 self.scroll_elem.scrollTop = scroll_top;
133 }
134 self.clear = function() {
135 self.update([]);
136 }
137 self.getRowsAmount = function() {
138 return rows.length;
139 }
140 self.getScrollProgress = function() {
141 return this.options.scroll_top / (rows.length * this.options.item_height) * 100 || 0;
142 }
143
144 var add = function(where, _new_rows) {
145 var new_rows = isArray(_new_rows)
146 ? _new_rows
147 : [];
148 if( ! new_rows.length) return;
149 rows = where == 'append'
150 ? rows.concat(new_rows)
151 : new_rows.concat(rows);
152 self.insertToDOM(rows, cache);
153 }
154 self.append = function(rows) {
155 add('append', rows);
156 }
157 self.prepend = function(rows) {
158 add('prepend', rows);
159 }
160 }
161
162 Clusterize.prototype = {
163 constructor: Clusterize,
164 // fetch existing markup
165 fetchMarkup: function() {
166 var rows = [], rows_nodes = this.getChildNodes(this.content_elem);
167 while (rows_nodes.length) {
168 rows.push(rows_nodes.shift().outerHTML);
169 }
170 return rows;
171 },
172 // get tag name, content tag name, tag height, calc cluster height
173 exploreEnvironment: function(rows) {
174 var opts = this.options;
175 opts.content_tag = this.content_elem.tagName.toLowerCase();
176 if( ! rows.length) return;
177 if(ie && ie <= 9 && ! opts.tag) opts.tag = rows[0].match(/<([^>\s/]*)/)[1].toLowerCase();
178 if(this.content_elem.children.length <= 1) this.html(rows[0] + rows[0] + rows[0]);
179 if( ! opts.tag) opts.tag = this.content_elem.children[0].tagName.toLowerCase();
180 this.getRowsHeight(rows);
181 },
182 getRowsHeight: function(rows) {
183 var opts = this.options,
184 prev_item_height = opts.item_height;
185 opts.cluster_height = 0
186 if( ! rows.length) return;
187 var nodes = this.content_elem.children;
188 opts.item_height = nodes[Math.floor(nodes.length / 2)].offsetHeight;
189 // consider table's border-spacing
190 if(opts.tag == 'tr' && getStyle('borderCollapse', this.content_elem) != 'collapse')
191 opts.item_height += parseInt(getStyle('borderSpacing', this.content_elem)) || 0;
192 opts.block_height = opts.item_height * opts.rows_in_block;
193 opts.rows_in_cluster = opts.blocks_in_cluster * opts.rows_in_block;
194 opts.cluster_height = opts.blocks_in_cluster * opts.block_height;
195 return prev_item_height != opts.item_height;
196 },
197 // get current cluster number
198 getClusterNum: function () {
199 this.options.scroll_top = this.scroll_elem.scrollTop;
200 return Math.floor(this.options.scroll_top / (this.options.cluster_height - this.options.block_height)) || 0;
201 },
202 // generate empty row if no data provided
203 generateEmptyRow: function() {
204 var opts = this.options;
205 if( ! opts.tag || ! opts.show_no_data_row) return [];
206 var empty_row = document.createElement(opts.tag),
207 no_data_content = document.createTextNode(opts.no_data_text), td;
208 empty_row.className = opts.no_data_class;
209 if(opts.tag == 'tr') {
210 td = document.createElement('td');
211 td.appendChild(no_data_content);
212 }
213 empty_row.appendChild(td || no_data_content);
214 return [empty_row.outerHTML];
215 },
216 // generate cluster for current scroll position
217 generate: function (rows, cluster_num) {
218 var opts = this.options,
219 rows_len = rows.length;
220 if (rows_len < opts.rows_in_block) {
221 return {
222 top_offset: 0,
223 bottom_offset: 0,
224 rows_above: 0,
225 rows: rows_len ? rows : this.generateEmptyRow()
226 }
227 }
228 if( ! opts.cluster_height) {
229 this.exploreEnvironment(rows);
230 }
231 var items_start = Math.max((opts.rows_in_cluster - opts.rows_in_block) * cluster_num, 0),
232 items_end = items_start + opts.rows_in_cluster,
233 top_offset = Math.max(items_start * opts.item_height, 0),
234 bottom_offset = Math.max((rows_len - items_end) * opts.item_height, 0),
235 this_cluster_rows = [],
236 rows_above = items_start;
237 if(top_offset < 1) {
238 rows_above++;
239 }
240 for (var i = items_start; i < items_end; i++) {
241 rows[i] && this_cluster_rows.push(rows[i]);
242 }
243 return {
244 top_offset: top_offset,
245 bottom_offset: bottom_offset,
246 rows_above: rows_above,
247 rows: this_cluster_rows
248 }
249 },
250 renderExtraTag: function(class_name, height) {
251 var tag = document.createElement(this.options.tag),
252 clusterize_prefix = 'clusterize-';
253 tag.className = [clusterize_prefix + 'extra-row', clusterize_prefix + class_name].join(' ');
254 height && (tag.style.height = height + 'px');
255 return tag.outerHTML;
256 },
257 // if necessary verify data changed and insert to DOM
258 insertToDOM: function(rows, cache) {
259 var data = this.generate(rows, this.getClusterNum()),
260 this_cluster_rows = data.rows.join(''),
261 this_cluster_content_changed = this.checkChanges('data', this_cluster_rows, cache),
262 only_bottom_offset_changed = this.checkChanges('bottom', data.bottom_offset, cache),
263 callbacks = this.options.callbacks,
264 layout = [];
265
266 if(this_cluster_content_changed) {
267 if(data.top_offset) {
268 this.options.keep_parity && layout.push(this.renderExtraTag('keep-parity'));
269 layout.push(this.renderExtraTag('top-space', data.top_offset));
270 }
271 layout.push(this_cluster_rows);
272 data.bottom_offset && layout.push(this.renderExtraTag('bottom-space', data.bottom_offset));
273 callbacks.clusterWillChange && callbacks.clusterWillChange();
274 this.html(layout.join(''));
275 this.options.content_tag == 'ol' && this.content_elem.setAttribute('start', data.rows_above);
276 callbacks.clusterChanged && callbacks.clusterChanged();
277 } else if(only_bottom_offset_changed) {
278 this.content_elem.lastChild.style.height = data.bottom_offset + 'px';
279 }
280 },
281 // unfortunately ie <= 9 does not allow to use innerHTML for table elements, so make a workaround
282 html: function(data) {
283 var content_elem = this.content_elem;
284 if(ie && ie <= 9 && this.options.tag == 'tr') {
285 var div = document.createElement('div'), last;
286 div.innerHTML = '<table><tbody>' + data + '</tbody></table>';
287 while((last = content_elem.lastChild)) {
288 content_elem.removeChild(last);
289 }
290 var rows_nodes = this.getChildNodes(div.firstChild.firstChild);
291 while (rows_nodes.length) {
292 content_elem.appendChild(rows_nodes.shift());
293 }
294 } else {
295 content_elem.innerHTML = data;
296 }
297 },
298 getChildNodes: function(tag) {
299 var child_nodes = tag.children, nodes = [];
300 for (var i = 0, ii = child_nodes.length; i < ii; i++) {
301 nodes.push(child_nodes[i]);
302 }
303 return nodes;
304 },
305 checkChanges: function(type, value, cache) {
306 var changed = value != cache[type];
307 cache[type] = value;
308 return changed;
309 }
310 }
311
312 // support functions
313 function on(evt, element, fnc) {
314 return element.addEventListener ? element.addEventListener(evt, fnc, false) : element.attachEvent("on" + evt, fnc);
315 }
316 function off(evt, element, fnc) {
317 return element.removeEventListener ? element.removeEventListener(evt, fnc, false) : element.detachEvent("on" + evt, fnc);
318 }
319 function isArray(arr) {
320 return Object.prototype.toString.call(arr) === '[object Array]';
321 }
322 function getStyle(prop, elem) {
323 return window.getComputedStyle ? window.getComputedStyle(elem)[prop] : elem.currentStyle[prop];
324 }
325
326 return Clusterize;
327}));
\No newline at end of file