renderer.tsx 6.7 KB

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