import Pipelined from "../interface/Pipelined"; import PopupButton from "../helpers/PopupButton"; export default class SortBy implements Pipelined { protected sortByColumn: null | string = null; protected isDescending: boolean = false; render( options: Array, onClick: Function, buttonStyle = { background: "transparent", color: "#000", border: "1px solid #323232", }, popupStyle = { background: "white", color: "#000", border: "1px solid #323232", } ) { let { button, toggleVisibility, placeholder, div } = PopupButton( buttonStyle, popupStyle ); let descendingIcon = ``; let ascendingIcon = ``; placeholder.innerHTML = `${this.isDescending ? descendingIcon : ascendingIcon } Sort By: ${this.sortByColumn ?? "None"}`; options.forEach((option, i) => { let btn = document.createElement("button"); btn.innerText = option; btn.className = "px-8 py-3 hover:opacity-80"; btn.addEventListener("click", (e) => { e.stopPropagation(); e.preventDefault(); toggleVisibility(); onClick(option, i); placeholder.innerHTML = `${this.isDescending ? descendingIcon : ascendingIcon } Sort By: ${this.sortByColumn ?? "None"}`; }); if (i !== options.length - 1) { btn.classList.add("border-b"); } div.appendChild(btn); }); return button; } column(name: string) { this.isDescending = name === this.sortByColumn ? !this.isDescending : false; this.sortByColumn = name; return this; } handle(data: Array | object): Array | object { if (!this.sortByColumn) { return data; } let order = this.isDescending ? -1 : 1; let orderFn = (itemA: object, itemB: object) => itemA[this.sortByColumn!] >= itemB[this.sortByColumn!] ? order : -1 * order; if (data instanceof Array) { return data.sort(orderFn); } Object.keys(data).forEach((key) => { let values = data[key]; if (!values.sort) { return; } data[key] = this.handle(values); }); return data; } toQuery() { return ""; } }