@elastic/eui
Version:
Elastic UI Component Library
316 lines (290 loc) • 18.1 kB
JavaScript
import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["id", "onClose", "onActive", "level", "size", "minWidth", "historyKey", "css", "flyoutMenuProps"];
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 _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.
*/
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState, forwardRef } from 'react';
import { css } from '@emotion/react';
import { flushSync } from 'react-dom';
import { useCombinedRefs, useEuiMemoizedStyles } from '../../../services';
import { useEuiI18n } from '../../i18n';
import { useResizeObserver } from '../../observer/resize_observer';
import { EuiFlyoutComponent } from '../flyout.component';
import { EuiFlyoutMenuContext } from '../flyout_menu_context';
import { useFlyoutActivityStage } from './activity_stage';
import { LAYOUT_MODE_SIDE_BY_SIDE, LEVEL_CHILD, LEVEL_MAIN, PROPERTY_FLYOUT, PROPERTY_LAYOUT_MODE, PROPERTY_LEVEL } from './const';
import { EuiFlyoutIsManagedProvider } from './context';
import { euiManagedFlyoutStyles } from './flyout_managed.styles';
import { useFlyoutManager as _useFlyoutManager, useFlyoutId, useFlyoutPagination } from './hooks';
import { useIsFlyoutRegistered } from './selectors';
import { getFlyoutManagerStore } from './store';
import { createValidationErrorMessage, isNamedSize, validateManagedFlyoutSize, validateSizeCombination } from './validation';
/**
* 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.
*/
import { jsx as ___EmotionJSX } from "@emotion/react";
var useFlyoutManager = function useFlyoutManager() {
var context = _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__
};
export var EuiManagedFlyout = /*#__PURE__*/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 = useFlyoutId(id);
var _useState = useState(null),
_useState2 = _slicedToArray(_useState, 2),
flyoutRef = _useState2[0],
setFlyoutRef = _useState2[1];
var refs = useMemo(function () {
return [setFlyoutRef, ref];
}, [ref]);
var combinedRef = 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 : 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 === 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 = useEuiMemoizedStyles(euiManagedFlyoutStyles);
// Set default size based on level: main defaults to 'm', child defaults to 's'
var size = sizeProp !== null && sizeProp !== void 0 ? sizeProp : level === LEVEL_CHILD ? 's' : 'm';
// Validate size
var sizeTypeError = validateManagedFlyoutSize(size, flyoutId, level);
if (sizeTypeError) {
throw new Error(createValidationErrorMessage(sizeTypeError));
}
// For child flyouts, validate parent-child combinations
if (level === LEVEL_CHILD && parentSize && isNamedSize(size) && isNamedSize(parentSize)) {
var combinationError = 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(createValidationErrorMessage(combinationError));
}
}
var defaultTitle = 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 === 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 = useIsFlyoutRegistered(flyoutId);
// Stabilize the onClose callback
var onCloseCallbackRef = useRef();
onCloseCallbackRef.current = function (e, meta) {
if (onCloseProp) {
var event = e || new MouseEvent('click');
onCloseProp(event, meta);
}
};
// Stabilize the onActive callback
var onActiveCallbackRef = useRef();
onActiveCallbackRef.current = onActiveProp;
// Track if flyout was ever registered to avoid false positives on initial mount
var wasRegisteredRef = 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 = useRef(flyoutExistsInManager);
// Update ref when flyoutExistsInManager changes
useEffect(function () {
flyoutExistsInManagerRef.current = flyoutExistsInManager;
}, [flyoutExistsInManager]);
// Register with flyout manager context when open, remove when closed
// Using useLayoutEffect to run synchronously before DOM updates
useLayoutEffect(function () {
addFlyout(flyoutId, title, level, size, level === LEVEL_MAIN ? historyKey : undefined, _flyoutMenuProps === null || _flyoutMenuProps === void 0 ? void 0 : _flyoutMenuProps.iconType, typeof minWidth === 'number' ? minWidth : undefined);
return function () {
var 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 === 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
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 = 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
useEffect(function () {
if (!onActiveCallbackRef.current || !currentSession) {
return;
}
// Make sure callback is only fired for the flyout that changed
var mainChanged = level === LEVEL_MAIN && currentSession.mainFlyoutId === flyoutId;
var childChanged = level === LEVEL_CHILD && currentSession.childFlyoutId === flyoutId;
if (mainChanged || childChanged) {
onActiveCallbackRef.current();
}
}, [currentSession, flyoutId, level]);
// Track width changes for flyouts
var _useResizeObserver = 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
flushSync(function () {
level === 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
useEffect(function () {
if (isActive && width) {
setFlyoutWidth(flyoutId, width);
}
}, [flyoutId, level, isActive, width, setFlyoutWidth]);
var _useFlyoutActivitySta = useFlyoutActivityStage({
flyoutId: flyoutId,
level: level,
shouldAnimate: false
}),
activityStage = _useFlyoutActivitySta.activityStage,
onAnimationEnd = _useFlyoutActivitySta.onAnimationEnd;
// Note: history controls are only relevant for main flyouts
var historyItems = useMemo(function () {
var result = level === LEVEL_MAIN ? _historyItems : undefined;
return result;
}, [level, _historyItems]);
var backButtonProps = useMemo(function () {
return level === 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 = 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 ___EmotionJSX(EuiFlyoutIsManagedProvider, {
isManaged: true
}, ___EmotionJSX(EuiFlyoutMenuContext.Provider, {
value: {
onClose: onClose
}
}, ___EmotionJSX(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
}, PROPERTY_FLYOUT, true), PROPERTY_LAYOUT_MODE, layoutMode), PROPERTY_LEVEL, level))))));
});
EuiManagedFlyout.displayName = 'EuiManagedFlyout';