UNPKG

@enact/sandstone

Version:

Large-screen/TV support library for Enact, containing a variety of UI components.

316 lines (312 loc) 16.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = exports.ViewportDecorator = exports.ViewportBase = exports.Viewport = exports.PanelsStateContext = void 0; var _classnames = _interopRequireDefault(require("classnames")); var _handle = _interopRequireWildcard(require("@enact/core/handle")); var _util = require("@enact/core/util"); var _I18nDecorator = require("@enact/i18n/I18nDecorator"); var _spotlight = _interopRequireDefault(require("@enact/spotlight")); var _Pause = _interopRequireDefault(require("@enact/spotlight/Pause")); var _ViewManager = _interopRequireWildcard(require("@enact/ui/ViewManager")); var _invariant = _interopRequireDefault(require("invariant")); var _propTypes = _interopRequireDefault(require("prop-types")); var _compose = _interopRequireDefault(require("ramda/src/compose")); var _react = require("react"); var _captureKeys = require("./captureKeys"); var _SharedStateDecorator = _interopRequireWildcard(require("../SharedStateDecorator")); var _util2 = require("./util"); var _ViewportModule = _interopRequireDefault(require("./Viewport.module.css")); var _jsxRuntime = require("react/jsx-runtime"); var _excluded = ["arranger", "children", "generateId", "index", "noAnimation", "rtl", "type"]; var _class; function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } 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 _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 _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); } var PanelsStateContext = exports.PanelsStateContext = /*#__PURE__*/(0, _react.createContext)({}); /** * The container for a set of Panels * * @class Viewport * @memberof sandstone/Panels * @private */ var ViewportBase = exports.ViewportBase = (_class = /*#__PURE__*/function (_Component) { _inherits(ViewportBase, _Component); var _super = _createSuper(ViewportBase); function ViewportBase() { var _this; _classCallCheck(this, ViewportBase); _this = _super.call(this); _this.addTransitioningClass = function () { if (_this.node) { _this.node.classList.add(_ViewportModule["default"].transitioning); } return true; }; _this.removeTransitioningClass = function () { if (_this.node) { _this.node.classList.remove(_ViewportModule["default"].transitioning); } return true; }; _this.pause = function () { (0, _captureKeys.startCapture)(); _this.paused.pause(); }; _this.resume = function () { (0, _captureKeys.stopCapture)(); _this.paused.resume(); }; _this.handle = _handle["default"].bind(_assertThisInitialized(_this)); _this.handleTransition = _this.handle((0, _handle.forward)('onTransition'), _this.removeTransitioningClass, _this.resume); _this.handleWillTransition = _this.handle((0, _handle.forward)('onWillTransition'), _this.addTransitioningClass, _this.pause); _this.mapChildren = function (children, generateId) { return (0, _util.mapAndFilterChildren)(children, function (child, index) { var _child$props$spotligh = child.props.spotlightId, spotlightId = _child$props$spotligh === void 0 ? generateId(index, 'panel-container', _spotlight["default"].remove) : _child$props$spotligh; var props = { spotlightId: spotlightId, 'data-index': index }; // Respect Panel-configured autoFocus if it is set if (child.props.autoFocus == null) { if (_this.props.autoFocus) { // if not and Viewport-wide autoFocus is configured, use it props.autoFocus = _this.props.autoFocus; } else if (_this.state.direction === 'forward') { // Otherwise, only set autofocus when moving forward props.autoFocus = 'default-element'; } } return /*#__PURE__*/(0, _react.cloneElement)(child, props); }); }; _this.getEnteringProp = function (noAnimation) { return noAnimation ? null : 'hideChildren'; }; _this.nodeRef = /*#__PURE__*/(0, _react.createRef)(); _this.paused = new _Pause["default"]('Viewport'); _this.state = { prevIndex: -1, direction: 'forward' }; return _this; } _createClass(ViewportBase, [{ key: "componentDidMount", value: function componentDidMount() { this.node = this.nodeRef.current; } }, { key: "shouldComponentUpdate", value: function shouldComponentUpdate(_ref) { var index = _ref.index; // FIXME: This is non-standard but is the only API in the current architecture to do this // work. It should be refactored in the future in order to not overload this method with // side effects. if (index !== this.props.index) { var current = _spotlight["default"].getCurrent(); // :scope refers to the current node and allows us to use the direct descendant '>' // selector to limit the results to views (and not other components with [data-index]) var panel = this.node.querySelector(":scope > [data-index='".concat(this.props.index, "']")); if (current && panel && panel.contains(current)) { current.blur(); } } return true; } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { for (var i = prevProps.index; this.context && i > this.props.index; i--) { this.context["delete"](i); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.resume(); } }, { key: "render", value: function render() { var _this$props = this.props, arranger = _this$props.arranger, children = _this$props.children, generateId = _this$props.generateId, index = _this$props.index, noAnimation = _this$props.noAnimation, rtl = _this$props.rtl, type = _this$props.type, rest = _objectWithoutProperties(_this$props, _excluded); var enteringProp = this.getEnteringProp(noAnimation); var mappedChildren = this.mapChildren(children, generateId); var className = (0, _classnames["default"])(_ViewportModule["default"].viewport, rest.className); var count = _react.Children.count(mappedChildren); !(index === 0 && count === 0 || index < count) ? process.env.NODE_ENV !== "production" ? (0, _invariant["default"])(false, "Panels index, ".concat(index, ", is invalid for number of children, ").concat(count)) : (0, _invariant["default"])(false) : void 0; // Relay each of the state-specific props to the context var panelsContext = { type: type, index: index, count: count }; delete rest.className; return /*#__PURE__*/(0, _jsxRuntime.jsx)(PanelsStateContext.Provider, { value: panelsContext, children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_ViewManager["default"], _objectSpread(_objectSpread({}, rest), {}, { arranger: arranger, className: className, component: "main", duration: 250, enteringDelay: 100 // TODO: Can we remove this? , enteringProp: enteringProp, index: index, noAnimation: noAnimation, onTransition: this.handleTransition, onWillTransition: this.handleWillTransition, ref: this.nodeRef, rtl: rtl, children: mappedChildren })) }); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(props, state) { return { prevIndex: props.index, direction: state.prevIndex > props.index ? 'backward' : 'forward' }; } }]); return ViewportBase; }(_react.Component), _class.displayName = 'Viewport', _class.contextType = _SharedStateDecorator.SharedState, _class.propTypes = /** @lends sandstone/Panels.Viewport.prototype */{ /** * A function that generates a globally-unique identifier for a panel index * * @type {Function} * @required */ generateId: _propTypes["default"].func.isRequired, /** * Set of functions that control how the panels are transitioned into and out of the * viewport * * @type {Arranger} */ arranger: _ViewManager.shape, /** * Forwarded as `autoFocus` to each panel. * * If the `Panel` already has an `autoFocus` prop, it is maintained. * * Otherwise, if `autoFocus` is set, the value of this prop is added to the props. If it is * unset, 'default-element' is passed when navigating to a higher index. * * @type {String} */ autoFocus: _propTypes["default"].string, /** * Sets the hint string read when focusing the back button. * * @type {String} */ backButtonAriaLabel: _propTypes["default"].string, /** * The background opacity of the application back button. * * @type {('opaque'|'transparent')} */ backButtonBackgroundOpacity: _propTypes["default"].oneOf(['opaque', 'transparent']), /** * Panels to be rendered * * @type {Panel} */ children: _propTypes["default"].node, /** * Hint string read when focusing the application close button. * * @type {String} */ closeButtonAriaLabel: _propTypes["default"].string, /** * Background opacity of the application close button. * * @type {('opaque'|'transparent')} */ closeButtonBackgroundOpacity: _propTypes["default"].oneOf(['opaque', 'transparent']), /** * Index of the active panel * * @type {Number} * @default 0 */ index: _propTypes["default"].number, /** * Disable panel transitions * * @type {Boolean} * @default false */ noAnimation: _propTypes["default"].bool, /** * Omits the back button. * * @type {Boolean} */ noBackButton: _propTypes["default"].bool, /** * Omits the close button. * * @type {Boolean} */ noCloseButton: _propTypes["default"].bool, /** * Called with cancel/back key events. * * @type {Function} */ onBack: _propTypes["default"].func, /** * Called when the app close button is clicked. * * @type {Function} */ onClose: _propTypes["default"].func, /** * Passed to `arranger` for use in determining how to animate. * * @type {Boolean} */ rtl: _propTypes["default"].bool, type: _propTypes["default"].string }, _class.defaultProps = { index: 0, noAnimation: false }, _class); var ViewportDecorator = exports.ViewportDecorator = (0, _compose["default"])(_util2.ContextAsDefaults, _SharedStateDecorator["default"], (0, _I18nDecorator.I18nContextDecorator)({ rtlProp: 'rtl' })); var Viewport = exports.Viewport = ViewportDecorator(ViewportBase); var _default = exports["default"] = Viewport;