UNPKG

@elastic/eui

Version:

Elastic UI Component Library

336 lines (311 loc) 22.5 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports.EuiManagedFlyout = void 0; var _propTypes = _interopRequireDefault(require("prop-types")); var _react = _interopRequireWildcard(require("react")); var _react2 = require("@emotion/react"); var _reactDom = require("react-dom"); var _services = require("../../../services"); var _i18n = require("../../i18n"); var _resize_observer = require("../../observer/resize_observer"); var _flyout = require("../flyout.component"); var _flyout_menu_context = require("../flyout_menu_context"); var _activity_stage = require("./activity_stage"); var _const = require("./const"); var _context = require("./context"); var _flyout_managed = require("./flyout_managed.styles"); var _hooks = require("./hooks"); var _selectors = require("./selectors"); var _store = require("./store"); var _validation = require("./validation"); var _excluded = ["id", "onClose", "onActive", "level", "size", "minWidth", "historyKey", "css", "flyoutMenuProps"]; 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 && {}.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(e) { return e && e.__esModule ? e : { default: e }; } function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } 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 _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 _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], t.indexOf(o) >= 0 || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.indexOf(n) >= 0) continue; t[n] = r[n]; } return t; } function _EMOTION_STRINGIFIED_CSS_ERROR__() { return "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop)."; } /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ /** * Props for `EuiManagedFlyout`, the internal persistent flyout used by * the manager. Extends base flyout props and requires a `level` to * distinguish `main` vs `child` behavior. */ var useFlyoutManager = function useFlyoutManager() { var context = (0, _hooks.useFlyoutManager)(); if (!context) { throw new Error('EuiManagedFlyout must be used within an EuiFlyoutManager'); } return context; }; /** * Persistent managed flyout rendered inside the provider. Handles: * - registration/unregistration with the manager * - size validation and parent/child size compatibility * - width tracking for responsive layouts * - lifecycle stage transitions and data attributes for styling */ var _ref = process.env.NODE_ENV === "production" ? { name: "1wrw3pf-EuiManagedFlyout", styles: "animation-duration:0s!important;label:EuiManagedFlyout;" } : { name: "1wrw3pf-EuiManagedFlyout", styles: "animation-duration:0s!important;label:EuiManagedFlyout;", toString: _EMOTION_STRINGIFIED_CSS_ERROR__ }; var EuiManagedFlyout = exports.EuiManagedFlyout = /*#__PURE__*/(0, _react.forwardRef)(function (_ref2, ref) { var _managerSessions, _managerState$layoutM, _managerState$flyouts, _managerState$session, _managerState$flyouts2, _managerSessions$leng, _session$childHistory, _session$childHistory2; var id = _ref2.id, onCloseProp = _ref2.onClose, onActiveProp = _ref2.onActive, level = _ref2.level, sizeProp = _ref2.size, minWidth = _ref2.minWidth, historyKey = _ref2.historyKey, customCss = _ref2.css, _flyoutMenuProps = _ref2.flyoutMenuProps, props = _objectWithoutProperties(_ref2, _excluded); var flyoutId = (0, _hooks.useFlyoutId)(id); var _useState = (0, _react.useState)(null), _useState2 = _slicedToArray(_useState, 2), flyoutRef = _useState2[0], setFlyoutRef = _useState2[1]; var refs = (0, _react.useMemo)(function () { return [setFlyoutRef, ref]; }, [ref]); var combinedRef = (0, _services.useCombinedRefs)(refs); var _useFlyoutManager2 = useFlyoutManager(), addFlyout = _useFlyoutManager2.addFlyout, closeFlyout = _useFlyoutManager2.closeFlyout, closeAllFlyouts = _useFlyoutManager2.closeAllFlyouts, setFlyoutWidth = _useFlyoutManager2.setFlyoutWidth, goBack = _useFlyoutManager2.goBack, _historyItems = _useFlyoutManager2.historyItems, managerState = _useFlyoutManager2.state; var managerSessions = managerState === null || managerState === void 0 ? void 0 : managerState.sessions; var currentSession = managerSessions ? (_managerSessions = managerSessions[managerSessions.length - 1]) !== null && _managerSessions !== void 0 ? _managerSessions : null : null; var layoutMode = (_managerState$layoutM = managerState === null || managerState === void 0 ? void 0 : managerState.layoutMode) !== null && _managerState$layoutM !== void 0 ? _managerState$layoutM : _const.LAYOUT_MODE_SIDE_BY_SIDE; var isActive = (currentSession === null || currentSession === void 0 ? void 0 : currentSession.mainFlyoutId) === flyoutId || (currentSession === null || currentSession === void 0 ? void 0 : currentSession.childFlyoutId) === flyoutId; // Derive parentFlyout and parentSize from single state read var parentFlyoutId = currentSession === null || currentSession === void 0 ? void 0 : currentSession.mainFlyoutId; var parentFlyout = parentFlyoutId ? (_managerState$flyouts = managerState === null || managerState === void 0 ? void 0 : managerState.flyouts.find(function (f) { return f.flyoutId === parentFlyoutId; })) !== null && _managerState$flyouts !== void 0 ? _managerState$flyouts : null : null; // parentSize: the size of the parent (main) flyout for a child flyout var session = (_managerState$session = managerState === null || managerState === void 0 ? void 0 : managerState.sessions.find(function (s) { return s.mainFlyoutId === flyoutId || s.childFlyoutId === flyoutId; })) !== null && _managerState$session !== void 0 ? _managerState$session : null; var parentSize = session !== null && session !== void 0 && session.mainFlyoutId ? managerState === null || managerState === void 0 || (_managerState$flyouts2 = managerState.flyouts.find(function (f) { return f.flyoutId === session.mainFlyoutId; })) === null || _managerState$flyouts2 === void 0 ? void 0 : _managerState$flyouts2.size : undefined; // Animate opening only for the first main flyout (sole session) or first child (no prior child in session). var shouldAnimateOpening = level === _const.LEVEL_MAIN ? ((_managerSessions$leng = managerSessions === null || managerSessions === void 0 ? void 0 : managerSessions.length) !== null && _managerSessions$leng !== void 0 ? _managerSessions$leng : 0) <= 1 && (currentSession === null || currentSession === void 0 ? void 0 : currentSession.mainFlyoutId) === flyoutId : ((_session$childHistory = session === null || session === void 0 || (_session$childHistory2 = session.childHistory) === null || _session$childHistory2 === void 0 ? void 0 : _session$childHistory2.length) !== null && _session$childHistory !== void 0 ? _session$childHistory : 0) === 0; var styles = (0, _services.useEuiMemoizedStyles)(_flyout_managed.euiManagedFlyoutStyles); // Set default size based on level: main defaults to 'm', child defaults to 's' var size = sizeProp !== null && sizeProp !== void 0 ? sizeProp : level === _const.LEVEL_CHILD ? 's' : 'm'; // Validate size var sizeTypeError = (0, _validation.validateManagedFlyoutSize)(size, flyoutId, level); if (sizeTypeError) { throw new Error((0, _validation.createValidationErrorMessage)(sizeTypeError)); } // For child flyouts, validate parent-child combinations if (level === _const.LEVEL_CHILD && parentSize && (0, _validation.isNamedSize)(size) && (0, _validation.isNamedSize)(parentSize)) { var combinationError = (0, _validation.validateSizeCombination)(parentSize, size); if (combinationError) { combinationError.flyoutId = flyoutId; combinationError.parentFlyoutId = parentFlyout === null || parentFlyout === void 0 ? void 0 : parentFlyout.flyoutId; combinationError.level = level; throw new Error((0, _validation.createValidationErrorMessage)(combinationError)); } } var defaultTitle = (0, _i18n.useEuiI18n)('euiFlyoutManaged.defaultTitle', 'Unknown Flyout'); // Set title from flyoutMenuProps or aria-label // TODO: allow aria-labelledby references to be used var title = (_flyoutMenuProps === null || _flyoutMenuProps === void 0 ? void 0 : _flyoutMenuProps.title) || props['aria-label']; if (process.env.NODE_ENV === 'development' && level === _const.LEVEL_MAIN && !title) { console.warn("Managed flyout \"".concat(flyoutId, "\" requires a title, which can be provided through 'flyoutMenuProps.title' or 'aria-label'. Using default title: \"").concat(defaultTitle, "\"")); title = defaultTitle; } var flyoutExistsInManager = (0, _selectors.useIsFlyoutRegistered)(flyoutId); // Stabilize the onClose callback var onCloseCallbackRef = (0, _react.useRef)(); onCloseCallbackRef.current = function (e, meta) { if (onCloseProp) { var event = e || new MouseEvent('click'); onCloseProp(event, meta); } }; // Stabilize the onActive callback var onActiveCallbackRef = (0, _react.useRef)(); onActiveCallbackRef.current = onActiveProp; // Track if flyout was ever registered to avoid false positives on initial mount var wasRegisteredRef = (0, _react.useRef)(false); // Track flyoutExistsInManager in a ref to avoid dependency loop // The cleanup function needs the current value but shouldn't cause re-runs var flyoutExistsInManagerRef = (0, _react.useRef)(flyoutExistsInManager); // Update ref when flyoutExistsInManager changes (0, _react.useEffect)(function () { flyoutExistsInManagerRef.current = flyoutExistsInManager; }, [flyoutExistsInManager]); // Register with flyout manager context when open, remove when closed // Using useLayoutEffect to run synchronously before DOM updates (0, _react.useLayoutEffect)(function () { addFlyout(flyoutId, title, level, size, level === _const.LEVEL_MAIN ? historyKey : undefined, _flyoutMenuProps === null || _flyoutMenuProps === void 0 ? void 0 : _flyoutMenuProps.iconType, typeof minWidth === 'number' ? minWidth : undefined); return function () { var store = (0, _store.getFlyoutManagerStore)(); var stillInStore = store.getState().flyouts.some(function (f) { return f.flyoutId === flyoutId; }); if (stillInStore) { // Normal cleanup (deps changed or explicit close via isOpen=false) level === _const.LEVEL_MAIN ? closeAllFlyouts() : closeFlyout(flyoutId); } else if (wasRegisteredRef.current) { var _onCloseCallbackRef$c, _store$consumeCloseMe; // Removed externally while mounted: forward the store-stamped reason // (e.g. `navigation-back` from goBack), defaulting to cascade. (_onCloseCallbackRef$c = onCloseCallbackRef.current) === null || _onCloseCallbackRef$c === void 0 || _onCloseCallbackRef$c.call(onCloseCallbackRef, new MouseEvent('navigation'), (_store$consumeCloseMe = store.consumeCloseMeta(flyoutId)) !== null && _store$consumeCloseMe !== void 0 ? _store$consumeCloseMe : { reason: 'navigation-cascade' }); } wasRegisteredRef.current = false; }; }, [flyoutId, title, level, size, minWidth, historyKey, _flyoutMenuProps === null || _flyoutMenuProps === void 0 ? void 0 : _flyoutMenuProps.iconType, addFlyout, closeFlyout, closeAllFlyouts]); // Detect when flyout has been removed from manager state (e.g., via Back button) // and trigger onClose callback to notify the parent component (0, _react.useEffect)(function () { if (flyoutExistsInManager) { wasRegisteredRef.current = true; } // If flyout was previously registered, is marked as open, but no longer // exists in manager state, it was removed externally while still mounted. // Forward the store-stamped reason (e.g. `navigation-back` from goBack); // any other removal (e.g. a closeAllFlyouts cascade reaching a backgrounded // flyout) defaults to `navigation-cascade`. if (wasRegisteredRef.current && !flyoutExistsInManager) { var _onCloseCallbackRef$c2, _getFlyoutManagerStor; (_onCloseCallbackRef$c2 = onCloseCallbackRef.current) === null || _onCloseCallbackRef$c2 === void 0 || _onCloseCallbackRef$c2.call(onCloseCallbackRef, new MouseEvent('navigation'), (_getFlyoutManagerStor = (0, _store.getFlyoutManagerStore)().consumeCloseMeta(flyoutId)) !== null && _getFlyoutManagerStor !== void 0 ? _getFlyoutManagerStor : { reason: 'navigation-cascade' }); wasRegisteredRef.current = false; // Reset to avoid repeated calls } }, [flyoutExistsInManager, flyoutId]); // Monitor current session changes and fire onActive callback when this flyout becomes active (0, _react.useEffect)(function () { if (!onActiveCallbackRef.current || !currentSession) { return; } // Make sure callback is only fired for the flyout that changed var mainChanged = level === _const.LEVEL_MAIN && currentSession.mainFlyoutId === flyoutId; var childChanged = level === _const.LEVEL_CHILD && currentSession.childFlyoutId === flyoutId; if (mainChanged || childChanged) { onActiveCallbackRef.current(); } }, [currentSession, flyoutId, level]); // Track width changes for flyouts var _useResizeObserver = (0, _resize_observer.useResizeObserver)(isActive ? flyoutRef : null, 'width'), width = _useResizeObserver.width; // Pass the stabilized onClose callback to the flyout menu context var onClose = function onClose(e, meta) { // Clear before flushSync so that effects flushed synchronously inside it // (the navigation-back detector) see wasRegisteredRef = false and do not // misidentify this user-initiated close as a Back-button navigation. wasRegisteredRef.current = false; // CRITICAL: Update manager state FIRST before allowing React to unmount // This prevents race conditions during portal → inline DOM transitions // and ensures cascade close logic runs before DOM cleanup begins // Using flushSync to force synchronous state update completion (0, _reactDom.flushSync)(function () { level === _const.LEVEL_MAIN ? closeAllFlyouts() : closeFlyout(flyoutId); }); if (onCloseCallbackRef.current) { var event = e || new MouseEvent('click'); onCloseCallbackRef.current(event, meta); } }; // Update width in manager state when it changes (0, _react.useEffect)(function () { if (isActive && width) { setFlyoutWidth(flyoutId, width); } }, [flyoutId, level, isActive, width, setFlyoutWidth]); var _useFlyoutActivitySta = (0, _activity_stage.useFlyoutActivityStage)({ flyoutId: flyoutId, level: level, shouldAnimate: false }), activityStage = _useFlyoutActivitySta.activityStage, onAnimationEnd = _useFlyoutActivitySta.onAnimationEnd; // Note: history controls are only relevant for main flyouts var historyItems = (0, _react.useMemo)(function () { var result = level === _const.LEVEL_MAIN ? _historyItems : undefined; return result; }, [level, _historyItems]); var backButtonProps = (0, _react.useMemo)(function () { return level === _const.LEVEL_MAIN ? { onClick: goBack } : undefined; }, [level, goBack]); var showBackButton = historyItems ? historyItems.length > 0 : false; // When the store has a defined pagination value it takes precedence; the // prop acts as a fallback for callers that don't use the cross-root store. // Using both simultaneously is not supported and will log a warning in dev. var storePagination = (0, _hooks.useFlyoutPagination)(flyoutId); var propPagination = _flyoutMenuProps === null || _flyoutMenuProps === void 0 ? void 0 : _flyoutMenuProps.pagination; if (process.env.NODE_ENV === 'development' && storePagination != null && propPagination != null) { console.warn("flyout-pagination-dual-source-".concat(flyoutId), "[EuiFlyoutManager] flyout \"".concat(flyoutId, "\" has pagination set both via the store (setPagination) ") + 'and via flyoutMenuProps.pagination. The store value will be used. Remove one source to avoid confusion.'); } var pagination = storePagination !== null && storePagination !== void 0 ? storePagination : propPagination; var showPaginationControls = pagination != null && pagination.total > 1; var flyoutMenuProps = _objectSpread(_objectSpread({}, _flyoutMenuProps), {}, { historyItems: showPaginationControls ? [] : historyItems, showBackButton: showPaginationControls ? false : showBackButton, backButtonProps: backButtonProps, title: title, pagination: pagination }); return (0, _react2.jsx)(_context.EuiFlyoutIsManagedProvider, { isManaged: true }, (0, _react2.jsx)(_flyout_menu_context.EuiFlyoutMenuContext.Provider, { value: { onClose: onClose } }, (0, _react2.jsx)(_flyout.EuiFlyoutComponent, _extends({ id: flyoutId, ref: combinedRef, css: [styles.managedFlyout, customCss, styles.stage(activityStage, props.side, level), // Suppress EuiFlyout's built-in opening animation for non-initial flyouts. !shouldAnimateOpening && _ref, ";label:EuiManagedFlyout;"] }, _objectSpread(_objectSpread({}, props), {}, _defineProperty(_defineProperty(_defineProperty({ onClose: onClose, size: size, minWidth: minWidth, flyoutMenuProps: flyoutMenuProps, onAnimationEnd: onAnimationEnd }, _const.PROPERTY_FLYOUT, true), _const.PROPERTY_LAYOUT_MODE, layoutMode), _const.PROPERTY_LEVEL, level)))))); }); EuiManagedFlyout.propTypes = { level: _propTypes.default.oneOfType([_propTypes.default.any.isRequired, _propTypes.default.any.isRequired]).isRequired, historyKey: _propTypes.default.any, flyoutMenuProps: _propTypes.default.any, onActive: _propTypes.default.func }; EuiManagedFlyout.displayName = 'EuiManagedFlyout';