formulaInput.tsx 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import {useCallback, useEffect, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import debounce from 'lodash/debounce';
  4. import Input, {inputStyles} from 'sentry/components/input';
  5. import {DEFAULT_DEBOUNCE_DURATION} from 'sentry/constants';
  6. import {t} from 'sentry/locale';
  7. import {unescapeMetricsFormula} from 'sentry/utils/metrics';
  8. import {FormulaFormatter} from 'sentry/views/metrics/formulaParser/formatter';
  9. import {joinTokens, parseFormula} from 'sentry/views/metrics/formulaParser/parser';
  10. import {type TokenList, TokenType} from 'sentry/views/metrics/formulaParser/types';
  11. interface Props extends Omit<React.ComponentProps<typeof Input>, 'onChange' | 'value'> {
  12. availableVariables: Set<string>;
  13. onChange: (formula: string) => void;
  14. value: string;
  15. }
  16. function escapeVariables(tokens: TokenList): TokenList {
  17. return tokens.map(token => {
  18. if (token.type !== TokenType.VARIABLE) {
  19. return token;
  20. }
  21. return {
  22. ...token,
  23. content: `$${token.content}`,
  24. };
  25. });
  26. }
  27. function equalizeWhitespace(formula: TokenList): TokenList {
  28. return formula.map(token => {
  29. // Ensure equal spacing
  30. if (token.type === TokenType.WHITESPACE) {
  31. return {...token, content: ' '};
  32. }
  33. return token;
  34. });
  35. }
  36. export function FormulaInput({
  37. availableVariables,
  38. value: valueProp,
  39. onChange,
  40. ...props
  41. }: Props) {
  42. const [errors, setErrors] = useState<any>([]);
  43. const [showErrors, setIsValidationEnabled] = useState(false);
  44. const [value, setValue] = useState<string>(() => unescapeMetricsFormula(valueProp));
  45. const validateVariable = useCallback(
  46. (variable: string): string | null => {
  47. if (!availableVariables.has(variable)) {
  48. return t('Unknown query "%s"', variable);
  49. }
  50. return null;
  51. },
  52. [availableVariables]
  53. );
  54. const parseAndValidateFormula = useCallback(
  55. (formula: string): TokenList | null => {
  56. let tokens: TokenList = [];
  57. const newErrors: any[] = [];
  58. if (formula) {
  59. try {
  60. tokens = parseFormula(formula);
  61. } catch (err) {
  62. newErrors.push({
  63. message: err.message,
  64. start: err.location.start.offset,
  65. });
  66. }
  67. }
  68. // validate variables
  69. let charCount = 0;
  70. tokens.forEach(token => {
  71. if (token.type === TokenType.VARIABLE) {
  72. const error = validateVariable(token.content);
  73. if (error) {
  74. newErrors.push({
  75. message: error,
  76. start: charCount,
  77. end: charCount + token.content.length,
  78. });
  79. }
  80. }
  81. charCount += token.content.length;
  82. });
  83. newErrors.sort((a, b) => a.start - b.start);
  84. setErrors(newErrors);
  85. if (newErrors.length > 0) {
  86. return null;
  87. }
  88. return tokens;
  89. },
  90. [validateVariable]
  91. );
  92. useEffect(() => {
  93. setIsValidationEnabled(false);
  94. const timeoutId = setTimeout(() => {
  95. setIsValidationEnabled(true);
  96. }, 500);
  97. return () => {
  98. clearTimeout(timeoutId);
  99. };
  100. }, [value]);
  101. // Parse and validate formula everytime the validation criteria changes
  102. useEffect(() => {
  103. parseAndValidateFormula(value);
  104. // eslint-disable-next-line react-hooks/exhaustive-deps
  105. }, [parseAndValidateFormula]);
  106. const handleChange = useMemo(
  107. () =>
  108. debounce((e: React.ChangeEvent<HTMLInputElement>) => {
  109. const newValue = e.target.value.trim();
  110. const tokens = parseAndValidateFormula(newValue);
  111. if (!tokens) {
  112. return;
  113. }
  114. onChange(joinTokens(equalizeWhitespace(escapeVariables(tokens))));
  115. }, DEFAULT_DEBOUNCE_DURATION),
  116. [onChange, parseAndValidateFormula]
  117. );
  118. return (
  119. <Wrapper>
  120. <StyledInput
  121. {...props}
  122. monospace
  123. hasError={showErrors && errors.length > 0}
  124. defaultValue={value}
  125. placeholder="e.g. (a / b) * 100"
  126. onChange={e => {
  127. setValue(e.target.value);
  128. handleChange(e);
  129. }}
  130. />
  131. <RendererOverlay monospace>
  132. <FormulaFormatter formula={value} errors={showErrors ? errors : []} />
  133. </RendererOverlay>
  134. </Wrapper>
  135. );
  136. }
  137. const Wrapper = styled('div')`
  138. position: relative;
  139. `;
  140. const RendererOverlay = styled('div')`
  141. ${inputStyles}
  142. border-color: transparent;
  143. position: absolute;
  144. top: 0;
  145. right: 0;
  146. bottom: 0;
  147. left: 0;
  148. align-items: center;
  149. justify-content: center;
  150. pointer-events: none;
  151. background: none;
  152. white-space: nowrap;
  153. overflow: hidden;
  154. resize: none;
  155. `;
  156. const StyledInput = styled(Input)<{hasError: boolean}>`
  157. caret-color: ${p => p.theme.subText};
  158. color: transparent;
  159. ${p =>
  160. p.hasError &&
  161. `
  162. border-color: ${p.theme.error};
  163. &:focus {
  164. border-color: ${p.theme.errorFocus};
  165. box-shadow: none;
  166. }
  167. `}
  168. `;