chart.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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, processTableResults} from 'sentry/components/charts/utils';
  18. import {WorldMapChart} from 'sentry/components/charts/worldMapChart';
  19. import LoadingIndicator from 'sentry/components/loadingIndicator';
  20. import Placeholder, {PlaceholderProps} from 'sentry/components/placeholder';
  21. import {Tooltip} from 'sentry/components/tooltip';
  22. import {IconWarning} from 'sentry/icons';
  23. import {space} from 'sentry/styles/space';
  24. import {Organization, PageFilters} from 'sentry/types';
  25. import {EChartDataZoomHandler, EChartEventHandler} from 'sentry/types/echarts';
  26. import {
  27. axisLabelFormatter,
  28. axisLabelFormatterUsingAggregateOutputType,
  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(
  141. widget.title,
  142. widget.queries[0],
  143. selection,
  144. widget.displayType
  145. );
  146. return (
  147. <StyledSimpleTableChart
  148. key={`table:${result.title}`}
  149. eventView={eventView}
  150. fieldAliases={fieldAliases}
  151. location={location}
  152. fields={fields}
  153. title={tableResults.length > 1 ? result.title : ''}
  154. loading={loading}
  155. loader={<LoadingPlaceholder />}
  156. metadata={result.meta}
  157. data={result.data}
  158. organization={organization}
  159. stickyHeaders
  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 = fieldRenderer(
  198. shouldExpandInteger ? {[field]: dataRow[field].toLocaleString()} : dataRow,
  199. {location, organization, unit}
  200. );
  201. const isModalWidget = !(widget.id || widget.tempId);
  202. if (isModalWidget || isMobile) {
  203. return <BigNumber key={`big_number:${result.title}`}>{rendered}</BigNumber>;
  204. }
  205. // The font size is the container height, minus the top and bottom padding
  206. const fontSize = !expandNumbers
  207. ? containerHeight - parseInt(space(1), 10) - parseInt(space(3), 10)
  208. : `max(min(8vw, 90px), ${space(4)})`;
  209. return (
  210. <BigNumber
  211. key={`big_number:${result.title}`}
  212. style={{
  213. fontSize,
  214. ...(expandNumbers ? {padding: `${space(1)} ${space(3)} 0 ${space(3)}`} : {}),
  215. }}
  216. >
  217. <Tooltip title={rendered} showOnlyOnOverflow>
  218. {rendered}
  219. </Tooltip>
  220. </BigNumber>
  221. );
  222. });
  223. }
  224. chartComponent(chartProps): React.ReactNode {
  225. const {widget} = this.props;
  226. const stacked = widget.queries[0]?.columns.length > 0;
  227. switch (widget.displayType) {
  228. case 'bar':
  229. return <BarChart {...chartProps} stacked={stacked} />;
  230. case 'area':
  231. case 'top_n':
  232. return <AreaChart stacked {...chartProps} />;
  233. case 'world_map':
  234. return <WorldMapChart {...chartProps} />;
  235. case 'line':
  236. default:
  237. return <LineChart {...chartProps} />;
  238. }
  239. }
  240. render() {
  241. const {
  242. theme,
  243. tableResults,
  244. timeseriesResults,
  245. errorMessage,
  246. loading,
  247. widget,
  248. onZoom,
  249. legendOptions,
  250. expandNumbers,
  251. showSlider,
  252. noPadding,
  253. chartZoomOptions,
  254. timeseriesResultsTypes,
  255. } = this.props;
  256. if (widget.displayType === 'table') {
  257. return getDynamicText({
  258. value: (
  259. <TransitionChart loading={loading} reloading={loading}>
  260. <LoadingScreen loading={loading} />
  261. {this.tableResultComponent({tableResults, loading, errorMessage})}
  262. </TransitionChart>
  263. ),
  264. fixed: <Placeholder height="200px" testId="skeleton-ui" />,
  265. });
  266. }
  267. if (widget.displayType === 'big_number') {
  268. return (
  269. <TransitionChart loading={loading} reloading={loading}>
  270. <LoadingScreen loading={loading} />
  271. <BigNumberResizeWrapper
  272. ref={el => {
  273. if (el !== null && !expandNumbers) {
  274. const {height} = el.getBoundingClientRect();
  275. if (height !== this.state.containerHeight) {
  276. this.setState({containerHeight: height});
  277. }
  278. }
  279. }}
  280. >
  281. {this.bigNumberComponent({tableResults, loading, errorMessage})}
  282. </BigNumberResizeWrapper>
  283. </TransitionChart>
  284. );
  285. }
  286. if (errorMessage) {
  287. return (
  288. <StyledErrorPanel>
  289. <IconWarning color="gray500" size="lg" />
  290. </StyledErrorPanel>
  291. );
  292. }
  293. const {location, router, selection, onLegendSelectChanged} = this.props;
  294. const {start, end, period, utc} = selection.datetime;
  295. // Only allow height resizing for widgets that are on a dashboard
  296. const autoHeightResize = Boolean(widget.id || widget.tempId);
  297. if (widget.displayType === 'world_map') {
  298. const {data, title} = processTableResults(tableResults);
  299. const series = [
  300. {
  301. seriesName: title,
  302. data,
  303. },
  304. ];
  305. return (
  306. <TransitionChart loading={loading} reloading={loading}>
  307. <LoadingScreen loading={loading} />
  308. <ChartWrapper autoHeightResize={autoHeightResize}>
  309. {getDynamicText({
  310. value: this.chartComponent({
  311. series,
  312. autoHeightResize,
  313. }),
  314. fixed: <Placeholder height="200px" testId="skeleton-ui" />,
  315. })}
  316. </ChartWrapper>
  317. </TransitionChart>
  318. );
  319. }
  320. const legend = {
  321. left: 0,
  322. top: 0,
  323. selected: getSeriesSelection(location),
  324. formatter: (seriesName: string) => {
  325. const arg = getAggregateArg(seriesName);
  326. if (arg !== null) {
  327. const slug = getMeasurementSlug(arg);
  328. if (slug !== null) {
  329. seriesName = slug.toUpperCase();
  330. }
  331. }
  332. if (maybeEquationAlias(seriesName)) {
  333. seriesName = stripEquationPrefix(seriesName);
  334. }
  335. return seriesName;
  336. },
  337. ...legendOptions,
  338. };
  339. const axisField = widget.queries[0]?.aggregates?.[0] ?? 'count()';
  340. const axisLabel = isEquation(axisField) ? getEquation(axisField) : axisField;
  341. const chartOptions = {
  342. autoHeightResize,
  343. grid: {
  344. left: 0,
  345. right: 4,
  346. top: '40px',
  347. bottom: showSlider ? SLIDER_HEIGHT : 0,
  348. },
  349. seriesOptions: {
  350. showSymbol: false,
  351. },
  352. tooltip: {
  353. trigger: 'axis',
  354. valueFormatter: (value: number, seriesName: string) => {
  355. const aggregateName = seriesName?.split(':').pop()?.trim();
  356. if (aggregateName) {
  357. return timeseriesResultsTypes
  358. ? tooltipFormatter(value, timeseriesResultsTypes[aggregateName])
  359. : tooltipFormatter(value, aggregateOutputType(aggregateName));
  360. }
  361. return tooltipFormatter(value, 'number');
  362. },
  363. },
  364. yAxis: {
  365. axisLabel: {
  366. color: theme.chartLabel,
  367. formatter: (value: number) => {
  368. if (timeseriesResultsTypes) {
  369. // Check to see if all series output types are the same. If not, then default to number.
  370. const outputType =
  371. new Set(Object.values(timeseriesResultsTypes)).size === 1
  372. ? timeseriesResultsTypes[axisLabel]
  373. : 'number';
  374. return axisLabelFormatterUsingAggregateOutputType(value, outputType);
  375. }
  376. return axisLabelFormatter(value, aggregateOutputType(axisLabel));
  377. },
  378. },
  379. },
  380. };
  381. return (
  382. <ChartZoom
  383. router={router}
  384. period={period}
  385. start={start}
  386. end={end}
  387. utc={utc}
  388. showSlider={showSlider}
  389. chartZoomOptions={chartZoomOptions}
  390. >
  391. {zoomRenderProps => {
  392. if (errorMessage) {
  393. return (
  394. <StyledErrorPanel>
  395. <IconWarning color="gray500" size="lg" />
  396. </StyledErrorPanel>
  397. );
  398. }
  399. const otherRegex = new RegExp(`(?:.* : ${OTHER}$)|^${OTHER}$`);
  400. const shouldColorOther = timeseriesResults?.some(
  401. ({seriesName}) => seriesName && seriesName.match(otherRegex)
  402. );
  403. const colors = timeseriesResults
  404. ? theme.charts.getColorPalette(
  405. timeseriesResults.length - (shouldColorOther ? 3 : 2)
  406. )
  407. : [];
  408. // TODO(wmak): Need to change this when updating dashboards to support variable topEvents
  409. if (shouldColorOther) {
  410. colors[colors.length] = theme.chartOther;
  411. }
  412. // Create a list of series based on the order of the fields,
  413. const series = timeseriesResults
  414. ? timeseriesResults.map((values, i: number) => {
  415. let seriesName = '';
  416. if (values.seriesName !== undefined) {
  417. seriesName = isEquation(values.seriesName)
  418. ? getEquation(values.seriesName)
  419. : values.seriesName;
  420. }
  421. return {
  422. ...values,
  423. seriesName,
  424. color: colors[i],
  425. };
  426. })
  427. : [];
  428. const seriesStart = series[0]?.data[0]?.name;
  429. const seriesEnd = series[0]?.data[series[0].data.length - 1]?.name;
  430. return (
  431. <TransitionChart loading={loading} reloading={loading}>
  432. <LoadingScreen loading={loading} />
  433. <ChartWrapper autoHeightResize={autoHeightResize} noPadding={noPadding}>
  434. {getDynamicText({
  435. value: this.chartComponent({
  436. ...zoomRenderProps,
  437. ...chartOptions,
  438. // Override default datazoom behaviour for updating Global Selection Header
  439. ...(onZoom
  440. ? {
  441. onDataZoom: (evt, chartProps) =>
  442. // Need to pass seriesStart and seriesEnd to onZoom since slider zooms
  443. // callback with percentage instead of datetime values. Passing seriesStart
  444. // and seriesEnd allows calculating datetime values with percentage.
  445. onZoom({...evt, seriesStart, seriesEnd}, chartProps),
  446. }
  447. : {}),
  448. legend,
  449. series,
  450. onLegendSelectChanged,
  451. }),
  452. fixed: <Placeholder height="200px" testId="skeleton-ui" />,
  453. })}
  454. </ChartWrapper>
  455. </TransitionChart>
  456. );
  457. }}
  458. </ChartZoom>
  459. );
  460. }
  461. }
  462. export default withTheme(WidgetCardChart);
  463. const StyledTransparentLoadingMask = styled(props => (
  464. <TransparentLoadingMask {...props} maskBackgroundColor="transparent" />
  465. ))`
  466. display: flex;
  467. justify-content: center;
  468. align-items: center;
  469. `;
  470. const LoadingScreen = ({loading}: {loading: boolean}) => {
  471. if (!loading) {
  472. return null;
  473. }
  474. return (
  475. <StyledTransparentLoadingMask visible={loading}>
  476. <LoadingIndicator mini />
  477. </StyledTransparentLoadingMask>
  478. );
  479. };
  480. const LoadingPlaceholder = styled(({className}: PlaceholderProps) => (
  481. <Placeholder height="200px" className={className} />
  482. ))`
  483. background-color: ${p => p.theme.surface300};
  484. `;
  485. const BigNumberResizeWrapper = styled('div')`
  486. height: 100%;
  487. width: 100%;
  488. overflow: hidden;
  489. `;
  490. const BigNumber = styled('div')`
  491. line-height: 1;
  492. display: inline-flex;
  493. flex: 1;
  494. width: 100%;
  495. min-height: 0;
  496. font-size: 32px;
  497. color: ${p => p.theme.headingColor};
  498. padding: ${space(1)} ${space(3)} ${space(3)} ${space(3)};
  499. * {
  500. text-align: left !important;
  501. }
  502. `;
  503. const ChartWrapper = styled('div')<{autoHeightResize: boolean; noPadding?: boolean}>`
  504. ${p => p.autoHeightResize && 'height: 100%;'}
  505. padding: ${p => (p.noPadding ? `0` : `0 ${space(3)} ${space(3)}`)};
  506. `;
  507. const StyledSimpleTableChart = styled(SimpleTableChart)`
  508. margin-top: ${space(1.5)};
  509. border-bottom-left-radius: ${p => p.theme.borderRadius};
  510. border-bottom-right-radius: ${p => p.theme.borderRadius};
  511. font-size: ${p => p.theme.fontSizeMedium};
  512. box-shadow: none;
  513. `;
  514. const StyledErrorPanel = styled(ErrorPanel)`
  515. padding: ${space(2)};
  516. `;