UnitPicker.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import React, { PureComponent } from 'react';
  2. import Select from 'react-select';
  3. import UnitGroup from './UnitGroup';
  4. import UnitOption from './UnitOption';
  5. import ResetStyles from '../ResetStyles';
  6. import kbn from '../../../utils/kbn';
  7. interface Props {
  8. onSelected: (item: any) => {} | void;
  9. defaultValue?: string;
  10. width?: number;
  11. }
  12. export default class UnitPicker extends PureComponent<Props> {
  13. static defaultProps = {
  14. width: 12,
  15. };
  16. render() {
  17. const { defaultValue, onSelected, width } = this.props;
  18. const unitGroups = kbn.getUnitFormats();
  19. // Need to transform the data structure to work well with Select
  20. const groupOptions = unitGroups.map(group => {
  21. const options = group.submenu.map(unit => {
  22. return {
  23. label: unit.text,
  24. value: unit.value,
  25. };
  26. });
  27. return {
  28. label: group.text,
  29. options,
  30. };
  31. });
  32. const styles = {
  33. ...ResetStyles,
  34. menu: () => ({
  35. maxHeight: '75%',
  36. overflow: 'scroll',
  37. }),
  38. menuList: () =>
  39. ({
  40. overflowY: 'auto',
  41. position: 'relative',
  42. } as React.CSSProperties),
  43. valueContainer: () =>
  44. ({
  45. overflow: 'hidden',
  46. textOverflow: 'ellipsis',
  47. maxWidth: '90px',
  48. whiteSpace: 'nowrap',
  49. } as React.CSSProperties),
  50. };
  51. const value = groupOptions.map(group => {
  52. return group.options.find(option => option.value === defaultValue);
  53. });
  54. return (
  55. <Select
  56. classNamePrefix="gf-form-select-box"
  57. className={`width-${width} gf-form-input gf-form-input--form-dropdown`}
  58. defaultValue={value}
  59. isSearchable={true}
  60. menuShouldScrollIntoView={false}
  61. options={groupOptions}
  62. placeholder="Choose"
  63. onChange={onSelected}
  64. components={{
  65. Group: UnitGroup,
  66. Option: UnitOption,
  67. }}
  68. styles={styles}
  69. />
  70. );
  71. }
  72. }