All files / src/components/zd-grid data-navigator.ts

100% Statements 35/35
100% Branches 12/12
100% Functions 9/9
100% Lines 34/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74    93x       253x       6x 6x 10x   6x 2x     4x 1x     3x 1x     2x       1x 1x 1x 1x       1x 1x 1x 1x       2x 1x 1x     1x       4x 4x 2x         6x 6x 4x         2x 2x 2x 2x      
import { Direction, IDataNavigator, IGrid, IIterableTable } from './interfaces';
 
export class DataNavigator implements IDataNavigator {
	protected iterable: IGrid & IIterableTable;
 
	constructor(iterable: IGrid & IIterableTable) {
		this.iterable = iterable;
	}
 
	public navigateDatasource(direction: Direction) {
		const { uniqueKey, currentRow } = this.iterable.datasource;
		const data = this.iterable.getData();
		const rowIndex = data.findIndex((row) => row[uniqueKey] === currentRow[uniqueKey]);
 
		if (rowIndex === -1) {
			return this.navigateInitial(direction);
		}
 
		if (direction === 'up' && rowIndex === 0) {
			return this.navigatePageDown();
		}
 
		if (direction === 'down' && rowIndex === data.length - 1) {
			return this.navigatePageUp();
		}
 
		return this.navigateCurrentRow(direction, rowIndex);
	}
 
	private navigateFirst() {
		const data = this.iterable.getData();
		const currentRow = data[0];
		const currentColumn = this.iterable.columns[0];
		this.iterable.selectCell(currentRow, currentColumn);
	}
 
	private navigateLast() {
		const data = this.iterable.getData();
		const currentRow = data[data.length - 1];
		const currentColumn = this.iterable.columns[0];
		this.iterable.selectCell(currentRow, currentColumn);
	}
 
	private navigateInitial(direction: Direction) {
		if (direction === 'up') {
			this.navigateLast();
			return;
		}
 
		this.navigateFirst();
	}
 
	public navigatePageDown() {
		const page = this.iterable.getPage();
		if (page > 1) {
			this.iterable.setPage(page - 1);
		}
	}
 
	public navigatePageUp() {
		const page = this.iterable.getPage();
		if (page < this.iterable.getLastPage()) {
			this.iterable.setPage(page + 1);
		}
	}
 
	private navigateCurrentRow(direction: Direction, rowIndex: number) {
		const addIndex = direction === 'up' ? -1 : 1;
		const data = this.iterable.getData();
		const row = data[rowIndex + addIndex];
		this.iterable.setCurrentRow(row);
	}
}