UNPKG

@elastic/eui

Version:

Elastic UI Component Library

293 lines (292 loc) 20.6 kB
var _excluded = ["children", "className", "gutterSize", "popoverBreakpoints", "popoverButtonProps", "popoverProps"], _excluded2 = ["onClick", "iconType"]; 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 _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; } /* * 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, { useState, useEffect, useCallback } from 'react'; import PropTypes from "prop-types"; import classNames from 'classnames'; import { useEuiTheme } from '../../../services'; import { EuiIcon } from '../../icon'; import { EuiPopover } from '../../popover'; import { EuiI18n } from '../../i18n'; import { EuiHeaderSectionItemButton } from '../header_section'; import { EuiHideFor, EuiShowFor } from '../../responsive'; import { euiHeaderLinksStyles } from './header_links.styles'; import { jsx as ___EmotionJSX } from "@emotion/react"; export var GUTTER_SIZES = ['xs', 's', 'm', 'l']; export var EuiHeaderLinks = function EuiHeaderLinks(_ref) { var children = _ref.children, className = _ref.className, _ref$gutterSize = _ref.gutterSize, gutterSize = _ref$gutterSize === void 0 ? 's' : _ref$gutterSize, _ref$popoverBreakpoin = _ref.popoverBreakpoints, popoverBreakpoints = _ref$popoverBreakpoin === void 0 ? ['xs', 's'] : _ref$popoverBreakpoin, popoverButtonProps = _ref.popoverButtonProps, popoverProps = _ref.popoverProps, rest = _objectWithoutProperties(_ref, _excluded); var euiTheme = useEuiTheme(); var styles = euiHeaderLinksStyles(euiTheme); var _ref2 = popoverButtonProps || {}, onClick = _ref2.onClick, _ref2$iconType = _ref2.iconType, iconType = _ref2$iconType === void 0 ? 'apps' : _ref2$iconType, popoverButtonRest = _objectWithoutProperties(_ref2, _excluded2); var _useState = useState(false), _useState2 = _slicedToArray(_useState, 2), mobileMenuIsOpen = _useState2[0], setMobileMenuIsOpen = _useState2[1]; var onMenuButtonClick = useCallback(function (e) { onClick === null || onClick === void 0 || onClick(e); setMobileMenuIsOpen(function (mobileMenuIsOpen) { return !mobileMenuIsOpen; }); }, [onClick]); var closeMenu = useCallback(function () { setMobileMenuIsOpen(false); }, []); useEffect(function () { window.addEventListener('resize', closeMenu); return function () { window.removeEventListener('resize', closeMenu); }; }, [closeMenu]); var classes = classNames('euiHeaderLinks', className); var button = ___EmotionJSX(EuiI18n, { token: "euiHeaderLinks.openNavigationMenu", default: "Open menu" }, function (openNavigationMenu) { return ___EmotionJSX(EuiHeaderSectionItemButton, _extends({ "aria-label": openNavigationMenu, onClick: onMenuButtonClick }, popoverButtonRest), ___EmotionJSX(EuiIcon, { type: iconType, size: "m" })); }); var renderedChildren = typeof children === 'function' ? children(closeMenu) : children; return ___EmotionJSX(EuiI18n, { token: "euiHeaderLinks.appNavigation", default: "App menu" }, function (appNavigation) { return ___EmotionJSX("nav", _extends({ className: classes, css: styles.euiHeaderLinks, "aria-label": appNavigation }, rest), ___EmotionJSX(EuiHideFor, { sizes: popoverBreakpoints }, ___EmotionJSX("div", { className: "euiHeaderLinks__list", css: [styles.euiHeaderLinks__list, styles.gutterSizes[gutterSize], ";label:EuiHeaderLinks;"] }, renderedChildren)), ___EmotionJSX(EuiShowFor, { sizes: popoverBreakpoints }, ___EmotionJSX(EuiPopover, _extends({ button: button, isOpen: mobileMenuIsOpen, anchorPosition: "downRight", closePopover: closeMenu, panelPaddingSize: "s", repositionOnScroll: true }, popoverProps), ___EmotionJSX("div", { className: "euiHeaderLinks__mobileList", css: styles.euiHeaderLinks__mobileList }, renderedChildren)))); }); }; EuiHeaderLinks.propTypes = { className: PropTypes.string, "aria-label": PropTypes.string, "data-test-subj": PropTypes.string, css: PropTypes.any, /** * Takes any rendered node(s), typically of `EuiHeaderLink`s. * * Optionally takes a render function that will pass a callback allowing you * to close the mobile popover from within your popover content. */ children: PropTypes.oneOfType([PropTypes.node.isRequired, PropTypes.func.isRequired]), /** * Spacing between direct children */ gutterSize: PropTypes.any, /** * A list of named breakpoints at which to show the popover version */ popoverBreakpoints: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.any.isRequired).isRequired, PropTypes.oneOf(["all", "none"])]), /** * Extend the functionality of the EuiPopover.button which is a EuiHeaderSectionItemButton. * With the addition of `iconType` to change the display icon which defaults to `apps` */ popoverButtonProps: PropTypes.shape({ iconType: PropTypes.oneOfType([PropTypes.oneOf(["accessibility", "addDataApp", "advancedSettingsApp", "agentApp", "aggregate", "analyzeEvent", "annotation", "anomalyChart", "anomalySwimLane", "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", "changePointDetection", "check", "checkInCircleFilled", "cheer", "classificationJob", "clickLeft", "clickRight", "clock", "clockCounter", "cloudDrizzle", "cloudStormy", "cloudSunny", "cluster", "codeApp", "color", "compute", "console", "consoleApp", "container", "continuityAbove", "continuityAboveBelow", "continuityBelow", "continuityWithin", "controlsHorizontal", "controlsVertical", "copy", "copyClipboard", "createAdvancedJob", "createMultiMetricJob", "createPopulationJob", "createSingleMetricJob", "cross", "crossClusterReplicationApp", "crossInCircle", "crosshairs", "currency", "cut", "dashboardApp", "dataVisualizer", "database", "desktop", "devToolsApp", "diff", "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", "endpoint", "eql", "eraser", "error", "errorFilled", "esqlVis", "exit", "expand", "expandMini", "exportAction", "eye", "eyeClosed", "faceHappy", "faceNeutral", "faceSad", "fieldStatistics", "filebeatApp", "filter", "filterExclude", "filterIgnore", "filterInclude", "filterInCircle", "flag", "fleetApp", "fold", "folderCheck", "folderClosed", "folderExclamation", "folderOpen", "frameNext", "framePrevious", "fullScreen", "fullScreenExit", "function", "gear", "gisApp", "glasses", "globe", "grab", "grabHorizontal", "grabOmnidirectional", "gradient", "graphApp", "grid", "grokApp", "heart", "heartbeatApp", "heatmap", "help", "home", "iInCircle", "image", "importAction", "index", "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", "logPatternAnalysis", "logRateAnalysis", "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", "minusInSquare", "mobile", "monitoringApp", "moon", "move", "namespace", "nested", "newChat", "node", "notebookApp", "number", "offline", "online", "outlierDetectionJob", "package", "packetbeatApp", "pageSelect", "pagesSelect", "palette", "paperClip", "partial", "pause", "payment", "pencil", "percent", "pin", "pinFilled", "pipeBreaks", "pipelineApp", "pipeNoBreaks", "pivot", "play", "playFilled", "plus", "plusInCircle", "plusInCircleFilled", "plusInSquare", "popout", "push", "questionInCircle", "quote", "recentlyViewedApp", "refresh", "regressionJob", "reporter", "reportingApp", "returnKey", "save", "savedObjectsApp", "scale", "search", "searchProfilerApp", "securityAnalyticsApp", "securityApp", "securitySignal", "securitySignalDetected", "securitySignalResolved", "sessionViewer", "shard", "share", "singleMetricViewer", "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", "transitionLeftIn", "transitionLeftOut", "transitionTopIn", "transitionTopOut", "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", "warningFilled", "alert", "watchesApp", "wordWrap", "wordWrapDisabled", "workplaceSearchApp", "wrench", "tokenAlias", "tokenAnnotation", "tokenArray", "tokenBinary", "tokenBoolean", "tokenClass", "tokenCompletionSuggester", "tokenConstant", "tokenDate", "tokenDimension", "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", "tokenSemanticText", "tokenShape", "tokenString", "tokenStruct", "tokenSymbol", "tokenTag", "tokenText", "tokenTokenCount", "tokenVariable", "tokenVectorDense", "tokenDenseVector", "tokenVectorSparse"]).isRequired, PropTypes.string.isRequired, PropTypes.elementType.isRequired]) }), /** * Extend the functionality of the EuiPopover */ popoverProps: PropTypes.shape({ /** * Alignment of the popover and arrow relative to the button */ anchorPosition: PropTypes.any, /** * Style and position alteration for arrow-less attachment. * Intended for use with inputs as anchors, e.g. EuiInputPopover */ attachToAnchor: PropTypes.bool, /** * Restrict the popover's position within this element */ container: PropTypes.any, /** * CSS display type for both the popover and anchor */ display: PropTypes.any, /** * Object of props passed to EuiFocusTrap */ focusTrapProps: PropTypes.any, /** * Show arrow indicating to originating button */ hasArrow: PropTypes.bool, /** * Specifies what element should initially have focus; Can be a DOM * node, or a selector string (which will be passed to * document.querySelector() to find the DOM node), or a function that * returns a DOM node. * * If not passed, initial focus defaults to the popover panel. */ initialFocus: PropTypes.any, /** * Passed directly to EuiPortal for DOM positioning. Both properties are * required if prop is specified */ insert: PropTypes.shape({ sibling: PropTypes.any.isRequired, position: PropTypes.oneOf(["before", "after"]).isRequired }), /** * Traps tab focus within the popover contents */ ownFocus: PropTypes.bool, /** * Custom class added to the EuiPanel containing the popover contents */ panelClassName: PropTypes.string, /** * EuiPanel padding on all sides */ panelPaddingSize: PropTypes.any, /** * Standard DOM `style` attribute. Passed to the EuiPanel */ panelStyle: PropTypes.any, /** * Object of props passed to EuiPanel. See #EuiPopoverPanelProps */ panelProps: PropTypes.shape({ element: PropTypes.oneOf(["div"]), /** * Padding for all four sides */ paddingSize: PropTypes.any, /** * Corner border radius */ borderRadius: PropTypes.any, /** * When true the panel will grow in height to match `EuiFlexItem` */ grow: PropTypes.bool, panelRef: PropTypes.any, className: PropTypes.string, "aria-label": PropTypes.string, "data-test-subj": PropTypes.string, css: PropTypes.any }), panelRef: PropTypes.any, /** * Optional screen reader instructions to announce upon popover open, * in addition to EUI's default popover instructions for Escape on close. * Useful for popovers that may have additional keyboard capabilities such as * arrow navigation. */ popoverScreenReaderText: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.node.isRequired]), popoverRef: PropTypes.any, /** * When `true`, the popover's position is re-calculated when the user * scrolls, this supports having fixed-position popover anchors. When nesting * an `EuiPopover` in a scrollable container, `repositionOnScroll` should be `true` */ repositionOnScroll: PropTypes.bool, /** * By default, popovers will attempt to position themselves along the initial * axis specified. If there is not enough room either vertically or horizontally * however, the popover will attempt to reposition itself along the secondary * cross axis if there is room there instead. * * If you do not not want this repositioning to occur (and it is acceptable for * the popover to appear offscreen), set this to false to disable this behavior. * * @default true */ repositionToCrossAxis: PropTypes.bool, /** * Must be set to true if using `EuiDragDropContext` within a popover, * otherwise your nested drag & drop will have incorrect positioning * * @deprecated - use `usePortal` prop on children `EuiDraggable` components instead. */ hasDragDrop: PropTypes.bool, /** * By default, popover content inherits the z-index of the anchor * component; pass `zIndex` to override */ zIndex: PropTypes.number, /** * Distance away from the anchor that the popover will render */ offset: PropTypes.number, /** * Minimum distance between the popover and the bounding container; * Pass an array of 4 values to adjust each side differently: `[top, right, bottom, left]` * @default 16 */ buffer: PropTypes.oneOfType([PropTypes.number.isRequired, PropTypes.any.isRequired]), /** * Element to pass as the child element of the arrow; * Use case is typically limited to an accompanying `EuiBeacon` */ arrowChildren: PropTypes.node, /** * Provide a name to the popover panel */ "aria-label": PropTypes.string, /** * Alternative option to `aria-label` that takes an `id`. * Usually takes the `id` of the popover title */ "aria-labelledby": PropTypes.string, /** * Function callback for when the popover positon changes */ onPositionChange: PropTypes.func, className: PropTypes.string, "data-test-subj": PropTypes.string, css: PropTypes.any }) };