All files / components/list SingleDropdownList.jsx

51.47% Statements 70/136
48.31% Branches 57/118
53.13% Functions 17/32
50.75% Lines 68/134

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                                        1x                   1x 1x     7x 7x             7x 7x                                                                               7x         7x 7x         7x 7x     7x   7x   7x   7x 1x                                                                                                         1x                                 7x 7x 7x 7x 7x 7x 7x   7x       7x 1x 1x               6x               6x                       12x 12x                                                                           1x 1x 1x 1x 1x     1x                                                                       1x 1x 1x               1x                                               7x       7x       7x                   7x               1x 1x                 1x         7x       1x 1x 1x                 1x 1x                 1x             1x                     1x   1x 7x 7x                 1x   24x                                 1x             1x               1x         1x      
import { Actions, helper } from '@appbaseio/reactivecore';
import { componentTypes } from '@appbaseio/reactivecore/lib/utils/constants';
import VueTypes from 'vue-types';
import types from '../../utils/vueTypes';
import { getAggsQuery } from './utils';
import ComponentWrapper from '../basic/ComponentWrapper.jsx';
import Title from '../../styles/Title';
import Container from '../../styles/Container';
import Button, { loadMoreContainer } from '../../styles/Button';
import Dropdown from '../shared/DropDown.jsx';
import {
	getComponent,
	hasCustomRenderer,
	isFunction,
	connect,
	updateCustomQuery,
	updateDefaultQuery,
	isQueryIdentical,
} from '../../utils/index';
 
const { updateQuery, setQueryOptions, setCustomQuery, setDefaultQuery } = Actions;
const {
	getQueryOptions,
	checkValueChange,
	checkPropChange,
	getClassName,
	isEqual,
	getCompositeAggsQuery,
	extractQueryFromCustomQuery,
	getOptionsForCustomQuery,
} = helper;
const SingleDropdownList = {
	name: 'SingleDropdownList',
	data() {
		const props = this.$props;
		this.__state = {
			currentValue: '',
			modifiedOptions: [],
			after: {},
			// for composite aggs
			isLastBucket: false,
		};
		this.internalComponent = `${props.componentId}__internal`;
		return this.__state;
	},
	props: {
		beforeValueChange: types.func,
		className: VueTypes.string.def(''),
		componentId: types.stringRequired,
		customQuery: types.func,
		dataField: types.stringRequired,
		defaultQuery: types.func,
		defaultValue: types.string,
		value: types.value,
		filterLabel: types.string,
		innerClass: types.style,
		placeholder: VueTypes.string.def('Select a value'),
		react: types.react,
		renderLabel: types.func,
		render: types.func,
		renderItem: types.func,
		renderError: types.title,
		renderNoResults: VueTypes.any,
		transformData: types.func,
		selectAllLabel: types.string,
		showCount: VueTypes.bool.def(true),
		showFilter: 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'),
		showSearch: VueTypes.bool.def(false),
		showClear: VueTypes.bool.def(false),
		showLoadMore: VueTypes.bool.def(false),
		loadMoreLabel: VueTypes.oneOfType([VueTypes.string, VueTypes.any]).def('Load More'),
		nestedField: types.string,
		index: VueTypes.string,
		searchPlaceholder: VueTypes.string.def('Type here to search...'),
		isOpen: VueTypes.bool.def(false),
	},
	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.updateQueryOptions(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, oldVal) {
			if (newVal) {
				checkPropChange(oldVal, newVal, () => {
					const { showLoadMore, dataField } = this.$props;
					const { modifiedOptions } = this.$data;
					if (showLoadMore) {
						// append options with showLoadMore
						const { buckets } = newVal[dataField];
						const nextOptions = [
							...modifiedOptions,
							...buckets.map((bucket) => ({
								key: bucket.key[dataField],
								doc_count: bucket.doc_count,
							})),
						];
						const after = newVal[dataField].after_key; // detect the last bucket by checking if the next set of buckets were empty
						const isLastBucket = !buckets.length;
						this.after = {
							after,
						};
						this.isLastBucket = isLastBucket;
						this.modifiedOptions = nextOptions;
					} else {
						this.modifiedOptions = newVal[this.$props.dataField]
							? newVal[this.$props.dataField].buckets
							: [];
					}
				});
			}
		},
		size() {
			this.updateQueryOptions(this.$props);
		},
		sortBy() {
			this.updateQueryOptions(this.$props);
		},
		dataField() {
			this.updateQueryOptions(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 { showLoadMore, loadMoreLabel, renderItem, renderError, renderLabel } = this.$props;
		const { isLastBucket } = this.$data;
		let selectAll = [];
		const renderItemCalc = this.$scopedSlots.renderItem || renderItem;
		const renderErrorCalc = this.$scopedSlots.renderError || renderError;
		const renderLabelCalc = this.$scopedSlots.renderLabel || renderLabel;
		const renderNoResults = this.$scopedSlots.renderNoResults || this.$props.renderNoResults;
 
		Iif (renderErrorCalc && this.error) {
			return isFunction(renderErrorCalc) ? renderErrorCalc(this.error) : renderErrorCalc;
		}
 
		if (!this.hasCustomRenderer && this.$data.modifiedOptions.length === 0 && !this.isLoading) {
			Eif (renderNoResults && isFunction(renderNoResults)) {
				return <div>{renderNoResults()}</div>;
			}
			if (renderNoResults && !isFunction(renderNoResults)) {
				return renderNoResults;
			}
			return null;
		}
 
		Iif (this.$props.selectAllLabel) {
			selectAll = [
				{
					key: this.$props.selectAllLabel,
				},
			];
		}
 
		return (
			<Container class={this.$props.className}>
				{this.$props.title && (
					<Title class={getClassName(this.$props.innerClass, 'title') || ''}>
						{this.$props.title}
					</Title>
				)}
				<Dropdown
					innerClass={this.$props.innerClass}
					items={[
						...selectAll,
						...this.$data.modifiedOptions
							.filter((item) => String(item.key).trim().length)
							.map((item) => ({
								...item,
								key: String(item.key),
							})),
					]}
					handleChange={this.handleChange}
					selectedItem={this.$data.currentValue}
					placeholder={this.$props.placeholder}
					labelField="key"
					showCount={this.$props.showCount}
					hasCustomRenderer={this.hasCustomRenderer}
					customRenderer={this.getComponent}
					renderItem={renderItemCalc}
					renderNoResults={
						this.$scopedSlots.renderNoResults || this.$props.renderNoResults
					}
					themePreset={this.themePreset}
					showSearch={this.$props.showSearch}
					showClear={this.$props.showClear}
					searchPlaceholder={this.$props.searchPlaceholder}
					transformData={this.$props.transformData}
					footer={
						showLoadMore
						&& !isLastBucket && (
							<div css={loadMoreContainer}>
								<Button onClick={this.handleLoadMore}>{loadMoreLabel}</Button>
							</div>
						)
					}
					customLabelRenderer={renderLabelCalc}
					open={this.$props.isOpen}
				/>
			</Container>
		);
	},
 
	methods: {
		setValue(value, props = this.$props) {
			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);
		},
 
		handleChange(item) {
			const { value } = this.$props;
			if (value === undefined) {
				this.setValue(item);
			} else {
				this.$emit('change', item);
			}
		},
 
		updateDefaultQueryHandler(value, props) {
			let query = SingleDropdownList.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.singleDropdownList,
			});
		},
 
		updateQueryHandler(value, props) {
			const { customQuery } = props;
			let query = SingleDropdownList.defaultQuery(value, props);
			Iif (customQuery) {
				const customQueryCalc = customQuery(value, props);
				query = extractQueryFromCustomQuery(customQueryCalc);
				updateCustomQuery(props.componentId, this.setCustomQuery, props, value);
 
				const customQueryOptions = getOptionsForCustomQuery(customQueryCalc);
				this.setQueryOptions(props.componentId, customQueryOptions, false);
			}
			this.updateQuery({
				componentId: props.componentId,
				query,
				value,
				label: props.filterLabel,
				showFilter: props.showFilter,
				URLParams: props.URLParams,
				componentType: componentTypes.singleDropdownList,
			});
		},
 
		generateQueryOptions(props, after) {
			const queryOptions = getQueryOptions(props);
			return props.showLoadMore
				? getCompositeAggsQuery({
					query: queryOptions,
					props,
					after,
				  })
				: getAggsQuery(queryOptions, props);
		},
 
		updateQueryOptions(props, addAfterKey = false) {
			// when using composite aggs flush the current options for a fresh query
			Iif (props.showLoadMore && !addAfterKey) {
				this.modifiedOptions = [];
			} // for a new query due to other changes don't append after to get fresh results
 
			const queryOptions = SingleDropdownList.generateQueryOptions(
				props,
				addAfterKey ? this.$data.after : {},
			);
			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);
			}
		},
 
		handleLoadMore() {
			this.updateQueryOptions(this.$props, true);
		},
		getComponent(items, downshiftProps = {}) {
			const { currentValue } = this.$data;
			const data = {
				error: this.error,
				loading: this.isLoading,
				value: currentValue,
				data: items || [],
				rawData: this.rawData,
				handleChange: this.handleChange,
				downshiftProps,
			};
			return getComponent(data, this);
		},
	},
	computed: {
		hasCustomRenderer() {
			return hasCustomRenderer(this);
		},
	},
};
SingleDropdownList.defaultQuery = (value, props) => {
	let query = null;
	Iif (props.selectAllLabel && props.selectAllLabel === value) {
		if (props.showMissing) {
			query = { match_all: {} };
		}
		query = {
			exists: {
				field: props.dataField,
			},
		};
	} else Eif (value) {
		Iif (props.showMissing && props.missingLabel === value) {
			query = {
				bool: {
					must_not: {
						exists: { field: props.dataField },
					},
				},
			};
		}
		query = {
			term: {
				[props.dataField]: value,
			},
		};
	}
 
	Iif (query && props.nestedField) {
		return {
			query: {
				nested: {
					path: props.nestedField,
					query,
				},
			},
		};
	}
 
	return query;
};
SingleDropdownList.generateQueryOptions = (props, after) => {
	const queryOptions = getQueryOptions(props);
	return props.showLoadMore
		? getCompositeAggsQuery({
			query: queryOptions,
			props,
			after,
		  })
		: getAggsQuery(queryOptions, props);
};
 
SingleDropdownList.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)(SingleDropdownList),
	{
		componentType: componentTypes.singleDropdownList,
		internalComponent: SingleDropdownList.hasInternalComponent(),
	},
);
 
SingleDropdownList.install = function (Vue) {
	Vue.component(SingleDropdownList.name, ListConnected);
};
 
// Add componentType for SSR
SingleDropdownList.componentType = componentTypes.singleDropdownList;
 
export default SingleDropdownList;