CoolFace
Datasetpublic

gradio/frontend

sourceHugging Faceupdated 9h agoView on Hugging Face
1likes413kdownloads
sort_utils.ts92 linesDownload Raw Back to utils
1import type { Headers, CellValue } from "../types";2import { sort_table_data } from "./table_utils";3 4export type SortDirection = "asc" | "desc";5 6export function get_sort_status(7	name: string,8	sort_columns: { col: number; direction: SortDirection }[],9	headers: Headers10): "none" | "asc" | "desc" {11	if (!sort_columns.length) return "none";12 13	const sort_item = sort_columns.find((item) => {14		const col = item.col;15		if (col < 0 || col >= headers.length) return false;16		return headers[col] === name;17	});18 19	if (!sort_item) return "none";20	return sort_item.direction;21}22 23export function sort_data(24	data: { id: string; value: CellValue }[][],25	sort_columns: { col: number; direction: SortDirection }[]26): number[] {27	if (!data || !data.length || !data[0]) {28		return [];29	}30 31	if (sort_columns.length > 0) {32		const row_indices = [...Array(data.length)].map((_, i) => i);33		row_indices.sort((row_a_idx, row_b_idx) => {34			const row_a = data[row_a_idx];35			const row_b = data[row_b_idx];36 37			for (const { col: sort_by, direction } of sort_columns) {38				if (39					!row_a ||40					!row_b ||41					sort_by < 0 ||42					sort_by >= row_a.length ||43					sort_by >= row_b.length ||44					!row_a[sort_by] ||45					!row_b[sort_by]46				) {47					continue;48				}49 50				const val_a = row_a[sort_by].value;51				const val_b = row_b[sort_by].value;52				const comparison = val_a < val_b ? -1 : val_a > val_b ? 1 : 0;53 54				if (comparison !== 0) {55					return direction === "asc" ? comparison : -comparison;56				}57			}58 59			return 0;60		});61		return row_indices;62	}63	return [...Array(data.length)].map((_, i) => i);64}65 66export function sort_data_and_preserve_selection(67	data: { id: string; value: CellValue }[][],68	display_value: string[][] | null,69	styling: string[][] | null,70	sort_columns: { col: number; direction: SortDirection }[],71	selected: [number, number] | false,72	get_current_indices: (73		id: string,74		data: { id: string; value: CellValue }[][]75	) => [number, number]76): { data: typeof data; selected: [number, number] | false } {77	let id = null;78	if (selected && selected[0] in data && selected[1] in data[selected[0]]) {79		id = data[selected[0]][selected[1]].id;80	}81 82	sort_table_data(data, display_value, styling, sort_columns);83 84	let new_selected = selected;85	if (id) {86		const [i, j] = get_current_indices(id, data);87		new_selected = [i, j];88	}89 90	return { data, selected: new_selected };91}92 
gradio/frontend · CoolFace