Skip to content

Commit

Permalink
Merge pull request #181 from harimohanraj89/column-keys
Browse files Browse the repository at this point in the history
Sort by column keys
  • Loading branch information
tristen committed Jan 23, 2020
2 parents 3f9153b + 4d99f99 commit c381b5b
Show file tree
Hide file tree
Showing 10 changed files with 149 additions and 23 deletions.
78 changes: 70 additions & 8 deletions demo/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ layout: default

<script>
new Tablesort(document.getElementById('table-id'));
</script>{% endhighlight %}
</script>{% endhighlight %}

## Sort types

Expand All @@ -26,7 +26,7 @@ You can pass an alternate sort order as a second parameter. By default sort is a
{% highlight js %}new Tablesort(document.getElementById('table-id'), {
descending: true
});
{% endhighlight %}
{% endhighlight %}

<div class='notice'>**Note:** If you are using the default CSS provided you'll need to reverse the class names that style the arrows.</div>

Expand All @@ -43,7 +43,7 @@ For columns or rows that do not require sorting, you can add attribute `data-sor
<td>Radishes</td>
<td>$0.63</td>
</tr>
{% endhighlight %}
{% endhighlight %}

### Override data that is sorted on

Expand All @@ -57,7 +57,7 @@ Sometimes text inside cells is not normalized. Using a `data-sort` attribute you
<td>2</td>
<td data-sort='1078673085'>3/7/2004 @ 9:24:45 EST</td>
</tr>
{% endhighlight %}
{% endhighlight %}

### Specify the sort method for a column

Expand All @@ -81,7 +81,7 @@ By adding a `data-sort-method` attribute to a table heading you can force Tables
</tr>
</tbody>
</table>
{% endhighlight %}
{% endhighlight %}

### Specify which table heading row enables sorting

Expand Down Expand Up @@ -115,7 +115,7 @@ table.addEventListener('beforeSort', function() {
table.addEventListener('afterSort', function() {
alert('Table sorted!');
});
{% endhighlight %}
{% endhighlight %}

<table id='event-table' class='sort'>
<thead>
Expand Down Expand Up @@ -149,7 +149,7 @@ var sort = new Tablesort(table);

// Make some Ajax request to fetch new data and on success:
sort.refresh();
{% endhighlight %}
{% endhighlight %}

<table id='refresh-table' class='sort'>
<thead>
Expand Down Expand Up @@ -180,7 +180,7 @@ sort.refresh();
It is possible to automatically sort the table once you create a Tablesort instance by adding `data-sort-default` attribute.

{% highlight html %}<th data-sort-default>Born</th>
{% endhighlight %}
{% endhighlight %}

<table id='defaulting' class='sort'>
<thead>
Expand All @@ -205,6 +205,67 @@ It is possible to automatically sort the table once you create a Tablesort insta
</tbody>
</table>

### Sorting by column keys

Sometimes, tables can have more complex column structures, especially when using colspans. In these cases, you can
explicitly connect a header to the cells in each row that it should sort by, by using the `data-sort-column-key`
attribute.

This example sorts products by price, even though the prices are not in the same column as their header.

{% highlight html %}<table class='sort'>
<thead>
<tr>
<th >Product</th>
<th colspan="2" data-sort-column-key="price">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apples</td>
<td>Sale!</td>
<td>20</td>
</tr>
<tr>
<td>Bread</td>
<td>Out of stock</td>
<td>10</td>
</tr>
<tr>
<td>Radishes</td>
<td>In Stock!</td>
<td>30</td>
</tr>
</tbody>
</table>
{% endhighlight %}

<table id='column-keys' class='sort'>
<thead>
<tr>
<th>Product</th>
<th colspan="2" data-sort-column-key="price">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apples</td>
<td>Sale!</td>
<td data-sort-column-key="price">20</td>
</tr>
<tr>
<td>Bread</td>
<td>Out of stock</td>
<td data-sort-column-key="price">10</td>
</tr>
<tr>
<td>Radishes</td>
<td>In Stock!</td>
<td data-sort-column-key="price">30</td>
</tr>
</tbody>
</table>

## CSS styling

Add the styling from [tablesort.css](../tablesort.css) file to your CSS or roll with your own.
Expand All @@ -219,6 +280,7 @@ MIT

<script>
new Tablesort(document.getElementById('defaulting'));
new Tablesort(document.getElementById('column-keys'));

var events = document.getElementById('event-table')
new Tablesort(events);
Expand Down
4 changes: 2 additions & 2 deletions dist/sorts/tablesort.date.min.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*!
* tablesort v5.1.0 (2018-09-14)
* tablesort v5.1.0 (2020-01-22)
* http://tristen.ca/tablesort/demo/
* Copyright (c) 2018 ; Licensed MIT
* Copyright (c) 2020 ; Licensed MIT
*/
!function(){var a=function(a){return a=a.replace(/\-/g,"/"),a=a.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2,4})/,"$3-$2-$1"),new Date(a).getTime()||-1};Tablesort.extend("date",function(b){return(-1!==b.search(/(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\.?\,?\s*/i)||-1!==b.search(/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/)||-1!==b.search(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i))&&!isNaN(a(b))},function(b,c){return b=b.toLowerCase(),c=c.toLowerCase(),a(c)-a(b)})}();
4 changes: 2 additions & 2 deletions dist/sorts/tablesort.dotsep.min.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*!
* tablesort v5.1.0 (2018-09-14)
* tablesort v5.1.0 (2020-01-22)
* http://tristen.ca/tablesort/demo/
* Copyright (c) 2018 ; Licensed MIT
* Copyright (c) 2020 ; Licensed MIT
*/
Tablesort.extend("dotsep",function(a){return/^(\d+\.)+\d+$/.test(a)},function(a,b){a=a.split("."),b=b.split(".");for(var c,d,e=0,f=a.length;e<f;e++)if(c=parseInt(a[e],10),d=parseInt(b[e],10),c!==d){if(c>d)return-1;if(c<d)return 1}return 0});
4 changes: 2 additions & 2 deletions dist/sorts/tablesort.filesize.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions dist/sorts/tablesort.monthname.min.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*!
* tablesort v5.1.0 (2018-09-14)
* tablesort v5.1.0 (2020-01-22)
* http://tristen.ca/tablesort/demo/
* Copyright (c) 2018 ; Licensed MIT
* Copyright (c) 2020 ; Licensed MIT
*/
!function(){Tablesort.extend("monthname",function(a){return-1!==a.search(/(January|February|March|April|May|June|July|August|September|October|November|December)/i)},function(a,b){var c=["January","February","March","April","May","June","July","August","September","October","November","December"];return c.indexOf(b)-c.indexOf(a)})}();
4 changes: 2 additions & 2 deletions dist/sorts/tablesort.number.min.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/*!
* tablesort v5.1.0 (2018-09-14)
* tablesort v5.1.0 (2020-01-22)
* http://tristen.ca/tablesort/demo/
* Copyright (c) 2018 ; Licensed MIT
* Copyright (c) 2020 ; Licensed MIT
*/
!function(){var a=function(a){return a.replace(/[^\-?0-9.]/g,"")},b=function(a,b){return a=parseFloat(a),b=parseFloat(b),a=isNaN(a)?0:a,b=isNaN(b)?0:b,a-b};Tablesort.extend("number",function(a){return a.match(/^[-+]?[£\x24Û¢´€]?\d+\s*([,\.]\d{0,2})/)||a.match(/^[-+]?\d+\s*([,\.]\d{0,2})?[£\x24Û¢´€]/)||a.match(/^[-+]?(\d)*-?([,\.]){0,1}-?(\d)+([E,e][\-+][\d]+)?%?$/)},function(c,d){return c=a(c),d=a(d),b(d,c)})}();
6 changes: 3 additions & 3 deletions dist/tablesort.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 25 additions & 2 deletions src/tablesort.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@
return -1;
};

var getCellByKey = function(cells, key) {
return [].slice.call(cells).find(function(cell) {
return cell.getAttribute('data-sort-column-key') === key;
});
};

// Stable sort function
// If two elements are equal under the original sort function,
// then there relative order is reversed
Expand Down Expand Up @@ -129,6 +135,7 @@

sortTable: function(header, update) {
var that = this,
columnKey = header.getAttribute('data-sort-column-key'),
column = header.cellIndex,
sortFunction = caseInsensitiveSort,
item = '',
Expand Down Expand Up @@ -156,8 +163,17 @@

// If we force a sort method, it is not necessary to check rows
if (!sortMethod) {
var cell;
while (items.length < 3 && i < that.table.tBodies[0].rows.length) {
item = getInnerText(that.table.tBodies[0].rows[i].cells[column]);
if(columnKey) {
cell = getCellByKey(that.table.tBodies[0].rows[i].cells, columnKey);
} else {
cell = that.table.tBodies[0].rows[i].cells[column];
}

// Treat missing cells as empty cells
item = cell ? getInnerText(cell) : "";

item = item.trim();

if (item.length > 0) {
Expand Down Expand Up @@ -196,16 +212,23 @@
if (that.table.tBodies[i].rows.length < 2) continue;

for (j = 0; j < that.table.tBodies[i].rows.length; j++) {
var cell;

item = that.table.tBodies[i].rows[j];
if (item.getAttribute('data-sort-method') === 'none') {
// keep no-sorts in separate list to be able to insert
// them back at their original position later
noSorts[totalRows] = item;
} else {
if (columnKey) {
cell = getCellByKey(item.cells, columnKey);
} else {
cell = item.cells[that.col];
}
// Save the index for stable sorting
newRows.push({
tr: item,
td: getInnerText(item.cells[that.col]),
td: cell ? getInnerText(cell) : '',
index: totalRows
});
}
Expand Down
28 changes: 28 additions & 0 deletions test/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,32 @@
</tbody>
</table>

<table id="sort-column-keys">
<thead>
<tr>
<th class="sort-header" colspan="2">Column 1</th>
<th >Column 2</th>
<th id="third-header" data-sort-column-key="third">Column 3</th>
</tr>
</thead>
<tbody>
<tr class="no-sort">
<td colspan="3">2</td>
<td data-sort-column-key="third">2</td>
</tr>
<tr>
<td colspan="2">3</td>
<td>3</td>
<td data-sort-column-key="third">3</td>
</tr>
<tr>
<td colspan="2">1</td>
<td>1</td>
<td data-sort-column-key="third">1</td>
</tr>
</tbody>
</table>

<script src='tape.js'></script>

<script src='../src/tablesort.js'></script>
Expand All @@ -194,13 +220,15 @@
tableMulti = document.getElementById('sort-multi');
tableSortRowSet = document.getElementById('sort-row-set');
tableSortRowAuto = document.getElementById('sort-row-auto');
tableSortColumnKeys = document.getElementById('sort-column-keys');
new Tablesort(table);
new Tablesort(tableDescend, { descending: true });
new Tablesort(tableExclude);
new Tablesort(tableDefault);
new Tablesort(tableMulti);
new Tablesort(tableSortRowSet);
new Tablesort(tableSortRowAuto);
new Tablesort(tableSortColumnKeys);
var refresh = new Tablesort(tableRefresh);

var rowCount = tableRefresh.rows.length;
Expand Down
13 changes: 13 additions & 0 deletions test/spec/tablesort.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,16 @@ tape('sort row is last', function(t) {
t.equal(tableSortRowAuto.querySelector("[role=columnheader]").innerHTML, 'Sort Row');
t.end();
});

tape('sorts with column keys', function(t) {
console.log(tableSortColumnKeys.rows[0].cells[0].innerHTML);
var el = tableSortColumnKeys.querySelector('th:nth-child(2)');
var event = document.createEvent('HTMLEvents');

event.initEvent('click', true, false);
el.dispatchEvent(event);

t.equal(tableSortColumnKeys.rows[1].cells[1].innerHTML, '1', 'was 1');
t.equal(tableSortColumnKeys.rows[2].cells[1].innerHTML, '2', 'was 2');
t.equal(tableSortColumnKeys.rows[3].cells[1].innerHTML, '3', 'was 3');
})

0 comments on commit c381b5b

Please sign in to comment.