VariableValuesPreview.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { css } from '@emotion/css';
  2. import React, { MouseEvent, useCallback, useEffect, useState } from 'react';
  3. import { GrafanaTheme } from '@grafana/data';
  4. import { selectors } from '@grafana/e2e-selectors';
  5. import { Button, InlineFieldRow, InlineLabel, useStyles, VerticalGroup } from '@grafana/ui';
  6. import { VariableOption, VariableWithOptions } from '../types';
  7. export interface VariableValuesPreviewProps {
  8. variable: VariableWithOptions;
  9. }
  10. export const VariableValuesPreview: React.FunctionComponent<VariableValuesPreviewProps> = ({
  11. variable: { options },
  12. }) => {
  13. const [previewLimit, setPreviewLimit] = useState(20);
  14. const [previewOptions, setPreviewOptions] = useState<VariableOption[]>([]);
  15. const showMoreOptions = useCallback(
  16. (event: MouseEvent) => {
  17. event.preventDefault();
  18. setPreviewLimit(previewLimit + 20);
  19. },
  20. [previewLimit, setPreviewLimit]
  21. );
  22. const styles = useStyles(getStyles);
  23. useEffect(() => setPreviewOptions(options.slice(0, previewLimit)), [previewLimit, options]);
  24. if (!previewOptions.length) {
  25. return null;
  26. }
  27. return (
  28. <VerticalGroup spacing="none">
  29. <h5>Preview of values</h5>
  30. <InlineFieldRow>
  31. {previewOptions.map((o, index) => (
  32. <InlineFieldRow key={`${o.value}-${index}`} className={styles.optionContainer}>
  33. <InlineLabel aria-label={selectors.pages.Dashboard.Settings.Variables.Edit.General.previewOfValuesOption}>
  34. <div className={styles.label}>{o.text}</div>
  35. </InlineLabel>
  36. </InlineFieldRow>
  37. ))}
  38. </InlineFieldRow>
  39. {options.length > previewLimit && (
  40. <InlineFieldRow className={styles.optionContainer}>
  41. <Button
  42. onClick={showMoreOptions}
  43. variant="secondary"
  44. size="sm"
  45. aria-label="Variable editor Preview of Values Show More link"
  46. >
  47. Show more
  48. </Button>
  49. </InlineFieldRow>
  50. )}
  51. </VerticalGroup>
  52. );
  53. };
  54. VariableValuesPreview.displayName = 'VariableValuesPreview';
  55. function getStyles(theme: GrafanaTheme) {
  56. return {
  57. optionContainer: css`
  58. margin-left: ${theme.spacing.xs};
  59. margin-bottom: ${theme.spacing.xs};
  60. `,
  61. label: css`
  62. white-space: nowrap;
  63. overflow: hidden;
  64. text-overflow: ellipsis;
  65. max-width: 50vw;
  66. `,
  67. };
  68. }