chart.tsx 18 KB

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