@enact/ui
Version:
A collection of simplified unstyled cross-platform UI components for Enact
246 lines (243 loc) • 11.7 kB
JavaScript
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(e) { return e && e.__esModule ? e : { "default": e }; }
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(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : 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 _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } /**
* 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 {Boolean}
* @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.stopPropagation();
* }},
* 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) {
function _Class(props) {
var _this;
_classCallCheck(this, _Class);
_this = _callSuper(this, _Class, [props]);
_this.handle = _handle.handle.bind(_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;
}
_inherits(_Class, _ReactComponent);
return _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);
}
}]);
}(_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;
;