All files / components/ContextMenu ContextMenu.jsx

67.65% Statements 46/68
48.08% Branches 25/52
66.67% Functions 2/3
67.16% Lines 45/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 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              120x                       120x               120x                                                                                                                     120x                                 120x                             171x 171x                                 51x 51x           51x 63x 7x 7x 1x             51x 51x       2x                                                                     151x   151x 149x     2x                           2x       2x       2x           2x   2x             2x             2x             2x 2x                                                                                                                                               34x   34x 32x     2x   2x           2x       2x 2x                                       174x   174x 174x 174x   174x 174x   174x                                                
import React from 'react';
import _ from 'lodash';
import Portal from '../Portal/Portal';
import { createClass, getFirst, omitProps } from '../../util/component-types';
import { getAbsoluteBoundingClientRect } from '../../util/dom-helpers';
import { lucidClassNames } from '../../util/style-helpers';
 
const cx = lucidClassNames.bind('&-ContextMenu');
 
const {
	PropTypes: {
		bool,
		node,
		func,
		number,
		object,
		oneOf,
		string,
	},
} = React;
 
/**
 *
 * {"categories": ["utility"], "madeFrom": ["Portal"]}
 *
 * A ContextMenu component is used to render a target and a flyout which is positioned relative to the target.
 */
const ContextMenu = createClass({
	displayName: 'ContextMenu',
	propTypes: {
		/**
		 * `children` should include exactly one ContextMenu.Target and one ContextMenu.FlyOut.
		 */
		children: node,
		/**
		 * Appended to the component-specific class names set on the root element.
		 */
		className: string,
		/**
		 * Passed through to the root element.
		 */
		style: object,
		/**
		 * direction of the FlyOut relative to Target. Defaults to `'down'`.
		 */
		direction: oneOf(['down', 'up', 'right', 'left']),
		/**
		 * the px offset along the axis of the direction
		 */
		directonOffset: number,
		/**
		 * alignment of the Flyout relative to Target in the cross axis from `direction` Defaults to `'start'`
		 */
		alignment: oneOf(['start', 'center', 'end']),
		/**
		 * the px offset along the axis of the alignment
		 */
		alignmentOffset: number,
		/**
		 * an alternative to `alignmentOffset`, a function that is applied with the width/height of the flyout. the result is used as the `alignmentOffset`
		 */
		getAlignmentOffset: func,
		/**
		 * Indicates whether the FlyOut will render or not. Defaults to `true`.
		 */
		isExpanded: bool,
		/**
		 * Called when a click event happenens outside of the ContextMenu, with the signature `({ props, event }) => { ... }`
		 */
		onClickOut: func,
		/**
		 * The `id` of the FlyOut portal element that is appended to `document.body`. Defaults to a generated `id`.
		 */
		portalId: string,
	},
 
	components: {
		/**
		 * Renders an element of `elementType` (defaults to `<span>`) that the menu `FlyOut` anchors to.
		 */
		Target: createClass({
			displayName: 'ContextMenu.Target',
			propTypes: {
				elementType: string,
			},
			getDefaultProps() {
				return {
					elementType: 'span',
				};
			},
		}),
		/*
		 * Renders a `<Portal>` anchored to the `Target`.
		 */
		FlyOut: createClass({
			displayName: 'ContextMenu.FlyOut',
			propTypes: {
				style: object,
			},
		}),
	},
 
	getDefaultProps() {
		return {
			direction: 'down',
			directonOffset: 0,
			alignment: 'start',
			// no default alignmentOffset so it can default to result of `getAlignmentOffset`
			getAlignmentOffset: _.constant(0),
			isExpanded: true,
			onClickOut: null,
			portalId: null,
		};
	},
 
	getInitialState() {
		const {
			portalId,
		} = this.props;
		return {
			portalId: portalId || _.uniqueId('ContextMenu-Portal-'),
			targetRect: {
				bottom: 0,
				top: 0,
				left: 0,
				right: 0,
				height: 0,
				width: 0,
			},
			flyOutHeight: 0,
			flyOutWidth: 0,
		};
	},
 
	componentDidMount() {
 
		_.defer(() => this.alignFlyOut());
		this.updateTargetRectangleIntervalId = setInterval(() => {
			if (this.props.isExpanded) {
				this.alignFlyOut();
			}
		}, 10);
 
		this.onClickBodyEventListener = window.addEventListener('click', (event) => {
			if (this.props.onClickOut && this.refs.flyOutPortal) {
				const flyOutEl = this.refs.flyOutPortal.portalElement.firstChild;
				if (!(flyOutEl.contains(event.target) || this.refs.target.contains(event.target))) {
					this.props.onClickOut({ props: this.props, event });
				}
			}
		});
	},
 
	componentWillUnmount() {
		clearInterval(this.updateTargetRectangleIntervalId);
		document.body.removeEventListener('click', this.onClickBodyEventListener);
	},
 
	componentWillReceiveProps() {
		this.alignFlyOut();
	},
 
	statics: {
		CENTER: 'center',
		DOWN: 'down',
		END: 'end',
		LEFT: 'left',
		RIGHT: 'right',
		START: 'start',
		UP: 'up',
	},
 
	getFlyoutPosition() {
 
		const {
			props: {
				alignment,
				getAlignmentOffset,
				direction,
				directonOffset,
			},
			state: {
				flyOutHeight,
				flyOutWidth,
				targetRect: {
					bottom,
					left,
					right,
					top,
					width,
					height,
				},
			},
			refs: { flyOutPortal },
		} = this;
 
		if (!flyOutPortal) {
			return {};
		}
 
		const alignmentOffset = !_.isUndefined(this.props.alignmentOffset)
			? this.props.alignmentOffset
			: (alignment === ContextMenu.CENTER)
			? (getAlignmentOffset(_.includes([ContextMenu.UP, ContextMenu.DOWN], direction) ? flyOutWidth : flyOutHeight))
			: 0;
 
		const {
			CENTER,
			DOWN,
			END,
			LEFT,
			RIGHT,
			START,
			UP,
		} = ContextMenu;
 
		const {
			clientWidth,
		} = document.body;
 
		// default styling hides portal because its position can't be calculated
		// properly until after 1st render so here we unhide it if the ref exists
		const style = {
			opacity: 1,
			maxHeight: 'none',
			left: 'auto',
			top: 'auto',
		};
		const matcher = _.matches({ direction, alignment });
 
		Iif (matcher({ direction: UP, alignment: START })) {
			return {
				...style,
				top: top - flyOutHeight - directonOffset,
				left: left - alignmentOffset,
			};
		}
		Iif (matcher({ direction: UP, alignment: END })) {
			return {
				...style,
				top: top - flyOutHeight - directonOffset,
				right: clientWidth - right - alignmentOffset,
			};
		}
		Iif (matcher({ direction: UP, alignment: CENTER })) {
			return {
				...style,
				top: top - flyOutHeight - directonOffset,
				left: left + (width / 2) - (flyOutWidth / 2) + alignmentOffset,
			};
		}
		Eif (matcher({ direction: DOWN, alignment: START })) {
			return {
				...style,
				top: bottom + directonOffset,
				left: left - alignmentOffset,
			};
		}
		if (matcher({ direction: DOWN, alignment: END })) {
			return {
				...style,
				top: bottom + directonOffset,
				right: clientWidth - right - alignmentOffset,
			};
		}
		if (matcher({ direction: DOWN, alignment: CENTER })) {
			return {
				...style,
				top: bottom + directonOffset,
				left: left + (width / 2) - (flyOutWidth / 2) + alignmentOffset,
			};
		}
		if (matcher({ direction: LEFT, alignment: START })) {
			return {
				...style,
				top: top - alignmentOffset,
				right: clientWidth - left + directonOffset,
			};
		}
		if (matcher({ direction: LEFT, alignment: END })) {
			return {
				...style,
				top: top - flyOutHeight + height + alignmentOffset,
				right: clientWidth - left + directonOffset,
			};
		}
		if (matcher({ direction: LEFT, alignment: CENTER })) {
			return {
				...style,
				top: top - (flyOutHeight / 2) + (height / 2) + alignmentOffset,
				right: clientWidth - left + directonOffset,
			};
		}
		if (matcher({ direction: RIGHT, alignment: START })) {
			return {
				...style,
				top: top - alignmentOffset,
				left: left + width + directonOffset,
			};
		}
		if (matcher({ direction: RIGHT, alignment: END })) {
			return {
				...style,
				top: top - flyOutHeight + height + alignmentOffset,
				left: left + width + directonOffset,
			};
		}
		if (matcher({ direction: RIGHT, alignment: CENTER })) {
			return {
				...style,
				top: top - (flyOutHeight / 2) + (height / 2) + alignmentOffset,
				left: left + width + directonOffset,
			};
		}
 
	},
 
	alignFlyOut() {
 
		const {
			refs: {
				flyOutPortal,
				target,
			},
		} = this;
 
		if (!target || !flyOutPortal) {
			return;
		}
 
		const targetRect = getAbsoluteBoundingClientRect(target);
 
		Iif (!flyOutPortal) {
			return this.setState({
				targetRect,
			});
		}
 
		const flyOutEl = flyOutPortal.portalElement.firstChild;
		const {
			height,
			width,
		} = flyOutEl.getBoundingClientRect();
		this.setState({
			targetRect,
			flyOutHeight: height,
			flyOutWidth: width,
		});
	},
 
	render() {
		const {
			props: {
				className,
				direction,
				isExpanded,
				style,
				...passThroughs,
			},
			state: {
				portalId,
				targetRect,
			},
		} = this;
 
		const targetElement = getFirst(this.props, ContextMenu.Target);
		const targetChildren = _.get(targetElement, 'props.children', null);
		const TargetElementType = targetElement.props.elementType;
 
		const flyoutElement = getFirst(this.props, ContextMenu.FlyOut);
		const flyProps = _.get(flyoutElement, 'props', {});
 
		return (
			<TargetElementType ref='target' {...omitProps(passThroughs, ContextMenu)} className={cx('&', className)} style={style}>
				{targetChildren}
				{isExpanded ? (
					<Portal
						ref='flyOutPortal'
						{...flyProps}
						className={cx('&-FlyOut', `&-FlyOut-${direction}`, flyProps.className)}
						portalId={portalId}
						style={{
							minWidth: targetRect.width,
							...this.getFlyoutPosition(),
							...flyProps.style,
						}}
					>
						{flyProps.children}
					</Portal>
				) : null}
			</TargetElementType>
		);
	},
});
 
export default ContextMenu;