UNPKG

rmwc

Version:

A thin React wrapper for Material Design (Web) Components

235 lines (195 loc) 9.33 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.withFoundation = exports.syncFoundationProp = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var React = _interopRequireWildcard(_react); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /************************************************************************ * Utils ***********************************************************************/ var requestFrames = function requestFrames(callback, frameCount) { var currentFrame = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; if (currentFrame < frameCount) { window.requestAnimationFrame(function () { return requestFrames(callback, frameCount, currentFrame + 1); }); } else { callback(); } }; /** Copies all known properties from source to target. This is being used in here for class merging. */ var copyProperties = function copyProperties(target, source) { var allPropertyNames = Object.getOwnPropertyNames(source); allPropertyNames.forEach(function (propertyName) { if (String(propertyName).match( // eslint-disable-next-line max-len /^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/)) { return; } var value = Object.getOwnPropertyDescriptor(source, propertyName); value !== undefined && Object.defineProperty(target, propertyName, value); }); }; /** Simplifies redundant checks for syncWithProps */ var syncFoundationProp = exports.syncFoundationProp = function syncFoundationProp(prop, foundationValue, callback) { if (prop !== undefined && prop !== foundationValue) { callback(); } }; /************************************************************************ * HOC ***********************************************************************/ var withFoundation = exports.withFoundation = function withFoundation(_ref) { var FoundationConstructor = _ref.constructor, _ref$adapter = _ref.adapter, adapter = _ref$adapter === undefined ? {} : _ref$adapter, _ref$refs = _ref.refs, refs = _ref$refs === undefined ? ['root_'] : _ref$refs; var F = function (_React$Component) { _inherits(Foundation, _React$Component); function Foundation(props) { _classCallCheck(this, Foundation); var _this = _possibleConstructorReturn(this, (Foundation.__proto__ || Object.getPrototypeOf(Foundation)).call(this, props)); _this.foundationRefs = refs.reduce(function (acc, r) { // Here we gracefully merge two refs together if one was passed down the chain var propName = props.elementRef && props.elementRef.refName_ === r ? 'elementRef' : r; acc[r] = function (ref) { // React will return a null ref when unmounting which will // in turn make our adapters error out. Make sure we only set a ref if its truthy. if (ref) { //$FlowFixMe _this[r] = ref; props[propName] && (typeof props === 'undefined' ? 'undefined' : _typeof(props)) === 'object' && props[propName](ref); } }; // Store the refname on the object so we can reference it later and merge two of the same references together acc[r].refName_ = r; return acc; }, {}); //$FlowFixMe _this.syncWithProps = _this.syncWithProps.bind(_this); return _this; } _createClass(Foundation, [{ key: 'componentDidMount', value: function componentDidMount() { this.initFoundation(); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { this._safeSyncWithProps(nextProps); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { var _this2 = this; this.destroyComponent(); // We need to hold onto our refs until all child components are unmounted // Here we just wait a few frames and set them to null so garbage collection will take over. requestFrames(function () { refs.forEach(function (refName) { //$FlowFixMe _this2[refName] && (_this2[refName] = undefined); }); }, 3); } }, { key: '_safeSyncWithProps', value: function _safeSyncWithProps(props) { this.foundation_ && this.syncWithProps(props); } }, { key: 'initFoundation', value: function initFoundation() { this.foundation_ = this.getDefaultFoundation(); // bind custom adapter methods passed into the factory for (var handlerName in adapter) { var handler = adapter[handlerName]; //$FlowFixMe this.foundation_.adapter_[handlerName] = handler.bind(this); } this.initialize(); this.foundation_ && this.foundation_.init(); this.initialSyncWithDOM(); this._safeSyncWithProps(this.props); // this method should be deprecated in the future in favor of standard refs typeof this.props.apiRef === 'function' && this.props.apiRef(this); } }, { key: 'destroyComponent', value: function destroyComponent() { this.destroy(); this.foundation_ && this.foundation_.destroy(); this.foundation_ = null; } }, { key: 'syncWithProps', value: function syncWithProps(nextProps) {} }, { key: 'initialize', value: function initialize() {} }, { key: 'initialSyncWithDOM', value: function initialSyncWithDOM() {} }, { key: 'destroy', value: function destroy() {} }, { key: 'getDefaultFoundation', value: function getDefaultFoundation() { return { adapter_: {}, init: function init() {}, destroy: function destroy() {} }; } /** * Fires a cross-browser-compatible custom event from the component root of the given type, */ }, { key: 'emit', value: function emit(evtType, evtData) { var shouldBubble = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var evt = void 0; if (typeof CustomEvent === 'function') { evt = new CustomEvent(evtType, { detail: evtData, bubbles: shouldBubble }); } else { evt = document.createEvent('CustomEvent'); evt.initCustomEvent(evtType, shouldBubble, false, evtData); } var baseName = evtType.split(':').slice(-1).pop() || ''; var propName = 'on' + baseName.charAt(0).toUpperCase() + baseName.slice(1); this.props[propName] && this.props[propName](evt); // MDC can change state internally, if we are triggering a handler, re-sync with our props this._safeSyncWithProps(this.props); return evt; } }, { key: 'listen', value: function listen(evtType, handler) { var root = this.root_; root && root.addEventListener(evtType, handler); } }, { key: 'unlisten', value: function unlisten(evtType, handler) { var root = this.root_; root && root.removeEventListener(evtType, handler); } }]); return Foundation; }(React.Component); copyProperties(F.prototype, FoundationConstructor.prototype); return F; };