@elastic/eui
Version:
Elastic UI Component Library
193 lines (188 loc) • 9.99 kB
JavaScript
var _excluded = ["children", "disabled", "max", "min", "step", "showTicks", "tickInterval", "ticks", "levels", "onChange", "value", "compressed", "showRange", "className"];
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 _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, { useState, useMemo, useEffect } from 'react';
import PropTypes from "prop-types";
import classNames from 'classnames';
import range from 'lodash/range';
import { useEuiTheme, isEvenlyDivisibleBy } from '../../../services';
import { EuiRangeLevels } from './range_levels';
import { EuiRangeTicks } from './range_ticks';
import { euiRangeTrackStyles } from './range_track.styles';
import { jsx as ___EmotionJSX } from "@emotion/react";
export var EuiRangeTrack = function EuiRangeTrack(_ref) {
var children = _ref.children,
disabled = _ref.disabled,
max = _ref.max,
min = _ref.min,
step = _ref.step,
showTicks = _ref.showTicks,
tickInterval = _ref.tickInterval,
ticks = _ref.ticks,
levels = _ref.levels,
onChange = _ref.onChange,
value = _ref.value,
compressed = _ref.compressed,
showRange = _ref.showRange,
className = _ref.className,
rest = _objectWithoutProperties(_ref, _excluded);
useEffect(function () {
validateValueIsInStep(max, {
min: min,
max: max,
step: step
});
}, [value, min, max, step]);
var _useState = useState(0),
_useState2 = _slicedToArray(_useState, 2),
trackWidth = _useState2[0],
setTrackWidth = _useState2[1];
var tickSequence = useMemo(function () {
if (showTicks !== true) return;
var sequence;
if (ticks) {
// If custom values were passed, use those for the sequence
// But make sure they align with the possible sequence
sequence = ticks.map(function (tick) {
return validateValueIsInStep(tick.value, {
min: min,
max: max,
step: step
});
});
} else {
// If a custom interval was passed, use those for the sequence
// But make sure they align with the possible sequence
var interval = tickInterval || step;
// Calculate sequence - loop from min to max, creating adding values at each interval
var sequenceRange = range(min, max, interval);
// range is non-inclusive of max, so make it inclusive
if (max % interval === 0 && !sequenceRange.includes(max)) {
sequenceRange.push(max);
}
sequence = sequenceRange.map(function (tick) {
return validateValueIsInStep(tick, {
min: min,
max: max,
step: step
});
});
}
// Error out if there are too many ticks to render
if (trackWidth && sequence.length) {
validateTickRenderCount(trackWidth, sequence.length);
}
return sequence;
}, [showTicks, ticks, min, max, tickInterval, step, trackWidth]);
var euiTheme = useEuiTheme();
var styles = euiRangeTrackStyles(euiTheme);
var cssStyles = [styles.euiRangeTrack, disabled && styles.disabled, levels && !!levels.length && styles.hasLevels, showTicks && (tickSequence || ticks) && styles.hasTicks];
var classes = classNames('euiRangeTrack', className);
return ___EmotionJSX("div", _extends({
className: classes,
css: cssStyles
}, rest, {
ref: function ref(node) {
var _node$clientWidth;
setTrackWidth((_node$clientWidth = node === null || node === void 0 ? void 0 : node.clientWidth) !== null && _node$clientWidth !== void 0 ? _node$clientWidth : 0);
}
}), levels && !!levels.length && ___EmotionJSX(EuiRangeLevels, {
levels: levels,
max: max,
min: min,
showTicks: showTicks,
showRange: showRange,
trackWidth: trackWidth
}), tickSequence && ___EmotionJSX(EuiRangeTicks, {
disabled: disabled,
compressed: compressed,
onChange: onChange,
ticks: ticks,
tickInterval: tickInterval || step,
tickSequence: tickSequence,
value: value,
min: min,
max: max,
trackWidth: trackWidth
}), typeof children === 'function' ? children(trackWidth) : children);
};
EuiRangeTrack.propTypes = {
onChange: PropTypes.func,
children: PropTypes.oneOfType([PropTypes.node.isRequired, PropTypes.func.isRequired]),
value: PropTypes.oneOfType([PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.number.isRequired]).isRequired, PropTypes.any.isRequired]),
max: PropTypes.number.isRequired,
min: PropTypes.number.isRequired,
/**
* The number to increment or decrement between each interval
* @default 1
*/
step: PropTypes.number,
/**
* Specified ticks at specified values
*/
ticks: PropTypes.arrayOf(PropTypes.shape({
value: PropTypes.number.isRequired,
label: PropTypes.node.isRequired
}).isRequired),
/**
* Modifies the number of tick marks and at what interval
*/
tickInterval: PropTypes.number,
/**
* Create colored indicators for certain intervals.
* An array of #EuiRangeLevel objects
*/
levels: PropTypes.arrayOf(PropTypes.shape({
/**
* Accepts one of `["primary", "success", "warning", "danger"]` or a valid CSS color value.
*/
color: PropTypes.oneOfType([PropTypes.any.isRequired, PropTypes.any.isRequired]).isRequired,
className: PropTypes.string,
"aria-label": PropTypes.string,
"data-test-subj": PropTypes.string,
css: PropTypes.any
}).isRequired)
};
var validateValueIsInStep = function validateValueIsInStep(value, _ref2) {
var min = _ref2.min,
max = _ref2.max,
step = _ref2.step;
if (value < min) {
throw new Error("The value of ".concat(value, " is lower than the min value of ").concat(min, "."));
}
if (value > max) {
throw new Error("The value of ".concat(value, " is higher than the max value of ").concat(max, "."));
}
// Error out if the value doesn't line up with the sequence of steps
if (!isEvenlyDivisibleBy(value - min, step !== undefined ? step : 1)) {
throw new Error("The value of ".concat(value, " is not included in the possible sequence provided by the step of ").concat(step, "."));
}
// Return the value if nothing fails
return value;
};
var validateTickRenderCount = function validateTickRenderCount(trackWidth, tickCount) {
var tickWidth = trackWidth / tickCount;
// These widths are guesstimations - it's possible we should use actual label content/widths instead
var COMFORTABLE_TICK_WIDTH = 20; // Set a warning threshold before throwing
var MIN_TICK_WIDTH = 5; // If ticks are smaller than this, something's gone seriously wrong and we should throw
var message = "The number of ticks to render (".concat(tickCount, ") is too high for the range width. Ensure all ticks are visible on the page at multiple screen widths, or use EUI's breakpoint hook utilities to reduce the tick interval responsively.");
if (tickWidth <= MIN_TICK_WIDTH) {
throw new Error(message);
} else if (tickWidth < COMFORTABLE_TICK_WIDTH) {
console.warn(message);
}
};