All files / src/components/zd-select select.ts

100% Statements 206/206
100% Branches 112/112
100% Functions 44/44
100% Lines 191/191

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 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 66993x                     93x 93x   93x 93x           93x                 149x         149x         149x         149x         149x         149x         149x         149x         149x         149x         149x         149x         149x         149x         149x         149x         149x         149x         149x         149x   149x   149x             149x                           149x       149x   149x                                                                                                             109x   109x 109x       102x   102x               8x   5x               149x 5x 5x   149x 149x 149x             2x 2x   2x               149x 149x 149x 149x                                 234x       61x 101x 9x     101x 47x     101x 27x     101x 77x 77x     61x       24x       48x 48x 48x 48x       45x 45x                 102x 33x                 33x   33x 33x   33x   33x       47x 47x       25x 9x 9x     25x   25x   23x 23x             630x       164x 164x 164x   8x       99x   99x 10x   89x     99x 30x         99x 50x 50x     49x   49x   49x   49x 21x     49x 12x   12x     37x   37x                 99x 37x   62x   99x 99x             539x 324x     215x             227x   66x   56x               7x 7x 7x 7x         67x               6x   5x 5x               36x   13x             3x             2x 2x       13x 10x   3x 3x 3x 3x       149x           4x                 32x 31x 31x   31x     32x       13x 1x     13x   12x 12x   12x 6x 6x     6x 5x                         5x                             2x             1x 1x             255x   293x       93x                       339x 161x     178x 4x     174x   174x 174x 174x 206x 185x 185x   21x 21x 6x 6x   15x       174x 206x 172x 172x 172x 20x 20x   172x   34x         93x  
import {
	Accessor,
	Datasource,
	DatasourceFactory,
	FormatterParserProvider,
	IDatasource,
	IDictionary,
	Loader,
	Mask,
	Utils,
} from '@zeedhi/core';
import debounce from 'lodash.debounce';
import { DataValueOutHelper, DatasourceSearcher, ISelectDataValueOutItem, SearchParam } from '../../utils';
import { IComponentRender } from '../zd-component/interfaces';
import { InputFactory } from '../zd-input/input-factory';
import { TextInput } from '../zd-text-input/text-input';
import { ISelect } from './interfaces';
 
/**
 * Base class for Select component.
 */
export class Select extends TextInput implements ISelect {
	/**
	 * Source of select items
	 */
	public datasource: Datasource;
 
	/**
	 * Field used to display values
	 */
	public dataText: string | any[] = '';
 
	/**
	 * Field used to display values when the select is closed
	 */
	public dataTextDiscrete: string | any[] = '';
 
	/**
	 * Value used to join display values
	 */
	public dataTextSeparator = ' | ';
 
	/**
	 * Field used to save values
	 */
	public dataValue = '';
 
	/**
	 * Field used to make the item disabled
	 */
	public dataDisabled = 'disabled';
 
	/**
	 * Defines if field value should be an object
	 */
	public returnObject = false;
 
	/**
	 * Enables search input
	 */
	public autocomplete = true;
 
	/**
	 * Automatically select option if only one is filtered
	 */
	public autoSelection = true;
 
	/**
	 * Prevents load select data when the input is focused
	 */
	public preventLoadOnFocus = true;
 
	/**
	 * Maximum height of select menu
	 */
	public menuMaxHeight: string | number = 304;
 
	/**
	 * Maximum width of select menu
	 */
	public menuMaxWidth: string | number = 'auto';
 
	/**
	 * Input select value
	 */
	public selectValue: IDictionary<any> | null = null;
 
	/**
	 * Components that will be rendered in itemAfterSlot case
	 */
	public itemAfterSlot: IComponentRender[] = [];
 
	/**
	 * Components that will be rendered in itemBeforeSlot case
	 */
	public itemBeforeSlot: IComponentRender[] = [];
 
	/**
	 * Items that will be disabled for selection. Users will still see them
	 */
	public disabledItems: any[] = [];
 
	/**
	 * Defines if data handling should be manual or automatic
	 */
	public manualMode = false;
 
	/**
	 * Defines if data handling should be manual or automatic
	 */
	public searchParam: SearchParam = 'SEARCH';
 
	/**
	 * Defines other columns that must me set on form on change
	 */
	public dataValueOut: ISelectDataValueOutItem[] = [];
 
	/**
	 * Defines the name of the form target to set using dataValueOut
	 */
	public dataValueOutFormName = '';
 
	/**
	 * Input search value
	 */
	private searchValue = '';
 
	protected dirtySearchValue = '';
 
	protected formatterFn = FormatterParserProvider.getFormatter('ZdSelect');
 
	private discreteProps?: {
		dataText: string | any[];
		dataTextSeparator: string;
	};
 
	public loadMoreAmount = 0;
 
	/**
	 * Conditions for pushing a value:
	 * 1. Every time a value from outside the datasource is set
	 * 2. On blur, if the current value is not part of the cache
	 * 3. When the datasource is reloaded, if the current value is not part of the datasource but is in another page
	 *
	 * Conditions for removing a push
	 * 1. When the datasource is reloaded, if the current value cannot be found in another page
	 * 2. When the datasource is reloaded, if the push is already part of the datasource
	 * 3. When the search is empty
	 * 4. On blur, if the current value is null
	 */
	public pushedValue: IDictionary | null = null;
 
	public defaultValue: any;
 
	protected cachedData: IDictionary[] = [];
 
	protected cachedTotal = 0;
 
	/* istanbul ignore next */
	/**
	 * Create a new Select.
	 * @param props Select properties
	 */
	constructor(props: ISelect) {
		super({ ...props, value: undefined });
		this.appendIcon = this.getInitValue('appendIcon', props.appendIcon, 'expand');
		this.dataText = this.getInitValue('dataText', props.dataText, this.dataText);
		this.dataTextDiscrete = this.getInitValue('dataTextDiscrete', props.dataTextDiscrete, this.dataTextDiscrete);
		this.dataTextSeparator = this.getInitValue('dataTextSeparator', props.dataTextSeparator, this.dataTextSeparator);
		this.dataValue = this.getInitValue('dataValue', props.dataValue, this.dataValue);
		this.dataDisabled = this.getInitValue('dataDisabled', props.dataDisabled, this.dataDisabled);
		this.menuMaxHeight = this.getInitValue('menuMaxHeight', props.menuMaxHeight, this.menuMaxHeight);
		this.menuMaxWidth = this.getInitValue('menuMaxWidth', props.menuMaxWidth, this.menuMaxWidth);
		this.returnObject = this.getInitValue('returnObject', props.returnObject, this.returnObject);
		this.autocomplete = this.getInitValue('autocomplete', props.autocomplete, this.autocomplete);
		this.autoSelection = this.getInitValue('autoSelection', props.autoSelection, this.autoSelection);
		this.disabledItems = this.getInitValue('disabledItems', props.disabledItems, this.disabledItems);
		this.manualMode = this.getInitValue('manualMode', props.manualMode, this.manualMode);
		this.searchParam = this.getInitValue('searchParam', props.searchParam, this.searchParam);
		this.dataValueOut = this.getInitValue('dataValueOut', props.dataValueOut, this.dataValueOut);
		this.dataValueOutFormName = this.getInitValue(
			'dataValueOutFormName',
			props.dataValueOutFormName,
			this.dataValueOutFormName,
		);
		this.setDataProperties(props);
		const defaultDatasource = this.getDefaultDatasource(props);
		this.datasource = DatasourceFactory.factory(defaultDatasource);
 
		this.defaultValue = props.value;
		if (Accessor.isAccessorDefinition(props.value)) {
			this.defaultValue = this.getAccessorValue(props.value);
 
			this.getInitValue('value', props.value, this.value);
		}
 
		this.preventLoadOnFocus = !defaultDatasource.lazyLoad;
		this.preventLoadOnFocus = this.getInitValue(
			'preventLoadOnFocus',
			props.preventLoadOnFocus,
			this.preventLoadOnFocus,
		);
		this.loadMoreAmount = this.datasource.limit;
		this.itemAfterSlot = props.itemAfterSlot || this.itemAfterSlot;
		this.itemBeforeSlot = props.itemBeforeSlot || this.itemBeforeSlot;
 
		this.internalDisplayValue = this.formatter(this.selectValue);
		this.createAccessors();
	}
 
	public async onCreated(): Promise<void> {
		super.onCreated();
 
		this.registerGetCallback();
		await this.datasource.initialize();
	}
 
	public onMounted(element: any) {
		super.onMounted(element);
 
		this.setDefaultValue(this.defaultValue);
	}
 
	/**
	 * Select items list, containing all of the items that appear on the menu
	 * including the pushedValue
	 */
	get items() {
		if (!this.pushedValue) return this.datasource.data;
 
		return [this.pushedValue, ...this.datasource.data];
	}
 
	/**
	 * Initializes the select data properties: dataText, dataValue and dataTextDiscrete
	 * @param props Select props
	 */
	private setDataProperties(props: ISelect) {
		if (props.datasource?.type === 'simple') {
			this.dataValue = 'value';
			this.dataText = this.dataText || this.dataValue;
		}
		if (this.dataText && !Array.isArray(this.dataText)) this.dataText = [this.dataText];
		if (this.dataTextDiscrete && !Array.isArray(this.dataTextDiscrete)) this.dataTextDiscrete = [this.dataTextDiscrete];
		this.discreteProps = {
			dataText: this.dataTextDiscrete,
			dataTextSeparator: this.dataTextSeparator,
		};
	}
 
	private getAccessorValue(accessorName: string) {
		const [controller, accessor] = Accessor.getAccessor(accessorName);
		const instance = Loader.getInstance(controller);
 
		return instance[accessor];
	}
 
	/**
	 * Retrieves datasource structure applying infinity scroll
	 * @param field Field structure
	 */
	private getDefaultDatasource(field: ISelect): IDatasource {
		const getDataTextNames = (text: any) => (typeof text === 'string' ? text : text.name);
		const searchInDefault = this.dataText ? (this.dataText as any[]).map(getDataTextNames) : [];
		const searchIn = (field.datasource?.searchIn || []).concat(searchInDefault);
		return {
			...field.datasource,
			searchIn,
			lazyLoad: (field.value !== '' && field.value !== undefined) || field.datasource?.lazyLoad,
		};
	}
 
	/**
	 * Returns the currentRow in the dataText key
	 */
	public formatter(
		value?: string | IDictionary<any> | null,
		props?: {
			dataText: string | any[];
			dataTextSeparator: string;
		},
	): any {
		return this.formatterFn(value, props ?? this);
	}
 
	protected registerGetCallback() {
		const callback = async () => {
			if (this.value && this.indexOf(this.value) === -1 && !this.pushedValue) {
				this.pushedValue = this.selectValue;
			}
 
			if (this.indexOf(this.value) === -1 && !this.datasource.search && !this.isFocused) {
				await this.setValue(this.value, false);
			}
 
			if (this.indexOf(this.value) !== -1) {
				this.pushedValue = null;
			}
 
			if (!this.datasource.search && !this.manualMode) {
				this.cachedData = [...this.datasource.data];
				this.cachedTotal = this.datasource.total;
			}
		};
		this.datasource.registerGetCallback(callback);
	}
 
	public get search() {
		return this.searchValue;
	}
 
	public set search(value: string) {
		this.searchValue = value || '';
		const formattedSelectValue = this.formatter(this.selectValue);
		const formattedDiscreteValue = this.formatter(this.selectValue, this.discreteProps);
		if (
			this.searchValue === '' ||
			(this.searchValue !== formattedSelectValue && this.searchValue !== formattedDiscreteValue)
		) {
			this.dirtySearchValue = this.searchValue;
			if (this.isFocused) this.debounceSearch(this.searchValue);
		}
	}
 
	/**
	 * Sets select default value and dispatches defaultAssigned event.
	 * @param value Default value
	 */
	protected async setDefaultValue(value: any) {
		if (value || typeof value === 'number') {
			await this.setValue(value, false);
		}
	}
 
	/**
	 * Finds and retrieves items searching by value
	 * @param value Default value
	 */
	protected async getItemsBySearchValue(value: any) {
		this.datasource.loading = true;
 
		const datasourceSearcher = new DatasourceSearcher();
		const result = await datasourceSearcher.search(this.datasource, value, this.dataValue, this.searchParam);
 
		this.datasource.loading = false;
 
		return result;
	}
 
	public async focus(event: Event, element: any) {
		super.focus(event, element);
		this.afterFocus();
	}
 
	protected async afterFocus() {
		if (!this.preventLoadOnFocus) {
			await this.datasource.get();
			this.preventLoadOnFocus = true;
		}
 
		this.updateSearch(this.dirtySearchValue);
 
		if (this.manualMode) return;
 
		this.cachedData = [...this.datasource.data];
		this.cachedTotal = this.datasource.total;
	}
 
	/**
	 * Field value
	 */
	get value() {
		return this.getReturnValue(this.selectValue);
	}
 
	set value(value: any) {
		const valueToSet = this.getValue(value);
		const fieldSingleValue = this.getValue(this.selectValue);
		if (Utils.isEqual(valueToSet, fieldSingleValue)) return;
 
		this.setValue(value);
	}
 
	public async setValue(value: any, callEvent = true) {
		const foundInAnotherPage = await this.setFieldValue(value);
 
		if (foundInAnotherPage) {
			this.pushedValue = this.selectValue;
		} else {
			this.pushedValue = null;
		}
 
		if (callEvent) {
			this.callChangeEvent(this.selectValue);
		}
	}
 
	protected async setFieldValue(value: any) {
		if (typeof value !== 'number' && (!value || Object.keys(value).length === 0)) {
			this.setFieldRowValue(null);
			return false;
		}
 
		const filterValue = this.getValue(value);
 
		const rowFromData = this.datasource.data.find((row) => row[this.dataValue] === filterValue);
 
		let rowFromSearch = rowFromData;
 
		if (!rowFromData && !this.manualMode) {
			[rowFromSearch] = await this.getItemsBySearchValue(filterValue);
		}
 
		if (!rowFromSearch) {
			this.setFieldRowValue(null);
 
			return false;
		}
 
		this.setFieldRowValue(rowFromSearch);
 
		return !rowFromData;
	}
 
	/**
	 * Set value accessors
	 * @param row
	 * @param value
	 */
	protected setFieldRowValue(row: any) {
		if (row) {
			this.selectValue = row;
		} else {
			this.selectValue = null;
		}
		this.datasource.currentRow = row;
		this.internalDisplayValue = this.formatter(this.selectValue);
	}
 
	/**
	 * Retrieves value based on the returnObject definition
	 */
	protected getReturnValue(value: IDictionary | null) {
		if (!value) {
			return null;
		}
 
		return this.returnObject ? value : value[this.dataValue];
	}
 
	/**
	 * Retrieves a single-value (dataValue property)
	 */
	protected getValue(value: any | IDictionary | null) {
		if (!value) return null;
 
		if (typeof value === 'object') return value[this.dataValue];
 
		return value;
	}
 
	/**
	 * Event trigged when component loses the focus and value changes
	 * @param value inputted value
	 */
	public selectChange(value: any, event?: Event, element?: any) {
		const changeValue = this.getReturnValue(value);
		this.setValue(value, false).then(() => {
			DataValueOutHelper.setDataValueOut(this, value);
			this.callChangeEvent(changeValue, event, element);
		});
	}
 
	protected callChangeEvent(value: any, event?: Event, element?: any) {
		this.callEvent('change', { event, element, value, component: this });
	}
 
	/**
	 * Event trigged when value is inputted
	 * @param value inputted value
	 */
	public selectInput(value: any, event?: Event, element?: any) {
		if (value === this.lastInputValue) return;
 
		this.lastInputValue = value;
		this.callEvent('input', { event, element, value, component: this });
	}
 
	/**
	 * Updates search value
	 * @param value Search value
	 */
	public async updateSearch(value: string) {
		if (value === this.datasource.search) return;
 
		await this.datasource.setSearch(value);
	}
 
	/**
	 * Update datasource data
	 */
	public async updateData(data: IDictionary<any>[]): Promise<any> {
		return this.datasource.updateData(data);
	}
 
	/**
	 * Update datasource items
	 */
	public async updateItems(items: (string | number)[]): Promise<any> {
		const data = items.map((item: string | number) => ({ value: item }));
		return this.datasource.updateData(data);
	}
 
	protected async doSearch(value: string) {
		if (this.manualMode || value) {
			await this.updateSearch(value);
		} else {
			this.datasource.search = this.searchValue;
			this.pushedValue = null;
			this.datasource.data = [...this.cachedData];
			this.datasource.total = this.cachedTotal;
		}
	}
 
	private debounceSearch: (value: string) => void = debounce(this.doSearch, 500);
 
	/**
	 * Load more data
	 */
	public async loadMore() {
		await this.datasource.setLimit(this.datasource.limit + this.loadMoreAmount);
	}
 
	/**
	 * Triggered when the component loses focus.
	 * @param event DOM event
	 * @param element Element that lost the focus
	 */
	public blur(event: Event, element: any) {
		if (this.autocomplete) {
			this.datasource.search = '';
			this.dirtySearchValue = '';
 
			this.checkValueOnBlur();
		}
 
		super.blur(event, element);
	}
 
	protected checkValueOnBlur() {
		if (!this.search && this.value !== null) {
			this.setValue(null);
		}
 
		if (this.manualMode) return;
 
		this.datasource.data = [...this.cachedData];
		this.datasource.total = this.cachedTotal;
 
		if (this.value === null) {
			this.pushedValue = null;
			return;
		}
 
		if (this.indexOf(this.value, this.cachedData) === -1) {
			this.pushedValue = this.selectValue;
		}
	}
 
	/**
	 * Checks if the 'load more' option should be shown \
	 * conditions to show:
	 * - datasource has data
	 * - datasource is not loading
	 * - datasource is not loadAll
	 * - datasource current data length is less than the total
	 */
	public showLoadMore() {
		return (
			!!this.datasource.data.length &&
			!this.datasource.loading &&
			!this.datasource.loadAll &&
			this.datasource.data.length < this.datasource.total
		);
	}
 
	/**
	 * Checks if skeleton loaders should be shown \
	 * conditions to show:
	 * - datasource is loading and
	 * - datasource has no data or has less data than the total
	 */
	public showSkeletonLoaders() {
		return (
			this.datasource.loading &&
			(this.datasource.data.length === 0 || this.datasource.data.length < this.datasource.total)
		);
	}
 
	public onBeforeDestroy() {
		super.onBeforeDestroy();
		this.datasource!.destroy();
	}
 
	/**
	 * Retrieves the index of a select value inside a data array
	 */
	public indexOf(search: IDictionary | string | number, data: IDictionary[] = this.datasource.data) {
		const value = search && typeof search === 'object' ? search[this.dataValue] : search;
 
		return data.findIndex((row: IDictionary) => row[this.dataValue] === value);
	}
}
 
FormatterParserProvider.registerFormatter(
	'ZdSelect',
	(
		value: any,
		{
			dataText,
			dataTextSeparator = ' | ',
		}: {
			dataText: string | any[];
			dataTextSeparator: string;
		},
	) => {
		if (value === null || value === undefined) {
			return null;
		}
 
		if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
			return value;
		}
 
		const dataTextArr = Array.isArray(dataText) ? dataText : [dataText];
 
		const dataTextNames: string[] = [];
		const masks: any[] = [];
		dataTextArr.forEach((text: any) => {
			if (typeof text === 'string') {
				dataTextNames.push(text);
				masks.push('');
			} else {
				dataTextNames.push(text.name);
				if (Accessor.isAccessorDefinition(text.mask)) {
					const [controller, accessor] = Accessor.getAccessor(text.mask);
					masks.push(Loader.getInstance(controller)[accessor]);
				} else {
					masks.push(text.mask);
				}
			}
		});
		return dataTextNames.reduce((result: string, column: string, index: number) => {
			if (value[column] !== null && value[column] !== undefined) {
				const separator = index > 0 ? dataTextSeparator : '';
				let masked = value[column];
				if (masks[index]) {
					const maskValue = typeof masks[index] === 'function' ? masks[index](value[column]) : masks[index];
					masked = Mask.getValueWithMask(value[column], maskValue);
				}
				return result + separator + masked;
			}
			return result;
		}, '');
	},
);
 
InputFactory.register('ZdSelect', Select);