All files / src/utils/tree-data-structure tree-data-structure.ts

100% Statements 210/210
100% Branches 89/89
100% Functions 43/43
100% Lines 201/201

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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521      95x                           59x         59x         59x         59x   59x               59x 59x 59x 59x         249x       2x   1x             54x 54x 54x 54x     59x             54x 86x 86x   86x 32x 17x 15x 5x       86x 1x 1x     85x 85x 6x   79x     85x                 88x 11x 77x 16x   61x                 61x 61x   61x 257x 257x 126x   257x     61x 61x               316x 316x 255x 255x 255x 255x 255x 255x 255x     316x 255x     316x 255x 255x         54x 67x             16x   16x 13x 13x 13x     16x 16x 16x 2x     16x 41x                 41x 2x     41x     16x   8x     16x 14x   2x     16x             64x 64x 64x 7x 7x 7x     64x 64x 64x                       134x 141x   134x 270x 270x 270x 270x 70x                                         142x           142x 123x 123x 1x   122x   19x 16x   3x                 11x 11x   11x 11x                 3x 3x 2x 2x 2x     3x                 2x 2x 1x 1x 1x     2x                 9x 9x 9x 9x           2x 2x 1x   2x 2x 2x 2x 2x 2x   2x     7x               31x 17x   14x 14x               3x 3x 3x 2x 1x 1x 1x                   3x             17x 17x   70x                 17x 17x             1x 1x 1x 5x   5x 26x 26x 26x     5x 5x 2x 2x 2x 1x 1x         1x             298x 298x 298x 298x 298x 298x 298x               45x 45x 45x 24x 24x   45x                 8x   7x 7x   7x       3x 3x       3x 3x   1x 1x     7x       8x       2x 2x      
import { Datasource, IDictionary } from '@zeedhi/core';
import { ITreeComponent, ITreeDataStructure } from './interfaces';
 
export class TreeDataStructure implements ITreeDataStructure {
	/**
	 * Original datasource
	 */
	private originalDatasource!: Datasource;
 
	/**
	 * Parent field Name
	 */
	private parentField: string;
 
	/**
	 * Defines if the tree will be opened or not (true/false) or if it should open only until a specific level
	 */
	public openLevelOnLoad: number | boolean = false;
 
	/**
	 * Stores tree data
	 */
	public treeData: IDictionary<any>[] = [];
 
	/**
	 * Search returns no data
	 */
	public searchHasNoData = false;
 
	/**
	 * Stores tree structure
	 */
	private treeStructure: any = {};
 
	public fieldHasChild?: string = '';
 
	/**
	 * Tree component
	 */
	private tree!: ITreeComponent;
 
	constructor(tree: ITreeComponent) {
		this.parentField = tree.parentField;
		this.openLevelOnLoad = tree.openLevelOnLoad;
		this.fieldHasChild = tree.fieldHasChild;
		this.tree = tree;
	}
	detach?: boolean | undefined;
 
	get fetchOnDemand() {
		return this.tree.fetchOnDemand || false;
	}
 
	set fetchOnDemand(value: boolean) {
		if (this.tree.fetchOnDemand === undefined) return;
 
		this.tree.fetchOnDemand = value;
	}
 
	/**
	 * Creates properties and methods
	 */
	public initialize() {
		this.originalDatasource = this.tree.datasource;
		const originalGetFunction = this.originalDatasource.get;
		this.originalDatasource.get = this.treeGetData(originalGetFunction);
		(this.originalDatasource as any).reloadAndUpdateSelectedRows = this.reloadAndUpdateSelectedRows.bind(this);
	}
 
	private searchValue = '';
 
	/**
	 * Redefine get method
	 * @param originalGet originalDatasource get function
	 */
	private treeGetData(originalGet: () => Promise<any>) {
		return async () => {
			this.searchValue = this.originalDatasource.search;
			this.searchHasNoData = false;
 
			if (this.fetchOnDemand) {
				if (this.tree.detach || this.originalDatasource.search) {
					delete this.originalDatasource.filter[this.parentField];
				} else if (!this.originalDatasource.filter[this.parentField]) {
					this.originalDatasource.filter[this.parentField] = 'NULL';
				}
			}
 
			if (!this.tree.detach && !this.fetchOnDemand && this.searchValue) {
				this.searchAllData();
				return Promise.resolve(this.originalDatasource.data);
			}
 
			return originalGet.call(this.originalDatasource).then((data: IDictionary<any>[]) => {
				if (this.searchValue) {
					this.buildDetached();
				} else {
					this.buildTree();
				}
 
				return data;
			});
		};
	}
 
	/**
	 * search data
	 */
	public buildTree() {
		if (this.tree.detach) {
			this.buildDetached();
		} else if (this.fetchOnDemand) {
			this.buildOnDemand();
		} else {
			this.buildAllData();
		}
	}
 
	/**
	 * Build tree without fetchOnDemand
	 * @param data datasource data
	 */
	private buildAllData() {
		this.treeData = [];
		this.treeStructure = {};
 
		this.originalDatasource.data.forEach((row) => {
			const parentKey = row[this.parentField] || 'no-parent';
			if (!this.treeStructure[parentKey]) {
				this.treeStructure[parentKey] = [];
			}
			this.treeStructure[parentKey].push({ ...row });
		});
 
		this.buildTreeData();
		this.sortData();
	}
 
	/**
	 * Build tree data using a parent row
	 * @param parentRow Parent row (undefined = build entire tree)
	 */
	private buildTreeData(parentRow: any = undefined) {
		const parentKey = parentRow?.[this.originalDatasource.uniqueKey] || 'no-parent';
		const childrenData = (this.treeStructure[parentKey] || []).map((row: IDictionary<any>) => {
			const level = (parentRow?.tree__level || 0) + 1;
			row.tree__children = [{}];
			row.tree__opened = this.openLevelOnLoad === true || level <= this.openLevelOnLoad;
			row.tree__parent = parentRow;
			row.tree__level = level;
			row.tree__searched = false;
			return row;
		});
 
		if (parentRow) {
			parentRow.tree__children = childrenData;
		}
 
		childrenData.forEach((row: any) => {
			this.treeData.push(row);
			this.buildTreeData(row);
		});
	}
 
	public findDataIndex(data: IDictionary<any>[], value: any) {
		const { uniqueKey } = this.originalDatasource;
		return data.findIndex((item) => item[uniqueKey] === value);
	}
 
	/**
	 * Build tree with fetchOnDemand
	 */
	private buildOnDemand() {
		let parentKey = this.originalDatasource.filter[this.parentField];
 
		if (parentKey === 'NULL') {
			parentKey = 'no-parent';
			this.treeData = [];
			this.treeStructure = {};
		}
 
		const parentIdx = this.findDataIndex(this.treeData, parentKey);
		const parent = parentIdx !== -1 ? this.treeData[parentIdx] : undefined;
		if (parent) {
			parent.tree__children = [];
		}
 
		const childData = this.originalDatasource.data.map((row) => {
			const item = {
				...row,
				tree__children: [{}],
				tree__opened: false,
				tree__searched: false,
				tree__level: parent ? parent.tree__level + 1 : 1,
				tree__parent: parent,
			};
 
			if (parent) {
				parent.tree__children.push(item);
			}
 
			return item;
		});
 
		if (parent) {
			// remove all existing children to add new ones
			this.treeData = this.treeData.filter((item) => item.tree__parent !== parent);
		}
 
		if (!parent) {
			this.treeData = childData;
		} else {
			this.treeData.splice(parentIdx + 1, 0, ...childData);
		}
 
		this.treeStructure[parentKey] = [...childData];
	}
 
	/**
	 * Sort data
	 */
	private sortData() {
		const columns: string[] = [];
		const order: string[] = [];
		this.originalDatasource.order.forEach((value) => {
			const splitted = value.split('.');
			columns.push(splitted[0]);
			order.push(splitted[1]);
		});
 
		this.treeData = [];
		this.originalDatasource.data = [];
		this.sortTreeDataRows(this.treeStructure['no-parent'] || [], columns, order);
	}
 
	/**
	 * Sort tree data rows
	 * @param dataToSort Data to sort
	 * @param columns Columns used to oreder the collection
	 * @param types Order orientation. All values must be asc or desc
	 * @param index Columns and types position
	 * @returns Sorted data
	 */
	private sortTreeDataRows(dataToSort: IDictionary<any>[], columns: string[], types: string[]) {
		const { uniqueKey } = this.originalDatasource;
		const childrenData = dataToSort.sort((row, nextRow) => this.sort(row, nextRow, columns, types));
 
		childrenData.forEach((row) => {
			this.treeData.push(row);
			this.originalDatasource.data.push(this.clearRow(row));
			const key = row[uniqueKey];
			if (this.treeStructure[key]?.length) {
				this.sortTreeDataRows(this.treeStructure[key], columns, types);
			}
		});
	}
 
	/**
	 * Custom sort for collections
	 * @param row Collection row
	 * @param nextRow Next row from collection
	 * @param columns Columns used to oreder the collection
	 * @param types Order orientation. All values must be asc or desc
	 * @param index Columns and types position
	 * @returns Row's position
	 */
	private sort(
		row: IDictionary<any>,
		nextRow: IDictionary<any>,
		columns: string[],
		types: string[],
		index = 0,
	): number {
		const orderTypes: IDictionary<number> = {
			asc: 1,
			desc: -1,
			same: 0,
		};
 
		if (row[columns[index]] === nextRow[columns[index]]) {
			const nextIndex = index + 1;
			if (Object.hasOwn(columns, nextIndex)) {
				return this.sort(row, nextRow, columns, types, nextIndex);
			}
			return orderTypes.same;
		}
		if (row[columns[index]] > nextRow[columns[index]]) {
			return orderTypes[types[index]];
		}
		return orderTypes[types[index]] * -1;
	}
 
	/**
	 * Return if tree element and its parents are opened
	 * @param row datasource row
	 * @returns Element and parents are opened
	 */
	public isOpened(row: IDictionary<any>): boolean {
		const rowData = this.getRowData(row);
		const isSearched = !this.searchValue || rowData.tree__searched;
		const isOpened =
			!rowData.tree__parent || (rowData.tree__parent.tree__opened && this.isOpened(rowData.tree__parent));
		return isSearched && isOpened;
	}
 
	/**
	 * Return previous opened row index
	 * @param rowIdx row index
	 * @returns previous row index
	 */
	public previousOpenedRow(rowIdx: number) {
		let result = -1;
		for (let i = rowIdx - 1; i >= 0; i -= 1) {
			if (this.isOpened(this.treeData[i])) {
				result = i;
				break;
			}
		}
		return result;
	}
 
	/**
	 * Return next opened row index
	 * @param rowIdx row index
	 * @returns next row index
	 */
	public nextOpenedRow(rowIdx: number) {
		let result = -1;
		for (let i = rowIdx + 1; i < this.treeData.length; i += 1) {
			if (this.isOpened(this.treeData[i])) {
				result = i;
				break;
			}
		}
		return result;
	}
 
	/**
	 * Expands or collapses a row
	 * @param row Row object
	 * @param rowIndex Row index
	 */
	public async toggleExpand(row: IDictionary<any>, rowIndex = -1) {
		const { uniqueKey } = this.originalDatasource;
		const rowData = this.getRowData(row);
		rowData.tree__opened = !rowData.tree__opened;
		if (
			rowData.tree__opened &&
			this.fetchOnDemand &&
			rowData.tree__children.length === 1 &&
			!rowData.tree__children[0][uniqueKey]
		) {
			let index = rowIndex;
			if (index === -1) {
				index = this.findDataIndex(this.treeData, row[uniqueKey]);
			}
			const originalData = [...this.originalDatasource.data];
			const data: IDictionary<any>[] = await this.originalDatasource.addFilter(this.parentField, row[uniqueKey]);
			originalData.splice(index + 1, 0, ...data);
			this.originalDatasource.data = originalData;
			this.originalDatasource.currentRow = this.clearRow(row);
			delete this.originalDatasource.filter[this.parentField];
 
			return data;
		}
 
		return undefined;
	}
 
	/**
	 * Return row with tree data
	 * @param row datasource row
	 */
	public getRowData(row: IDictionary<any>) {
		if (row.tree__opened !== undefined) {
			return row;
		}
		const rowIdx = this.findDataIndex(this.treeData, row[this.originalDatasource.uniqueKey]);
		return this.treeData[rowIdx];
	}
 
	/**
	 * Toggle expand/collapse using navigation keys
	 * @param collapse Should collapse
	 */
	public navigateToggle(collapse: boolean) {
		const { currentRow } = this.originalDatasource;
		const rowData = this.getRowData(currentRow);
		if (rowData.tree__opened === collapse && rowData.tree__children.length > 0) {
			this.toggleExpand(rowData);
		} else if (collapse) {
			if (rowData.tree__parent) {
				this.originalDatasource.currentRow = this.clearRow(rowData.tree__parent);
			}
		}
	}
 
	/**
	 * Updates selected rows, fetches and retrieves data collection
	 * @returns Promise with data collection
	 */
	private async reloadAndUpdateSelectedRows() {
		this.sortData();
	}
 
	/**
	 * Arrange treeData in a uniform structure
	 */
	public buildDetached() {
		this.treeData = [];
		this.treeStructure = {};
 
		const childData = this.originalDatasource.data.map((row) => ({
			...row,
			tree__children: [],
			tree__opened: false,
			tree__searched: !!this.searchValue,
			tree__level: 1,
			tree__parent: undefined,
		}));
 
		this.treeData = childData;
		this.treeStructure['no-parent'] = childData;
	}
 
	/**
	 * Search value against a memory datasource
	 */
	private searchAllData() {
		this.searchHasNoData = true;
		const searchValue = this.searchValue.toLowerCase();
		this.treeData.forEach((row) => {
			let filtered = false;
 
			Object.keys(row).every((key) => {
				const rowValue = (row[key] || '').toString().toLowerCase();
				filtered = this.originalDatasource.searchIn.indexOf(key) !== -1 && rowValue.indexOf(searchValue) !== -1;
				return !filtered;
			});
 
			row.tree__searched = filtered;
			if (filtered) {
				this.searchHasNoData = false;
				let parent = row.tree__parent;
				while (parent && !parent.tree__searched) {
					parent.tree__searched = true;
					parent = parent.tree__parent;
				}
			}
		});
 
		this.searchHasNoData = !this.treeData.some((row) => row.tree__searched);
	}
 
	/**
	 * Clear row removing 'tree__' props
	 */
	public clearRow(row: IDictionary<any>) {
		const result = { ...row };
		result.tree__children = undefined;
		result.tree__level = undefined;
		result.tree__parent = undefined;
		result.tree__opened = undefined;
		result.tree__searched = undefined;
		return result;
	}
 
	/**
	 * Get all children
	 * @param row datasource row
	 */
	public getChildren(row: IDictionary<any>) {
		let result: IDictionary<any>[] = [];
		const { uniqueKey } = this.originalDatasource;
		(this.treeStructure[row[uniqueKey]] || []).forEach((item: IDictionary<any>) => {
			result.push(this.clearRow(item));
			result = result.concat(this.getChildren(item));
		});
		return result;
	}
 
	/**
	 * Checks if a row has async children that are yet to be loaded
	 * @param row
	 * @returns `false` if the row has no children to be loaded, `true` if it does or if fieldHasChild is not defined
	 */
	public hasChildOnDemand(row: IDictionary<any>) {
		if (!this.fieldHasChild) return true;
 
		const rowHasChild: boolean | number | '0' | '1' = row[this.fieldHasChild];
		let isVisibleChevron = true;
 
		switch (rowHasChild) {
			case '0':
			case false:
			case 0:
				isVisibleChevron = false;
				break;
			case '1':
			case true:
			case 1:
				isVisibleChevron = true;
				break;
			default:
				isVisibleChevron = true;
				break;
		}
 
		return isVisibleChevron;
	}
 
	public getParentRow(row: IDictionary): IDictionary {
		return this.getRowData(row).tree__parent;
	}
 
	public resetTree() {
		this.treeData = [];
		this.buildTree();
	}
}