@elastic/eui
Version:
Elastic UI Component Library
269 lines (262 loc) • 21.9 kB
JavaScript
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
var _excluded = ["className", "toasts", "dismissToast", "toastLifeTimeMs", "side"],
_excluded2 = ["text", "toastLifeTimeMs"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
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 _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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; }
/*
* 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, { useCallback, useEffect, useRef, useState } from 'react';
import PropTypes from "prop-types";
import classNames from 'classnames';
import { keysOf } from '../common';
import { useEuiTheme } from '../../services';
import { Timer } from '../../services/time';
import { EuiGlobalToastListItem } from './global_toast_list_item';
import { EuiToast } from './toast';
import { euiGlobalToastListStyles } from './global_toast_list.styles';
import { jsx as ___EmotionJSX } from "@emotion/react";
var sideToClassNameMap = {
left: 'euiGlobalToastList--left',
right: 'euiGlobalToastList--right'
};
export var SIDES = keysOf(sideToClassNameMap);
export var TOAST_FADE_OUT_MS = 250;
export var EuiGlobalToastList = function EuiGlobalToastList(_ref) {
var className = _ref.className,
_ref$toasts = _ref.toasts,
toasts = _ref$toasts === void 0 ? [] : _ref$toasts,
dismissToastProp = _ref.dismissToast,
toastLifeTimeMs = _ref.toastLifeTimeMs,
_ref$side = _ref.side,
side = _ref$side === void 0 ? 'right' : _ref$side,
rest = _objectWithoutProperties(_ref, _excluded);
var _useState = useState({}),
_useState2 = _slicedToArray(_useState, 2),
toastIdToDismissedMap = _useState2[0],
setToastIdToDismissedMap = _useState2[1];
var _useState3 = useState(),
_useState4 = _slicedToArray(_useState3, 2),
toastToDismiss = _useState4[0],
setToastToDismiss = _useState4[1];
var prevToasts = useRef([]);
var dismissTimeoutIds = useRef([]);
var toastIdToTimerMap = useRef({});
var isScrollingToBottom = useRef(false);
var isScrolledToBottom = useRef(true);
var isUserInteracting = useRef(false);
// See [Return Value](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame#Return_value)
// for information on initial value of 0
var isScrollingAnimationFrame = useRef(0);
var startScrollingAnimationFrame = useRef(0);
var listElement = useRef(null);
var euiTheme = useEuiTheme();
var styles = euiGlobalToastListStyles(euiTheme);
var cssStyles = [styles.euiGlobalToastList, styles[side]];
var startScrollingToBottom = function startScrollingToBottom() {
isScrollingToBottom.current = true;
var scrollToBottom = function scrollToBottom() {
// Although we cancel the requestAnimationFrame in componentWillUnmount,
// it's possible for this.listElement to become null in the meantime
if (!listElement.current) {
return;
}
var position = listElement.current.scrollTop;
var destination = listElement.current.scrollHeight - listElement.current.clientHeight;
var distanceToDestination = destination - position;
if (distanceToDestination < 5) {
listElement.current.scrollTop = destination;
isScrollingToBottom.current = false;
isScrolledToBottom.current = true;
return;
}
listElement.current.scrollTop = position + distanceToDestination * 0.25;
if (isScrollingToBottom) {
isScrollingAnimationFrame.current = window.requestAnimationFrame(scrollToBottom);
}
};
startScrollingAnimationFrame.current = window.requestAnimationFrame(scrollToBottom);
};
var onMouseEnter = function onMouseEnter() {
// Stop scrolling to bottom if we're in mid-scroll, because the user wants to interact with
// the list.
isScrollingToBottom.current = false;
isUserInteracting.current = true;
// Don't let toasts dismiss themselves while the user is interacting with them.
for (var _toastId in toastIdToTimerMap.current) {
if (toastIdToTimerMap.current.hasOwnProperty(_toastId)) {
var timer = toastIdToTimerMap.current[_toastId];
timer.pause();
}
}
};
var onMouseLeave = function onMouseLeave() {
isUserInteracting.current = false;
for (var _toastId2 in toastIdToTimerMap.current) {
if (toastIdToTimerMap.current.hasOwnProperty(_toastId2)) {
var timer = toastIdToTimerMap.current[_toastId2];
timer.resume();
}
}
};
var onScroll = function onScroll() {
if (listElement.current) {
isScrolledToBottom.current = listElement.current.scrollHeight - listElement.current.scrollTop === listElement.current.clientHeight;
}
};
var dismissToast = useCallback(function (toast) {
// Remove the toast after it's done fading out.
dismissTimeoutIds.current.push(window.setTimeout(function () {
setToastToDismiss(toast);
}, TOAST_FADE_OUT_MS));
setToastIdToDismissedMap(function (prev) {
return _objectSpread(_objectSpread({}, prev), {}, _defineProperty({}, toast.id, true));
});
}, []);
var scheduleToastForDismissal = useCallback(function (toast) {
// Start fading the toast out once its lifetime elapses.
toastIdToTimerMap.current[toast.id] = new Timer(function () {
return dismissToast(toast);
}, toast.toastLifeTimeMs != null ? toast.toastLifeTimeMs : toastLifeTimeMs);
}, [dismissToast, toastLifeTimeMs]);
var scheduleAllToastsForDismissal = useCallback(function () {
toasts.forEach(function (toast) {
if (!toastIdToTimerMap.current[toast.id]) {
scheduleToastForDismissal(toast);
}
});
}, [scheduleToastForDismissal, toasts]);
var addListeners = function addListeners() {
if (listElement.current) {
listElement.current.addEventListener('scroll', onScroll);
listElement.current.addEventListener('mouseenter', onMouseEnter);
listElement.current.addEventListener('mouseleave', onMouseLeave);
}
};
var removeListeners = function removeListeners() {
if (listElement.current) {
listElement.current.removeEventListener('scroll', onScroll);
listElement.current.removeEventListener('mouseenter', onMouseEnter);
listElement.current.removeEventListener('mouseleave', onMouseLeave);
}
};
// componentDidMount
useEffect(function () {
addListeners();
// componentWillUnmount
return function () {
if (isScrollingAnimationFrame.current !== 0) {
window.cancelAnimationFrame(isScrollingAnimationFrame.current);
}
if (startScrollingAnimationFrame.current !== 0) {
window.cancelAnimationFrame(startScrollingAnimationFrame.current);
}
removeListeners();
dismissTimeoutIds.current.forEach(clearTimeout); // eslint-disable-line react-hooks/exhaustive-deps
for (var _toastId3 in toastIdToTimerMap.current) {
if (toastIdToTimerMap.current.hasOwnProperty(_toastId3)) {
var timer = toastIdToTimerMap.current[_toastId3]; // eslint-disable-line react-hooks/exhaustive-deps
timer.clear();
}
}
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
// componentDidUpdate
useEffect(function () {
scheduleAllToastsForDismissal();
if (!isUserInteracting.current) {
// If the user has scrolled up the toast list then we don't want to annoy them by scrolling
// all the way back to the bottom.
if (isScrolledToBottom.current) {
if (prevToasts.current.length < toasts.length) {
startScrollingToBottom();
}
}
}
prevToasts.current = toasts;
}, [toasts, scheduleAllToastsForDismissal]);
// Toast dismissal side effect
// Ensure the callback has correct state by not enclosing it in `setTimeout`
useEffect(function () {
var toast = toastToDismiss;
// Because this is triggered by a setTimeout, and because React does not guarantee when
// state updates happen, it is possible to double-dismiss a toast
// including by double-clicking the "x" button on the toast
// so, first check to make sure we haven't already dismissed this toast
if (toast && toastIdToTimerMap.current.hasOwnProperty(toast.id)) {
dismissToastProp(toast);
toastIdToTimerMap.current[toast.id].clear();
delete toastIdToTimerMap.current[toast.id];
setToastIdToDismissedMap(function (prev) {
var toastIdToDismissedMap = _objectSpread({}, prev);
delete toastIdToDismissedMap[toast.id];
return toastIdToDismissedMap;
});
}
}, [toastToDismiss, dismissToastProp]);
var renderedToasts = toasts.map(function (toast) {
var text = toast.text,
toastLifeTimeMs = toast.toastLifeTimeMs,
rest = _objectWithoutProperties(toast, _excluded2);
var onClose = function onClose() {
return dismissToast(toast);
};
return ___EmotionJSX(EuiGlobalToastListItem, {
key: toast.id,
isDismissed: toastIdToDismissedMap[toast.id]
}, ___EmotionJSX(EuiToast, _extends({
onClose: onClose,
onFocus: onMouseEnter,
onBlur: onMouseLeave
}, rest), text));
});
var classes = classNames('euiGlobalToastList', className);
return ___EmotionJSX("div", _extends({
"aria-live": "polite",
role: "region",
ref: listElement,
css: cssStyles,
className: classes
}, rest), renderedToasts);
};
EuiGlobalToastList.propTypes = {
toasts: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string.isRequired,
text: PropTypes.node,
toastLifeTimeMs: PropTypes.number,
title: PropTypes.node,
color: PropTypes.any,
iconType: PropTypes.oneOfType([PropTypes.oneOf(["accessibility", "addDataApp", "advancedSettingsApp", "agentApp", "aggregate", "analyzeEvent", "annotation", "apmApp", "apmTrace", "appSearchApp", "apps", "arrowDown", "arrowLeft", "arrowRight", "arrowUp", "arrowStart", "arrowEnd", "article", "asterisk", "at", "auditbeatApp", "beaker", "bell", "bellSlash", "beta", "bolt", "boxesHorizontal", "boxesVertical", "branch", "branchUser", "broom", "brush", "bug", "bullseye", "calendar", "canvasApp", "casesApp", "check", "checkInCircleFilled", "cheer", "classificationJob", "clock", "cloudDrizzle", "cloudStormy", "cloudSunny", "cluster", "codeApp", "color", "compute", "console", "consoleApp", "container", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "createAdvancedJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crosshairs", "currency", "cut", "dashboardApp", "dataVisualizer", "database", "desktop", "devToolsApp", "discoverApp", "discuss", "document", "documentEdit", "documentation", "documents", "dot", "dotInCircle", "doubleArrowLeft", "doubleArrowRight", "download", "editorAlignCenter", "editorAlignLeft", "editorAlignRight", "editorBold", "editorChecklist", "editorCodeBlock", "editorComment", "editorDistributeHorizontal", "editorDistributeVertical", "editorHeading", "editorItalic", "editorItemAlignBottom", "editorItemAlignCenter", "editorItemAlignLeft", "editorItemAlignMiddle", "editorItemAlignRight", "editorItemAlignTop", "editorLink", "editorOrderedList", "editorPositionBottomLeft", "editorPositionBottomRight", "editorPositionTopLeft", "editorPositionTopRight", "editorRedo", "editorStrike", "editorTable", "editorUnderline", "editorUndo", "editorUnorderedList", "email", "empty", "emsApp", "eql", "eraser", "error", "exit", "expand", "expandMini", "exportAction", "eye", "eyeClosed", "faceHappy", "faceNeutral", "faceSad", "filebeatApp", "filter", "filterExclude", "filterIgnore", "filterInclude", "filterInCircle", "flag", "fleetApp", "fold", "folderCheck", "folderClosed", "folderExclamation", "folderOpen", "frameNext", "framePrevious", "fullScreen", "fullScreenExit", "function", "gear", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "home", "iInCircle", "image", "importAction", "indexClose", "indexEdit", "indexFlush", "indexManagementApp", "indexMapping", "indexOpen", "indexPatternApp", "indexRollupApp", "indexRuntime", "indexSettings", "indexTemporary", "infinity", "inputOutput", "inspect", "invert", "ip", "key", "keyboard", "kqlField", "kqlFunction", "kqlOperand", "kqlSelector", "kqlValue", "kubernetesNode", "kubernetesPod", "launch", "layers", "lensApp", "lettering", "lineDashed", "lineDotted", "lineSolid", "link", "list", "listAdd", "lock", "lockOpen", "logoAWS", "logoAWSMono", "logoAerospike", "logoApache", "logoAppSearch", "logoAzure", "logoAzureMono", "logoBeats", "logoBusinessAnalytics", "logoCeph", "logoCloud", "logoCloudEnterprise", "logoCode", "logoCodesandbox", "logoCouchbase", "logoDocker", "logoDropwizard", "logoElastic", "logoElasticStack", "logoElasticsearch", "logoEnterpriseSearch", "logoEtcd", "logoGCP", "logoGCPMono", "logoGithub", "logoGmail", "logoGolang", "logoGoogleG", "logoHAproxy", "logoIBM", "logoIBMMono", "logoKafka", "logoKibana", "logoKubernetes", "logoLogging", "logoLogstash", "logoMaps", "logoMemcached", "logoMetrics", "logoMongodb", "logoMySQL", "logoNginx", "logoObservability", "logoOsquery", "logoPhp", "logoPostgres", "logoPrometheus", "logoRabbitmq", "logoRedis", "logoSecurity", "logoSiteSearch", "logoSketch", "logoSlack", "logoUptime", "logoVulnerabilityManagement", "logoWebhook", "logoWindows", "logoWorkplaceSearch", "logsApp", "logstashFilter", "logstashIf", "logstashInput", "logstashOutput", "logstashQueue", "machineLearningApp", "magnet", "magnifyWithExclamation", "magnifyWithMinus", "magnifyWithPlus", "managementApp", "mapMarker", "memory", "menu", "menuDown", "menuLeft", "menuRight", "menuUp", "merge", "metricbeatApp", "metricsApp", "minimize", "minus", "minusInCircle", "minusInCircleFilled", "mobile", "monitoringApp", "moon", "namespace", "nested", "node", "notebookApp", "number", "offline", "online", "outlierDetectionJob", "package", "packetbeatApp", "pageSelect", "pagesSelect", "paperClip", "partial", "pause", "payment", "pencil", "percent", "pin", "pinFilled", "pipelineApp", "pivot", "play", "playFilled", "plus", "plusInCircle", "plusInCircleFilled", "popout", "push", "questionInCircle", "quote", "recentlyViewedApp", "refresh", "regressionJob", "reporter", "reportingApp", "returnKey", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "sessionViewer", "shard", "share", "snowflake", "sortAscending", "sortDescending", "sortDown", "sortLeft", "sortRight", "sortUp", "sortable", "spaces", "spacesApp", "sparkles", "sqlApp", "starEmpty", "starEmptySpace", "starFilled", "starFilledSpace", "starMinusEmpty", "starMinusFilled", "starPlusEmpty", "starPlusFilled", "stats", "stop", "stopFilled", "stopSlash", "storage", "string", "submodule", "sun", "swatchInput", "symlink", "tableDensityCompact", "tableDensityExpanded", "tableDensityNormal", "tableOfContents", "tag", "tear", "temperature", "timeline", "timelineWithArrow", "timelionApp", "timeRefresh", "timeslider", "training", "trash", "unfold", "unlink", "upgradeAssistantApp", "uptimeApp", "user", "userAvatar", "users", "usersRolesApp", "vector", "videoPlayer", "visArea", "visAreaStacked", "visBarHorizontal", "visBarHorizontalStacked", "visBarVertical", "visBarVerticalStacked", "visGauge", "visGoal", "visLine", "visMapCoordinate", "visMapRegion", "visMetric", "visPie", "visTable", "visTagCloud", "visText", "visTimelion", "visVega", "visVisualBuilder", "visualizeApp", "vulnerabilityManagementApp", "warning", "alert", "watchesApp", "wordWrap", "wordWrapDisabled", "workplaceSearchApp", "wrench", "tokenAlias", "tokenAnnotation", "tokenArray", "tokenBinary", "tokenBoolean", "tokenClass", "tokenCompletionSuggester", "tokenConstant", "tokenDate", "tokenDenseVector", "tokenElement", "tokenEnum", "tokenEnumMember", "tokenEvent", "tokenException", "tokenField", "tokenFile", "tokenFlattened", "tokenFunction", "tokenGeo", "tokenHistogram", "tokenInterface", "tokenIP", "tokenJoin", "tokenKey", "tokenKeyword", "tokenMethod", "tokenMetricCounter", "tokenMetricGauge", "tokenModule", "tokenNamespace", "tokenNested", "tokenNull", "tokenNumber", "tokenObject", "tokenOperator", "tokenPackage", "tokenParameter", "tokenPercolator", "tokenProperty", "tokenRange", "tokenRankFeature", "tokenRankFeatures", "tokenRepo", "tokenSearchType", "tokenShape", "tokenString", "tokenStruct", "tokenSymbol", "tokenTag", "tokenText", "tokenTokenCount", "tokenVariable"]).isRequired, PropTypes.string.isRequired, PropTypes.elementType.isRequired]),
onClose: PropTypes.func,
className: PropTypes.string,
"aria-label": PropTypes.string,
"data-test-subj": PropTypes.string,
css: PropTypes.any
}).isRequired),
dismissToast: PropTypes.func.isRequired,
toastLifeTimeMs: PropTypes.number.isRequired,
/**
* Determines which side of the browser window the toasts should appear
*/
side: PropTypes.oneOf(["right", "left"]),
className: PropTypes.string,
"aria-label": PropTypes.string,
"data-test-subj": PropTypes.string,
css: PropTypes.any
};