traceSearchInput.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import type React from 'react';
  2. import {Fragment, useCallback, useLayoutEffect, useRef, useState} from 'react';
  3. import styled from '@emotion/styled';
  4. import {InputGroup} from 'sentry/components/inputGroup';
  5. import LoadingIndicator from 'sentry/components/loadingIndicator';
  6. import {SearchBarTrailingButton} from 'sentry/components/searchBar';
  7. import {IconChevron, IconClose, IconSearch} from 'sentry/icons';
  8. import {t} from 'sentry/locale';
  9. import {space} from 'sentry/styles/space';
  10. import type {Organization} from 'sentry/types/organization';
  11. import {trackAnalytics} from 'sentry/utils/analytics';
  12. import type {DispatchingReducerMiddleware} from 'sentry/utils/useDispatchingReducer';
  13. import useOrganization from 'sentry/utils/useOrganization';
  14. import {traceAnalytics} from '../traceAnalytics';
  15. import type {TraceTree} from '../traceModels/traceTree';
  16. import type {TraceTreeNode} from '../traceModels/traceTreeNode';
  17. import type {TraceReducer} from '../traceState';
  18. import type {TraceSearchState} from '../traceState/traceSearch';
  19. import {
  20. useTraceState,
  21. useTraceStateDispatch,
  22. useTraceStateEmitter,
  23. } from '../traceState/traceStateProvider';
  24. interface TraceSearchInputProps {
  25. onTraceSearch: (
  26. query: string,
  27. node: TraceTreeNode<TraceTree.NodeValue> | null,
  28. behavior: 'track result' | 'persist'
  29. ) => void;
  30. organization: Organization;
  31. }
  32. const MIN_LOADING_TIME = 300;
  33. export function TraceSearchInput(props: TraceSearchInputProps) {
  34. const organization = useOrganization();
  35. const traceState = useTraceState();
  36. const traceDispatch = useTraceStateDispatch();
  37. const traceStateEmitter = useTraceStateEmitter();
  38. const [status, setStatus] = useState<TraceSearchState['status']>([0, 'success']);
  39. const timeoutRef = useRef<number | undefined>(undefined);
  40. const statusRef = useRef<TraceSearchState['status']>(status);
  41. statusRef.current = status;
  42. const traceStateRef = useRef(traceState);
  43. traceStateRef.current = traceState;
  44. const onTraceSearch = props.onTraceSearch;
  45. useLayoutEffect(() => {
  46. if (typeof timeoutRef.current === 'number') {
  47. window.clearTimeout(timeoutRef.current);
  48. timeoutRef.current = undefined;
  49. }
  50. // if status is loading, show loading icon immediately
  51. // if previous status was loading, show loading icon for at least 500ms
  52. if (!statusRef.current && traceState.search.status) {
  53. setStatus([performance.now(), traceState.search.status[1]]);
  54. return undefined;
  55. }
  56. let cancel = false;
  57. const nextStatus = traceState.search.status;
  58. if (nextStatus) {
  59. const elapsed = performance.now() - nextStatus[0];
  60. if (elapsed > MIN_LOADING_TIME || nextStatus[1] === 'loading') {
  61. setStatus(nextStatus);
  62. return undefined;
  63. }
  64. const schedule = nextStatus[0] + MIN_LOADING_TIME - performance.now();
  65. timeoutRef.current = window.setTimeout(() => {
  66. if (!cancel) {
  67. setStatus(nextStatus);
  68. }
  69. }, schedule);
  70. } else {
  71. setStatus(nextStatus);
  72. }
  73. return () => {
  74. cancel = true;
  75. };
  76. }, [traceState.search.status]);
  77. const onSearchFocus = useCallback(() => {
  78. traceAnalytics.trackSearchFocus(organization);
  79. if (traceStateRef.current.rovingTabIndex.node) {
  80. traceDispatch({type: 'clear roving index'});
  81. }
  82. }, [traceDispatch, organization]);
  83. const onChange = useCallback(
  84. (event: React.ChangeEvent<HTMLInputElement>) => {
  85. if (!event.target.value) {
  86. traceDispatch({type: 'clear query'});
  87. return;
  88. }
  89. traceDispatch({type: 'set query', query: event.target.value});
  90. onTraceSearch(
  91. event.target.value,
  92. traceStateRef.current.rovingTabIndex.node ?? traceStateRef.current.search.node,
  93. 'track result'
  94. );
  95. },
  96. [traceDispatch, onTraceSearch]
  97. );
  98. const onSearchClear = useCallback(() => {
  99. trackAnalytics('trace.trace_layout.search_clear', {
  100. organization,
  101. });
  102. traceDispatch({type: 'clear query'});
  103. }, [traceDispatch, organization]);
  104. const onKeyDown = useCallback(
  105. (event: React.KeyboardEvent<HTMLInputElement>) => {
  106. switch (event.key) {
  107. case 'ArrowDown':
  108. trackAnalytics('trace.trace_layout.search_match_navigate', {
  109. organization,
  110. direction: 'next',
  111. interaction: 'arrowKey',
  112. });
  113. traceDispatch({
  114. type: event.shiftKey ? 'go to last match' : 'go to next match',
  115. });
  116. break;
  117. case 'ArrowUp':
  118. trackAnalytics('trace.trace_layout.search_match_navigate', {
  119. organization,
  120. direction: 'prev',
  121. interaction: 'arrowKey',
  122. });
  123. traceDispatch({
  124. type: event.shiftKey ? 'go to first match' : 'go to previous match',
  125. });
  126. break;
  127. case 'Enter':
  128. trackAnalytics('trace.trace_layout.search_match_navigate', {
  129. organization,
  130. direction: event.shiftKey ? 'prev' : 'next',
  131. interaction: 'enterKey',
  132. });
  133. traceDispatch({
  134. type: event.shiftKey ? 'go to previous match' : 'go to next match',
  135. });
  136. break;
  137. default:
  138. }
  139. },
  140. [traceDispatch, organization]
  141. );
  142. const onNextSearchClick = useCallback(() => {
  143. trackAnalytics('trace.trace_layout.search_match_navigate', {
  144. organization,
  145. direction: 'next',
  146. interaction: 'click',
  147. });
  148. if (traceStateRef.current.rovingTabIndex.node) {
  149. traceDispatch({type: 'clear roving index'});
  150. }
  151. traceDispatch({type: 'go to next match'});
  152. }, [traceDispatch, organization]);
  153. const onPreviousSearchClick = useCallback(() => {
  154. trackAnalytics('trace.trace_layout.search_match_navigate', {
  155. organization,
  156. direction: 'prev',
  157. interaction: 'click',
  158. });
  159. if (traceStateRef.current.rovingTabIndex.node) {
  160. traceDispatch({type: 'clear roving index'});
  161. }
  162. traceDispatch({type: 'go to previous match'});
  163. }, [traceDispatch, organization]);
  164. const inputRef = useRef<HTMLInputElement>(null);
  165. useLayoutEffect(() => {
  166. const beforeTraceNextStateDispatch: DispatchingReducerMiddleware<
  167. typeof TraceReducer
  168. >['before next state'] = (_prevState, _nextState, action) => {
  169. if (
  170. action.type === 'set query' &&
  171. action.source === 'external' &&
  172. action.query &&
  173. inputRef.current
  174. ) {
  175. inputRef.current.value = action.query;
  176. traceDispatch({type: 'clear roving index'});
  177. onTraceSearch(action.query, traceStateRef.current.search.node, 'track result');
  178. }
  179. };
  180. traceStateEmitter.on('before next state', beforeTraceNextStateDispatch);
  181. return () => {
  182. traceStateEmitter.off('before next state', beforeTraceNextStateDispatch);
  183. };
  184. }, [traceStateEmitter, onTraceSearch, traceDispatch]);
  185. return (
  186. <StyledSearchBar>
  187. <InputGroup.LeadingItems>
  188. <InvisiblePlaceholder />
  189. {status?.[1] === 'loading' ? (
  190. <StyledLoadingIndicator data-test-id="trace-search-loading" size={12} />
  191. ) : (
  192. <StyledSearchIcon
  193. data-test-id="trace-search-success"
  194. color="subText"
  195. size={'xs'}
  196. />
  197. )}
  198. </InputGroup.LeadingItems>
  199. <InputGroup.Input
  200. ref={inputRef}
  201. size="xs"
  202. type="text"
  203. name="query"
  204. autoComplete="off"
  205. placeholder={t('Search in trace')}
  206. defaultValue={traceState.search.query}
  207. onChange={onChange}
  208. onKeyDown={onKeyDown}
  209. onFocus={onSearchFocus}
  210. />
  211. <InputGroup.TrailingItems>
  212. <StyledTrailingText data-test-id="trace-search-result-iterator">
  213. {`${
  214. traceState.search.query && !traceState.search.results?.length
  215. ? t('no results')
  216. : traceState.search.query
  217. ? (traceState.search.resultIteratorIndex !== null
  218. ? traceState.search.resultIteratorIndex + 1
  219. : '-') + `/${traceState.search.results?.length ?? 0}`
  220. : ''
  221. }`}
  222. </StyledTrailingText>
  223. {traceState.search.query ? (
  224. <Fragment>
  225. <StyledSearchBarTrailingButton
  226. size="zero"
  227. borderless
  228. icon={<IconChevron size="xs" />}
  229. aria-label={t('Next')}
  230. disabled={status?.[1] === 'loading'}
  231. onClick={onPreviousSearchClick}
  232. />
  233. <StyledSearchBarTrailingButton
  234. size="zero"
  235. borderless
  236. icon={<IconChevron size="xs" direction="down" />}
  237. aria-label={t('Previous')}
  238. disabled={status?.[1] === 'loading'}
  239. onClick={onNextSearchClick}
  240. />
  241. <StyledSearchBarTrailingButton
  242. size="zero"
  243. borderless
  244. disabled={status?.[1] === 'loading'}
  245. onClick={onSearchClear}
  246. icon={<IconClose size="xs" />}
  247. aria-label={t('Clear')}
  248. />
  249. </Fragment>
  250. ) : null}
  251. </InputGroup.TrailingItems>
  252. </StyledSearchBar>
  253. );
  254. }
  255. const InvisiblePlaceholder = styled('div')`
  256. pointer-events: none;
  257. visibility: hidden;
  258. width: 12px;
  259. height: 12px;
  260. `;
  261. const StyledLoadingIndicator = styled(LoadingIndicator)`
  262. margin: 0;
  263. left: 0;
  264. top: 50%;
  265. position: absolute;
  266. transform: translate(-2px, -50%);
  267. animation: showLoadingIndicator 0.3s ease-in-out forwards;
  268. @keyframes showLoadingIndicator {
  269. from {
  270. opacity: 0;
  271. transform: translate(-2px, -50%) scale(0.86);
  272. }
  273. to {
  274. opacity: 1;
  275. transform: translate(-2px, -50%) scale(1);
  276. }
  277. }
  278. .loading-indicator {
  279. border-width: 2px;
  280. }
  281. .loading-message {
  282. display: none;
  283. }
  284. `;
  285. const StyledSearchIcon = styled(IconSearch)`
  286. position: absolute;
  287. left: 0;
  288. top: 50%;
  289. transform: scale(1) translateY(-50%);
  290. animation: showSearchIcon 0.3s ease-in-out forwards;
  291. @keyframes showSearchIcon {
  292. from {
  293. opacity: 0;
  294. transform: scale(0.86) translateY(-50%);
  295. }
  296. to {
  297. opacity: 1;
  298. transform: scale(1) translateY(-50%);
  299. }
  300. }
  301. `;
  302. const StyledSearchBarTrailingButton = styled(SearchBarTrailingButton)`
  303. padding: 0;
  304. &:last-child {
  305. svg {
  306. width: 10px;
  307. height: 10px;
  308. }
  309. }
  310. `;
  311. const StyledTrailingText = styled('span')`
  312. color: ${p => p.theme.subText};
  313. font-size: ${p => p.theme.fontSizeSmall};
  314. `;
  315. const StyledSearchBar = styled(InputGroup)`
  316. flex: 1 1 100%;
  317. margin-bottom: ${space(1)};
  318. > div > div:last-child {
  319. gap: ${space(0.25)};
  320. }
  321. `;