formulaInput.tsx 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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) {
  60. try {
  61. tokens = parseFormula(formula);
  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. newErrors.sort((a, b) => a.start - b.start);
  85. setErrors(newErrors);
  86. if (newErrors.length > 0) {
  87. return null;
  88. }
  89. return tokens;
  90. },
  91. [validateVariable]
  92. );
  93. useEffect(() => {
  94. setIsValidationEnabled(false);
  95. const timeoutId = setTimeout(() => {
  96. setIsValidationEnabled(true);
  97. }, 500);
  98. return () => {
  99. clearTimeout(timeoutId);
  100. };
  101. }, [value]);
  102. // Parse and validate equation everytime the validation criteria changes
  103. useEffect(() => {
  104. parseAndValidateFormula(value);
  105. // eslint-disable-next-line react-hooks/exhaustive-deps
  106. }, [parseAndValidateFormula]);
  107. const handleChange = useMemo(
  108. () =>
  109. debounce((e: React.ChangeEvent<HTMLInputElement>) => {
  110. const newValue = e.target.value.trim();
  111. const tokens = parseAndValidateFormula(newValue);
  112. if (!tokens) {
  113. return;
  114. }
  115. onChange(joinTokens(equalizeWhitespace(escapeVariables(tokens))));
  116. }, DEFAULT_DEBOUNCE_DURATION),
  117. [onChange, parseAndValidateFormula]
  118. );
  119. return (
  120. <Wrapper>
  121. <StyledInput
  122. {...props}
  123. monospace
  124. hasError={showErrors && errors.length > 0}
  125. defaultValue={value}
  126. placeholder="e.g. (a / b) * 100"
  127. onChange={e => {
  128. setValue(e.target.value);
  129. handleChange(e);
  130. }}
  131. />
  132. <RendererOverlay monospace>
  133. <EquationFormatter equation={value} errors={showErrors ? errors : []} />
  134. </RendererOverlay>
  135. </Wrapper>
  136. );
  137. }
  138. const Wrapper = styled('div')`
  139. position: relative;
  140. `;
  141. const RendererOverlay = styled('div')`
  142. ${inputStyles}
  143. border-color: transparent;
  144. position: absolute;
  145. top: 0;
  146. right: 0;
  147. bottom: 0;
  148. left: 0;
  149. align-items: center;
  150. justify-content: center;
  151. pointer-events: none;
  152. background: none;
  153. white-space: nowrap;
  154. overflow: hidden;
  155. resize: none;
  156. `;
  157. const StyledInput = styled(Input)<{hasError: boolean}>`
  158. caret-color: ${p => p.theme.subText};
  159. color: transparent;
  160. ${p =>
  161. p.hasError &&
  162. `
  163. border-color: ${p.theme.error};
  164. &:focus {
  165. border-color: ${p.theme.errorFocus};
  166. box-shadow: none;
  167. }
  168. `}
  169. `;