All files / components/list SingleList.jsx

56.03% Statements 79/141
55.8% Branches 77/138
59.38% Functions 19/32
55.4% Lines 77/139

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                                            1x               1x   1x                                                                     7x 7x         7x 7x     7x         7x 7x         7x 7x     7x   7x   7x   7x 1x                                                           1x                               7x 7x 7x   7x       7x 1x 1x           7x   7x       7x 12x 12x         12x         7x                                                                                           10x                                                                                                                               1x   1x     1x 1x 1x 1x 1x     1x                                                         1x 1x 1x               1x                                 7x 7x                   7x                   7x 6x                           1x       1x 1x 1x 1x     1x               1x                                           2x 2x                 7x         1x 7x 7x   1x 1x 1x                   1x 1x         1x                     1x                     1x   1x   24x                                 1x             1x               1x         1x      
import { Actions, helper } from '@appbaseio/reactivecore';
import { componentTypes } from '@appbaseio/reactivecore/lib/utils/constants';
import { replaceDiacritics } from '@appbaseio/reactivecore/lib/utils/suggestions';
import VueTypes from 'vue-types';
import Title from '../../styles/Title';
import Input from '../../styles/Input';
import Container from '../../styles/Container';
import {
	connect,
	getComponent,
	hasCustomRenderer,
	isEvent,
	isFunction,
	updateCustomQuery,
	updateDefaultQuery,
	isQueryIdentical,
} from '../../utils/index';
import ComponentWrapper from '../basic/ComponentWrapper.jsx';
import types from '../../utils/vueTypes';
import { UL, Radio } from '../../styles/FormControlList';
import { getAggsQuery } from './utils';
 
const { updateQuery, setQueryOptions, setCustomQuery, setDefaultQuery } = Actions;
const {
	getQueryOptions,
	checkValueChange,
	getClassName,
	isEqual,
	extractQueryFromCustomQuery,
	getOptionsForCustomQuery,
} = helper;
 
const SingleList = {
	name: 'SingleList',
	props: {
		beforeValueChange: types.func,
		className: VueTypes.string.def(''),
		componentId: types.stringRequired,
		customQuery: types.func,
		dataField: types.stringRequired,
		defaultValue: types.string,
		value: types.value,
		defaultQuery: types.func,
		filterLabel: types.string,
		innerClass: types.style,
		placeholder: VueTypes.string.def('Search'),
		react: types.react,
		render: types.func,
		renderItem: types.func,
		renderNoResults: VueTypes.any,
		transformData: types.func,
		selectAllLabel: types.string,
		showCount: VueTypes.bool.def(true),
		showFilter: VueTypes.bool.def(true),
		showRadio: VueTypes.bool.def(true),
		showSearch: VueTypes.bool.def(true),
		size: VueTypes.number,
		sortBy: VueTypes.oneOf(['asc', 'desc', 'count']).def('count'),
		title: types.title,
		URLParams: VueTypes.bool.def(false),
		showMissing: VueTypes.bool.def(false),
		missingLabel: VueTypes.string.def('N/A'),
		nestedField: types.string,
		index: VueTypes.string,
		enableStrictSelection: VueTypes.bool.def(false),
	},
	data() {
		const props = this.$props;
		this.__state = {
			currentValue: '',
			modifiedOptions: [],
			searchTerm: '',
		};
		this.internalComponent = `${props.componentId}__internal`;
		return this.__state;
	},
	created() {
		Iif (!this.enableAppbase && this.$props.index) {
			console.warn(
				'Warning(ReactiveSearch): In order to use the `index` prop, the `enableAppbase` prop must be set to true in `ReactiveBase`.',
			);
		}
		const props = this.$props;
		this.modifiedOptions
			= this.options && this.options[props.dataField]
				? this.options[props.dataField].buckets
				: [];
		// Set custom and default queries in store
		updateCustomQuery(this.componentId, this.setCustomQuery, this.$props, this.currentValue);
		updateDefaultQuery(this.componentId, this.setDefaultQuery, this.$props, this.currentValue);
	},
	beforeMount() {
		this.updateQueryHandlerOptions(this.$props);
 
		Iif (this.selectedValue) {
			this.setValue(this.selectedValue);
		} else Iif (this.$props.value) {
			this.setValue(this.$props.value);
		} else if (this.$props.defaultValue) {
			this.setValue(this.$props.defaultValue);
		}
	},
	watch: {
		options(newVal) {
			if (newVal) {
				this.modifiedOptions = newVal[this.$props.dataField]
					? newVal[this.$props.dataField].buckets
					: [];
			}
		},
		size() {
			this.updateQueryHandlerOptions(this.$props);
		},
		sortBy() {
			this.updateQueryHandlerOptions(this.$props);
		},
		dataField() {
			this.updateQueryHandlerOptions(this.$props);
			this.updateQueryHandler(this.$data.currentValue, this.$props);
		},
		defaultValue(newVal) {
			this.setValue(newVal);
		},
		value(newVal, oldVal) {
			if (!isEqual(newVal, oldVal)) {
				this.setValue(newVal);
			}
		},
		selectedValue(newVal) {
			Iif (this.$data.currentValue !== newVal) {
				this.setValue(newVal || '');
			}
		},
		defaultQuery(newVal, oldVal) {
			if (!isQueryIdentical(newVal, oldVal, this.$data.currentValue, this.$props)) {
				this.updateDefaultQueryHandler(this.$data.currentValue, this.$props);
			}
		},
		customQuery(newVal, oldVal) {
			if (!isQueryIdentical(newVal, oldVal, this.$data.currentValue, this.$props)) {
				this.updateQueryHandler(this.componentId, this.$data.currentValue, this.$props);
			}
		},
	},
	render() {
		const { selectAllLabel, renderItem, renderError } = this.$props;
		const renderItemCalc = this.$scopedSlots.renderItem || renderItem;
		const renderErrorCalc = this.$scopedSlots.renderError || renderError;
 
		Iif (renderErrorCalc && this.error) {
			return isFunction(renderErrorCalc) ? renderErrorCalc(this.error) : renderErrorCalc;
		}
 
		if (!this.hasCustomRenderer && this.modifiedOptions.length === 0 && !this.isLoading) {
			Eif (this.renderNoResult) {
				this.renderNoResult();
			} else {
				return null;
			}
		}
 
		let itemsToRender = this.$data.modifiedOptions;
 
		Iif (this.$props.transformData) {
			itemsToRender = this.$props.transformData(itemsToRender);
		}
 
		const filteredItemsToRender = itemsToRender.filter((item) => {
			Eif (String(item.key).length) {
				Iif (this.$props.showSearch && this.$data.searchTerm) {
					return replaceDiacritics(String(item.key))
						.toLowerCase()
						.includes(replaceDiacritics(this.$data.searchTerm.toLowerCase()));
				}
				return true;
			}
			return false;
		});
 
		return (
			<Container class={this.$props.className}>
				{this.$props.title && (
					<Title class={getClassName(this.$props.innerClass, 'title') || ''}>
						{this.$props.title}
					</Title>
				)}
				{this.renderSearch()}
				{this.hasCustomRenderer ? (
					this.getComponent()
				) : (
					<UL class={getClassName(this.$props.innerClass, 'list') || ''}>
						{selectAllLabel ? (
							<li
								key={selectAllLabel}
								class={`${
									this.$data.currentValue === selectAllLabel ? 'active' : ''
								}`}
							>
								<Radio
									class={getClassName(this.$props.innerClass, 'radio')}
									id={`${this.$props.componentId}-${selectAllLabel}`}
									name={this.$props.componentId}
									value={selectAllLabel}
									onClick={this.handleClick}
									readOnly
									show={this.$props.showRadio}
									{...{
										domProps: {
											checked: this.$data.currentValue === selectAllLabel,
										},
									}}
								/>
								<label
									class={getClassName(this.$props.innerClass, 'label') || null}
									for={`${this.$props.componentId}-${selectAllLabel}`}
								>
									{selectAllLabel}
								</label>
							</li>
						) : null}
						{!this.hasCustomRenderer
						&& filteredItemsToRender.length === 0
						&& !this.isLoading
							? this.renderNoResult()
							: filteredItemsToRender.map((item) => (
								<li
									key={item.key}
									class={`${
										this.currentValue === String(item.key) ? 'active' : ''
									}`}
								>
									<Radio
										class={getClassName(this.$props.innerClass, 'radio')}
										id={`${this.$props.componentId}-${item.key}`}
										name={this.$props.componentId}
										value={item.key}
										readOnly
										onClick={this.handleClick}
										type="radio"
										show={this.$props.showRadio}
										{...{
											domProps: {
												checked: this.currentValue === String(item.key),
											},
										}}
									/>
									<label
										class={
											getClassName(this.$props.innerClass, 'label')
												|| null
										}
										for={`${this.$props.componentId}-${item.key}`}
									>
										{renderItemCalc ? (
											renderItemCalc({
												label: item.key,
												count: item.doc_count,
												isChecked:
														this.currentValue === String(item.key),
											})
										) : (
											<span>
												{item.key}
												{this.$props.showCount && (
													<span
														class={
															getClassName(
																this.$props.innerClass,
																'count',
															) || null
														}
													>
															&nbsp;(
														{item.doc_count})
													</span>
												)}
											</span>
										)}
									</label>
								</li>
							  ))}
					</UL>
				)}
			</Container>
		);
	},
 
	methods: {
		setValue(nextValue, props = this.$props) {
			let value = nextValue;
 
			Iif (nextValue === this.$data.currentValue) {
				value = '';
			}
			const performUpdate = () => {
				this.currentValue = value;
				this.updateQueryHandler(value, props);
				this.$emit('valueChange', value);
				this.$emit('value-change', value);
			};
 
			checkValueChange(props.componentId, value, props.beforeValueChange, performUpdate);
		},
 
		updateDefaultQueryHandler(value, props) {
			let query = SingleList.defaultQuery(value, props);
 
			if (this.defaultQuery) {
				const defaultQueryToBeSet = this.defaultQuery(value, props) || {};
				const defaultQueryObj = extractQueryFromCustomQuery(defaultQueryToBeSet);
				if (defaultQueryObj) {
					query = defaultQueryObj;
				}
 
				// Update calculated default query in store
				updateDefaultQuery(props.componentId, this.setDefaultQuery, props, value);
 
				const defaultQueryOptions = getOptionsForCustomQuery(defaultQueryToBeSet);
 
				this.setQueryOptions(this.internalComponent, defaultQueryOptions, false);
			}
			this.updateQuery({
				componentId: this.internalComponent,
				query,
				value,
				componentType: componentTypes.singleList,
			});
		},
 
		updateQueryHandler(value, props) {
			const { customQuery } = props;
			let query = SingleList.defaultQuery(value, props);
			Iif (customQuery) {
				const customQueryCalc = customQuery(value, props);
				query = extractQueryFromCustomQuery(customQueryCalc);
				const customQueryOptions = getOptionsForCustomQuery(customQueryCalc);
				updateCustomQuery(props.componentId, this.setCustomQuery, props, value);
 
				this.setQueryOptions(props.componentId, customQueryOptions, false);
			}
			this.updateQuery({
				componentId: props.componentId,
				query,
				value,
				label: props.filterLabel,
				showFilter: props.showFilter,
				URLParams: props.URLParams,
				componentType: componentTypes.singleList,
			});
		},
 
		generateQueryOptions(props) {
			const queryOptions = getQueryOptions(props);
			return getAggsQuery(queryOptions, props);
		},
 
		updateQueryHandlerOptions(props) {
			const queryOptions = SingleList.generateQueryOptions(props);
			Iif (props.defaultQuery) {
				const value = this.$data.currentValue;
				const defaultQueryOptions = getOptionsForCustomQuery(
					props.defaultQuery(value, props),
				);
				this.setQueryOptions(this.internalComponent, {
					...queryOptions,
					...defaultQueryOptions,
				});
			} else {
				this.setQueryOptions(this.internalComponent, queryOptions);
			}
		},
 
		handleInputChange(e) {
			const { value } = e.target;
			this.searchTerm = value;
		},
 
		renderSearch() {
			if (this.$props.showSearch) {
				return (
					<Input
						class={getClassName(this.$props.innerClass, 'input') || ''}
						onInput={this.handleInputChange}
						value={this.$data.searchTerm}
						placeholder={this.$props.placeholder}
						style={{
							margin: '0 0 8px',
						}}
						themePreset={this.$props.themePreset}
					/>
				);
			}
 
			return null;
		},
 
		getComponent() {
			const { currentValue, modifiedOptions } = this.$data;
			const { transformData } = this.$props;
			let itemsToRender = modifiedOptions;
			Iif (transformData) {
				itemsToRender = transformData(itemsToRender);
			}
			const data = {
				error: this.error,
				loading: this.isLoading,
				value: currentValue,
				data: itemsToRender,
				rawData: this.rawData,
				handleChange: this.handleClick,
			};
			return getComponent(data, this);
		},
 
		handleClick(e) {
			let currentValue = e;
			if (isEvent(e)) {
				currentValue = e.target.value;
			}
			if (this.enableStrictSelection && currentValue === this.currentValue) {
				return false;
			}
			const { value } = this.$props;
			if (value === undefined) {
				this.setValue(currentValue);
			} else {
				this.$emit('change', currentValue);
			}
			return true;
		},
 
		renderNoResult() {
			const renderNoResults
				= this.$scopedSlots.renderNoResults || this.$props.renderNoResults;
			return (
				<p class={getClassName(this.$props.innerClass, 'noResults') || null}>
					{isFunction(renderNoResults) ? renderNoResults() : renderNoResults}
				</p>
			);
		},
	},
	computed: {
		hasCustomRenderer() {
			return hasCustomRenderer(this);
		},
	},
};
 
SingleList.generateQueryOptions = (props) => {
	const queryOptions = getQueryOptions(props);
	return getAggsQuery(queryOptions, props);
};
SingleList.defaultQuery = (value, props) => {
	let query = null;
	Iif (props.selectAllLabel && props.selectAllLabel === value) {
		if (props.showMissing) {
			query = { match_all: {} };
		}
		query = {
			exists: {
				field: props.dataField,
			},
		};
	}
	Eif (value) {
		query = {
			term: {
				[props.dataField]: value,
			},
		};
		Iif (props.showMissing && props.missingLabel === value) {
			query = {
				bool: {
					must_not: {
						exists: { field: props.dataField },
					},
				},
			};
		}
	}
 
	Iif (query && props.nestedField) {
		return {
			query: {
				nested: {
					path: props.nestedField,
					query,
				},
			},
		};
	}
 
	return query;
};
SingleList.hasInternalComponent = () => true;
 
const mapStateToProps = (state, props) => ({
	options:
		props.nestedField && state.aggregations[props.componentId]
			? state.aggregations[props.componentId].reactivesearch_nested
			: state.aggregations[props.componentId],
	rawData: state.rawData[props.componentId],
	isLoading: state.isLoading[props.componentId],
	selectedValue:
		(state.selectedValues[props.componentId]
			&& state.selectedValues[props.componentId].value)
		|| '',
	themePreset: state.config.themePreset,
	error: state.error[props.componentId],
	componentProps: state.props[props.componentId],
	enableAppbase: state.config.enableAppbase,
});
 
const mapDispatchtoProps = {
	setQueryOptions,
	updateQuery,
	setCustomQuery,
	setDefaultQuery,
};
 
export const ListConnected = ComponentWrapper(
	connect(mapStateToProps, mapDispatchtoProps)(SingleList),
	{
		componentType: componentTypes.singleList,
		internalComponent: SingleList.hasInternalComponent(),
	},
);
 
SingleList.install = function (Vue) {
	Vue.component(SingleList.name, ListConnected);
};
 
// Add componentType for SSR
SingleList.componentType = componentTypes.singleList;
 
export default SingleList;