UNPKG

lucid-ui

Version:

A UI component library from AppNexus.

483 lines (397 loc) 21.6 kB
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } import _keys from "lodash/keys"; import _get from "lodash/get"; import _defer from "lodash/defer"; import _includes from "lodash/includes"; import _isUndefined from "lodash/isUndefined"; import _constant from "lodash/constant"; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /* eslint-disable react/prop-types */ import React from 'react'; import PropTypes from 'react-peek/prop-types'; import Portal from '../Portal/Portal'; import { getFirst, omitProps } from '../../util/component-types'; import { getAbsoluteBoundingClientRect, sharesAncestor } from '../../util/dom-helpers'; import { lucidClassNames, uniqueName } from '../../util/style-helpers'; var cx = lucidClassNames.bind('&-ContextMenu'); var bool = PropTypes.bool, node = PropTypes.node, func = PropTypes.func, number = PropTypes.number, object = PropTypes.object, oneOf = PropTypes.oneOf, string = PropTypes.string; var ContextMenuTarget = function ContextMenuTarget(_props) { return null; }; ContextMenuTarget.displayName = 'ContextMenu.Target'; ContextMenuTarget.propName = 'Target'; ContextMenuTarget.peek = { description: "Renders an element of `elementType` (defaults to `<span>`)\n\tthat the menu `FlyOut` anchors to." }; ContextMenuTarget.propTypes = { elementType: string }; ContextMenuTarget.defaultProps = { elementType: 'span' }; var ContextMenuFlyOut = function ContextMenuFlyOut(_props) { return null; }; ContextMenuFlyOut.displayName = 'ContextMenu.FlyOut'; ContextMenuFlyOut.propName = 'FlyOut'; ContextMenuFlyOut.peek = { description: "Renders a `<Portal>` anchored to the `Target`." }; /** These have to be lowercase because: * 1. the key and value have to match * (limitation of TypeScript, see: https://github.com/Microsoft/TypeScript/issues/17198) * 2. the values are currently lowercase in the propTypes * */ export var EnumDirection; (function (EnumDirection) { EnumDirection["up"] = "up"; EnumDirection["down"] = "down"; EnumDirection["left"] = "left"; EnumDirection["right"] = "right"; })(EnumDirection || (EnumDirection = {})); export var EnumAlignment; (function (EnumAlignment) { EnumAlignment["start"] = "start"; EnumAlignment["center"] = "center"; EnumAlignment["end"] = "end"; })(EnumAlignment || (EnumAlignment = {})); /** 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 */ var defaultFlyoutPosition = { opacity: 1, maxHeight: 'none', left: 'auto', top: 'auto' }; var ContextMenu = /*#__PURE__*/function (_React$Component) { _inherits(ContextMenu, _React$Component); var _super = _createSuper(ContextMenu); function ContextMenu() { var _this; _classCallCheck(this, ContextMenu); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _super.call.apply(_super, [this].concat(args)); _defineProperty(_assertThisInitialized(_this), "targetRef", /*#__PURE__*/React.createRef()); _defineProperty(_assertThisInitialized(_this), "flyOutPortalRef", /*#__PURE__*/React.createRef()); _defineProperty(_assertThisInitialized(_this), "state", { portalId: _this.props.portalId || uniqueName('ContextMenu-Portal-'), targetRect: { bottom: 0, top: 0, left: 0, right: 0, height: 0, width: 0 }, flyOutHeight: 0, flyOutWidth: 0 }); _defineProperty(_assertThisInitialized(_this), "continueAlignment", false); _defineProperty(_assertThisInitialized(_this), "beginAlignment", function () { _this.continueAlignment = true; window.requestAnimationFrame(_this.handleAlignment); }); _defineProperty(_assertThisInitialized(_this), "endAlignment", function () { _this.continueAlignment = false; }); _defineProperty(_assertThisInitialized(_this), "handleAlignment", function () { if (_this.continueAlignment) { if (_this.props.isExpanded) { _this.alignFlyOut(true); } window.requestAnimationFrame(_this.handleAlignment); } }); _defineProperty(_assertThisInitialized(_this), "handleBodyClick", function (event) { var _assertThisInitialize = _assertThisInitialized(_this), props = _assertThisInitialize.props, onClickOut = _assertThisInitialize.props.onClickOut, flyOutPortalRef = _assertThisInitialize.flyOutPortalRef, targetRef = _assertThisInitialize.targetRef; // in this block, I assert the type of target because EventTarget -> Element -> HtmlElement (from general to specific typing) var eventTarget = event.target; if (onClickOut && flyOutPortalRef.current && targetRef.current && eventTarget && eventTarget.nodeName) { var flyOutEl = flyOutPortalRef.current.portalElement.firstChild; var wasALabelClick = eventTarget.nodeName === 'INPUT' && sharesAncestor(eventTarget, targetRef.current, 'LABEL'); // Attempt to detect <label> click and ignore it if (wasALabelClick) { return; } if (!(flyOutEl.contains(eventTarget) || targetRef.current.contains(eventTarget)) && event.type === 'click') { onClickOut({ props: props, event: event }); } } }); _defineProperty(_assertThisInitialized(_this), "calcAlignmentOffset", function (_ref) { var direction = _ref.direction, alignment = _ref.alignment, getAlignmentOffset = _ref.getAlignmentOffset, flyOutHeight = _ref.flyOutHeight, flyOutWidth = _ref.flyOutWidth; var UP = EnumDirection.up, DOWN = EnumDirection.down; var CENTER = EnumAlignment.center; return !_isUndefined(_this.props.alignmentOffset) ? _this.props.alignmentOffset : alignment === CENTER ? getAlignmentOffset(_includes([UP, DOWN], direction) ? flyOutWidth : flyOutHeight) : 0; }); _defineProperty(_assertThisInitialized(_this), "getMatch", function (_ref2) { var _UP, _DOWN, _LEFT, _RIGHT, _options; var direction = _ref2.direction, alignment = _ref2.alignment, flyOutHeight = _ref2.flyOutHeight, flyOutWidth = _ref2.flyOutWidth, clientWidth = _ref2.clientWidth, directonOffset = _ref2.directonOffset, alignmentOffset = _ref2.alignmentOffset, top = _ref2.top, bottom = _ref2.bottom, left = _ref2.left, right = _ref2.right, width = _ref2.width, height = _ref2.height; var UP = EnumDirection.up, DOWN = EnumDirection.down, LEFT = EnumDirection.left, RIGHT = EnumDirection.right; var START = EnumAlignment.start, CENTER = EnumAlignment.center, END = EnumAlignment.end; var options = (_options = {}, _defineProperty(_options, UP, (_UP = {}, _defineProperty(_UP, START, { top: top - flyOutHeight - directonOffset, left: left - alignmentOffset }), _defineProperty(_UP, CENTER, { top: top - flyOutHeight - directonOffset, left: left + width / 2 - flyOutWidth / 2 + alignmentOffset }), _defineProperty(_UP, END, { top: top - flyOutHeight - directonOffset, right: clientWidth - right - alignmentOffset }), _UP)), _defineProperty(_options, DOWN, (_DOWN = {}, _defineProperty(_DOWN, START, { top: bottom + directonOffset, left: left - alignmentOffset }), _defineProperty(_DOWN, CENTER, { top: bottom + directonOffset, left: left + width / 2 - flyOutWidth / 2 + alignmentOffset }), _defineProperty(_DOWN, END, { top: bottom + directonOffset, right: clientWidth - right - alignmentOffset }), _DOWN)), _defineProperty(_options, LEFT, (_LEFT = {}, _defineProperty(_LEFT, START, { top: top - alignmentOffset, right: clientWidth - left + directonOffset }), _defineProperty(_LEFT, CENTER, { top: top - flyOutHeight / 2 + height / 2 + alignmentOffset, right: clientWidth - left + directonOffset }), _defineProperty(_LEFT, END, { top: top - flyOutHeight + height + alignmentOffset, right: clientWidth - left + directonOffset }), _LEFT)), _defineProperty(_options, RIGHT, (_RIGHT = {}, _defineProperty(_RIGHT, START, { top: top - alignmentOffset, left: left + width + directonOffset }), _defineProperty(_RIGHT, CENTER, { top: top - flyOutHeight / 2 + height / 2 + alignmentOffset, left: left + width + directonOffset }), _defineProperty(_RIGHT, END, { top: top - flyOutHeight + height + alignmentOffset, left: left + width + directonOffset }), _RIGHT)), _options); return _objectSpread(_objectSpread({}, defaultFlyoutPosition), options[direction][alignment]); }); _defineProperty(_assertThisInitialized(_this), "getFlyoutPosition", function () { var _assertThisInitialize2 = _assertThisInitialized(_this), _assertThisInitialize3 = _assertThisInitialize2.props, direction = _assertThisInitialize3.direction, alignment = _assertThisInitialize3.alignment, _assertThisInitialize4 = _assertThisInitialize3.directonOffset, directonOffset = _assertThisInitialize4 === void 0 ? ContextMenu.defaultProps.directonOffset : _assertThisInitialize4, _assertThisInitialize5 = _assertThisInitialize3.getAlignmentOffset, getAlignmentOffset = _assertThisInitialize5 === void 0 ? ContextMenu.defaultProps.getAlignmentOffset : _assertThisInitialize5, _assertThisInitialize6 = _assertThisInitialize2.state, flyOutHeight = _assertThisInitialize6.flyOutHeight, flyOutWidth = _assertThisInitialize6.flyOutWidth, _assertThisInitialize7 = _assertThisInitialize6.targetRect, bottom = _assertThisInitialize7.bottom, left = _assertThisInitialize7.left, right = _assertThisInitialize7.right, top = _assertThisInitialize7.top, width = _assertThisInitialize7.width, height = _assertThisInitialize7.height, flyOutPortalRef = _assertThisInitialize2.flyOutPortalRef; var clientWidth = document.body.clientWidth; if (!flyOutPortalRef.current) return {}; if (direction && alignment) { return _this.getMatch({ direction: direction, alignment: alignment, flyOutHeight: flyOutHeight, flyOutWidth: flyOutWidth, clientWidth: clientWidth, directonOffset: directonOffset, alignmentOffset: _this.calcAlignmentOffset({ direction: direction, alignment: alignment, getAlignmentOffset: getAlignmentOffset, flyOutHeight: flyOutHeight, flyOutWidth: flyOutWidth }), top: top, bottom: bottom, left: left, right: right, width: width, height: height }); } }); _defineProperty(_assertThisInitialized(_this), "alignFlyOut", function () { var doRedunancyCheck = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var _assertThisInitialize8 = _assertThisInitialized(_this), flyOutPortalRef = _assertThisInitialize8.flyOutPortalRef, targetRef = _assertThisInitialize8.targetRef; if (!targetRef.current || !flyOutPortalRef.current) { return; } var targetRect = getAbsoluteBoundingClientRect(targetRef.current); var portalRef = flyOutPortalRef.current; // Don't cause a state-change if target dimensions are the same if (doRedunancyCheck && targetRect.left === _this.state.targetRect.left && targetRect.top === _this.state.targetRect.top && targetRect.height === _this.state.targetRect.height && targetRect.width === _this.state.targetRect.width) { return; } if (portalRef) { var flyOutEl = portalRef.portalElement.firstChild; var _getBoundingClientRec = flyOutEl.getBoundingClientRect(), height = _getBoundingClientRec.height, width = _getBoundingClientRec.width; _this.setState({ targetRect: targetRect, flyOutHeight: height, flyOutWidth: width }); } }); return _this; } _createClass(ContextMenu, [{ key: "UNSAFE_componentWillReceiveProps", value: function UNSAFE_componentWillReceiveProps() { var _this2 = this; _defer(function () { return _this2.alignFlyOut(); }); } }, { key: "componentDidMount", value: function componentDidMount() { var _this3 = this; _defer(function () { return _this3.alignFlyOut(); }); this.beginAlignment(); document.body.addEventListener('touchstart', this.handleBodyClick); document.body.addEventListener('click', this.handleBodyClick); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.endAlignment(); document.body.removeEventListener('click', this.handleBodyClick); } }, { key: "render", value: function render() { var _this$props = this.props, className = _this$props.className, direction = _this$props.direction, isExpanded = _this$props.isExpanded, style = _this$props.style, minWidthOffset = _this$props.minWidthOffset, passThroughs = _objectWithoutProperties(_this$props, ["className", "direction", "isExpanded", "style", "minWidthOffset"]), _this$state = this.state, portalId = _this$state.portalId, targetRect = _this$state.targetRect; var targetElement = getFirst(this.props, ContextMenu.Target); var targetChildren = _get(targetElement, 'props.children', null); var TargetElementType = targetElement.props.elementType; var flyoutElement = getFirst(this.props, ContextMenu.FlyOut); var flyProps = _get(flyoutElement, 'props', {}); return /*#__PURE__*/React.createElement(TargetElementType, _extends({ ref: this.targetRef }, omitProps(passThroughs, undefined, _keys(ContextMenu.propTypes)), { className: cx('&', className), style: style }), targetChildren, isExpanded ? /*#__PURE__*/React.createElement(Portal, _extends({ ref: this.flyOutPortalRef }, flyProps, { className: cx('&-FlyOut', "&-FlyOut-".concat(direction), flyProps.className), portalId: portalId, style: _objectSpread(_objectSpread({ minWidth: targetRect.width + minWidthOffset }, this.getFlyoutPosition()), flyProps.style) }), flyProps.children) : null); } }]); return ContextMenu; }(React.Component); _defineProperty(ContextMenu, "displayName", 'ContextMenu'); _defineProperty(ContextMenu, "peek", { description: "\n\t\t\tA ContextMenu component is used to render a target and a flyout which\n\t\t\tis positioned relative to the target.\n\t\t", categories: ['utility'], madeFrom: ['Portal'] }); _defineProperty(ContextMenu, "propTypes", { children: node, className: string, style: object, direction: oneOf(['down', 'up', 'right', 'left']), directonOffset: number, alignment: oneOf(['start', 'center', 'end']), alignmentOffset: number, getAlignmentOffset: func, minWidthOffset: number, isExpanded: bool, onClickOut: func, portalId: string, FlyOut: node, Target: node }); _defineProperty(ContextMenu, "UP", EnumDirection.up); _defineProperty(ContextMenu, "DOWN", EnumDirection.down); _defineProperty(ContextMenu, "LEFT", EnumDirection.left); _defineProperty(ContextMenu, "RIGHT", EnumDirection.right); _defineProperty(ContextMenu, "START", EnumAlignment.start); _defineProperty(ContextMenu, "CENTER", EnumAlignment.center); _defineProperty(ContextMenu, "END", EnumAlignment.end); _defineProperty(ContextMenu, "Target", ContextMenuTarget); _defineProperty(ContextMenu, "FlyOut", ContextMenuFlyOut); _defineProperty(ContextMenu, "defaultProps", { direction: 'down', directonOffset: 0, minWidthOffset: 0, alignment: 'start', // no default alignmentOffset so it can default to result of `getAlignmentOffset` getAlignmentOffset: _constant(0), isExpanded: true, onClickOut: null, portalId: null }); export default ContextMenu;