queries.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import {Fragment, useCallback, useLayoutEffect, useMemo} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as echarts from 'echarts/core';
  4. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  5. import {Button} from 'sentry/components/button';
  6. import {EquationInput} from 'sentry/components/metrics/equationInput';
  7. import {EquationSymbol} from 'sentry/components/metrics/equationSymbol';
  8. import {QueryBuilder} from 'sentry/components/metrics/queryBuilder';
  9. import {getQuerySymbol, QuerySymbol} from 'sentry/components/metrics/querySymbol';
  10. import SwitchButton from 'sentry/components/switchButton';
  11. import {Tooltip} from 'sentry/components/tooltip';
  12. import {IconAdd} from 'sentry/icons';
  13. import {t} from 'sentry/locale';
  14. import {space} from 'sentry/styles/space';
  15. import {trackAnalytics} from 'sentry/utils/analytics';
  16. import {
  17. isMetricsQueryWidget,
  18. MetricExpressionType,
  19. type MetricsEquationWidget,
  20. type MetricsQuery,
  21. type MetricsQueryWidget,
  22. type MetricsWidget,
  23. } from 'sentry/utils/metrics/types';
  24. import useOrganization from 'sentry/utils/useOrganization';
  25. import usePageFilters from 'sentry/utils/usePageFilters';
  26. import {METRIC_CHART_GROUP} from 'sentry/views/metrics/constants';
  27. import {useMetricsContext} from 'sentry/views/metrics/context';
  28. import {MetricFormulaContextMenu} from 'sentry/views/metrics/metricFormulaContextMenu';
  29. import {MetricQueryContextMenu} from 'sentry/views/metrics/metricQueryContextMenu';
  30. import {useFormulaDependencies} from 'sentry/views/metrics/utils/useFormulaDependencies';
  31. export function Queries() {
  32. const {
  33. widgets,
  34. updateWidget,
  35. setSelectedWidgetIndex,
  36. showQuerySymbols,
  37. selectedWidgetIndex,
  38. isMultiChartMode,
  39. setIsMultiChartMode,
  40. addWidget,
  41. toggleWidgetVisibility,
  42. } = useMetricsContext();
  43. const organization = useOrganization();
  44. const {selection} = usePageFilters();
  45. const formulaDependencies = useFormulaDependencies();
  46. // Make sure all charts are connected to the same group whenever the widgets definition changes
  47. useLayoutEffect(() => {
  48. echarts.connect(METRIC_CHART_GROUP);
  49. }, [widgets]);
  50. const handleChange = useCallback(
  51. (index: number, widget: Partial<MetricsWidget>) => {
  52. updateWidget(index, widget);
  53. },
  54. [updateWidget]
  55. );
  56. const handleAddWidget = useCallback(
  57. (type: MetricExpressionType) => {
  58. trackAnalytics('ddm.widget.add', {
  59. organization,
  60. type: type === MetricExpressionType.QUERY ? 'query' : 'equation',
  61. });
  62. addWidget(type);
  63. },
  64. [addWidget, organization]
  65. );
  66. const querySymbols = useMemo(() => {
  67. const querySymbolSet = new Set<string>();
  68. for (const widget of widgets) {
  69. const symbol = getQuerySymbol(widget.id);
  70. if (isMetricsQueryWidget(widget)) {
  71. querySymbolSet.add(symbol);
  72. }
  73. }
  74. return querySymbolSet;
  75. }, [widgets]);
  76. const visibleWidgets = widgets.filter(widget => !widget.isHidden);
  77. return (
  78. <Fragment>
  79. <Wrapper showQuerySymbols={showQuerySymbols}>
  80. {widgets.map((widget, index) => (
  81. <Row
  82. key={`${widget.type}_${widget.id}`}
  83. onFocusCapture={() => setSelectedWidgetIndex(index)}
  84. >
  85. {isMetricsQueryWidget(widget) ? (
  86. <Query
  87. widget={widget}
  88. onChange={handleChange}
  89. onToggleVisibility={toggleWidgetVisibility}
  90. index={index}
  91. projects={selection.projects}
  92. showQuerySymbols={showQuerySymbols}
  93. isSelected={isMultiChartMode && index === selectedWidgetIndex}
  94. canBeHidden={visibleWidgets.length > 1}
  95. />
  96. ) : (
  97. <Formula
  98. availableVariables={querySymbols}
  99. onChange={handleChange}
  100. onToggleVisibility={toggleWidgetVisibility}
  101. index={index}
  102. widget={widget}
  103. showQuerySymbols={showQuerySymbols}
  104. isSelected={isMultiChartMode && index === selectedWidgetIndex}
  105. canBeHidden={visibleWidgets.length > 1}
  106. formulaDependencies={formulaDependencies}
  107. />
  108. )}
  109. </Row>
  110. ))}
  111. </Wrapper>
  112. <ButtonBar addQuerySymbolSpacing={showQuerySymbols}>
  113. <GuideAnchor target="add_metric_query" position="bottom">
  114. <Button
  115. size="sm"
  116. icon={<IconAdd isCircled />}
  117. onClick={() => handleAddWidget(MetricExpressionType.QUERY)}
  118. >
  119. {t('Add metric')}
  120. </Button>
  121. </GuideAnchor>
  122. <Button
  123. size="sm"
  124. icon={<IconAdd isCircled />}
  125. onClick={() => handleAddWidget(MetricExpressionType.EQUATION)}
  126. >
  127. {t('Add equation')}
  128. </Button>
  129. {widgets.length > 1 && (
  130. <SwitchWrapper>
  131. {t('One chart per metric')}
  132. <SwitchButton
  133. isActive={isMultiChartMode}
  134. toggle={() => setIsMultiChartMode(!isMultiChartMode)}
  135. />
  136. </SwitchWrapper>
  137. )}
  138. </ButtonBar>
  139. </Fragment>
  140. );
  141. }
  142. interface QueryProps {
  143. canBeHidden: boolean;
  144. index: number;
  145. isSelected: boolean;
  146. onChange: (index: number, data: Partial<MetricsWidget>) => void;
  147. onToggleVisibility: (index: number) => void;
  148. projects: number[];
  149. showQuerySymbols: boolean;
  150. widget: MetricsQueryWidget;
  151. }
  152. function Query({
  153. widget,
  154. projects,
  155. onChange,
  156. onToggleVisibility,
  157. index,
  158. isSelected,
  159. showQuerySymbols,
  160. canBeHidden,
  161. }: QueryProps) {
  162. const metricsQuery = useMemo(
  163. () => ({
  164. mri: widget.mri,
  165. aggregation: widget.aggregation,
  166. condition: widget.condition,
  167. groupBy: widget.groupBy,
  168. query: widget.query,
  169. }),
  170. [widget.mri, widget.aggregation, widget.condition, widget.groupBy, widget.query]
  171. );
  172. const handleToggle = useCallback(() => {
  173. onToggleVisibility(index);
  174. }, [index, onToggleVisibility]);
  175. const handleChange = useCallback(
  176. (data: Partial<MetricsQuery>) => {
  177. onChange(index, data);
  178. },
  179. [index, onChange]
  180. );
  181. const isToggleDisabled = !canBeHidden && !widget.isHidden;
  182. return (
  183. <QueryWrapper hasSymbol={showQuerySymbols}>
  184. {showQuerySymbols && (
  185. <QueryToggle
  186. isHidden={widget.isHidden}
  187. disabled={isToggleDisabled}
  188. isSelected={isSelected}
  189. queryId={widget.id}
  190. onChange={handleToggle}
  191. type={MetricExpressionType.QUERY}
  192. />
  193. )}
  194. <QueryBuilder
  195. index={index}
  196. onChange={handleChange}
  197. metricsQuery={metricsQuery}
  198. projects={projects}
  199. />
  200. <MetricQueryContextMenu
  201. displayType={widget.displayType}
  202. widgetIndex={index}
  203. metricsQuery={{
  204. mri: widget.mri,
  205. query: widget.query,
  206. aggregation: widget.aggregation,
  207. condition: widget.condition,
  208. groupBy: widget.groupBy,
  209. }}
  210. />
  211. </QueryWrapper>
  212. );
  213. }
  214. interface FormulaProps {
  215. availableVariables: Set<string>;
  216. canBeHidden: boolean;
  217. formulaDependencies: ReturnType<typeof useFormulaDependencies>;
  218. index: number;
  219. isSelected: boolean;
  220. onChange: (index: number, data: Partial<MetricsWidget>) => void;
  221. onToggleVisibility: (index: number) => void;
  222. showQuerySymbols: boolean;
  223. widget: MetricsEquationWidget;
  224. }
  225. function Formula({
  226. availableVariables,
  227. index,
  228. widget,
  229. onChange,
  230. onToggleVisibility,
  231. canBeHidden,
  232. isSelected,
  233. showQuerySymbols,
  234. formulaDependencies,
  235. }: FormulaProps) {
  236. const handleToggle = useCallback(() => {
  237. onToggleVisibility(index);
  238. }, [index, onToggleVisibility]);
  239. const handleChange = useCallback(
  240. (data: Partial<MetricsEquationWidget>) => {
  241. onChange(index, data);
  242. },
  243. [index, onChange]
  244. );
  245. const isToggleDisabled = !canBeHidden && !widget.isHidden;
  246. return (
  247. <QueryWrapper hasSymbol={showQuerySymbols}>
  248. {showQuerySymbols && (
  249. <QueryToggle
  250. isHidden={widget.isHidden}
  251. disabled={isToggleDisabled}
  252. isSelected={isSelected}
  253. queryId={widget.id}
  254. onChange={handleToggle}
  255. type={MetricExpressionType.EQUATION}
  256. />
  257. )}
  258. <EquationInput
  259. availableVariables={availableVariables}
  260. value={widget.formula}
  261. onChange={formula => handleChange({formula})}
  262. />
  263. <MetricFormulaContextMenu
  264. widgetIndex={index}
  265. formulaWidget={widget}
  266. formulaDependencies={formulaDependencies}
  267. />
  268. </QueryWrapper>
  269. );
  270. }
  271. interface QueryToggleProps {
  272. disabled: boolean;
  273. isHidden: boolean;
  274. isSelected: boolean;
  275. onChange: (isHidden: boolean) => void;
  276. queryId: number;
  277. type: MetricExpressionType;
  278. }
  279. function QueryToggle({isHidden, queryId, disabled, onChange, type}: QueryToggleProps) {
  280. const tooltipTitle =
  281. type === MetricExpressionType.QUERY
  282. ? isHidden
  283. ? t('Show metric')
  284. : t('Hide metric')
  285. : isHidden
  286. ? t('Show equation')
  287. : t('Hide equation');
  288. return (
  289. <Tooltip
  290. title={!disabled ? tooltipTitle : t('At least one query must be visible')}
  291. delay={500}
  292. >
  293. {type === MetricExpressionType.QUERY ? (
  294. <StyledQuerySymbol
  295. isHidden={isHidden}
  296. queryId={queryId}
  297. isClickable={!disabled}
  298. aria-disabled={disabled}
  299. onClick={disabled ? undefined : () => onChange(!isHidden)}
  300. role="button"
  301. aria-label={tooltipTitle}
  302. />
  303. ) : (
  304. <StyledEquationSymbol
  305. isHidden={isHidden}
  306. equationId={queryId}
  307. isClickable={!disabled}
  308. aria-disabled={disabled}
  309. onClick={disabled ? undefined : () => onChange(!isHidden)}
  310. role="button"
  311. aria-label={tooltipTitle}
  312. />
  313. )}
  314. </Tooltip>
  315. );
  316. }
  317. const QueryWrapper = styled('div')<{hasSymbol: boolean}>`
  318. display: grid;
  319. gap: ${space(1)};
  320. padding-bottom: ${space(1)};
  321. grid-template-columns: 1fr max-content;
  322. ${p => p.hasSymbol && `grid-template-columns: min-content 1fr max-content;`}
  323. `;
  324. const StyledQuerySymbol = styled(QuerySymbol)<{isClickable: boolean}>`
  325. cursor: not-allowed;
  326. ${p => p.isClickable && `cursor: pointer;`}
  327. `;
  328. const StyledEquationSymbol = styled(EquationSymbol)<{isClickable: boolean}>`
  329. cursor: not-allowed;
  330. ${p => p.isClickable && `cursor: pointer;`}
  331. `;
  332. const Wrapper = styled('div')<{showQuerySymbols: boolean}>``;
  333. const Row = styled('div')`
  334. display: contents;
  335. `;
  336. const ButtonBar = styled('div')<{addQuerySymbolSpacing: boolean}>`
  337. align-items: center;
  338. display: flex;
  339. padding-bottom: ${space(2)};
  340. gap: ${space(2)};
  341. ${p =>
  342. p.addQuerySymbolSpacing &&
  343. `
  344. padding-left: ${space(1)};
  345. margin-left: 38px;
  346. `}
  347. `;
  348. const SwitchWrapper = styled('label')`
  349. display: flex;
  350. margin: 0;
  351. align-items: center;
  352. gap: ${space(1)};
  353. `;