All files / src Creatable.js

4.48% Statements 3/67
0% Branches 0/37
0% Functions 0/8
4.48% Lines 3/67
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          4x                                                                                                                   4x                                                                                                                                                                                                                                                                                                                                                                                                                                                                   4x  
import React from 'react';
import Select from './Select2';
import defaultFilterOptions from './utils/defaultFilterOptions';
import defaultMenuRenderer from './utils/defaultMenuRenderer';
 
const Creatable = React.createClass({
	displayName: 'CreatableSelect',
 
	propTypes: {
		// Child function responsible for creating the inner Select component
		// This component can be used to compose HOCs (eg Creatable and Async)
		// (props: Object): PropTypes.element
		children: React.PropTypes.func,
 
		// See Select.propTypes.filterOptions
		filterOptions: React.PropTypes.any,
 
		// Searches for any matching option within the set of options.
		// This function prevents duplicate options from being created.
		// ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean
		isOptionUnique: React.PropTypes.func,
 
	    // Determines if the current input text represents a valid option.
	    // ({ label: string }): boolean
	    isValidNewOption: React.PropTypes.func,
 
		// See Select.propTypes.menuRenderer
		menuRenderer: React.PropTypes.any,
 
	    // Factory to create new option.
	    // ({ label: string, labelKey: string, valueKey: string }): Object
		newOptionCreator: React.PropTypes.func,
 
		// input change handler: function (inputValue) {}
		onInputChange: React.PropTypes.func,
 
		// input keyDown handler: function (event) {}
		onInputKeyDown: React.PropTypes.func,
 
		// new option click handler: function (option) {}
		onNewOptionClick: React.PropTypes.func,
 
		// See Select.propTypes.options
		options: React.PropTypes.array,
 
	    // Creates prompt/placeholder option text.
	    // (filterText: string): string
		promptTextCreator: React.PropTypes.func,
 
		// Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option.
		shouldKeyDownEventCreateNewOption: React.PropTypes.func,
	},
 
	// Default prop methods
	statics: {
		isOptionUnique,
		isValidNewOption,
		newOptionCreator,
		promptTextCreator,
		shouldKeyDownEventCreateNewOption
	},
 
	getDefaultProps () {
		return {
			filterOptions: defaultFilterOptions,
			isOptionUnique,
			isValidNewOption,
			menuRenderer: defaultMenuRenderer,
			newOptionCreator,
			promptTextCreator,
			shouldKeyDownEventCreateNewOption,
		};
	},
 
	createNewOption () {
		const {
			isValidNewOption,
			newOptionCreator,
			onNewOptionClick,
			options = [],
			shouldKeyDownEventCreateNewOption
		} = this.props;
 
		if (isValidNewOption({ label: this.inputValue })) {
			const option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey });
			const isOptionUnique = this.isOptionUnique({ option });
 
			// Don't add the same option twice.
			if (isOptionUnique) {
				if (onNewOptionClick) {
					onNewOptionClick(option);
				} else {
					options.unshift(option);
 
					this.select.selectValue(option);
				}
			}
		}
	},
 
	filterOptions (...params) {
		const { filterOptions, isValidNewOption, options, promptTextCreator } = this.props;
 
		// TRICKY Check currently selected options as well.
		// Don't display a create-prompt for a value that's selected.
		// This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array.
		const excludeOptions = params[2] || [];
 
		const filteredOptions = filterOptions(...params) || [];
 
		if (isValidNewOption({ label: this.inputValue })) {
			const { newOptionCreator } = this.props;
 
			const option = newOptionCreator({
				label: this.inputValue,
				labelKey: this.labelKey,
				valueKey: this.valueKey
			});
 
			// TRICKY Compare to all options (not just filtered options) in case option has already been selected).
			// For multi-selects, this would remove it from the filtered list.
			const isOptionUnique = this.isOptionUnique({
				option,
				options: excludeOptions.concat(filteredOptions)
			});
 
			if (isOptionUnique) {
				const prompt = promptTextCreator(this.inputValue);
 
				this._createPlaceholderOption = newOptionCreator({
					label: prompt,
					labelKey: this.labelKey,
					valueKey: this.valueKey
				});
 
				filteredOptions.unshift(this._createPlaceholderOption);
			}
		}
 
		return filteredOptions;
	},
 
	isOptionUnique ({
		option,
		options
	}) {
		const { isOptionUnique } = this.props;
 
		options = options || this.select.filterOptions();
 
		return isOptionUnique({
			labelKey: this.labelKey,
			option,
			options,
			valueKey: this.valueKey
		});
	},
 
	menuRenderer (params) {
		const { menuRenderer } = this.props;
 
		return menuRenderer({
			...params,
			onSelect: this.onOptionSelect,
			selectValue: this.onOptionSelect
		});
	},
 
	onInputChange (input) {
		const { onInputChange } = this.props;
 
		if (onInputChange) {
			onInputChange(input);
		}
 
		// This value may be needed in between Select mounts (when this.select is null)
		this.inputValue = input;
	},
 
	onInputKeyDown (event) {
		const { shouldKeyDownEventCreateNewOption, onInputKeyDown } = this.props;
		const focusedOption = this.select.getFocusedOption();
 
		if (
			focusedOption &&
			focusedOption === this._createPlaceholderOption &&
			shouldKeyDownEventCreateNewOption({ keyCode: event.keyCode })
		) {
			this.createNewOption();
 
			// Prevent decorated Select from doing anything additional with this keyDown event
			event.preventDefault();
		} else if (onInputKeyDown) {
			onInputKeyDown(event);
		}
	},
 
	onOptionSelect (option, event) {
		if (option === this._createPlaceholderOption) {
			this.createNewOption();
		} else {
			this.select.selectValue(option);
		}
	},
 
	focus () {
		this.select.focus();
	},
 
	render () {
		const {
			newOptionCreator,
			shouldKeyDownEventCreateNewOption,
			...restProps
		} = this.props;
 
		let { children } = this.props;
 
		// We can't use destructuring default values to set the children,
		// because it won't apply work if `children` is null. A falsy check is
		// more reliable in real world use-cases.
		if (!children) {
			children = defaultChildren;
		}
 
		const props = {
			...restProps,
			allowCreate: true,
			filterOptions: this.filterOptions,
			menuRenderer: this.menuRenderer,
			onInputChange: this.onInputChange,
			onInputKeyDown: this.onInputKeyDown,
			ref: (ref) => {
				this.select = ref;
 
				// These values may be needed in between Select mounts (when this.select is null)
				if (ref) {
					this.labelKey = ref.props.labelKey;
					this.valueKey = ref.props.valueKey;
				}
			}
		};
 
		return children(props);
	}
});
 
function defaultChildren (props) {
	return (
		<Select {...props} />
	);
};
 
function isOptionUnique ({ option, options, labelKey, valueKey }) {
	return options
		.filter((existingOption) =>
			existingOption[labelKey] === option[labelKey] ||
			existingOption[valueKey] === option[valueKey]
		)
		.length === 0;
};
 
function isValidNewOption ({ label }) {
	return !!label;
};
 
function newOptionCreator ({ label, labelKey, valueKey }) {
	const option = {};
	option[valueKey] = label;
 	option[labelKey] = label;
 	option.className = 'Select-create-option-placeholder';
 	return option;
};
 
function promptTextCreator (label) {
	return `Create option "${label}"`;
}
 
function shouldKeyDownEventCreateNewOption ({ keyCode }) {
	switch (keyCode) {
		case 9:   // TAB
		case 13:  // ENTER
		case 188: // COMMA
			return true;
	}
 
	return false;
};
 
module.exports = Creatable;