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. timeseriesResultsType?: string;
  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
  223. ? {padding: `${space(1)} ${space(3)} 0 ${space(3)}`}
  224. : {}),
  225. }}
  226. >
  227. <Tooltip title={rendered} showOnlyOnOverflow>
  228. {rendered}
  229. </Tooltip>
  230. </BigNumber>
  231. );
  232. });
  233. }
  234. chartComponent(chartProps): React.ReactNode {
  235. const {organization, widget} = this.props;
  236. const stacked =
  237. organization.features.includes('new-widget-builder-experience-design') &&
  238. widget.queries[0].columns.length > 0;
  239. switch (widget.displayType) {
  240. case 'bar':
  241. return <BarChart {...chartProps} stacked={stacked} />;
  242. case 'area':
  243. case 'top_n':
  244. return <AreaChart stacked {...chartProps} />;
  245. case 'world_map':
  246. return <WorldMapChart {...chartProps} />;
  247. case 'line':
  248. default:
  249. return <LineChart {...chartProps} />;
  250. }
  251. }
  252. render() {
  253. const {
  254. theme,
  255. tableResults,
  256. timeseriesResults,
  257. errorMessage,
  258. loading,
  259. widget,
  260. organization,
  261. onZoom,
  262. legendOptions,
  263. expandNumbers,
  264. showSlider,
  265. noPadding,
  266. chartZoomOptions,
  267. timeseriesResultsType,
  268. } = this.props;
  269. if (widget.displayType === 'table') {
  270. return getDynamicText({
  271. value: (
  272. <TransitionChart loading={loading} reloading={loading}>
  273. <LoadingScreen loading={loading} />
  274. {this.tableResultComponent({tableResults, loading, errorMessage})}
  275. </TransitionChart>
  276. ),
  277. fixed: <Placeholder height="200px" testId="skeleton-ui" />,
  278. });
  279. }
  280. if (widget.displayType === 'big_number') {
  281. return (
  282. <TransitionChart loading={loading} reloading={loading}>
  283. <LoadingScreen loading={loading} />
  284. <BigNumberResizeWrapper
  285. ref={el => {
  286. if (el !== null && !!!expandNumbers) {
  287. const {height} = el.getBoundingClientRect();
  288. if (height !== this.state.containerHeight) {
  289. this.setState({containerHeight: height});
  290. }
  291. }
  292. }}
  293. >
  294. {this.bigNumberComponent({tableResults, loading, errorMessage})}
  295. </BigNumberResizeWrapper>
  296. </TransitionChart>
  297. );
  298. }
  299. if (errorMessage) {
  300. return (
  301. <StyledErrorPanel>
  302. <IconWarning color="gray500" size="lg" />
  303. </StyledErrorPanel>
  304. );
  305. }
  306. const {location, router, selection, onLegendSelectChanged} = this.props;
  307. const {start, end, period, utc} = selection.datetime;
  308. // Only allow height resizing for widgets that are on a dashboard
  309. const autoHeightResize = Boolean(
  310. organization.features.includes('dashboard-grid-layout') &&
  311. (widget.id || widget.tempId)
  312. );
  313. if (widget.displayType === 'world_map') {
  314. const {data, title} = processTableResults(tableResults);
  315. const series = [
  316. {
  317. seriesName: title,
  318. data,
  319. },
  320. ];
  321. return (
  322. <TransitionChart loading={loading} reloading={loading}>
  323. <LoadingScreen loading={loading} />
  324. <ChartWrapper autoHeightResize={autoHeightResize}>
  325. {getDynamicText({
  326. value: this.chartComponent({
  327. series,
  328. autoHeightResize,
  329. }),
  330. fixed: <Placeholder height="200px" testId="skeleton-ui" />,
  331. })}
  332. </ChartWrapper>
  333. </TransitionChart>
  334. );
  335. }
  336. const legend = {
  337. left: 0,
  338. top: 0,
  339. selected: getSeriesSelection(location),
  340. formatter: (seriesName: string) => {
  341. const arg = getAggregateArg(seriesName);
  342. if (arg !== null) {
  343. const slug = getMeasurementSlug(arg);
  344. if (slug !== null) {
  345. seriesName = slug.toUpperCase();
  346. }
  347. }
  348. if (maybeEquationAlias(seriesName)) {
  349. seriesName = stripEquationPrefix(seriesName);
  350. }
  351. return seriesName;
  352. },
  353. ...legendOptions,
  354. };
  355. const axisField = widget.queries[0]?.aggregates?.[0] ?? 'count()';
  356. const axisLabel = isEquation(axisField) ? getEquation(axisField) : axisField;
  357. const chartOptions = {
  358. autoHeightResize,
  359. grid: {
  360. left: 0,
  361. right: 4,
  362. top: '40px',
  363. bottom: showSlider ? SLIDER_HEIGHT : 0,
  364. },
  365. seriesOptions: {
  366. showSymbol: false,
  367. },
  368. tooltip: {
  369. trigger: 'axis',
  370. valueFormatter: (value: number, seriesName: string) =>
  371. timeseriesResultsType
  372. ? tooltipFormatter(value, timeseriesResultsType as AggregationOutputType)
  373. : tooltipFormatter(value, aggregateOutputType(seriesName)),
  374. },
  375. yAxis: {
  376. axisLabel: {
  377. color: theme.chartLabel,
  378. formatter: (value: number) =>
  379. timeseriesResultsType
  380. ? axisLabelFormatterUsingAggregateOutputType(value, timeseriesResultsType)
  381. : axisLabelFormatter(value, aggregateOutputType(axisLabel)),
  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. `;