chart.tsx 18 KB

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