Debian Codegraph @

frontend/src/sort/index.ts

raw
1 /**
2 * Sorting of tables and the journal.
3 *
4 * Only clicking on headers that have a data-sort attribute will have an
5 * effect. The currently supported values for `data-sort` are:
6 *
7 * - 'string': Case-insensitive string comparison.
8 * - 'num': Clean and parse to float.
9 *
10 * For the tables that are rendered in Svelte components, the logic necessary
11 * for sorting is also provided here (SortColumn and Sorter)
12 */
13
14 import { permute } from "d3-array";
15 import { get as store_get } from "svelte/store";
16
17 import { journalSortOrder } from "../stores/journal";
18
19 type SortOrder = "asc" | "desc";
20 type SortDirection = 1 | -1;
21
22 export const get_direction = (o: SortOrder): SortDirection =>
23 o === "asc" ? 1 : -1;
24
25 const collator = Intl.Collator();
26 /** A compare function for strings using the default browser locale. */
27 const compare_strings = collator.compare.bind(collator);
28
29 /**
30 * A column that can be used for sorting in some data.
31 *
32 * The data is simply an array of values, and this specifies a getter to be used
33 * to sort by this column. On sorting, this getter will be invoked once per element.
34 */
35 export interface SortColumn<T = unknown> {
36 /** The name of this column, usually to be used as a header in the table. */
37 readonly name: string;
38
39 /** Sort the data in the given direction. */
40 sort(data: readonly T[], direction: SortDirection): readonly T[];
41 }
42
43 /** A sorter of tabular data, is specified by a SortColumn and an order to sort by. */
44 export class Sorter<T = unknown> {
45 constructor(
46 readonly column: SortColumn<T>,
47 readonly order: SortOrder,
48 ) {}
49
50 /** Get a new sorter by switching to a possibly different column. */
51 switchColumn(column: SortColumn<T>): Sorter<T> {
52 if (column === this.column) {
53 return new Sorter(column, this.order === "asc" ? "desc" : "asc");
54 }
55 return new Sorter(column, "asc");
56 }
57
58 /** Sort the data. */
59 sort(data: readonly T[]): readonly T[] {
60 return this.column.sort(data, get_direction(this.order));
61 }
62 }
63
64 /**
65 * Sort array with provided string value getter.
66 */
67 export function sort_by_strings<T>(
68 data: readonly T[],
69 value: (v: T) => string,
70 ): T[] {
71 return sort_internal(data, value, compare_strings, 1);
72 }
73
74 /**
75 * Sort array with provided value getter and compare function.
76 * Calls the value getter only once per element.
77 */
78 function sort_internal<T, U>(
79 data: readonly T[],
80 value: (row: T) => U,
81 compare: (a: U, b: U) => number,
82 direction: SortDirection,
83 ): T[] {
84 const indices = Uint32Array.from(data, (_d, i) => i);
85 const values = data.map(value);
86 // values and indices are of the same length (as data), so this is safe
87 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
88 indices.sort((a, b) => direction * compare(values[a]!, values[b]!));
89 return permute(data, indices);
90 }
91
92 /** A SortColumn that does no sorting. */
93 export class UnsortedColumn<T> implements SortColumn<T> {
94 constructor(readonly name: string) {}
95
96 sort(data: readonly T[]): readonly T[] {
97 return data;
98 }
99 }
100
101 /** A SortColumn for numbers. */
102 export class NumberColumn<T> implements SortColumn<T> {
103 private compare = (a: number, b: number): number => a - b;
104
105 constructor(
106 readonly name: string,
107 private readonly value: (row: Readonly<T>) => number,
108 ) {}
109
110 sort(data: readonly T[], direction: SortDirection): readonly T[] {
111 return sort_internal(data, this.value, this.compare, direction);
112 }
113 }
114 /** A SortColumn for objects with a string date property. */
115 export class DateColumn<T extends { date: string }> extends NumberColumn<T> {
116 constructor(readonly name: string) {
117 super(name, (d: T) => new Date(d.date).valueOf());
118 }
119 }
120 /** A SortColumn for strings. */
121 export class StringColumn<T> implements SortColumn<T> {
122 private compare = compare_strings;
123
124 constructor(
125 readonly name: string,
126 private readonly value: (row: Readonly<T>) => string,
127 ) {}
128
129 sort(data: readonly T[], direction: 1 | -1): readonly T[] {
130 return sort_internal(data, this.value, this.compare, direction);
131 }
132 }
133
134 /** Parse a number from the string, ignoring all other characters. */
135 function parse_number(num: string): number {
136 const cleaned = num.replace(/[^\-?0-9.]/g, "");
137 const n = parseFloat(cleaned);
138 return Number.isNaN(n) ? 0 : n;
139 }
140
141 /** A function to compare strings which should contain numbers. */
142 function compare_numbers(a: string, b: string): number {
143 return parse_number(a) - parse_number(b);
144 }
145
146 /**
147 * Sort elements contained in a given parent element.
148 * @param parent - The element that the sorted children should be inserted into.
149 * @param elements - The elements to sort (children of parent).
150 * @param selector - Selector for the column that should be sorted by.
151 * @param order - The sort order.
152 * @param type - The type of the value that should be sorted by.
153 */
154 export function sortElements<T extends Element>(
155 parent: Element,
156 elements: T[],
157 selector: (e: T) => Element | null,
158 direction: SortDirection,
159 type: string | null,
160 ): void {
161 const comparator = type === "num" ? compare_numbers : compare_strings;
162 const value = (a: T) => {
163 const el = selector(a);
164 return el?.getAttribute("data-sort-value") ?? el?.textContent ?? "";
165 };
166 const sorted_elements = sort_internal(elements, value, comparator, direction);
167 const fragment = document.createDocumentFragment();
168 sorted_elements.forEach((el) => {
169 fragment.appendChild(el);
170 });
171 parent.appendChild(fragment);
172 }
173
174 /**
175 * Make the Fava journal sortable.
176 * @param ol - the <ol> element.
177 */
178 export function sortableJournal(ol: HTMLOListElement): void {
179 const head = ol.querySelector(".head");
180 if (!head) {
181 throw new Error("Journal is missing header.");
182 }
183 const headers = head.querySelectorAll("span[data-sort]");
184 const [initialColumn, initialOrder] = store_get(journalSortOrder);
185 headers.forEach((header) => {
186 const headerClass = header.classList[0];
187 const name = header.getAttribute("data-sort-name");
188 const type = header.getAttribute("data-sort");
189 if (headerClass == null || name == null || type == null) {
190 throw new Error(`Journal has invalid header: ${header.innerHTML}.`);
191 }
192
193 const sort = (order: SortOrder) => {
194 // update displayed sort order
195 headers.forEach((el) => {
196 el.removeAttribute("data-order");
197 });
198 header.setAttribute("data-order", order);
199 // sort elements
200 sortElements<HTMLLIElement>(
201 ol,
202 [].slice.call(ol.children, 1),
203 (li) => li.querySelector(`.${headerClass}`),
204 get_direction(order),
205 type,
206 );
207 };
208 if (name === initialColumn) {
209 sort(initialOrder);
210 }
211
212 header.addEventListener("click", () => {
213 const order =
214 header.getAttribute("data-order") === "asc" ? "desc" : "asc";
215 sort(order);
216 journalSortOrder.set([name, order]);
217 });
218 });
219 }