chart.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. import {Component} from 'react';
  2. import {InjectedRouter} from 'react-router';
  3. import {Theme, withTheme} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import {DataZoomComponentOption, LegendComponentOption} from 'echarts';
  6. import {Location} from 'history';
  7. import isEqual from 'lodash/isEqual';
  8. import omit from 'lodash/omit';
  9. import {AreaChart} from 'sentry/components/charts/areaChart';
  10. import {BarChart} from 'sentry/components/charts/barChart';
  11. import ChartZoom from 'sentry/components/charts/chartZoom';
  12. import ErrorPanel from 'sentry/components/charts/errorPanel';
  13. import {LineChart} from 'sentry/components/charts/lineChart';
  14. import SimpleTableChart from 'sentry/components/charts/simpleTableChart';
  15. import TransitionChart from 'sentry/components/charts/transitionChart';
  16. import TransparentLoadingMask from 'sentry/components/charts/transparentLoadingMask';
  17. import {getSeriesSelection} from 'sentry/components/charts/utils';
  18. import LoadingIndicator from 'sentry/components/loadingIndicator';
  19. import Placeholder, {PlaceholderProps} from 'sentry/components/placeholder';
  20. import {Tooltip} from 'sentry/components/tooltip';
  21. import {IconWarning} from 'sentry/icons';
  22. import {space} from 'sentry/styles/space';
  23. import {Organization, PageFilters} from 'sentry/types';
  24. import {EChartDataZoomHandler, EChartEventHandler} from 'sentry/types/echarts';
  25. import {
  26. axisLabelFormatter,
  27. axisLabelFormatterUsingAggregateOutputType,
  28. getDurationUnit,
  29. tooltipFormatter,
  30. } from 'sentry/utils/discover/charts';
  31. import {getFieldFormatter} from 'sentry/utils/discover/fieldRenderers';
  32. import {
  33. aggregateOutputType,
  34. AggregationOutputType,
  35. getAggregateArg,
  36. getEquation,
  37. getMeasurementSlug,
  38. isEquation,
  39. maybeEquationAlias,
  40. stripDerivedMetricsPrefix,
  41. stripEquationPrefix,
  42. } from 'sentry/utils/discover/fields';
  43. import getDynamicText from 'sentry/utils/getDynamicText';
  44. import {
  45. formatMetricAxisValue,
  46. renderMetricField,
  47. } from 'sentry/views/dashboards/datasetConfig/metrics';
  48. import {eventViewFromWidget} from 'sentry/views/dashboards/utils';
  49. import {getDatasetConfig} from '../datasetConfig/base';
  50. import {DisplayType, Widget, WidgetType} from '../types';
  51. import {GenericWidgetQueriesChildrenProps} from './genericWidgetQueries';
  52. const OTHER = 'Other';
  53. export const SLIDER_HEIGHT = 60;
  54. export type AugmentedEChartDataZoomHandler = (
  55. params: Parameters<EChartDataZoomHandler>[0] & {
  56. seriesEnd: string | number;
  57. seriesStart: string | number;
  58. },
  59. instance: Parameters<EChartDataZoomHandler>[1]
  60. ) => void;
  61. type TableResultProps = Pick<
  62. GenericWidgetQueriesChildrenProps,
  63. 'errorMessage' | 'loading' | 'tableResults'
  64. >;
  65. type WidgetCardChartProps = Pick<
  66. GenericWidgetQueriesChildrenProps,
  67. 'timeseriesResults' | 'tableResults' | 'errorMessage' | 'loading'
  68. > & {
  69. location: Location;
  70. organization: Organization;
  71. router: InjectedRouter;
  72. selection: PageFilters;
  73. theme: Theme;
  74. widget: Widget;
  75. chartZoomOptions?: DataZoomComponentOption;
  76. expandNumbers?: boolean;
  77. isMobile?: boolean;
  78. legendOptions?: LegendComponentOption;
  79. noPadding?: boolean;
  80. onLegendSelectChanged?: EChartEventHandler<{
  81. name: string;
  82. selected: Record<string, boolean>;
  83. type: 'legendselectchanged';
  84. }>;
  85. onZoom?: AugmentedEChartDataZoomHandler;
  86. showSlider?: boolean;
  87. timeseriesResultsTypes?: Record<string, AggregationOutputType>;
  88. windowWidth?: number;
  89. };
  90. type State = {
  91. // For tracking height of the container wrapping BigNumber widgets
  92. // so we can dynamically scale font-size
  93. containerHeight: number;
  94. };
  95. class WidgetCardChart extends Component<WidgetCardChartProps, State> {
  96. state = {containerHeight: 0};
  97. shouldComponentUpdate(nextProps: WidgetCardChartProps, nextState: State): boolean {
  98. if (
  99. this.props.widget.displayType === DisplayType.BIG_NUMBER &&
  100. nextProps.widget.displayType === DisplayType.BIG_NUMBER &&
  101. (this.props.windowWidth !== nextProps.windowWidth ||
  102. !isEqual(this.props.widget?.layout, nextProps.widget?.layout))
  103. ) {
  104. return true;
  105. }
  106. // Widget title changes should not update the WidgetCardChart component tree
  107. const currentProps = {
  108. ...omit(this.props, ['windowWidth']),
  109. widget: {
  110. ...this.props.widget,
  111. title: '',
  112. },
  113. };
  114. nextProps = {
  115. ...omit(nextProps, ['windowWidth']),
  116. widget: {
  117. ...nextProps.widget,
  118. title: '',
  119. },
  120. };
  121. return !isEqual(currentProps, nextProps) || !isEqual(this.state, nextState);
  122. }
  123. tableResultComponent({
  124. loading,
  125. errorMessage,
  126. tableResults,
  127. }: TableResultProps): React.ReactNode {
  128. const {location, widget, organization, selection} = this.props;
  129. if (errorMessage) {
  130. return (
  131. <StyledErrorPanel>
  132. <IconWarning color="gray500" size="lg" />
  133. </StyledErrorPanel>
  134. );
  135. }
  136. if (typeof tableResults === 'undefined') {
  137. // Align height to other charts.
  138. return <LoadingPlaceholder />;
  139. }
  140. const datasetConfig = getDatasetConfig(widget.widgetType);
  141. return tableResults.map((result, i) => {
  142. const fields = widget.queries[i]?.fields?.map(stripDerivedMetricsPrefix) ?? [];
  143. const fieldAliases = widget.queries[i]?.fieldAliases ?? [];
  144. const eventView = eventViewFromWidget(widget.title, widget.queries[0], selection);
  145. return (
  146. <StyledSimpleTableChart
  147. key={`table:${result.title}`}
  148. eventView={eventView}
  149. fieldAliases={fieldAliases}
  150. location={location}
  151. fields={fields}
  152. title={tableResults.length > 1 ? result.title : ''}
  153. loading={loading}
  154. loader={<LoadingPlaceholder />}
  155. metadata={result.meta}
  156. data={result.data}
  157. organization={organization}
  158. stickyHeaders
  159. fieldHeaderMap={datasetConfig.getFieldHeaderMap?.(widget.queries[i])}
  160. getCustomFieldRenderer={datasetConfig.getCustomFieldRenderer}
  161. />
  162. );
  163. });
  164. }
  165. bigNumberComponent({
  166. loading,
  167. errorMessage,
  168. tableResults,
  169. }: TableResultProps): React.ReactNode {
  170. if (errorMessage) {
  171. return (
  172. <StyledErrorPanel>
  173. <IconWarning color="gray500" size="lg" />
  174. </StyledErrorPanel>
  175. );
  176. }
  177. if (typeof tableResults === 'undefined' || loading) {
  178. return <BigNumber>{'\u2014'}</BigNumber>;
  179. }
  180. const {containerHeight} = this.state;
  181. const {location, organization, widget, isMobile, expandNumbers} = this.props;
  182. return tableResults.map(result => {
  183. const tableMeta = {...result.meta};
  184. const fields = Object.keys(tableMeta);
  185. const field = fields[0];
  186. // Change tableMeta for the field from integer to string since we will be rendering with toLocaleString
  187. const shouldExpandInteger = !!expandNumbers && tableMeta[field] === 'integer';
  188. if (shouldExpandInteger) {
  189. tableMeta[field] = 'string';
  190. }
  191. if (!field || !result.data?.length) {
  192. return <BigNumber key={`big_number:${result.title}`}>{'\u2014'}</BigNumber>;
  193. }
  194. const dataRow = result.data[0];
  195. const fieldRenderer = getFieldFormatter(field, tableMeta, false);
  196. const unit = tableMeta.units?.[field];
  197. const rendered =
  198. widget.widgetType === WidgetType.METRICS
  199. ? renderMetricField(field, dataRow[field])
  200. : fieldRenderer(
  201. shouldExpandInteger ? {[field]: dataRow[field].toLocaleString()} : dataRow,
  202. {location, organization, unit}
  203. );
  204. const isModalWidget = !(widget.id || widget.tempId);
  205. if (isModalWidget || isMobile) {
  206. return <BigNumber key={`big_number:${result.title}`}>{rendered}</BigNumber>;
  207. }
  208. // The font size is the container height, minus the top and bottom padding
  209. const fontSize = !expandNumbers
  210. ? containerHeight - parseInt(space(1), 10) - parseInt(space(3), 10)
  211. : `max(min(8vw, 90px), ${space(4)})`;
  212. return (
  213. <BigNumber
  214. key={`big_number:${result.title}`}
  215. style={{
  216. fontSize,
  217. ...(expandNumbers ? {padding: `${space(1)} ${space(3)} 0 ${space(3)}`} : {}),
  218. }}
  219. >
  220. <Tooltip title={rendered} showOnlyOnOverflow>
  221. {rendered}
  222. </Tooltip>
  223. </BigNumber>
  224. );
  225. });
  226. }
  227. chartComponent(chartProps): React.ReactNode {
  228. const {widget} = this.props;
  229. const stacked = widget.queries[0]?.columns.length > 0;
  230. switch (widget.displayType) {
  231. case 'bar':
  232. return <BarChart {...chartProps} stacked={stacked} />;
  233. case 'area':
  234. case 'top_n':
  235. return <AreaChart stacked {...chartProps} />;
  236. case 'line':
  237. default:
  238. return <LineChart {...chartProps} />;
  239. }
  240. }
  241. render() {
  242. const {
  243. theme,
  244. tableResults,
  245. timeseriesResults,
  246. errorMessage,
  247. loading,
  248. widget,
  249. onZoom,
  250. legendOptions,
  251. expandNumbers,
  252. showSlider,
  253. noPadding,
  254. chartZoomOptions,
  255. timeseriesResultsTypes,
  256. } = this.props;
  257. if (widget.displayType === 'table') {
  258. return getDynamicText({
  259. value: (
  260. <TransitionChart loading={loading} reloading={loading}>
  261. <LoadingScreen loading={loading} />
  262. {this.tableResultComponent({tableResults, loading, errorMessage})}
  263. </TransitionChart>
  264. ),
  265. fixed: <Placeholder height="200px" testId="skeleton-ui" />,
  266. });
  267. }
  268. if (widget.displayType === 'big_number') {
  269. return (
  270. <TransitionChart loading={loading} reloading={loading}>
  271. <LoadingScreen loading={loading} />
  272. <BigNumberResizeWrapper
  273. ref={el => {
  274. if (el !== null && !expandNumbers) {
  275. const {height} = el.getBoundingClientRect();
  276. if (height !== this.state.containerHeight) {
  277. this.setState({containerHeight: height});
  278. }
  279. }
  280. }}
  281. >
  282. {this.bigNumberComponent({tableResults, loading, errorMessage})}
  283. </BigNumberResizeWrapper>
  284. </TransitionChart>
  285. );
  286. }
  287. if (errorMessage) {
  288. return (
  289. <StyledErrorPanel>
  290. <IconWarning color="gray500" size="lg" />
  291. </StyledErrorPanel>
  292. );
  293. }
  294. const {location, router, selection, onLegendSelectChanged} = this.props;
  295. const {start, end, period, utc} = selection.datetime;
  296. // Only allow height resizing for widgets that are on a dashboard
  297. const autoHeightResize = Boolean(widget.id || widget.tempId);
  298. const legend = {
  299. left: 0,
  300. top: 0,
  301. selected: getSeriesSelection(location),
  302. formatter: (seriesName: string) => {
  303. const arg = getAggregateArg(seriesName);
  304. if (arg !== null) {
  305. const slug = getMeasurementSlug(arg);
  306. if (slug !== null) {
  307. seriesName = slug.toUpperCase();
  308. }
  309. }
  310. if (maybeEquationAlias(seriesName)) {
  311. seriesName = stripEquationPrefix(seriesName);
  312. }
  313. return seriesName;
  314. },
  315. ...legendOptions,
  316. };
  317. const axisField = widget.queries[0]?.aggregates?.[0] ?? 'count()';
  318. const axisLabel = isEquation(axisField) ? getEquation(axisField) : axisField;
  319. // Check to see if all series output types are the same. If not, then default to number.
  320. const outputType =
  321. timeseriesResultsTypes && new Set(Object.values(timeseriesResultsTypes)).size === 1
  322. ? timeseriesResultsTypes[axisLabel]
  323. : 'number';
  324. const isDurationChart = outputType === 'duration';
  325. const durationUnit = isDurationChart
  326. ? timeseriesResults && getDurationUnit(timeseriesResults, legendOptions)
  327. : undefined;
  328. const chartOptions = {
  329. autoHeightResize,
  330. grid: {
  331. left: 0,
  332. right: 4,
  333. top: '40px',
  334. bottom: showSlider ? SLIDER_HEIGHT : 0,
  335. },
  336. seriesOptions: {
  337. showSymbol: false,
  338. },
  339. tooltip: {
  340. trigger: 'axis',
  341. valueFormatter: (value: number, seriesName: string) => {
  342. if (widget.widgetType === WidgetType.METRICS) {
  343. return formatMetricAxisValue(axisField, value);
  344. }
  345. const aggregateName = seriesName?.split(':').pop()?.trim();
  346. if (aggregateName) {
  347. return timeseriesResultsTypes
  348. ? tooltipFormatter(value, timeseriesResultsTypes[aggregateName])
  349. : tooltipFormatter(value, aggregateOutputType(aggregateName));
  350. }
  351. return tooltipFormatter(value, 'number');
  352. },
  353. },
  354. yAxis: {
  355. axisLabel: {
  356. color: theme.chartLabel,
  357. formatter: (value: number) => {
  358. if (widget.widgetType === WidgetType.METRICS) {
  359. return formatMetricAxisValue(axisField, value);
  360. }
  361. if (timeseriesResultsTypes) {
  362. return axisLabelFormatterUsingAggregateOutputType(
  363. value,
  364. outputType,
  365. undefined,
  366. durationUnit
  367. );
  368. }
  369. return axisLabelFormatter(value, aggregateOutputType(axisLabel));
  370. },
  371. },
  372. minInterval: durationUnit ?? 0,
  373. },
  374. };
  375. return (
  376. <ChartZoom
  377. router={router}
  378. period={period}
  379. start={start}
  380. end={end}
  381. utc={utc}
  382. showSlider={showSlider}
  383. chartZoomOptions={chartZoomOptions}
  384. >
  385. {zoomRenderProps => {
  386. if (errorMessage) {
  387. return (
  388. <StyledErrorPanel>
  389. <IconWarning color="gray500" size="lg" />
  390. </StyledErrorPanel>
  391. );
  392. }
  393. const otherRegex = new RegExp(`(?:.* : ${OTHER}$)|^${OTHER}$`);
  394. const shouldColorOther = timeseriesResults?.some(
  395. ({seriesName}) => seriesName && seriesName.match(otherRegex)
  396. );
  397. const colors = timeseriesResults
  398. ? theme.charts.getColorPalette(
  399. timeseriesResults.length - (shouldColorOther ? 3 : 2)
  400. )
  401. : [];
  402. // TODO(wmak): Need to change this when updating dashboards to support variable topEvents
  403. if (shouldColorOther) {
  404. colors[colors.length] = theme.chartOther;
  405. }
  406. // Create a list of series based on the order of the fields,
  407. const series = timeseriesResults
  408. ? timeseriesResults.map((values, i: number) => {
  409. let seriesName = '';
  410. if (values.seriesName !== undefined) {
  411. seriesName = isEquation(values.seriesName)
  412. ? getEquation(values.seriesName)
  413. : values.seriesName;
  414. }
  415. return {
  416. ...values,
  417. seriesName,
  418. color: colors[i],
  419. };
  420. })
  421. : [];
  422. const seriesStart = series[0]?.data[0]?.name;
  423. const seriesEnd = series[0]?.data[series[0].data.length - 1]?.name;
  424. return (
  425. <TransitionChart loading={loading} reloading={loading}>
  426. <LoadingScreen loading={loading} />
  427. <ChartWrapper autoHeightResize={autoHeightResize} noPadding={noPadding}>
  428. {getDynamicText({
  429. value: this.chartComponent({
  430. ...zoomRenderProps,
  431. ...chartOptions,
  432. // Override default datazoom behaviour for updating Global Selection Header
  433. ...(onZoom
  434. ? {
  435. onDataZoom: (evt, chartProps) =>
  436. // Need to pass seriesStart and seriesEnd to onZoom since slider zooms
  437. // callback with percentage instead of datetime values. Passing seriesStart
  438. // and seriesEnd allows calculating datetime values with percentage.
  439. onZoom({...evt, seriesStart, seriesEnd}, chartProps),
  440. }
  441. : {}),
  442. legend,
  443. series,
  444. onLegendSelectChanged,
  445. }),
  446. fixed: <Placeholder height="200px" testId="skeleton-ui" />,
  447. })}
  448. </ChartWrapper>
  449. </TransitionChart>
  450. );
  451. }}
  452. </ChartZoom>
  453. );
  454. }
  455. }
  456. export default withTheme(WidgetCardChart);
  457. const StyledTransparentLoadingMask = styled(props => (
  458. <TransparentLoadingMask {...props} maskBackgroundColor="transparent" />
  459. ))`
  460. display: flex;
  461. justify-content: center;
  462. align-items: center;
  463. `;
  464. function LoadingScreen({loading}: {loading: boolean}) {
  465. if (!loading) {
  466. return null;
  467. }
  468. return (
  469. <StyledTransparentLoadingMask visible={loading}>
  470. <LoadingIndicator mini />
  471. </StyledTransparentLoadingMask>
  472. );
  473. }
  474. const LoadingPlaceholder = styled(({className}: PlaceholderProps) => (
  475. <Placeholder height="200px" className={className} />
  476. ))`
  477. background-color: ${p => p.theme.surface300};
  478. `;
  479. const BigNumberResizeWrapper = styled('div')`
  480. height: 100%;
  481. width: 100%;
  482. overflow: hidden;
  483. `;
  484. const BigNumber = styled('div')`
  485. line-height: 1;
  486. display: inline-flex;
  487. flex: 1;
  488. width: 100%;
  489. min-height: 0;
  490. font-size: 32px;
  491. color: ${p => p.theme.headingColor};
  492. padding: ${space(1)} ${space(3)} ${space(3)} ${space(3)};
  493. * {
  494. text-align: left !important;
  495. }
  496. `;
  497. const ChartWrapper = styled('div')<{autoHeightResize: boolean; noPadding?: boolean}>`
  498. ${p => p.autoHeightResize && 'height: 100%;'}
  499. padding: ${p => (p.noPadding ? `0` : `0 ${space(3)} ${space(3)}`)};
  500. `;
  501. const StyledSimpleTableChart = styled(SimpleTableChart)`
  502. margin-top: ${space(1.5)};
  503. border-bottom-left-radius: ${p => p.theme.borderRadius};
  504. border-bottom-right-radius: ${p => p.theme.borderRadius};
  505. font-size: ${p => p.theme.fontSizeMedium};
  506. box-shadow: none;
  507. `;
  508. const StyledErrorPanel = styled(ErrorPanel)`
  509. padding: ${space(2)};
  510. `;