Skip to content

Instantly share code, notes, and snippets.

@mdchaney
Created August 3, 2024 19:28
Show Gist options
  • Save mdchaney/51b7b87683911a00e78654ec8a482d29 to your computer and use it in GitHub Desktop.
Save mdchaney/51b7b87683911a00e78654ec8a482d29 to your computer and use it in GitHub Desktop.
import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="table-sortable-headers"
export default class extends Controller {
static targets = [ "sortingHeader", "sortableRow", "sortableTbody" ];
static values = {
sortColumn: { type: String, default: "" },
sortDirection: { type: String, default: "" }
};
connect() {
}
resort() {
if (this.sortColumnValue == event.target.dataset.column) {
this.sortDirectionValue = this.sortDirectionValue == "asc" ? "desc" : "asc";
} else {
this.sortColumnValue = event.target.dataset.column;
this.sortDirectionValue = "asc";
}
let trs = this.sortableRowTargets.map((tr) => {
let td = tr.querySelector(`td[data-name="${this.sortColumnValue}"]`);
return [td.dataset.value, tr.dataset.rowNumber, tr];
})
const sort_direction = this.sortDirectionValue;
trs.sort(function(a,b) {
if (sort_direction == 'asc') {
if (a[0] < b[0]) {
return -1;
} else if (a[0] == b[0]) {
// primary key equal, sort by row number
return a[1] - b[1];
} else {
return 1;
}
} else {
if (a[0] < b[0]) {
return 1;
} else if (a[0] == b[0]) {
// primary key equal, sort by row number
return b[1] - a[1];
} else {
return -1;
}
}
});
let row_number = 0;
const tbody = this.sortableTbodyTarget;
trs.forEach(function(tr_arr) {
tr_arr[1] = row_number;
let tr = tr_arr[2];
tr.dataset['rowNumber'] = row_number;
tbody.appendChild(tr);
row_number++;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment