renderer.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 ref={filterElementRef} active={isActive} invalid={showInvalid}>
  111. {filter.negated && <Negation>!</Negation>}
  112. <KeyToken token={filter.key} negated={filter.negated} />
  113. {filter.operator && <Operator>{filter.operator}</Operator>}
  114. <Value>{renderToken(filter.value, cursor)}</Value>
  115. </Filter>
  116. </Tooltip>
  117. );
  118. };
  119. const KeyToken = ({
  120. token,
  121. negated,
  122. }: {
  123. token: TokenResult<Token.KeySimple | Token.KeyAggregate | Token.KeyExplicitTag>;
  124. negated?: boolean;
  125. }) => {
  126. let value: React.ReactNode = token.text;
  127. if (token.type === Token.KeyExplicitTag) {
  128. value = (
  129. <ExplicitKey prefix={token.prefix}>
  130. {token.key.quoted ? `"${token.key.value}"` : token.key.value}
  131. </ExplicitKey>
  132. );
  133. }
  134. return <Key negated={!!negated}>{value}:</Key>;
  135. };
  136. const ListToken = ({
  137. token,
  138. cursor,
  139. }: {
  140. cursor: number;
  141. token: TokenResult<Token.ValueNumberList | Token.ValueTextList>;
  142. }) => (
  143. <InList>
  144. {token.items.map(({value, separator}) => [
  145. <ListComma key="comma">{separator}</ListComma>,
  146. value && renderToken(value, cursor),
  147. ])}
  148. </InList>
  149. );
  150. const NumberToken = ({token}: {token: TokenResult<Token.ValueNumber>}) => (
  151. <Fragment>
  152. {token.value}
  153. <Unit>{token.unit}</Unit>
  154. </Fragment>
  155. );
  156. type FilterProps = {
  157. active: boolean;
  158. invalid: boolean;
  159. };
  160. const colorType = (p: FilterProps) =>
  161. `${p.invalid ? 'invalid' : 'valid'}${p.active ? 'Active' : ''}` as const;
  162. const Filter = styled('span')<FilterProps>`
  163. --token-bg: ${p => p.theme.searchTokenBackground[colorType(p)]};
  164. --token-border: ${p => p.theme.searchTokenBorder[colorType(p)]};
  165. --token-value-color: ${p => (p.invalid ? p.theme.red300 : p.theme.blue300)};
  166. position: relative;
  167. animation-name: ${shakeAnimation};
  168. `;
  169. const filterCss = css`
  170. background: var(--token-bg);
  171. border: 0.5px solid var(--token-border);
  172. padding: ${space(0.25)} 0;
  173. `;
  174. const Negation = styled('span')`
  175. ${filterCss};
  176. border-right: none;
  177. padding-left: 1px;
  178. margin-left: -2px;
  179. font-weight: bold;
  180. border-radius: 2px 0 0 2px;
  181. color: ${p => p.theme.red300};
  182. `;
  183. const Key = styled('span')<{negated: boolean}>`
  184. ${filterCss};
  185. border-right: none;
  186. font-weight: bold;
  187. ${p =>
  188. !p.negated
  189. ? css`
  190. border-radius: 2px 0 0 2px;
  191. padding-left: 1px;
  192. margin-left: -2px;
  193. `
  194. : css`
  195. border-left: none;
  196. margin-left: 0;
  197. `};
  198. `;
  199. const ExplicitKey = styled('span')<{prefix: string}>`
  200. &:before,
  201. &:after {
  202. color: ${p => p.theme.subText};
  203. }
  204. &:before {
  205. content: '${p => p.prefix}[';
  206. }
  207. &:after {
  208. content: ']';
  209. }
  210. `;
  211. const Operator = styled('span')`
  212. ${filterCss};
  213. border-left: none;
  214. border-right: none;
  215. margin: -1px 0;
  216. color: ${p => p.theme.pink300};
  217. `;
  218. const Value = styled('span')`
  219. ${filterCss};
  220. border-left: none;
  221. border-radius: 0 2px 2px 0;
  222. color: var(--token-value-color);
  223. margin: -1px -2px -1px 0;
  224. padding-right: 1px;
  225. `;
  226. const Unit = styled('span')`
  227. font-weight: bold;
  228. color: ${p => p.theme.green300};
  229. `;
  230. const LogicBoolean = styled('span')`
  231. font-weight: bold;
  232. color: ${p => p.theme.gray300};
  233. `;
  234. const Boolean = styled('span')`
  235. color: ${p => p.theme.pink300};
  236. `;
  237. const DateTime = styled('span')`
  238. color: ${p => p.theme.green300};
  239. `;
  240. const ListComma = styled('span')`
  241. color: ${p => p.theme.gray300};
  242. `;
  243. const InList = styled('span')`
  244. &:before {
  245. content: '[';
  246. font-weight: bold;
  247. color: ${p => p.theme.purple300};
  248. }
  249. &:after {
  250. content: ']';
  251. font-weight: bold;
  252. color: ${p => p.theme.purple300};
  253. }
  254. ${Value} {
  255. color: ${p => p.theme.purple300};
  256. }
  257. `;
  258. const LogicGroup = styled(({children, ...props}) => (
  259. <span {...props}>
  260. <span>(</span>
  261. {children}
  262. <span>)</span>
  263. </span>
  264. ))`
  265. > span:first-child,
  266. > span:last-child {
  267. position: relative;
  268. color: transparent;
  269. &:before {
  270. position: absolute;
  271. top: -5px;
  272. color: ${p => p.theme.pink300};
  273. font-size: 16px;
  274. font-weight: bold;
  275. }
  276. }
  277. > span:first-child:before {
  278. left: -3px;
  279. content: '(';
  280. }
  281. > span:last-child:before {
  282. right: -3px;
  283. content: ')';
  284. }
  285. `;