tables.sortable.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /*
  2. * tablesaw: A set of plugins for responsive tables
  3. * Sortable column headers
  4. * Copyright (c) 2013 Filament Group, Inc.
  5. * MIT License
  6. */
  7. ;(function( $ ) {
  8. function getSortValue( cell ) {
  9. return $.map( cell.childNodes, function( el ) {
  10. var $el = $( el );
  11. if( $el.is( 'input, select' ) ) {
  12. return $el.val();
  13. } else if( $el.hasClass( 'tablesaw-cell-label' ) ) {
  14. return;
  15. }
  16. return $.trim( $el.text() );
  17. }).join( '' );
  18. }
  19. var pluginName = "tablesaw-sortable",
  20. initSelector = "table[data-" + pluginName + "]",
  21. sortableSwitchSelector = "[data-" + pluginName + "-switch]",
  22. attrs = {
  23. defaultCol: "data-tablesaw-sortable-default-col",
  24. numericCol: "data-tablesaw-sortable-numeric"
  25. },
  26. classes = {
  27. head: pluginName + "-head",
  28. ascend: pluginName + "-ascending",
  29. descend: pluginName + "-descending",
  30. switcher: pluginName + "-switch",
  31. tableToolbar: 'tablesaw-toolbar',
  32. sortButton: pluginName + "-btn"
  33. },
  34. methods = {
  35. _create: function( o ){
  36. return $( this ).each(function() {
  37. var init = $( this ).data( "init" + pluginName );
  38. if( init ) {
  39. return false;
  40. }
  41. $( this )
  42. .data( "init"+ pluginName, true )
  43. .trigger( "beforecreate." + pluginName )
  44. [ pluginName ]( "_init" , o )
  45. .trigger( "create." + pluginName );
  46. });
  47. },
  48. _init: function(){
  49. var el = $( this ),
  50. heads,
  51. $switcher;
  52. var addClassToTable = function(){
  53. el.addClass( pluginName );
  54. },
  55. addClassToHeads = function( h ){
  56. $.each( h , function( i , v ){
  57. $( v ).addClass( classes.head );
  58. });
  59. },
  60. makeHeadsActionable = function( h , fn ){
  61. $.each( h , function( i , v ){
  62. var b = $( "<button class='" + classes.sortButton + "'/>" );
  63. b.bind( "click" , { col: v } , fn );
  64. $( v ).wrapInner( b );
  65. });
  66. },
  67. clearOthers = function( sibs ){
  68. $.each( sibs , function( i , v ){
  69. var col = $( v );
  70. col.removeAttr( attrs.defaultCol );
  71. col.removeClass( classes.ascend );
  72. col.removeClass( classes.descend );
  73. });
  74. },
  75. headsOnAction = function( e ){
  76. if( $( e.target ).is( 'a[href]' ) ) {
  77. return;
  78. }
  79. e.stopPropagation();
  80. var head = $( this ).parent(),
  81. v = e.data.col,
  82. newSortValue = heads.index( head );
  83. clearOthers( head.siblings() );
  84. if( head.hasClass( classes.descend ) ){
  85. el[ pluginName ]( "sortBy" , v , true);
  86. newSortValue += '_asc';
  87. } else {
  88. el[ pluginName ]( "sortBy" , v );
  89. newSortValue += '_desc';
  90. }
  91. if( $switcher ) {
  92. $switcher.find( 'select' ).val( newSortValue ).trigger( 'refresh' );
  93. }
  94. e.preventDefault();
  95. },
  96. handleDefault = function( heads ){
  97. $.each( heads , function( idx , el ){
  98. var $el = $( el );
  99. if( $el.is( "[" + attrs.defaultCol + "]" ) ){
  100. if( !$el.hasClass( classes.descend ) ) {
  101. $el.addClass( classes.ascend );
  102. }
  103. }
  104. });
  105. },
  106. addSwitcher = function( heads ){
  107. $switcher = $( '<div>' ).addClass( classes.switcher ).addClass( classes.tableToolbar ).html(function() {
  108. var html = [ '<label>' + Tablesaw.i18n.sort + ':' ];
  109. html.push( '<span class="btn btn-small">&#160;<select>' );
  110. heads.each(function( j ) {
  111. var $t = $( this );
  112. var isDefaultCol = $t.is( "[" + attrs.defaultCol + "]" );
  113. var isDescending = $t.hasClass( classes.descend );
  114. var hasNumericAttribute = $t.is( '[data-sortable-numeric]' );
  115. var numericCount = 0;
  116. // Check only the first four rows to see if the column is numbers.
  117. var numericCountMax = 5;
  118. $( this.cells ).slice( 0, numericCountMax ).each(function() {
  119. if( !isNaN( parseInt( getSortValue( this ), 10 ) ) ) {
  120. numericCount++;
  121. }
  122. });
  123. var isNumeric = numericCount === numericCountMax;
  124. if( !hasNumericAttribute ) {
  125. $t.attr( "data-sortable-numeric", isNumeric ? "" : "false" );
  126. }
  127. html.push( '<option' + ( isDefaultCol && !isDescending ? ' selected' : '' ) + ' value="' + j + '_asc">' + $t.text() + ' ' + ( isNumeric ? '&#x2191;' : '(A-Z)' ) + '</option>' );
  128. html.push( '<option' + ( isDefaultCol && isDescending ? ' selected' : '' ) + ' value="' + j + '_desc">' + $t.text() + ' ' + ( isNumeric ? '&#x2193;' : '(Z-A)' ) + '</option>' );
  129. });
  130. html.push( '</select></span></label>' );
  131. return html.join('');
  132. });
  133. var $toolbar = el.prev().filter( '.tablesaw-bar' ),
  134. $firstChild = $toolbar.children().eq( 0 );
  135. if( $firstChild.length ) {
  136. $switcher.insertBefore( $firstChild );
  137. } else {
  138. $switcher.appendTo( $toolbar );
  139. }
  140. $switcher.find( '.btn' ).tablesawbtn();
  141. $switcher.find( 'select' ).on( 'change', function() {
  142. var val = $( this ).val().split( '_' ),
  143. head = heads.eq( val[ 0 ] );
  144. clearOthers( head.siblings() );
  145. el[ pluginName ]( 'sortBy', head.get( 0 ), val[ 1 ] === 'asc' );
  146. });
  147. };
  148. addClassToTable();
  149. heads = el.find( "thead th[data-" + pluginName + "-col]" );
  150. addClassToHeads( heads );
  151. makeHeadsActionable( heads , headsOnAction );
  152. handleDefault( heads );
  153. if( el.is( sortableSwitchSelector ) ) {
  154. addSwitcher( heads, el.find('tbody tr:nth-child(-n+3)') );
  155. }
  156. },
  157. getColumnNumber: function( col ){
  158. return $( col ).prevAll().length;
  159. },
  160. getTableRows: function(){
  161. return $( this ).find( "tbody tr" );
  162. },
  163. sortRows: function( rows , colNum , ascending, col ){
  164. var cells, fn, sorted;
  165. var getCells = function( rows ){
  166. var cells = [];
  167. $.each( rows , function( i , r ){
  168. var element = $( r ).children().get( colNum );
  169. cells.push({
  170. element: element,
  171. cell: getSortValue( element ),
  172. rowNum: i
  173. });
  174. });
  175. return cells;
  176. },
  177. getSortFxn = function( ascending, forceNumeric ){
  178. var fn,
  179. regex = /[^\-\+\d\.]/g;
  180. if( ascending ){
  181. fn = function( a , b ){
  182. if( forceNumeric ) {
  183. return parseFloat( a.cell.replace( regex, '' ) ) - parseFloat( b.cell.replace( regex, '' ) );
  184. } else {
  185. return a.cell.toLowerCase() > b.cell.toLowerCase() ? 1 : -1;
  186. }
  187. };
  188. } else {
  189. fn = function( a , b ){
  190. if( forceNumeric ) {
  191. return parseFloat( b.cell.replace( regex, '' ) ) - parseFloat( a.cell.replace( regex, '' ) );
  192. } else {
  193. return a.cell.toLowerCase() < b.cell.toLowerCase() ? 1 : -1;
  194. }
  195. };
  196. }
  197. return fn;
  198. },
  199. applyToRows = function( sorted , rows ){
  200. var newRows = [], i, l, cur;
  201. for( i = 0, l = sorted.length ; i < l ; i++ ){
  202. cur = sorted[ i ].rowNum;
  203. newRows.push( rows[cur] );
  204. }
  205. return newRows;
  206. };
  207. cells = getCells( rows );
  208. var customFn = $( col ).data( 'tablesaw-sort' );
  209. fn = ( customFn && typeof customFn === "function" ? customFn( ascending ) : false ) ||
  210. getSortFxn( ascending, $( col ).is( '[data-sortable-numeric]' ) && !$( col ).is( '[data-sortable-numeric="false"]' ) );
  211. sorted = cells.sort( fn );
  212. rows = applyToRows( sorted , rows );
  213. return rows;
  214. },
  215. replaceTableRows: function( rows ){
  216. var el = $( this ),
  217. body = el.find( "tbody" );
  218. body.html( rows );
  219. },
  220. makeColDefault: function( col , a ){
  221. var c = $( col );
  222. c.attr( attrs.defaultCol , "true" );
  223. if( a ){
  224. c.removeClass( classes.descend );
  225. c.addClass( classes.ascend );
  226. } else {
  227. c.removeClass( classes.ascend );
  228. c.addClass( classes.descend );
  229. }
  230. },
  231. sortBy: function( col , ascending ){
  232. var el = $( this ), colNum, rows;
  233. colNum = el[ pluginName ]( "getColumnNumber" , col );
  234. rows = el[ pluginName ]( "getTableRows" );
  235. rows = el[ pluginName ]( "sortRows" , rows , colNum , ascending, col );
  236. el[ pluginName ]( "replaceTableRows" , rows );
  237. el[ pluginName ]( "makeColDefault" , col , ascending );
  238. }
  239. };
  240. // Collection method.
  241. $.fn[ pluginName ] = function( arrg ) {
  242. var args = Array.prototype.slice.call( arguments , 1),
  243. returnVal;
  244. // if it's a method
  245. if( arrg && typeof( arrg ) === "string" ){
  246. returnVal = $.fn[ pluginName ].prototype[ arrg ].apply( this[0], args );
  247. return (typeof returnVal !== "undefined")? returnVal:$(this);
  248. }
  249. // check init
  250. if( !$( this ).data( pluginName + "data" ) ){
  251. $( this ).data( pluginName + "active", true );
  252. $.fn[ pluginName ].prototype._create.call( this , arrg );
  253. }
  254. return $(this);
  255. };
  256. // add methods
  257. $.extend( $.fn[ pluginName ].prototype, methods );
  258. $( document ).on( "tablesawcreate", function( e, Tablesaw ) {
  259. if( Tablesaw.$table.is( initSelector ) ) {
  260. Tablesaw.$table[ pluginName ]();
  261. }
  262. });
  263. }( jQuery ));