chart.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. getDurationUnit,
  30. tooltipFormatter,
  31. } from 'sentry/utils/discover/charts';
  32. import {getFieldFormatter} from 'sentry/utils/discover/fieldRenderers';
  33. import {
  34. aggregateOutputType,
  35. AggregationOutputType,
  36. getAggregateArg,
  37. getEquation,
  38. getMeasurementSlug,
  39. isEquation,
  40. maybeEquationAlias,
  41. stripDerivedMetricsPrefix,
  42. stripEquationPrefix,
  43. } from 'sentry/utils/discover/fields';
  44. import getDynamicText from 'sentry/utils/getDynamicText';
  45. import {eventViewFromWidget} from 'sentry/views/dashboards/utils';
  46. import {getDatasetConfig} from '../datasetConfig/base';
  47. import {DisplayType, Widget} 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. return tableResults.map(result => {
  184. const tableMeta = {...result.meta};
  185. const fields = Object.keys(tableMeta);
  186. const field = fields[0];
  187. // Change tableMeta for the field from integer to string since we will be rendering with toLocaleString
  188. const shouldExpandInteger = !!expandNumbers && tableMeta[field] === 'integer';
  189. if (shouldExpandInteger) {
  190. tableMeta[field] = 'string';
  191. }
  192. if (!field || !result.data?.length) {
  193. return <BigNumber key={`big_number:${result.title}`}>{'\u2014'}</BigNumber>;
  194. }
  195. const dataRow = result.data[0];
  196. const fieldRenderer = getFieldFormatter(field, tableMeta, false);
  197. const unit = tableMeta.units?.[field];
  198. const rendered = fieldRenderer(
  199. shouldExpandInteger ? {[field]: dataRow[field].toLocaleString()} : dataRow,
  200. {location, organization, unit}
  201. );
  202. const isModalWidget = !(widget.id || widget.tempId);
  203. if (isModalWidget || isMobile) {
  204. return <BigNumber key={`big_number:${result.title}`}>{rendered}</BigNumber>;
  205. }
  206. // The font size is the container height, minus the top and bottom padding
  207. const fontSize = !expandNumbers
  208. ? containerHeight - parseInt(space(1), 10) - parseInt(space(3), 10)
  209. : `max(min(8vw, 90px), ${space(4)})`;
  210. return (
  211. <BigNumber
  212. key={`big_number:${result.title}`}
  213. style={{
  214. fontSize,
  215. ...(expandNumbers ? {padding: `${space(1)} ${space(3)} 0 ${space(3)}`} : {}),
  216. }}
  217. >
  218. <Tooltip title={rendered} showOnlyOnOverflow>
  219. {rendered}
  220. </Tooltip>
  221. </BigNumber>
  222. );
  223. });
  224. }
  225. chartComponent(chartProps): React.ReactNode {
  226. const {widget} = this.props;
  227. const stacked = widget.queries[0]?.columns.length > 0;
  228. switch (widget.displayType) {
  229. case 'bar':
  230. return <BarChart {...chartProps} stacked={stacked} />;
  231. case 'area':
  232. case 'top_n':
  233. return <AreaChart stacked {...chartProps} />;
  234. case 'world_map':
  235. return <WorldMapChart {...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. if (widget.displayType === 'world_map') {
  299. const {data, title} = processTableResults(tableResults);
  300. const series = [
  301. {
  302. seriesName: title,
  303. data,
  304. },
  305. ];
  306. return (
  307. <TransitionChart loading={loading} reloading={loading}>
  308. <LoadingScreen loading={loading} />
  309. <ChartWrapper autoHeightResize={autoHeightResize}>
  310. {getDynamicText({
  311. value: this.chartComponent({
  312. series,
  313. autoHeightResize,
  314. }),
  315. fixed: <Placeholder height="200px" testId="skeleton-ui" />,
  316. })}
  317. </ChartWrapper>
  318. </TransitionChart>
  319. );
  320. }
  321. const legend = {
  322. left: 0,
  323. top: 0,
  324. selected: getSeriesSelection(location),
  325. formatter: (seriesName: string) => {
  326. const arg = getAggregateArg(seriesName);
  327. if (arg !== null) {
  328. const slug = getMeasurementSlug(arg);
  329. if (slug !== null) {
  330. seriesName = slug.toUpperCase();
  331. }
  332. }
  333. if (maybeEquationAlias(seriesName)) {
  334. seriesName = stripEquationPrefix(seriesName);
  335. }
  336. return seriesName;
  337. },
  338. ...legendOptions,
  339. };
  340. const axisField = widget.queries[0]?.aggregates?.[0] ?? 'count()';
  341. const axisLabel = isEquation(axisField) ? getEquation(axisField) : axisField;
  342. // Check to see if all series output types are the same. If not, then default to number.
  343. const outputType =
  344. timeseriesResultsTypes && new Set(Object.values(timeseriesResultsTypes)).size === 1
  345. ? timeseriesResultsTypes[axisLabel]
  346. : 'number';
  347. const isDurationChart = outputType === 'duration';
  348. const durationUnit = isDurationChart
  349. ? timeseriesResults && getDurationUnit(timeseriesResults, legendOptions)
  350. : undefined;
  351. const chartOptions = {
  352. autoHeightResize,
  353. grid: {
  354. left: 0,
  355. right: 4,
  356. top: '40px',
  357. bottom: showSlider ? SLIDER_HEIGHT : 0,
  358. },
  359. seriesOptions: {
  360. showSymbol: false,
  361. },
  362. tooltip: {
  363. trigger: 'axis',
  364. valueFormatter: (value: number, seriesName: string) => {
  365. const aggregateName = seriesName?.split(':').pop()?.trim();
  366. if (aggregateName) {
  367. return timeseriesResultsTypes
  368. ? tooltipFormatter(value, timeseriesResultsTypes[aggregateName])
  369. : tooltipFormatter(value, aggregateOutputType(aggregateName));
  370. }
  371. return tooltipFormatter(value, 'number');
  372. },
  373. },
  374. yAxis: {
  375. axisLabel: {
  376. color: theme.chartLabel,
  377. formatter: (value: number) => {
  378. if (timeseriesResultsTypes) {
  379. return axisLabelFormatterUsingAggregateOutputType(
  380. value,
  381. outputType,
  382. undefined,
  383. durationUnit
  384. );
  385. }
  386. return axisLabelFormatter(value, aggregateOutputType(axisLabel));
  387. },
  388. },
  389. minInterval: durationUnit ?? 0,
  390. },
  391. };
  392. return (
  393. <ChartZoom
  394. router={router}
  395. period={period}
  396. start={start}
  397. end={end}
  398. utc={utc}
  399. showSlider={showSlider}
  400. chartZoomOptions={chartZoomOptions}
  401. >
  402. {zoomRenderProps => {
  403. if (errorMessage) {
  404. return (
  405. <StyledErrorPanel>
  406. <IconWarning color="gray500" size="lg" />
  407. </StyledErrorPanel>
  408. );
  409. }
  410. const otherRegex = new RegExp(`(?:.* : ${OTHER}$)|^${OTHER}$`);
  411. const shouldColorOther = timeseriesResults?.some(
  412. ({seriesName}) => seriesName && seriesName.match(otherRegex)
  413. );
  414. const colors = timeseriesResults
  415. ? theme.charts.getColorPalette(
  416. timeseriesResults.length - (shouldColorOther ? 3 : 2)
  417. )
  418. : [];
  419. // TODO(wmak): Need to change this when updating dashboards to support variable topEvents
  420. if (shouldColorOther) {
  421. colors[colors.length] = theme.chartOther;
  422. }
  423. // Create a list of series based on the order of the fields,
  424. const series = timeseriesResults
  425. ? timeseriesResults.map((values, i: number) => {
  426. let seriesName = '';
  427. if (values.seriesName !== undefined) {
  428. seriesName = isEquation(values.seriesName)
  429. ? getEquation(values.seriesName)
  430. : values.seriesName;
  431. }
  432. return {
  433. ...values,
  434. seriesName,
  435. color: colors[i],
  436. };
  437. })
  438. : [];
  439. const seriesStart = series[0]?.data[0]?.name;
  440. const seriesEnd = series[0]?.data[series[0].data.length - 1]?.name;
  441. return (
  442. <TransitionChart loading={loading} reloading={loading}>
  443. <LoadingScreen loading={loading} />
  444. <ChartWrapper autoHeightResize={autoHeightResize} noPadding={noPadding}>
  445. {getDynamicText({
  446. value: this.chartComponent({
  447. ...zoomRenderProps,
  448. ...chartOptions,
  449. // Override default datazoom behaviour for updating Global Selection Header
  450. ...(onZoom
  451. ? {
  452. onDataZoom: (evt, chartProps) =>
  453. // Need to pass seriesStart and seriesEnd to onZoom since slider zooms
  454. // callback with percentage instead of datetime values. Passing seriesStart
  455. // and seriesEnd allows calculating datetime values with percentage.
  456. onZoom({...evt, seriesStart, seriesEnd}, chartProps),
  457. }
  458. : {}),
  459. legend,
  460. series,
  461. onLegendSelectChanged,
  462. }),
  463. fixed: <Placeholder height="200px" testId="skeleton-ui" />,
  464. })}
  465. </ChartWrapper>
  466. </TransitionChart>
  467. );
  468. }}
  469. </ChartZoom>
  470. );
  471. }
  472. }
  473. export default withTheme(WidgetCardChart);
  474. const StyledTransparentLoadingMask = styled(props => (
  475. <TransparentLoadingMask {...props} maskBackgroundColor="transparent" />
  476. ))`
  477. display: flex;
  478. justify-content: center;
  479. align-items: center;
  480. `;
  481. function LoadingScreen({loading}: {loading: boolean}) {
  482. if (!loading) {
  483. return null;
  484. }
  485. return (
  486. <StyledTransparentLoadingMask visible={loading}>
  487. <LoadingIndicator mini />
  488. </StyledTransparentLoadingMask>
  489. );
  490. }
  491. const LoadingPlaceholder = styled(({className}: PlaceholderProps) => (
  492. <Placeholder height="200px" className={className} />
  493. ))`
  494. background-color: ${p => p.theme.surface300};
  495. `;
  496. const BigNumberResizeWrapper = styled('div')`
  497. height: 100%;
  498. width: 100%;
  499. overflow: hidden;
  500. `;
  501. const BigNumber = styled('div')`
  502. line-height: 1;
  503. display: inline-flex;
  504. flex: 1;
  505. width: 100%;
  506. min-height: 0;
  507. font-size: 32px;
  508. color: ${p => p.theme.headingColor};
  509. padding: ${space(1)} ${space(3)} ${space(3)} ${space(3)};
  510. * {
  511. text-align: left !important;
  512. }
  513. `;
  514. const ChartWrapper = styled('div')<{autoHeightResize: boolean; noPadding?: boolean}>`
  515. ${p => p.autoHeightResize && 'height: 100%;'}
  516. padding: ${p => (p.noPadding ? `0` : `0 ${space(3)} ${space(3)}`)};
  517. `;
  518. const StyledSimpleTableChart = styled(SimpleTableChart)`
  519. margin-top: ${space(1.5)};
  520. border-bottom-left-radius: ${p => p.theme.borderRadius};
  521. border-bottom-right-radius: ${p => p.theme.borderRadius};
  522. font-size: ${p => p.theme.fontSizeMedium};
  523. box-shadow: none;
  524. `;
  525. const StyledErrorPanel = styled(ErrorPanel)`
  526. padding: ${space(2)};
  527. `;