Skip to content

Commit

Permalink
refactor(pix-table): simplify HeaderContext class
Browse files Browse the repository at this point in the history
  • Loading branch information
fael-b committed Dec 6, 2024
1 parent 8e78f54 commit 72ba020
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 26 deletions.
2 changes: 1 addition & 1 deletion addon/components/pix-table.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</thead>
<tbody>
{{this.headerContext.date}}
{{#each this.computedData as |row|}}
{{#each this.sortedData as |row|}}
<tr>
{{yield row this.cellContext to="columns"}}
</tr>
Expand Down
41 changes: 16 additions & 25 deletions addon/components/pix-table.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import Component from '@glimmer/component';
import { warn } from '@ember/debug';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class PixTable extends Component {
headerContext = new HeaderContext({
type: 'header',
toggleSort: this.toggleSort,
});
headerContext = new HeaderContext();

@tracked
computedData = [...this.args.data];
get sortedData() {
if (!this.headerContext.currentSortedColumnId) return this.args.data;
const sortedCopy = [...this.args.data].sort(this.headerContext.sortFun);
if (this.headerContext.sortOrder === 'asc') {
return sortedCopy;
}
return sortedCopy.reverse();
}

get variant() {
const value = this.args.variant ?? 'primary';
Expand Down Expand Up @@ -41,33 +43,22 @@ export default class PixTable extends Component {
type: 'cell',
};
}

@action
toggleSort(id, sortFun) {
this.headerContext.refresh(id);
if (this.headerContext.sortOrder === 'asc') {
this.computedData = this.computedData.sort(sortFun);
return;
}
this.computedData = this.computedData.reverse();
}
}

class HeaderContext {
@tracked sortOrder;
@tracked sortFun;
@tracked currentSortedColumnId;

constructor({ type, toggleSort, sortOrder, currentSortedColumnId }) {
this.type = type;
this.toggleSort = toggleSort;
this.sortOrder = sortOrder;
this.currentSortedColumnId = currentSortedColumnId;
constructor() {
this.type = 'header';
}

refresh(id) {
if (id !== this.currentSortedColumnId) {
toggleSort(columnId, newSortFun) {
if (columnId !== this.currentSortedColumnId) {
this.sortOrder = 'asc';
this.currentSortedColumnId = id;
this.sortFun = newSortFun;
this.currentSortedColumnId = columnId;
} else {
this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
}
Expand Down

0 comments on commit 72ba020

Please sign in to comment.