chart.tsx 17 KB

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