/** * How rows order. * * Separate from the table that draws them, because ordering is a fact about * values and not about rendering — and because the two rules below are the * subtle ones, and a rule nothing can exercise is a rule nobody checks. */ /** * The value a column orders on: objective, comparable, and separate from what * the cell draws. A cell renders a badge, an address, a price with a currency * on it; none of those sort. `null` is the reading that does not exist, and it * is deliberately NOT zero — a market with no resting bid is not a market bid * at nothing, and sorting the two together prices a hole. */ export type Rank = string | number | bigint | null /** Direction, spelled as `aria-sort` spells it, so nothing has to translate. */ export type Sense = 'ascending' | 'descending' /** * Missing last, and numbers compared as numbers. * * `bigint` and `number` are both here because chain quantities arrive as * `bigint` and `Number(1n << 64n)` is lossy — `<` compares the two kinds * directly and correctly, where subtracting them would throw. * * Which is also why equality is asked twice. `1n === 1` is false, so a column * that reads a chain and falls back to a cached figure — the pairing the union * is here for — has two values that are the same quantity and not the same * value. Answering "greater" for the pair in both directions is not an * ordering, and a browser handed one shuffles the rows it cannot separate: four * equal values sorted descending came back BDAC. So the second `<` decides * equality where `===` could not. */ export function compare(a: Rank, b: Rank): number { if (a === b) return 0 if (a === null) return 1 if (b === null) return -1 if (typeof a === 'string' || typeof b === 'string') return String(a).localeCompare(String(b)) return a < b ? -1 : b < a ? 1 : 0 } /** * A sorted copy, which is the whole of the sorting this component does. * * Copied, because sorting in place would reorder the caller's array and the * "no default order" promise would last exactly one click. `sort` is stable, so * ties keep the order they arrived in. */ export function order(rows: R[], rank: (row: R) => Rank, sense: Sense): R[] { const way = sense === 'ascending' ? 1 : -1 return [...rows].sort((a, b) => { const x = rank(a) const y = rank(b) // A missing reading sorts last whichever way the column points. Flipping it // would put every hole at the top of a descending column, where it reads as // the largest value in the venue. return x === null || y === null ? compare(x, y) : way * compare(x, y) }) }