sort2Hash: add text & saveSort override options. Fixes #962

* Add `sort2Hash_useHeaderText` - use column header text or zero-based index
* Add `sort2Hash_processHeaderText` - extra column header text processing
* Add `sort2Hash_directionText` - sort direction text array
* Add `sort2Hash_overrideSaveSort` - override saveSort stored sort if true
This commit is contained in:
Mottie 2015-07-21 21:33:15 -05:00
parent 7d21962a03
commit 9b6f8fb379
3 changed files with 154 additions and 38 deletions

View File

@ -1,2 +1,2 @@
/*! Widget: sort2Hash */ /*! Widget: sort2Hash - updated 7/21/2015 (v2.22.4) */
!function(a){"use strict";var b=a.tablesorter||{},c={init:function(a,b){var d,e,f,g,h,i=c.getSort(a,b);if(i){for(d=i.split(b.sort2Hash_separator),f=d.length,i=[],e=0;f>e;e++)g=d[e++],h=d[e],"undefined"!=typeof h&&i.push([g,h]);i.length&&(a.sortList=i)}a.$table.on("sortEnd.sort2hash",function(){c.setHash(a,b)})},getTableId:function(b,c){return c.sort2Hash_tableId||b.table.id||"table"+a("table").index(b.$table)},getSort:function(a,b,d){var e=c.getTableId(a,b).replace(/[\[]/,"\\[").replace(/[\]]/,"\\]"),f=new RegExp("[\\#&]"+e+"=([^&]*)").exec(window.location.hash);return null===f?"":(d&&(window.location.hash=window.location.hash.replace("&"+e+"="+f[1],"")),f[1])},setHash:function(a,b){var d=c.getTableId(a,b)+"=",e=a.sortList||[],f=e.length;f&&(c.getSort(a,b,!0),window.location.hash+=(window.location.hash.length?"":b.sort2Hash_hash)+"&"+d+[].concat.apply([],e).join(b.sort2Hash_separator))}};b.addWidget({id:"sort2Hash",options:{sort2Hash_hash:"#",sort2Hash_separator:"-",sort2Hash_tableId:null},init:function(a,b,d,e){c.init(d,e)},remove:function(a,b){b.$table.off("sortEnd.sort2hash")}})}(jQuery); !function(a){"use strict";var b=a.tablesorter||{},c={init:function(a,d){var e=b.hasWidget(a.table,"saveSort"),f=c.getSort(a,d);(f&&!e||f&&e&&d.sort2Hash_overrideSaveSort)&&c.processHash(a,d,f),a.$table.on("sortEnd.sort2hash",function(){c.setHash(a,d)})},getTableId:function(b,c){return c.sort2Hash_tableId||b.table.id||"table"+a("table").index(b.$table)},getSort:function(a,b,d){var e,f=c.getTableId(a,b).replace(/[\[]/,"\\[").replace(/[\]]/,"\\]"),g=new RegExp("[\\#&]"+f+"=([^&]*)").exec(window.location.hash);return null===g?"":(e=c.processSort(a,b,g[1]),d?(window.location.hash=window.location.hash.replace("&"+f+"="+g[1],""),e):g[1])},processHash:function(a,b,c){for(var d,e,f,g,h=decodeURI(c||"").split(b.sort2Hash_separator),i=0,j=h.length,k=[];j>i;)e=h[i++],g=parseInt(e,10),(isNaN(g)||g>a.columns)&&(d=new RegExp("("+e+")","i"),e=a.$headers.filter(function(b,c){return d.test(a.$headers[b].textContent||"")}).attr("data-column")),f=h[i++],"undefined"!=typeof f&&(isNaN(f)&&(f=f.indexOf(b.sort2Hash_directionText[1])>-1?1:0),k.push([e,f]));k.length&&(a.sortList=k)},processSort:function(b,c){var d,e,f,g,h=[],i=b.sortList||[],j=i.length;for(d=0;j>d;d++)f=i[d][0],c.sort2Hash_useHeaderText&&(e=a.trim(b.$headerIndexed[f].text()),"function"==typeof c.sort2Hash_processHeaderText&&(e=c.sort2Hash_processHeaderText(e,config,f)),f=e),h.push(f),g=c.sort2Hash_directionText[i[d][1]],h.push(g);return h.join(c.sort2Hash_separator)},setHash:function(a,b){var d=c.processSort(a,b);d.length&&(c.getSort(a,b,!0),window.location.hash+=(window.location.hash.length?"":b.sort2Hash_hash)+"&"+c.getTableId(a,b)+"="+encodeURI(d))}};b.addWidget({id:"sort2Hash",priority:30,options:{sort2Hash_hash:"#",sort2Hash_separator:"-",sort2Hash_tableId:null,sort2Hash_useHeaderText:!1,sort2Hash_processHeaderText:null,sort2Hash_directionText:[0,1],sort2Hash_overrideSaveSort:!1},init:function(a,b,d,e){c.init(d,e)},remove:function(a,b){b.$table.off("sortEnd.sort2hash")}})}(jQuery);

View File

@ -18,20 +18,29 @@
<!-- Tablesorter: required --> <!-- Tablesorter: required -->
<link rel="stylesheet" href="../css/theme.blue.css"> <link rel="stylesheet" href="../css/theme.blue.css">
<script src="../js/jquery.tablesorter.js"></script> <script src="../js/jquery.tablesorter.js"></script>
<script src="../js/jquery.tablesorter.widgets.js"></script>
<script src="../js/widgets/widget-sort2Hash.js"></script> <script src="../js/widgets/widget-sort2Hash.js"></script>
<script id="js">$(function() { <script id="js">$(function() {
$( 'table' ).tablesorter({ $( 'table' ).tablesorter({
theme: 'blue', theme: 'blue',
widgets: [ 'zebra', 'sort2Hash' ], widgets: [ 'zebra', 'sort2Hash', 'saveSort' ],
widgetOptions : { widgetOptions : {
// hash prefix // hash prefix
sort2Hash_hash : '#', sort2Hash_hash : '#',
// don't '#' or '=' here // don't '#' or '=' here
sort2Hash_separator : ',', sort2Hash_separator : ',',
// this option > table ID > table index on page // this option > table ID > table index on page
sort2Hash_tableId : null sort2Hash_tableId : null,
// if true, show header cell text instead of a zero-based column index
sort2Hash_useHeaderText : false,
// allow processing of text if sort2Hash_useHeaderText: true
sort2Hash_processHeaderText : null, // function( text, config, columnIndex ) {},
// direction text shown in the URL e.g. [ 'asc', 'desc' ]
sort2Hash_directionText : [ 0, 1 ], // default values
// if true, override saveSort widget sort, if used & stored sort is available
sort2Hash_overrideSaveSort : true
} }
}); });
@ -69,7 +78,7 @@
</div> </div>
<table class="tablesorter-blue options"> <table class="tablesorter-blue options">
<thead> <thead>
<tr><th>Option</th><th>Default</th><th>Description</th></tr> <tr><th>Option</th><th>Default</th><th class="sorter-false">Description</th></tr>
</thead> </thead>
<tbody> <tbody>
@ -108,6 +117,64 @@
</td> </td>
</tr> </tr>
<tr id="sort2hash_useheadertext">
<td><a href="#" class="permalink">sort2Hash_useHeaderText</a></td>
<td><code>false</code></td>
<td>
If <code>true</code>, text from the header is used instead of a zero-based column index.
<div class="collapsible">
<br>
Please be aware that if the column text contains spaces or special characters, they will be encoded in the URL. So, <code>"First &#xa3;$&#x20ac;&#x00a4;&#x00a5;&#xa2; Name"</code> will become <code>"First%20%C2%A3$%E2%82%AC%C2%A4%C2%A5%C2%A2%20Name"</code>. This would make the hash very difficult to read.
<p>Further processing of this header cell text can be done using the <code>sort2Hash_processHeaderText</code> function.</p>
</div>
</td>
</tr>
<tr id="sort2hash_processheadertext">
<td><a href="#" class="permalink">sort2Hash_processHeaderText</a></td>
<td><code>null</code></td>
<td>
If the <code>sort2Hash_useHeaderText</code> option is <code>true</code>, a function here will further process the header cell text.
<div class="collapsible">
<br>
Use this function to perform any processing on the header cell text, as desired.
<p>At this point, the header cell text has not been encoded.</p>
<p>Here is one example:</p>
<pre class="prettyprint lang-js">sort2Hash_processHeaderText : function( text, config, columnIndex ) {
// remove all non-alphanumeric characters (including spaces)
return text.replace( /[^a-z0-9]/gi, '' );
}</pre>
Another example:
<pre class="prettyprint lang-js">sort2Hash_processHeaderText : function( text, config, columnIndex ) {
// completely custom text to use for the hash
// this method assumes that the table layout is constant
// (i.e. columns are not added, removed or rearranged)
return [ 'first', 'last', 'age', 'total', 'disc', 'date' ][ columnIndex ];
}</pre>
</div>
</td>
</tr>
<tr id="sort2hash_directiontext">
<td><a href="#" class="permalink">sort2Hash_directionText</a></td>
<td><code>[ 0, 1 ]</code></td>
<td>
Set the direction text shown in the URL.
<div class="collapsible">
<br>
Only the first two values will be used from this array. The first value is assigned to ascending sorts and the second is assigned to descending sorts.
<p>Use the option as follows:</p>
<pre class="prettyprint lang-js">sort2Hash_directionText : [ 'asc', 'desc' ]</pre>
<span class="label warning">*NOTE*</span> When converting the hash into a value, if the direction hash does not match the second value (<code>'desc'</code> in the example above), it will fallback to an ascending sort no matter what text in contained within the first value.
</div>
</td>
</tr>
<tr id="sort2hash_overridesavesort">
<td><span class="permalink">sort2Hash_overrideSaveSort</span></td>
<td><code>false</code></td>
<td>if <code>true</code>, the hash sort will override any stored sort (saveSort widget).</td>
</tr>
</tbody> </tbody>
</table> </table>

View File

@ -1,26 +1,13 @@
/*! Widget: sort2Hash */ /*! Widget: sort2Hash - updated 7/21/2015 (v2.22.4) */
;( function( $ ) { ;( function( $ ) {
'use strict'; 'use strict';
var ts = $.tablesorter || {}, var ts = $.tablesorter || {},
s2h = { s2h = {
init : function( c, wo ) { init : function( c, wo ) {
var arry, indx, len, column, direction, var hasSaveSort = ts.hasWidget( c.table, 'saveSort' ),
sort = s2h.getSort( c, wo ); sort = s2h.getSort( c, wo );
if (sort) { if ( ( sort && !hasSaveSort ) || ( sort && hasSaveSort && wo.sort2Hash_overrideSaveSort ) ) {
arry = sort.split( wo.sort2Hash_separator ); s2h.processHash( c, wo, sort );
len = arry.length;
sort = [];
for ( indx = 0; indx < len; indx++ ) {
column = arry[ indx++ ];
direction = arry[ indx ];
// ignore unpaired values
if ( typeof direction !== 'undefined' ) {
sort.push( [ column, direction ] );
}
}
if ( sort.length ) {
c.sortList = sort;
}
} }
c.$table.on( 'sortEnd.sort2hash', function() { c.$table.on( 'sortEnd.sort2hash', function() {
s2h.setHash( c, wo ); s2h.setHash( c, wo );
@ -34,39 +21,101 @@ s2h = {
}, },
getSort : function( c, wo, clean ) { getSort : function( c, wo, clean ) {
// modified original code from http://www.netlobo.com/url_query_string_javascript.html // modified original code from http://www.netlobo.com/url_query_string_javascript.html
var name = s2h.getTableId( c, wo ).replace( /[\[]/, '\\[' ).replace( /[\]]/, '\\]' ), var value,
name = s2h.getTableId( c, wo ).replace( /[\[]/, '\\[' ).replace( /[\]]/, '\\]' ),
sort = ( new RegExp( '[\\#&]' + name + '=([^&]*)' ) ).exec( window.location.hash ); sort = ( new RegExp( '[\\#&]' + name + '=([^&]*)' ) ).exec( window.location.hash );
if ( sort === null ) { if ( sort === null ) {
return ''; return '';
} else { } else {
value = s2h.processSort( c, wo, sort[ 1 ] );
if ( clean ) { if ( clean ) {
window.location.hash = window.location.hash.replace( '&' + name + '=' + sort[ 1 ], '' ); window.location.hash = window.location.hash.replace( '&' + name + '=' + sort[ 1 ], '' );
return value;
} }
return sort[ 1 ]; return sort[ 1 ];
} }
}, },
// convert 'first%20name,asc,last%20name,desc' into [[0,0], [1,1]]
processHash : function( c, wo, sortHash ) {
var regex, column, direction, temp,
arry = decodeURI( sortHash || '' ).split( wo.sort2Hash_separator ),
indx = 0,
len = arry.length,
sort = [];
while ( indx < len ) {
// column index or text
column = arry[ indx++ ];
temp = parseInt( column, 10 );
// ignore wo.sort2Hash_useHeaderText setting &
// just see if column contains a number
if ( isNaN( temp ) || temp > c.columns ) {
regex = new RegExp( '(' + column + ')', 'i' );
column = c.$headers.filter( function( index, cell ) {
return regex.test( c.$headers[ index ].textContent || '' );
}).attr( 'data-column' );
}
direction = arry[ indx++ ];
// ignore unpaired values
if ( typeof direction !== 'undefined' ) {
// convert text to 0, 1
if ( isNaN( direction ) ) {
// default to ascending sort
direction = direction.indexOf( wo.sort2Hash_directionText[ 1 ] ) > -1 ? 1 : 0;
}
sort.push( [ column, direction ] );
}
}
if ( sort.length ) {
c.sortList = sort;
}
},
// convert [[0,0],[1,1]] to 'first%20name,asc,last%20name,desc'
processSort : function( c, wo ) {
var index, txt, column, direction,
sort = [],
arry = c.sortList || [],
len = arry.length;
for ( index = 0; index < len; index++ ) {
column = arry[ index ][ 0 ];
if ( wo.sort2Hash_useHeaderText ) {
txt = $.trim( c.$headerIndexed[ column ].text() );
if ( typeof wo.sort2Hash_processHeaderText === 'function' ) {
txt = wo.sort2Hash_processHeaderText( txt, config, column );
}
column = txt;
}
sort.push( column );
direction = wo.sort2Hash_directionText[ arry[ index ][ 1 ] ];
sort.push( direction );
}
// join with separator
return sort.join( wo.sort2Hash_separator );
},
setHash : function( c, wo ) { setHash : function( c, wo ) {
var hash, indx, var arry = [],
arry = [], sort = s2h.processSort( c, wo );
tableId = s2h.getTableId( c, wo ) + '=', if ( sort.length ) {
sort = c.sortList || [], // remove old hash
len = sort.length; s2h.getSort( c, wo, true );
if ( len ) {
s2h.getSort( c, wo, true ); // remove hash
window.location.hash += ( window.location.hash.length ? '' : wo.sort2Hash_hash ) + window.location.hash += ( window.location.hash.length ? '' : wo.sort2Hash_hash ) +
'&' + tableId + '&' + s2h.getTableId( c, wo ) + '=' + encodeURI( sort );
// flatten array, then join with separator
[].concat.apply( [], sort ).join( wo.sort2Hash_separator );
} }
} }
}; };
ts.addWidget({ ts.addWidget({
id: 'sort2Hash', id: 'sort2Hash',
priority: 30, // after saveSort
options: { options: {
sort2Hash_hash : '#', // hash prefix sort2Hash_hash : '#', // hash prefix
sort2Hash_separator : '-', // don't '#' or '=' here sort2Hash_separator : '-', // don't '#' or '=' here
sort2Hash_tableId : null // this option > table ID > table index on page sort2Hash_tableId : null, // this option > table ID > table index on page,
sort2Hash_useHeaderText : false, // use column header text (true) or zero-based column index
sort2Hash_processHeaderText : null, // function( text, config, columnIndex ) {},
sort2Hash_directionText : [ 0, 1 ], // [ 'asc', 'desc' ],
sort2Hash_overrideSaveSort : false, // if true, override saveSort widget if saved sort available
}, },
init: function(table, thisWidget, c, wo) { init: function(table, thisWidget, c, wo) {
s2h.init( c, wo ); s2h.init( c, wo );