All files / components URLParamsProvider.jsx

25.77% Statements 25/97
8.11% Branches 6/74
30.43% Functions 7/23
26.37% Lines 24/91

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            8x 8x   8x                   53x   53x                                                                   22x 22x 20x     20x 20x 20x   20x 20x                                                                     20x 20x           20x                                   53x     53x 53x                                                                                                                                                               53x 53x       542x         8x         8x              
import { Actions, helper } from '@appbaseio/reactivecore';
import VueTypes from 'vue-types';
import { connect } from '../utils/index';
import types from '../utils/vueTypes';
import Base from '../styles/Base';
 
const { setHeaders, setValue } = Actions;
const { isEqual } = helper;
 
const URLParamsProvider = {
	name: 'URLParamsProvider',
	props: {
		className: types.string,
		headers: types.headers,
		getSearchParams: types.func,
		setSearchParams: types.func,
		as: VueTypes.string.def('div'),
	},
	mounted() {
		this.init();
 
		window.onpopstate = () => {
			this.init();
			const activeComponents = Array.from(this.params.keys());
 
			// remove inactive components from selectedValues
			Object.keys(this.currentSelectedState)
				.filter(item => !activeComponents.includes(item))
				.forEach(component => {
					this.setValue(component, null);
				});
 
			// update active components in selectedValues
			Array.from(this.params.entries()).forEach(item => {
				try {
					const [component, value] = item;
					const { label, showFilter, URLParams } = this.selectedValues[component] || {
						label: component,
					};
					this.setValue(component, JSON.parse(value), label, showFilter, URLParams);
				} catch (e) {
					// Do not set value if JSON parsing fails.
					console.error(e);
				}
			});
		};
	},
	watch: {
		$route() {
			// this ensures the url params change are handled
			// when the url changes, which enables us to
			// make `onpopstate` event handler work with history.pushState updates
			this.checkForURLParamsChange();
		},
		selectedValues(newVal, oldVal) {
			this.currentSelectedState = newVal;
			if (!isEqual(newVal, oldVal)) {
				this.searchString = this.$props.getSearchParams
					? this.$props.getSearchParams()
					: window.location.search;
				this.params = new URLSearchParams(this.searchString);
				const currentComponents = Object.keys(newVal);
				const urlComponents = Array.from(this.params.keys());
 
				currentComponents
					.filter(component => newVal[component].URLParams)
					.forEach(component => {
						// prevents empty history pollution on initial load
						if (
							this.hasValidValue(newVal[component])
							|| this.hasValidValue(oldVal[component])
						) {
							const selectedValues = newVal[component];
							if (selectedValues.URLParams) {
								if (selectedValues.category) {
									this.setURL(
										component,
										this.getValue({
											category: selectedValues.category,
											value: selectedValues.value,
										}),
									);
								} else {
									this.setURL(component, this.getValue(selectedValues.value));
								}
							} else {
								this.params.delete(component);
								this.pushToHistory();
							}
						} else if (
							!this.hasValidValue(newVal[component])
							&& urlComponents.includes(component)
						) {
							// doesn't have a valid value, but the url has a (stale) valid value set
							this.params.delete(component);
							this.pushToHistory();
						}
					});
 
				// remove unmounted components
				Object.keys(newVal)
					.filter(component => !currentComponents.includes(component))
					.forEach(component => {
						this.params.delete(component);
						this.pushToHistory();
					});
 
				Iif (!currentComponents.length) {
					Array.from(this.params.keys()).forEach(item => {
						if(this.searchComponents && this.searchComponents.includes(item)) {
							this.params.delete(item);
						}
					});
					this.pushToHistory();
				}
			}
		},
		headers(newVal, oldVal) {
			if (!isEqual(oldVal, newVal)) {
				this.setHeaders(newVal);
			}
		},
	},
	methods: {
		init() {
			this.searchString = this.$props.getSearchParams
				? this.$props.getSearchParams()
				: window.location.search;
			this.params = new URLSearchParams(this.searchString);
			this.currentSelectedState = this.selectedValues || {};
		},
 
		checkForURLParamsChange() {
			// we only compare the search string (window.location.search by default)
			// to see if the route has changed (or) not. This handles the following usecase:
			// search on homepage -> route changes -> search results page with same search query
			if (window) {
				const searchString = this.$props.getSearchParams
					? this.$props.getSearchParams()
					: window.location.search;
 
				if (searchString !== this.searchString) {
					let event;
					if (typeof Event === 'function') {
						event = new Event('popstate');
					} else {
						// Correctly fire popstate event on IE11 to prevent app crash.
						event = document.createEvent('Event');
						event.initEvent('popstate', true, true);
					}
 
					window.dispatchEvent(event);
				}
			}
		},
 
		hasValidValue(component) {
			if (!component) return false;
			if (Array.isArray(component.value)) return !!component.value.length;
			return !!component.value;
		},
 
		getValue(value) {
			if (Array.isArray(value) && value.length) {
				return value.map(item => this.getValue(item));
			} if (value && typeof value === 'object') {
				// TODO: support for NestedList
				if (value.location) return value;
				if (value.category) return value;
				return value.label || value.key || null;
			}
			return value;
		},
 
		setURL(component, value) {
			this.searchString = this.$props.getSearchParams
				? this.$props.getSearchParams()
				: window.location.search;
			this.params = new URLSearchParams(this.searchString);
			if (
				!value
				|| (typeof value === 'string' && value.trim() === '')
				|| (Array.isArray(value) && value.length === 0)
			) {
				this.params.delete(component);
				this.pushToHistory();
			} else {
				const data = JSON.stringify(this.getValue(value));
				if (data !== this.params.get(component)) {
					this.params.set(component, data);
					this.pushToHistory();
				}
			}
		},
 
		pushToHistory() {
			const paramsSting = this.params.toString() ? `?${this.params.toString()}` : '';
			const base = window.location.href.split('?')[0];
			const newURL = `${base}${paramsSting}`;
 
			if (this.$props.setSearchParams) {
				this.$props.setSearchParams(newURL);
			} else if (window.history.pushState) {
				window.history.pushState({ path: newURL }, '', newURL);
			}
			this.init();
		},
	},
	render() {
		const children = this.$slots.default;
		return <Base as={this.$props.as} class={this.$props.className}>{children}</Base>;
	},
};
 
const mapStateToProps = state => ({
	selectedValues: state.selectedValues,
	searchComponents: state.components,
});
 
const mapDispatchtoProps = {
	setHeaders,
	setValue,
};
 
URLParamsProvider.install = function (Vue) {
	Vue.component(URLParamsProvider.name, URLParamsProvider);
};
export default connect(
	mapStateToProps,
	mapDispatchtoProps,
)(URLParamsProvider);