renderer.tsx 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import {Fragment, useEffect, useRef, useState} from 'react';
  2. import {css, keyframes} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import {useReducedMotion} from 'framer-motion';
  5. import Tooltip from 'sentry/components/tooltip';
  6. import space from 'sentry/styles/space';
  7. import {ParseResult, Token, TokenResult} from './parser';
  8. import {isWithinToken} from './utils';
  9. type Props = {
  10. /**
  11. * The result from parsing the search query string
  12. */
  13. parsedQuery: ParseResult;
  14. /**
  15. * The current location of the cursor within the query. This is used to
  16. * highlight active tokens and trigger error tooltips.
  17. */
  18. cursorPosition?: number;
  19. };
  20. /**
  21. * Renders the parsed query with syntax highlighting.
  22. */
  23. export default function HighlightQuery({parsedQuery, cursorPosition}: Props) {
  24. const result = renderResult(parsedQuery, cursorPosition ?? -1);
  25. return <Fragment>{result}</Fragment>;
  26. }
  27. function renderResult(result: ParseResult, cursor: number) {
  28. return result
  29. .map(t => renderToken(t, cursor))
  30. .map((renderedToken, i) => <Fragment key={i}>{renderedToken}</Fragment>);
  31. }
  32. function renderToken(token: TokenResult<Token>, cursor: number) {
  33. switch (token.type) {
  34. case Token.Spaces:
  35. return token.value;
  36. case Token.Filter:
  37. return <FilterToken filter={token} cursor={cursor} />;
  38. case Token.ValueTextList:
  39. case Token.ValueNumberList:
  40. return <ListToken token={token} cursor={cursor} />;
  41. case Token.ValueNumber:
  42. return <NumberToken token={token} />;
  43. case Token.ValueBoolean:
  44. return <Boolean>{token.text}</Boolean>;
  45. case Token.ValueIso8601Date:
  46. return <DateTime>{token.text}</DateTime>;
  47. case Token.LogicGroup:
  48. return <LogicGroup>{renderResult(token.inner, cursor)}</LogicGroup>;
  49. case Token.LogicBoolean:
  50. return <LogicBoolean>{token.value}</LogicBoolean>;
  51. default:
  52. return token.text;
  53. }
  54. }
  55. // XXX(epurkhiser): We have to animate `left` here instead of `transform` since
  56. // inline elements cannot be transformed. The filter _must_ be inline to
  57. // support text wrapping.
  58. const shakeAnimation = keyframes`
  59. ${new Array(4)
  60. .fill(0)
  61. .map((_, i) => `${i * (100 / 4)}% { left: ${3 * (i % 2 === 0 ? 1 : -1)}px; }`)
  62. .join('\n')}
  63. `;
  64. const FilterToken = ({
  65. filter,
  66. cursor,
  67. }: {
  68. cursor: number;
  69. filter: TokenResult<Token.Filter>;
  70. }) => {
  71. const isActive = isWithinToken(filter, cursor);
  72. // This state tracks if the cursor has left the filter token. We initialize it
  73. // to !isActive in the case where the filter token is rendered without the
  74. // cursor initially being in it.
  75. const [hasLeft, setHasLeft] = useState(!isActive);
  76. // Used to trigger the shake animation when the element becomes invalid
  77. const filterElementRef = useRef<HTMLSpanElement>(null);
  78. // Trigger the effect when isActive changes to updated whether the cursor has
  79. // left the token.
  80. useEffect(() => {
  81. if (!isActive && !hasLeft) {
  82. setHasLeft(true);
  83. }
  84. }, [hasLeft, isActive]);
  85. const showInvalid = hasLeft && !!filter.invalid;
  86. const showTooltip = showInvalid && isActive;
  87. const reduceMotion = useReducedMotion();
  88. // Trigger the shakeAnimation when showInvalid is set to true. We reset the
  89. // animation by clearing the style, set it to running, and re-applying the
  90. // animation
  91. useEffect(() => {
  92. if (!filterElementRef.current || !showInvalid || reduceMotion) {
  93. return;
  94. }
  95. const style = filterElementRef.current.style;
  96. style.animation = 'none';
  97. void filterElementRef.current.offsetTop;
  98. window.requestAnimationFrame(
  99. () => (style.animation = `${shakeAnimation.name} 300ms`)
  100. );
  101. }, [reduceMotion, showInvalid]);
  102. return (
  103. <Tooltip
  104. disabled={!showTooltip}
  105. title={filter.invalid?.reason}
  106. overlayStyle={{maxWidth: '350px'}}
  107. forceVisible
  108. skipWrapper
  109. >
  110. <Filter
  111. ref={filterElementRef}
  112. active={isActive}
  113. invalid={showInvalid}
  114. data-test-id={showInvalid ? 'filter-token-invalid' : 'filter-token'}
  115. >
  116. {filter.negated && <Negation>!</Negation>}
  117. <KeyToken token={filter.key} negated={filter.negated} />
  118. {filter.operator && <Operator>{filter.operator}</Operator>}
  119. <Value>{renderToken(filter.value, cursor)}</Value>
  120. </Filter>
  121. </Tooltip>
  122. );
  123. };
  124. const KeyToken = ({
  125. token,
  126. negated,
  127. }: {
  128. token: TokenResult<Token.KeySimple | Token.KeyAggregate | Token.KeyExplicitTag>;
  129. negated?: boolean;
  130. }) => {
  131. let value: React.ReactNode = token.text;
  132. if (token.type === Token.KeyExplicitTag) {
  133. value = (
  134. <ExplicitKey prefix={token.prefix}>
  135. {token.key.quoted ? `"${token.key.value}"` : token.key.value}
  136. </ExplicitKey>
  137. );
  138. }
  139. return <Key negated={!!negated}>{value}:</Key>;
  140. };
  141. const ListToken = ({
  142. token,
  143. cursor,
  144. }: {
  145. cursor: number;
  146. token: TokenResult<Token.ValueNumberList | Token.ValueTextList>;
  147. }) => (
  148. <InList>
  149. {token.items.map(({value, separator}) => [
  150. <ListComma key="comma">{separator}</ListComma>,
  151. value && renderToken(value, cursor),
  152. ])}
  153. </InList>
  154. );
  155. const NumberToken = ({token}: {token: TokenResult<Token.ValueNumber>}) => (
  156. <Fragment>
  157. {token.value}
  158. <Unit>{token.unit}</Unit>
  159. </Fragment>
  160. );
  161. type FilterProps = {
  162. active: boolean;
  163. invalid: boolean;
  164. };
  165. const colorType = (p: FilterProps) =>
  166. `${p.invalid ? 'invalid' : 'valid'}${p.active ? 'Active' : ''}` as const;
  167. const Filter = styled('span')<FilterProps>`
  168. --token-bg: ${p => p.theme.searchTokenBackground[colorType(p)]};
  169. --token-border: ${p => p.theme.searchTokenBorder[colorType(p)]};
  170. --token-value-color: ${p => (p.invalid ? p.theme.red300 : p.theme.blue300)};
  171. position: relative;
  172. animation-name: ${shakeAnimation};
  173. `;
  174. const filterCss = css`
  175. background: var(--token-bg);
  176. border: 0.5px solid var(--token-border);
  177. padding: ${space(0.25)} 0;
  178. `;
  179. const Negation = styled('span')`
  180. ${filterCss};
  181. border-right: none;
  182. padding-left: 1px;
  183. margin-left: -2px;
  184. font-weight: bold;
  185. border-radius: 2px 0 0 2px;
  186. color: ${p => p.theme.red300};
  187. `;
  188. const Key = styled('span')<{negated: boolean}>`
  189. ${filterCss};
  190. border-right: none;
  191. font-weight: bold;
  192. ${p =>
  193. !p.negated
  194. ? css`
  195. border-radius: 2px 0 0 2px;
  196. padding-left: 1px;
  197. margin-left: -2px;
  198. `
  199. : css`
  200. border-left: none;
  201. margin-left: 0;
  202. `};
  203. `;
  204. const ExplicitKey = styled('span')<{prefix: string}>`
  205. &:before,
  206. &:after {
  207. color: ${p => p.theme.subText};
  208. }
  209. &:before {
  210. content: '${p => p.prefix}[';
  211. }
  212. &:after {
  213. content: ']';
  214. }
  215. `;
  216. const Operator = styled('span')`
  217. ${filterCss};
  218. border-left: none;
  219. border-right: none;
  220. margin: -1px 0;
  221. color: ${p => p.theme.pink300};
  222. `;
  223. const Value = styled('span')`
  224. ${filterCss};
  225. border-left: none;
  226. border-radius: 0 2px 2px 0;
  227. color: var(--token-value-color);
  228. margin: -1px -2px -1px 0;
  229. padding-right: 1px;
  230. `;
  231. const Unit = styled('span')`
  232. font-weight: bold;
  233. color: ${p => p.theme.green300};
  234. `;
  235. const LogicBoolean = styled('span')`
  236. font-weight: bold;
  237. color: ${p => p.theme.gray300};
  238. `;
  239. const Boolean = styled('span')`
  240. color: ${p => p.theme.pink300};
  241. `;
  242. const DateTime = styled('span')`
  243. color: ${p => p.theme.green300};
  244. `;
  245. const ListComma = styled('span')`
  246. color: ${p => p.theme.gray300};
  247. `;
  248. const InList = styled('span')`
  249. &:before {
  250. content: '[';
  251. font-weight: bold;
  252. color: ${p => p.theme.purple300};
  253. }
  254. &:after {
  255. content: ']';
  256. font-weight: bold;
  257. color: ${p => p.theme.purple300};
  258. }
  259. ${Value} {
  260. color: ${p => p.theme.purple300};
  261. }
  262. `;
  263. const LogicGroup = styled(({children, ...props}) => (
  264. <span {...props}>
  265. <span>(</span>
  266. {children}
  267. <span>)</span>
  268. </span>
  269. ))`
  270. > span:first-child,
  271. > span:last-child {
  272. position: relative;
  273. color: transparent;
  274. &:before {
  275. position: absolute;
  276. top: -5px;
  277. color: ${p => p.theme.pink300};
  278. font-size: 16px;
  279. font-weight: bold;
  280. }
  281. }
  282. > span:first-child:before {
  283. left: -3px;
  284. content: '(';
  285. }
  286. > span:last-child:before {
  287. right: -3px;
  288. content: ')';
  289. }
  290. `;