formulaInput.tsx 5.0 KB

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