queries.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. op: widget.op,
  166. groupBy: widget.groupBy,
  167. query: widget.query,
  168. }),
  169. [widget.groupBy, widget.mri, widget.op, widget.query]
  170. );
  171. const handleToggle = useCallback(() => {
  172. onToggleVisibility(index);
  173. }, [index, onToggleVisibility]);
  174. const handleChange = useCallback(
  175. (data: Partial<MetricsQuery>) => {
  176. onChange(index, data);
  177. },
  178. [index, onChange]
  179. );
  180. const isToggleDisabled = !canBeHidden && !widget.isHidden;
  181. return (
  182. <QueryWrapper hasSymbol={showQuerySymbols}>
  183. {showQuerySymbols && (
  184. <QueryToggle
  185. isHidden={widget.isHidden}
  186. disabled={isToggleDisabled}
  187. isSelected={isSelected}
  188. queryId={widget.id}
  189. onChange={handleToggle}
  190. type={MetricExpressionType.QUERY}
  191. />
  192. )}
  193. <QueryBuilder
  194. index={index}
  195. onChange={handleChange}
  196. metricsQuery={metricsQuery}
  197. projects={projects}
  198. />
  199. <MetricQueryContextMenu
  200. displayType={widget.displayType}
  201. widgetIndex={index}
  202. metricsQuery={{
  203. mri: widget.mri,
  204. query: widget.query,
  205. op: widget.op,
  206. groupBy: widget.groupBy,
  207. }}
  208. />
  209. </QueryWrapper>
  210. );
  211. }
  212. interface FormulaProps {
  213. availableVariables: Set<string>;
  214. canBeHidden: boolean;
  215. formulaDependencies: ReturnType<typeof useFormulaDependencies>;
  216. index: number;
  217. isSelected: boolean;
  218. onChange: (index: number, data: Partial<MetricsWidget>) => void;
  219. onToggleVisibility: (index: number) => void;
  220. showQuerySymbols: boolean;
  221. widget: MetricsEquationWidget;
  222. }
  223. function Formula({
  224. availableVariables,
  225. index,
  226. widget,
  227. onChange,
  228. onToggleVisibility,
  229. canBeHidden,
  230. isSelected,
  231. showQuerySymbols,
  232. formulaDependencies,
  233. }: FormulaProps) {
  234. const handleToggle = useCallback(() => {
  235. onToggleVisibility(index);
  236. }, [index, onToggleVisibility]);
  237. const handleChange = useCallback(
  238. (data: Partial<MetricsEquationWidget>) => {
  239. onChange(index, data);
  240. },
  241. [index, onChange]
  242. );
  243. const isToggleDisabled = !canBeHidden && !widget.isHidden;
  244. return (
  245. <QueryWrapper hasSymbol={showQuerySymbols}>
  246. {showQuerySymbols && (
  247. <QueryToggle
  248. isHidden={widget.isHidden}
  249. disabled={isToggleDisabled}
  250. isSelected={isSelected}
  251. queryId={widget.id}
  252. onChange={handleToggle}
  253. type={MetricExpressionType.EQUATION}
  254. />
  255. )}
  256. <EquationInput
  257. availableVariables={availableVariables}
  258. value={widget.formula}
  259. onChange={formula => handleChange({formula})}
  260. />
  261. <MetricFormulaContextMenu
  262. widgetIndex={index}
  263. formulaWidget={widget}
  264. formulaDependencies={formulaDependencies}
  265. />
  266. </QueryWrapper>
  267. );
  268. }
  269. interface QueryToggleProps {
  270. disabled: boolean;
  271. isHidden: boolean;
  272. isSelected: boolean;
  273. onChange: (isHidden: boolean) => void;
  274. queryId: number;
  275. type: MetricExpressionType;
  276. }
  277. function QueryToggle({isHidden, queryId, disabled, onChange, type}: QueryToggleProps) {
  278. const tooltipTitle =
  279. type === MetricExpressionType.QUERY
  280. ? isHidden
  281. ? t('Show metric')
  282. : t('Hide metric')
  283. : isHidden
  284. ? t('Show equation')
  285. : t('Hide equation');
  286. return (
  287. <Tooltip
  288. title={!disabled ? tooltipTitle : t('At least one query must be visible')}
  289. delay={500}
  290. >
  291. {type === MetricExpressionType.QUERY ? (
  292. <StyledQuerySymbol
  293. isHidden={isHidden}
  294. queryId={queryId}
  295. isClickable={!disabled}
  296. aria-disabled={disabled}
  297. onClick={disabled ? undefined : () => onChange(!isHidden)}
  298. role="button"
  299. aria-label={tooltipTitle}
  300. />
  301. ) : (
  302. <StyledEquationSymbol
  303. isHidden={isHidden}
  304. equationId={queryId}
  305. isClickable={!disabled}
  306. aria-disabled={disabled}
  307. onClick={disabled ? undefined : () => onChange(!isHidden)}
  308. role="button"
  309. aria-label={tooltipTitle}
  310. />
  311. )}
  312. </Tooltip>
  313. );
  314. }
  315. const QueryWrapper = styled('div')<{hasSymbol: boolean}>`
  316. display: grid;
  317. gap: ${space(1)};
  318. padding-bottom: ${space(1)};
  319. grid-template-columns: 1fr max-content;
  320. ${p => p.hasSymbol && `grid-template-columns: min-content 1fr max-content;`}
  321. `;
  322. const StyledQuerySymbol = styled(QuerySymbol)<{isClickable: boolean}>`
  323. cursor: not-allowed;
  324. ${p => p.isClickable && `cursor: pointer;`}
  325. `;
  326. const StyledEquationSymbol = styled(EquationSymbol)<{isClickable: boolean}>`
  327. cursor: not-allowed;
  328. ${p => p.isClickable && `cursor: pointer;`}
  329. `;
  330. const Wrapper = styled('div')<{showQuerySymbols: boolean}>``;
  331. const Row = styled('div')`
  332. display: contents;
  333. `;
  334. const ButtonBar = styled('div')<{addQuerySymbolSpacing: boolean}>`
  335. align-items: center;
  336. display: flex;
  337. padding-bottom: ${space(2)};
  338. gap: ${space(2)};
  339. ${p =>
  340. p.addQuerySymbolSpacing &&
  341. `
  342. padding-left: ${space(1)};
  343. margin-left: 38px;
  344. `}
  345. `;
  346. const SwitchWrapper = styled('label')`
  347. display: flex;
  348. margin: 0;
  349. align-items: center;
  350. gap: ${space(1)};
  351. `;