UNPKG

@enact/ui

Version:

A collection of simplified unstyled cross-platform UI components for Enact

248 lines (245 loc) 12.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Cancelable = void 0; Object.defineProperty(exports, "addCancelHandler", { enumerable: true, get: function get() { return _cancelHandler.addCancelHandler; } }); exports["default"] = void 0; Object.defineProperty(exports, "removeCancelHandler", { enumerable: true, get: function get() { return _cancelHandler.removeCancelHandler; } }); var _handle = require("@enact/core/handle"); var _hoc = _interopRequireDefault(require("@enact/core/hoc")); var _keymap = require("@enact/core/keymap"); var _invariant = _interopRequireDefault(require("invariant")); var _propTypes = _interopRequireDefault(require("prop-types")); var _react = require("react"); var _cancelHandler = require("./cancelHandler"); var _modalHandler = require("./modalHandler"); var _jsxRuntime = require("react/jsx-runtime"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 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, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } 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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : 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; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } 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() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /** * Provides components and methods to add support for handling cancel actions. * * @module ui/Cancelable * @exports addCancelHandler * @exports Cancelable * @exports removeCancelHandle */ /** * Default config for {@link ui/Cancelable.Cancelable} * * @memberof ui/Cancelable.Cancelable * @hocconfig */ var defaultConfig = { /** * Called when a cancel action is invoked by the user. * * If it is a string, the cancel handler will attempt to invoke a function passed as a prop of * that name. If it is a function, that function will be called with the current props as the * only argument. * * If the function handles the cancel action, it should call `stopPropagation()` on the provided * event object prevent container or `modal` Cancelable instances from also handling the action. * * @type {String|Function} * @required * @memberof ui/Cancelable.Cancelable.defaultConfig */ onCancel: null, /** * Subscribes to cancel events globally for this instance. * * When `true`, the `Cancelable` instance will handle cancel events globally that successfully * bubble up to `window` regardless of which component is focused. * * `modal` cancel handlers are processed in reverse of the order they are created such that the * innermost instance (in terms of the component hierarchy) have the first opportunity to handle * the event before its container components. * * @type {String} * @default false * @memberof ui/Cancelable.Cancelable.defaultConfig */ modal: false, /** * The component that will contain the wrapped component. * * When set, the wrapped component will be contained within an instance of `component`. This may * be necessary if the props passed to the wrapped component are not placed on the root element. * * @type {Component} * @default null * @memberof ui/Cancelable.Cancelable.defaultConfig */ component: null }; // Add keymap for escape key (0, _keymap.add)('cancel', 27); /** * A higher-order component that adds support to a component to handle cancel actions. * * The cancel event may be handled either by a design-time config function or a run-time prop * function. If the component handles the event and wants to prevent upstream components from also * handling the event, the callback should invoke `stopPropagation()` on the event object. * * Note: This HoC passes a number of props to the wrapped component that should be passed to the * main DOM node. * * Usage of config function: * ``` * import Cancelable from '@enact/ui/Cancelable'; * * const MyComponent = ({myProp, ...rest}) => ( * <div {...rest}>{myProp}</div> * ); * ... * const CancelableComponent = Cancelable( * {cancel: function (ev, props) { * // Can inspect either the `onCancel` event, `ev`, and/or the `props` to determine how * // to handle the event (e.g. invoking an event handler from `props`). * * // Stop upstream instances of Cancelable from handling the event * ev.stopPropagaion(); * }}, * MyComponent * ); * ``` * * Usage of prop function: * ``` * import Cancelable from '@enact/ui/Cancelable'; * * const CancelableComponent = Cancelable( * // When a cancel action is received and a handler function exists for the prop * // `onCancel`, it will be invoked and passed the `onCancel` event object. * {cancel: 'onCancel'}, * MyComponent * ); * ``` * * @class Cancelable * @memberof ui/Cancelable * @hoc * @public */ var Cancelable = exports.Cancelable = (0, _hoc["default"])(defaultConfig, function (config, Wrapped) { var _class; var onCancel = config.onCancel, modal = config.modal, Component = config.component; !onCancel ? process.env.NODE_ENV !== "production" ? (0, _invariant["default"])(false, 'onCancel must be specified with Cancelable') : (0, _invariant["default"])(false) : void 0; var onCancelIsString = typeof onCancel === 'string'; var onCancelIsFunction = typeof onCancel === 'function'; var dispatchCancelToConfig = function dispatchCancelToConfig(ev, props) { // by default, we return false which allows event propagation because it will "break" the // handler chain and not call `stop` and `stopImmediate` below var stopped = false; var cancelEvent = { type: 'onCancel', stopPropagation: function stopPropagation() { stopped = true; } }; if (onCancelIsString && typeof props[onCancel] === 'function') { // use the custom event name from the config cancelEvent.type = onCancel; props[onCancel](cancelEvent); } else if (onCancelIsFunction) { onCancel(cancelEvent, props); } return stopped; }; return _class = /*#__PURE__*/function (_ReactComponent) { _inherits(_class, _ReactComponent); var _super = _createSuper(_class); function _class(props) { var _this; _classCallCheck(this, _class); _this = _super.call(this, props); _this.handle = _handle.handle.bind(_assertThisInitialized(_this)); _this.handleCancel = _this.handle(_cancelHandler.forCancel, (0, _handle.forwardCustom)('onCancel'), dispatchCancelToConfig, _handle.stop, _handle.stopImmediate); _this.handleKeyUp = _this.handle((0, _handle.forward)('onKeyUp'), // nesting handlers for DRYness. note that if any conditions return false in // this.handleCancel(), this handler chain will stop too _this.handleCancel); _this.isFirstRender = true; return _this; } _createClass(_class, [{ key: "componentWillUnmount", value: function componentWillUnmount() { if (modal) { (0, _modalHandler.removeModal)(this); } } }, { key: "renderWrapped", value: function renderWrapped(props) { return /*#__PURE__*/(0, _jsxRuntime.jsx)(Component, { onKeyUp: this.handleKeyUp, children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread({}, props)) }); } }, { key: "renderUnwrapped", value: function renderUnwrapped(props) { return /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread(_objectSpread({}, props), {}, { onKeyUp: this.handleKeyUp })); } }, { key: "renderModal", value: function renderModal(props) { return /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread({}, props)); } }, { key: "render", value: function render() { var props = Object.assign({}, this.props); delete props.onCancel; delete props[onCancel]; if (this.isFirstRender && modal) { (0, _modalHandler.addModal)(this); this.isFirstRender = false; } return modal && this.renderModal(props) || Component && this.renderWrapped(props) || this.renderUnwrapped(props); } }]); return _class; }(_react.Component), _class.displayName = 'Cancelable', _class.propTypes = /** @lends ui/Cancelable.Cancelable.prototype */{ /** * Called when a cancel action is received. * * This callback is invoked for every cancel action before the config or prop handler is * invoked. * * @type {Function} * @public */ onCancel: _propTypes["default"].func }, _class; }); var _default = exports["default"] = Cancelable;