renderer.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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.VALUE_TEXT_LIST:
  39. case Token.VALUE_NUMBER_LIST:
  40. return <ListToken token={token} cursor={cursor} />;
  41. case Token.VALUE_NUMBER:
  42. return <NumberToken token={token} />;
  43. case Token.VALUE_BOOLEAN:
  44. return <Boolean>{token.text}</Boolean>;
  45. case Token.VALUE_ISO_8601_DATE:
  46. return <DateTime>{token.text}</DateTime>;
  47. case Token.LOGIC_GROUP:
  48. return <LogicGroup>{renderResult(token.inner, cursor)}</LogicGroup>;
  49. case Token.LOGIC_BOOLEAN:
  50. return <LogicBoolean>{token.value}</LogicBoolean>;
  51. case Token.FREE_TEXT:
  52. return <FreeTextToken token={token} cursor={cursor} />;
  53. default:
  54. return token.text;
  55. }
  56. }
  57. // XXX(epurkhiser): We have to animate `left` here instead of `transform` since
  58. // inline elements cannot be transformed. The filter _must_ be inline to
  59. // support text wrapping.
  60. const shakeAnimation = keyframes`
  61. ${new Array(4)
  62. .fill(0)
  63. .map((_, i) => `${i * (100 / 4)}% { left: ${3 * (i % 2 === 0 ? 1 : -1)}px; }`)
  64. .join('\n')}
  65. `;
  66. function FilterToken({
  67. filter,
  68. cursor,
  69. }: {
  70. cursor: number;
  71. filter: TokenResult<Token.FILTER>;
  72. }) {
  73. const isActive = isWithinToken(filter, cursor);
  74. // This state tracks if the cursor has left the filter token. We initialize it
  75. // to !isActive in the case where the filter token is rendered without the
  76. // cursor initially being in it.
  77. const [hasLeft, setHasLeft] = useState(!isActive);
  78. // Used to trigger the shake animation when the element becomes invalid
  79. const filterElementRef = useRef<HTMLSpanElement>(null);
  80. // Trigger the effect when isActive changes to updated whether the cursor has
  81. // left the token.
  82. useEffect(() => {
  83. if (!isActive && !hasLeft) {
  84. setHasLeft(true);
  85. }
  86. }, [hasLeft, isActive]);
  87. const showInvalid = hasLeft && !!filter.invalid;
  88. const showWarning = hasLeft && !!filter.warning;
  89. const showTooltip = (showInvalid || showWarning) && isActive;
  90. const reduceMotion = useReducedMotion();
  91. // Trigger the shakeAnimation when showInvalid is set to true. We reset the
  92. // animation by clearing the style, set it to running, and re-applying the
  93. // animation
  94. useEffect(() => {
  95. if (!filterElementRef.current || !showInvalid || reduceMotion) {
  96. return;
  97. }
  98. const style = filterElementRef.current.style;
  99. style.animation = 'none';
  100. void filterElementRef.current.offsetTop;
  101. window.requestAnimationFrame(
  102. () => (style.animation = `${shakeAnimation.name} 300ms`)
  103. );
  104. }, [reduceMotion, showInvalid]);
  105. return (
  106. <Tooltip
  107. disabled={!showTooltip}
  108. title={filter.invalid?.reason ?? filter.warning}
  109. overlayStyle={{maxWidth: '350px'}}
  110. forceVisible
  111. skipWrapper
  112. >
  113. <TokenGroup
  114. ref={filterElementRef}
  115. active={isActive}
  116. invalid={showInvalid}
  117. warning={showWarning}
  118. data-test-id={showInvalid ? 'filter-token-invalid' : 'filter-token'}
  119. >
  120. {filter.negated && <Negation>!</Negation>}
  121. <KeyToken token={filter.key} negated={filter.negated} />
  122. {filter.operator && <Operator>{filter.operator}</Operator>}
  123. <Value>{renderToken(filter.value, cursor)}</Value>
  124. </TokenGroup>
  125. </Tooltip>
  126. );
  127. }
  128. function FreeTextToken({
  129. token,
  130. cursor,
  131. }: {
  132. cursor: number;
  133. token: TokenResult<Token.FREE_TEXT>;
  134. }) {
  135. const isActive = isWithinToken(token, cursor);
  136. // This state tracks if the cursor has left the filter token. We initialize it
  137. // to !isActive in the case where the filter token is rendered without the
  138. // cursor initially being in it.
  139. const [hasLeft, setHasLeft] = useState(!isActive);
  140. // Used to trigger the shake animation when the element becomes invalid
  141. const filterElementRef = useRef<HTMLSpanElement>(null);
  142. // Trigger the effect when isActive changes to updated whether the cursor has
  143. // left the token.
  144. useEffect(() => {
  145. if (!isActive && !hasLeft) {
  146. setHasLeft(true);
  147. }
  148. }, [hasLeft, isActive]);
  149. const showInvalid = hasLeft && !!token.invalid;
  150. const showTooltip = showInvalid && isActive;
  151. const reduceMotion = useReducedMotion();
  152. // Trigger the shakeAnimation when showInvalid is set to true. We reset the
  153. // animation by clearing the style, set it to running, and re-applying the
  154. // animation
  155. useEffect(() => {
  156. if (!filterElementRef.current || !showInvalid || reduceMotion) {
  157. return;
  158. }
  159. const style = filterElementRef.current.style;
  160. style.animation = 'none';
  161. void filterElementRef.current.offsetTop;
  162. window.requestAnimationFrame(
  163. () => (style.animation = `${shakeAnimation.name} 300ms`)
  164. );
  165. }, [reduceMotion, showInvalid]);
  166. return (
  167. <Tooltip
  168. disabled={!showTooltip}
  169. title={token.invalid?.reason}
  170. overlayStyle={{maxWidth: '350px'}}
  171. forceVisible
  172. skipWrapper
  173. >
  174. <FreeTextTokenGroup ref={filterElementRef} active={isActive} invalid={showInvalid}>
  175. <FreeText>{token.text}</FreeText>
  176. </FreeTextTokenGroup>
  177. </Tooltip>
  178. );
  179. }
  180. function KeyToken({
  181. token,
  182. negated,
  183. }: {
  184. token: TokenResult<Token.KEY_SIMPLE | Token.KEY_AGGREGATE | Token.KEY_EXPLICIT_TAG>;
  185. negated?: boolean;
  186. }) {
  187. let value: React.ReactNode = token.text;
  188. if (token.type === Token.KEY_EXPLICIT_TAG) {
  189. value = (
  190. <ExplicitKey prefix={token.prefix}>
  191. {token.key.quoted ? `"${token.key.value}"` : token.key.value}
  192. </ExplicitKey>
  193. );
  194. }
  195. return <Key negated={!!negated}>{value}:</Key>;
  196. }
  197. function ListToken({
  198. token,
  199. cursor,
  200. }: {
  201. cursor: number;
  202. token: TokenResult<Token.VALUE_NUMBER_LIST | Token.VALUE_TEXT_LIST>;
  203. }) {
  204. return (
  205. <InList>
  206. {token.items.map(({value, separator}) => [
  207. <ListComma key="comma">{separator}</ListComma>,
  208. value && renderToken(value, cursor),
  209. ])}
  210. </InList>
  211. );
  212. }
  213. function NumberToken({token}: {token: TokenResult<Token.VALUE_NUMBER>}) {
  214. return (
  215. <Fragment>
  216. {token.value}
  217. <Unit>{token.unit}</Unit>
  218. </Fragment>
  219. );
  220. }
  221. type TokenGroupProps = {
  222. active: boolean;
  223. invalid: boolean;
  224. warning?: boolean;
  225. };
  226. const colorType = (p: TokenGroupProps) =>
  227. `${p.invalid ? 'invalid' : p.warning ? 'warning' : 'valid'}${
  228. p.active ? 'Active' : ''
  229. }` as const;
  230. const TokenGroup = styled('span')<TokenGroupProps>`
  231. --token-bg: ${p => p.theme.searchTokenBackground[colorType(p)]};
  232. --token-border: ${p => p.theme.searchTokenBorder[colorType(p)]};
  233. --token-value-color: ${p =>
  234. p.invalid ? p.theme.red400 : p.warning ? p.theme.gray400 : p.theme.blue400};
  235. position: relative;
  236. animation-name: ${shakeAnimation};
  237. `;
  238. const FreeTextTokenGroup = styled(TokenGroup)`
  239. ${p =>
  240. !p.invalid &&
  241. css`
  242. --token-bg: inherit;
  243. --token-border: inherit;
  244. --token-value-color: inherit;
  245. `}
  246. `;
  247. const filterCss = css`
  248. background: var(--token-bg);
  249. border: 0.5px solid var(--token-border);
  250. padding: ${space(0.25)} 0;
  251. `;
  252. const Negation = styled('span')`
  253. ${filterCss};
  254. border-right: none;
  255. padding-left: 1px;
  256. margin-left: -1px;
  257. font-weight: bold;
  258. border-radius: 2px 0 0 2px;
  259. color: ${p => p.theme.red400};
  260. `;
  261. const Key = styled('span')<{negated: boolean}>`
  262. ${filterCss};
  263. border-right: none;
  264. font-weight: bold;
  265. ${p =>
  266. !p.negated
  267. ? css`
  268. border-radius: 2px 0 0 2px;
  269. padding-left: 1px;
  270. margin-left: -2px;
  271. `
  272. : css`
  273. border-left: none;
  274. margin-left: 0;
  275. `};
  276. `;
  277. const ExplicitKey = styled('span')<{prefix: string}>`
  278. &:before,
  279. &:after {
  280. color: ${p => p.theme.subText};
  281. }
  282. &:before {
  283. content: '${p => p.prefix}[';
  284. }
  285. &:after {
  286. content: ']';
  287. }
  288. `;
  289. const Operator = styled('span')`
  290. ${filterCss};
  291. border-left: none;
  292. border-right: none;
  293. margin: -1px 0;
  294. color: ${p => p.theme.pink400};
  295. `;
  296. const Value = styled('span')`
  297. ${filterCss};
  298. border-left: none;
  299. border-radius: 0 2px 2px 0;
  300. color: var(--token-value-color);
  301. margin: -1px -2px -1px 0;
  302. padding-right: 1px;
  303. `;
  304. const FreeText = styled('span')`
  305. ${filterCss};
  306. border-radius: 2px;
  307. color: var(--token-value-color);
  308. margin: -1px -2px -1px 0;
  309. padding-right: 1px;
  310. padding-left: 1px;
  311. `;
  312. const Unit = styled('span')`
  313. font-weight: bold;
  314. color: ${p => p.theme.green400};
  315. `;
  316. const LogicBoolean = styled('span')`
  317. font-weight: bold;
  318. color: ${p => p.theme.gray300};
  319. `;
  320. const Boolean = styled('span')`
  321. color: ${p => p.theme.pink400};
  322. `;
  323. const DateTime = styled('span')`
  324. color: ${p => p.theme.green400};
  325. `;
  326. const ListComma = styled('span')`
  327. color: ${p => p.theme.gray300};
  328. `;
  329. const InList = styled('span')`
  330. &:before {
  331. content: '[';
  332. font-weight: bold;
  333. color: ${p => p.theme.purple400};
  334. }
  335. &:after {
  336. content: ']';
  337. font-weight: bold;
  338. color: ${p => p.theme.purple400};
  339. }
  340. ${Value} {
  341. color: ${p => p.theme.purple400};
  342. }
  343. `;
  344. const LogicGroup = styled(({children, ...props}) => (
  345. <span {...props}>
  346. <span>(</span>
  347. {children}
  348. <span>)</span>
  349. </span>
  350. ))`
  351. > span:first-child,
  352. > span:last-child {
  353. position: relative;
  354. color: transparent;
  355. &:before {
  356. position: absolute;
  357. top: -5px;
  358. color: ${p => p.theme.pink400};
  359. font-size: 16px;
  360. font-weight: bold;
  361. }
  362. }
  363. > span:first-child:before {
  364. left: -3px;
  365. content: '(';
  366. }
  367. > span:last-child:before {
  368. right: -3px;
  369. content: ')';
  370. }
  371. `;