UNPKG

@elastic/eui

Version:

Elastic UI Component Library

189 lines (188 loc) 9.7 kB
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; } /* * 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, useCallback, useMemo, useRef } from 'react'; import PropTypes from "prop-types"; import dateMath from '@elastic/datemath'; import { useEuiPaddingCSS } from '../../../../global_styling'; import { useUpdateEffect, useGeneratedHtmlId } from '../../../../services'; import { useEuiI18n, EuiI18n } from '../../../i18n'; import { EuiScreenReaderOnly } from '../../../accessibility'; import { EuiFlexGroup, EuiFlexItem } from '../../../flex'; import { EuiForm, EuiFormRow, EuiSelect, EuiFieldNumber, EuiFieldText, EuiSwitch, EuiFormLabel } from '../../../form'; import { EuiPopoverFooter } from '../../../popover'; import { EuiSpacer } from '../../../spacer'; import { INVALID_DATE } from '../date_modes'; import { parseRelativeParts, toRelativeStringFromParts } from '../relative_utils'; import { EuiTimeZoneDisplay } from './timezone_display'; import { jsx as ___EmotionJSX } from "@emotion/react"; export var EuiRelativeTab = function EuiRelativeTab(_ref) { var _ref$timeOptions = _ref.timeOptions, relativeOptions = _ref$timeOptions.relativeOptions, relativeRoundingLabels = _ref$timeOptions.relativeRoundingLabels, dateFormat = _ref.dateFormat, locale = _ref.locale, value = _ref.value, onChange = _ref.onChange, roundUp = _ref.roundUp, labelPrefix = _ref.labelPrefix, _ref$timeZoneDisplayP = _ref.timeZoneDisplayProps, timeZoneDisplayProps = _ref$timeZoneDisplayP === void 0 ? {} : _ref$timeZoneDisplayP; var initialRelativeParts = useRef(parseRelativeParts(value)); var roundUnit = initialRelativeParts.current.roundUnit; var _useState = useState(initialRelativeParts.current.unit), _useState2 = _slicedToArray(_useState, 2), unit = _useState2[0], setUnit = _useState2[1]; var onUnitChange = useCallback(function (event) { setUnit(event.target.value); }, []); var _useState3 = useState(initialRelativeParts.current.round), _useState4 = _slicedToArray(_useState3, 2), round = _useState4[0], setRound = _useState4[1]; var onRoundChange = useCallback(function (event) { setRound(event.target.checked); }, []); var _useState5 = useState(initialRelativeParts.current.count), _useState6 = _slicedToArray(_useState5, 2), count = _useState6[0], setCount = _useState6[1]; var onCountChange = useCallback(function (event) { var sanitizedValue = parseInt(event.target.value, 10); var count = isNaN(sanitizedValue) ? undefined : sanitizedValue; setCount(count); }, []); useUpdateEffect(function () { if (count === undefined || count < 0) return; var date = toRelativeStringFromParts({ count: count, round: !!round, roundUnit: roundUnit, unit: unit }); onChange(date); }, [onChange, count, round, roundUnit, unit]); var invalidDate = value === INVALID_DATE; var invalidValue = count === undefined || count < 0; var isInvalid = invalidValue || invalidDate; var formattedValue = useMemo(function () { if (isInvalid) return ''; var parsedValue = dateMath.parse(value, { roundUp: roundUp }); if (!parsedValue || !parsedValue.isValid()) return ''; return parsedValue.locale(locale || 'en').format(dateFormat); }, [isInvalid, value, roundUp, locale, dateFormat]); var textInputLabelId = useGeneratedHtmlId(); var relativeDateInputNumberDescriptionId = useGeneratedHtmlId(); var timeZomeDescriptionId = useGeneratedHtmlId(); var numberAriaLabel = useEuiI18n('euiRelativeTab.numberInputLabel', 'Time span amount'); var numberInputError = useEuiI18n('euiRelativeTab.numberInputError', 'Must be >= 0'); var dateInputError = useEuiI18n('euiRelativeTab.dateInputError', 'Must be a valid range'); var unitSelectAriaLabel = useEuiI18n('euiRelativeTab.unitInputLabel', 'Relative time span'); return ___EmotionJSX(React.Fragment, null, ___EmotionJSX(EuiForm, { css: useEuiPaddingCSS().s }, ___EmotionJSX(EuiFlexGroup, { gutterSize: "s", responsive: false }, ___EmotionJSX(EuiFlexItem, null, ___EmotionJSX(EuiFormRow, { isInvalid: isInvalid, error: invalidValue ? numberInputError : invalidDate ? dateInputError : null }, ___EmotionJSX(EuiFieldNumber, { compressed: true, "aria-label": numberAriaLabel, "aria-describedby": relativeDateInputNumberDescriptionId, "data-test-subj": "superDatePickerRelativeDateInputNumber", value: count, onChange: onCountChange, isInvalid: isInvalid }))), ___EmotionJSX(EuiFlexItem, null, ___EmotionJSX(EuiSelect, { compressed: true, "aria-label": unitSelectAriaLabel, "data-test-subj": "superDatePickerRelativeDateInputUnitSelector", value: unit, options: relativeOptions, onChange: onUnitChange }))), ___EmotionJSX(EuiSpacer, { size: "s" }), ___EmotionJSX(EuiFieldText, { "aria-labelledby": textInputLabelId, compressed: true, value: formattedValue, readOnly: true, "aria-describedby": timeZomeDescriptionId, prepend: ___EmotionJSX(EuiFormLabel, { id: textInputLabelId }, labelPrefix) }), ___EmotionJSX(EuiScreenReaderOnly, null, ___EmotionJSX("p", { id: relativeDateInputNumberDescriptionId }, ___EmotionJSX(EuiI18n, { token: "euiRelativeTab.fullDescription", default: "The unit is changeable. Currently set to {unit}.", values: { unit: unit } })))), ___EmotionJSX(EuiTimeZoneDisplay, _extends({ id: timeZomeDescriptionId }, timeZoneDisplayProps)), ___EmotionJSX(EuiPopoverFooter, { paddingSize: "s" }, ___EmotionJSX(EuiSwitch, { "data-test-subj": "superDatePickerRelativeDateRoundSwitch", label: relativeRoundingLabels[unit.substring(0, 1)], checked: !!round, onChange: onRoundChange }))); }; EuiRelativeTab.propTypes = { dateFormat: PropTypes.string.isRequired, locale: PropTypes.any, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, roundUp: PropTypes.bool, labelPrefix: PropTypes.string.isRequired, timeOptions: PropTypes.shape({ timeTenseOptions: PropTypes.arrayOf(PropTypes.any.isRequired).isRequired, timeUnitsOptions: PropTypes.arrayOf(PropTypes.any.isRequired).isRequired, relativeOptions: PropTypes.arrayOf(PropTypes.shape({ text: PropTypes.string.isRequired, value: PropTypes.oneOfType([PropTypes.oneOf(["s", "m", "h", "d", "w", "M", "y"]).isRequired, PropTypes.oneOf(["s+", "m+", "h+", "d+", "w+", "M+", "y+"]).isRequired]).isRequired }).isRequired).isRequired, relativeRoundingLabels: PropTypes.any.isRequired, refreshUnitsOptions: PropTypes.arrayOf(PropTypes.any.isRequired).isRequired, commonDurationRanges: PropTypes.arrayOf(PropTypes.shape({ end: PropTypes.oneOfType([PropTypes.oneOf(["now"]), PropTypes.string.isRequired]).isRequired, label: PropTypes.string, start: PropTypes.oneOfType([PropTypes.oneOf(["now"]), PropTypes.string.isRequired]).isRequired }).isRequired).isRequired }).isRequired, timeZoneDisplayProps: PropTypes.shape({ /** * A valid time zone name, from the IANA database, e.g. "America/Los_Angeles". * * @link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */ timeZone: PropTypes.string, /** * Render prop function to add additional content to the time zone display. * Useful for e.g. adding links to documentation or setting pages. */ customRender: PropTypes.func, /** * Reference date to be used while resolving the UTC offset. * Only useful for edge cases involving daylight saving time. */ date: PropTypes.any }) };