Debian Codegraph @

js/widgets/widget-stickyHeaders.js

raw symbols SCIP
1 /*! Widget: stickyHeaders - updated 9/27/2017 (v2.29.0) *//*
2 * Requires tablesorter v2.8+ and jQuery 1.4.3+
3 * by Rob Garrison
4 */
5 ;(function ($, window) {
6 'use strict';
7 var ts = $.tablesorter || {};
8
9 $.extend(ts.css, {
10 sticky : 'tablesorter-stickyHeader', // stickyHeader
11 stickyVis : 'tablesorter-sticky-visible',
12 stickyHide: 'tablesorter-sticky-hidden',
13 stickyWrap: 'tablesorter-sticky-wrapper'
14 });
15
16 // Add a resize event to table headers
17 ts.addHeaderResizeEvent = function(table, disable, settings) {
18 table = $(table)[0]; // make sure we're using a dom element
19 if ( !table.config ) { return; }
20 var defaults = {
21 timer : 250
22 },
23 options = $.extend({}, defaults, settings),
24 c = table.config,
25 wo = c.widgetOptions,
26 checkSizes = function( triggerEvent ) {
27 var index, headers, $header, sizes, width, height,
28 len = c.$headers.length;
29 wo.resize_flag = true;
30 headers = [];
31 for ( index = 0; index < len; index++ ) {
32 $header = c.$headers.eq( index );
33 sizes = $header.data( 'savedSizes' ) || [ 0, 0 ]; // fixes #394
34 width = $header[0].offsetWidth;
35 height = $header[0].offsetHeight;
36 if ( width !== sizes[0] || height !== sizes[1] ) {
37 $header.data( 'savedSizes', [ width, height ] );
38 headers.push( $header[0] );
39 }
40 }
41 if ( headers.length && triggerEvent !== false ) {
42 c.$table.triggerHandler( 'resize', [ headers ] );
43 }
44 wo.resize_flag = false;
45 };
46 clearInterval(wo.resize_timer);
47 if (disable) {
48 wo.resize_flag = false;
49 return false;
50 }
51 checkSizes( false );
52 wo.resize_timer = setInterval(function() {
53 if (wo.resize_flag) { return; }
54 checkSizes();
55 }, options.timer);
56 };
57
58 function getStickyOffset(c, wo) {
59 var $el = isNaN(wo.stickyHeaders_offset) ? $(wo.stickyHeaders_offset) : [];
60 return $el.length ?
61 $el.height() || 0 :
62 parseInt(wo.stickyHeaders_offset, 10) || 0;
63 }
64
65 // Sticky headers based on this awesome article:
66 // http://css-tricks.com/13465-persistent-headers/
67 // and https://github.com/jmosbech/StickyTableHeaders by Jonas Mosbech
68 // **************************
69 ts.addWidget({
70 id: 'stickyHeaders',
71 priority: 54, // sticky widget must be initialized after the filter & before pager widget!
72 options: {
73 stickyHeaders : '', // extra class name added to the sticky header row
74 stickyHeaders_appendTo : null, // jQuery selector or object to phycially attach the sticky headers
75 stickyHeaders_attachTo : null, // jQuery selector or object to attach scroll listener to (overridden by xScroll & yScroll settings)
76 stickyHeaders_xScroll : null, // jQuery selector or object to monitor horizontal scroll position (defaults: xScroll > attachTo > window)
77 stickyHeaders_yScroll : null, // jQuery selector or object to monitor vertical scroll position (defaults: yScroll > attachTo > window)
78 stickyHeaders_offset : 0, // number or jquery selector targeting the position:fixed element
79 stickyHeaders_filteredToTop: true, // scroll table top into view after filtering
80 stickyHeaders_cloneId : '-sticky', // added to table ID, if it exists
81 stickyHeaders_addResizeEvent : true, // trigger 'resize' event on headers
82 stickyHeaders_includeCaption : true, // if false and a caption exist, it won't be included in the sticky header
83 stickyHeaders_zIndex : 2 // The zIndex of the stickyHeaders, allows the user to adjust this to their needs
84 },
85 format: function(table, c, wo) {
86 // filter widget doesn't initialize on an empty table. Fixes #449
87 if ( c.$table.hasClass('hasStickyHeaders') || ($.inArray('filter', c.widgets) >= 0 && !c.$table.hasClass('hasFilters')) ) {
88 return;
89 }
90 var index, len, $t,
91 $table = c.$table,
92 // add position: relative to attach element, hopefully it won't cause trouble.
93 $attach = $(wo.stickyHeaders_attachTo || wo.stickyHeaders_appendTo),
94 namespace = c.namespace + 'stickyheaders ',
95 // element to watch for the scroll event
96 $yScroll = $(wo.stickyHeaders_yScroll || wo.stickyHeaders_attachTo || window),
97 $xScroll = $(wo.stickyHeaders_xScroll || wo.stickyHeaders_attachTo || window),
98 $thead = $table.children('thead:first'),
99 $header = $thead.children('tr').not('.sticky-false').children(),
100 $tfoot = $table.children('tfoot'),
101 stickyOffset = getStickyOffset(c, wo),
102 // is this table nested? If so, find parent sticky header wrapper (div, not table)
103 $nestedSticky = $table.parent().closest('.' + ts.css.table).hasClass('hasStickyHeaders') ?
104 $table.parent().closest('table.tablesorter')[0].config.widgetOptions.$sticky.parent() : [],
105 nestedStickyTop = $nestedSticky.length ? $nestedSticky.height() : 0,
106 // clone table, then wrap to make sticky header
107 $stickyTable = wo.$sticky = $table.clone()
108 .addClass('containsStickyHeaders ' + ts.css.sticky + ' ' + wo.stickyHeaders + ' ' + c.namespace.slice(1) + '_extra_table' )
109 .wrap('<div class="' + ts.css.stickyWrap + '">'),
110 $stickyWrap = $stickyTable.parent()
111 .addClass(ts.css.stickyHide)
112 .css({
113 position : $attach.length ? 'absolute' : 'fixed',
114 padding : parseInt( $stickyTable.parent().parent().css('padding-left'), 10 ),
115 top : stickyOffset + nestedStickyTop,
116 left : 0,
117 visibility : 'hidden',
118 zIndex : wo.stickyHeaders_zIndex || 2
119 }),
120 $stickyThead = $stickyTable.children('thead:first'),
121 $stickyCells,
122 laststate = '',
123 setWidth = function($orig, $clone) {
124 var index, width, border, $cell, $this,
125 $cells = $orig.filter(':visible'),
126 len = $cells.length;
127 for ( index = 0; index < len; index++ ) {
128 $cell = $clone.filter(':visible').eq(index);
129 $this = $cells.eq(index);
130 // code from https://github.com/jmosbech/StickyTableHeaders
131 if ($this.css('box-sizing') === 'border-box') {
132 width = $this.outerWidth();
133 } else {
134 if ($cell.css('border-collapse') === 'collapse') {
135 if (window.getComputedStyle) {
136 width = parseFloat( window.getComputedStyle($this[0], null).width );
137 } else {
138 // ie8 only
139 border = parseFloat( $this.css('border-width') );
140 width = $this.outerWidth() - parseFloat( $this.css('padding-left') ) - parseFloat( $this.css('padding-right') ) - border;
141 }
142 } else {
143 width = $this.width();
144 }
145 }
146 $cell.css({
147 'width': width,
148 'min-width': width,
149 'max-width': width
150 });
151 }
152 },
153 getLeftPosition = function(yWindow) {
154 if (yWindow === false && $nestedSticky.length) {
155 return $table.position().left;
156 }
157 return $attach.length ?
158 parseInt($attach.css('padding-left'), 10) || 0 :
159 $table.offset().left - parseInt($table.css('margin-left'), 10) - $(window).scrollLeft();
160 },
161 resizeHeader = function() {
162 $stickyWrap.css({
163 left : getLeftPosition(),
164 width: $table.outerWidth()
165 });
166 setWidth( $table, $stickyTable );
167 setWidth( $header, $stickyCells );
168 },
169 scrollSticky = function( resizing ) {
170 if (!$table.is(':visible')) { return; } // fixes #278
171 // Detect nested tables - fixes #724
172 nestedStickyTop = $nestedSticky.length ? $nestedSticky.offset().top - $yScroll.scrollTop() + $nestedSticky.height() : 0;
173 var tmp,
174 offset = $table.offset(),
175 stickyOffset = getStickyOffset(c, wo),
176 yWindow = $.isWindow( $yScroll[0] ), // $.isWindow needs jQuery 1.4.3
177 yScroll = yWindow ?
178 $yScroll.scrollTop() :
179 // use parent sticky position if nested AND inside of a scrollable element - see #1512
180 $nestedSticky.length ? parseInt($nestedSticky[0].style.top, 10) : $yScroll.offset().top,
181 attachTop = $attach.length ? yScroll : $yScroll.scrollTop(),
182 captionHeight = wo.stickyHeaders_includeCaption ? 0 : $table.children( 'caption' ).height() || 0,
183 scrollTop = attachTop + stickyOffset + nestedStickyTop - captionHeight,
184 tableHeight = $table.height() - ($stickyWrap.height() + ($tfoot.height() || 0)) - captionHeight,
185 isVisible = ( scrollTop > offset.top ) && ( scrollTop < offset.top + tableHeight ) ? 'visible' : 'hidden',
186 state = isVisible === 'visible' ? ts.css.stickyVis : ts.css.stickyHide,
187 needsUpdating = !$stickyWrap.hasClass( state ),
188 cssSettings = { visibility : isVisible };
189 if ($attach.length) {
190 // attached sticky headers always need updating
191 needsUpdating = true;
192 cssSettings.top = yWindow ? scrollTop - $attach.offset().top : $attach.scrollTop();
193 }
194 // adjust when scrolling horizontally - fixes issue #143
195 tmp = getLeftPosition(yWindow);
196 if (tmp !== parseInt($stickyWrap.css('left'), 10)) {
197 needsUpdating = true;
198 cssSettings.left = tmp;
199 }
200 cssSettings.top = ( cssSettings.top || 0 ) +
201 // If nested AND inside of a scrollable element, only add parent sticky height
202 (!yWindow && $nestedSticky.length ? $nestedSticky.height() : stickyOffset + nestedStickyTop);
203 if (needsUpdating) {
204 $stickyWrap
205 .removeClass( ts.css.stickyVis + ' ' + ts.css.stickyHide )
206 .addClass( state )
207 .css(cssSettings);
208 }
209 if (isVisible !== laststate || resizing) {
210 // make sure the column widths match
211 resizeHeader();
212 laststate = isVisible;
213 }
214 };
215 // only add a position relative if a position isn't already defined
216 if ($attach.length && !$attach.css('position')) {
217 $attach.css('position', 'relative');
218 }
219 // fix clone ID, if it exists - fixes #271
220 if ($stickyTable.attr('id')) { $stickyTable[0].id += wo.stickyHeaders_cloneId; }
221 // clear out cloned table, except for sticky header
222 // include caption & filter row (fixes #126 & #249) - don't remove cells to get correct cell indexing
223 $stickyTable.find('> thead:gt(0), tr.sticky-false').hide();
224 $stickyTable.find('> tbody, > tfoot').remove();
225 $stickyTable.find('caption').toggle(wo.stickyHeaders_includeCaption);
226 // issue #172 - find td/th in sticky header
227 $stickyCells = $stickyThead.children().children();
228 $stickyTable.css({ height:0, width:0, margin: 0 });
229 // remove resizable block
230 $stickyCells.find('.' + ts.css.resizer).remove();
231 // update sticky header class names to match real header after sorting
232 $table
233 .addClass('hasStickyHeaders')
234 .bind('pagerComplete' + namespace, function() {
235 resizeHeader();
236 });
237
238 ts.bindEvents(table, $stickyThead.children().children('.' + ts.css.header));
239
240 if (wo.stickyHeaders_appendTo) {
241 $(wo.stickyHeaders_appendTo).append( $stickyWrap );
242 } else {
243 // add stickyheaders AFTER the table. If the table is selected by ID, the original one (first) will be returned.
244 $table.after( $stickyWrap );
245 }
246
247 // onRenderHeader is defined, we need to do something about it (fixes #641)
248 if (c.onRenderHeader) {
249 $t = $stickyThead.children('tr').children();
250 len = $t.length;
251 for ( index = 0; index < len; index++ ) {
252 // send second parameter
253 c.onRenderHeader.apply( $t.eq( index ), [ index, c, $stickyTable ] );
254 }
255 }
256 // make it sticky!
257 $xScroll.add($yScroll)
258 .unbind( ('scroll resize '.split(' ').join( namespace )).replace(/\s+/g, ' ') )
259 .bind('scroll resize '.split(' ').join( namespace ), function( event ) {
260 scrollSticky( event.type === 'resize' );
261 });
262 c.$table
263 .unbind('stickyHeadersUpdate' + namespace)
264 .bind('stickyHeadersUpdate' + namespace, function() {
265 scrollSticky( true );
266 });
267
268 if (wo.stickyHeaders_addResizeEvent) {
269 ts.addHeaderResizeEvent(table);
270 }
271
272 // look for filter widget
273 if ($table.hasClass('hasFilters') && wo.filter_columnFilters) {
274 // scroll table into view after filtering, if sticky header is active - #482
275 $table.bind('filterEnd' + namespace, function() {
276 // $(':focus') needs jQuery 1.6+
277 var $td = $(document.activeElement).closest('td'),
278 column = $td.parent().children().index($td);
279 // only scroll if sticky header is active
280 if ($stickyWrap.hasClass(ts.css.stickyVis) && wo.stickyHeaders_filteredToTop) {
281 // scroll to original table (not sticky clone)
282 window.scrollTo(0, $table.position().top);
283 // give same input/select focus; check if c.$filters exists; fixes #594
284 if (column >= 0 && c.$filters) {
285 c.$filters.eq(column).find('a, select, input').filter(':visible').focus();
286 }
287 }
288 });
289 ts.filter.bindSearch( $table, $stickyCells.find('.' + ts.css.filter) );
290 // support hideFilters
291 if (wo.filter_hideFilters) {
292 ts.filter.hideFilters(c, $stickyTable);
293 }
294 }
295
296 // resize table (Firefox)
297 if (wo.stickyHeaders_addResizeEvent) {
298 $table.bind('resize' + c.namespace + 'stickyheaders', function() {
299 resizeHeader();
300 });
301 }
302
303 // make sure sticky is visible if page is partially scrolled
304 scrollSticky( true );
305 $table.triggerHandler('stickyHeadersInit');
306
307 },
308 remove: function(table, c, wo) {
309 var namespace = c.namespace + 'stickyheaders ';
310 c.$table
311 .removeClass('hasStickyHeaders')
312 .unbind( ('pagerComplete resize filterEnd stickyHeadersUpdate '.split(' ').join(namespace)).replace(/\s+/g, ' ') )
313 .next('.' + ts.css.stickyWrap).remove();
314 if (wo.$sticky && wo.$sticky.length) { wo.$sticky.remove(); } // remove cloned table
315 $(window)
316 .add(wo.stickyHeaders_xScroll)
317 .add(wo.stickyHeaders_yScroll)
318 .add(wo.stickyHeaders_attachTo)
319 .unbind( ('scroll resize '.split(' ').join(namespace)).replace(/\s+/g, ' ') );
320 ts.addHeaderResizeEvent(table, true);
321 }
322 });
323
324 })(jQuery, window);