index.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. import {Component, Fragment} from 'react';
  2. import LazyLoad from 'react-lazyload';
  3. import type {WithRouterProps} from 'react-router';
  4. import type {useSortable} from '@dnd-kit/sortable';
  5. import styled from '@emotion/styled';
  6. import type {Location} from 'history';
  7. import type {Client} from 'sentry/api';
  8. import {Alert} from 'sentry/components/alert';
  9. import ErrorPanel from 'sentry/components/charts/errorPanel';
  10. import {HeaderTitle} from 'sentry/components/charts/styles';
  11. import ErrorBoundary from 'sentry/components/errorBoundary';
  12. import ExternalLink from 'sentry/components/links/externalLink';
  13. import Panel from 'sentry/components/panels/panel';
  14. import PanelAlert from 'sentry/components/panels/panelAlert';
  15. import Placeholder from 'sentry/components/placeholder';
  16. import {parseSearch} from 'sentry/components/searchSyntax/parser';
  17. import {Tooltip} from 'sentry/components/tooltip';
  18. import {IconWarning} from 'sentry/icons';
  19. import {t, tct} from 'sentry/locale';
  20. import {space} from 'sentry/styles/space';
  21. import type {Organization, PageFilters} from 'sentry/types';
  22. import type {Series} from 'sentry/types/echarts';
  23. import {getFormattedDate} from 'sentry/utils/dates';
  24. import type {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  25. import type {AggregationOutputType} from 'sentry/utils/discover/fields';
  26. import {parseFunction} from 'sentry/utils/discover/fields';
  27. import {hasDDMFeature} from 'sentry/utils/metrics/features';
  28. import {hasOnDemandMetricWidgetFeature} from 'sentry/utils/onDemandMetrics/features';
  29. import {ExtractedMetricsTag} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
  30. import {
  31. MEPConsumer,
  32. MEPState,
  33. } from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  34. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  35. import useOrganization from 'sentry/utils/useOrganization';
  36. import withApi from 'sentry/utils/withApi';
  37. import withOrganization from 'sentry/utils/withOrganization';
  38. import withPageFilters from 'sentry/utils/withPageFilters';
  39. // eslint-disable-next-line no-restricted-imports
  40. import withSentryRouter from 'sentry/utils/withSentryRouter';
  41. import {DASHBOARD_CHART_GROUP} from 'sentry/views/dashboards/dashboard';
  42. import {MetricWidgetCard} from 'sentry/views/dashboards/widgetCard/metricWidgetCard';
  43. import {Toolbar} from 'sentry/views/dashboards/widgetCard/toolbar';
  44. import type {DashboardFilters, Widget} from '../types';
  45. import {DisplayType, OnDemandExtractionState, WidgetType} from '../types';
  46. import {getColoredWidgetIndicator, hasThresholdMaxValue} from '../utils';
  47. import {DEFAULT_RESULTS_LIMIT} from '../widgetBuilder/utils';
  48. import {DashboardsMEPConsumer, DashboardsMEPProvider} from './dashboardsMEPContext';
  49. import WidgetCardChartContainer from './widgetCardChartContainer';
  50. import WidgetCardContextMenu from './widgetCardContextMenu';
  51. const SESSION_DURATION_INGESTION_STOP_DATE = new Date('2023-01-12');
  52. export const SESSION_DURATION_ALERT = (
  53. <PanelAlert type="warning">
  54. {t(
  55. 'session.duration is no longer being recorded as of %s. Data in this widget may be incomplete.',
  56. getFormattedDate(SESSION_DURATION_INGESTION_STOP_DATE, 'MMM D, YYYY')
  57. )}
  58. </PanelAlert>
  59. );
  60. type DraggableProps = Pick<ReturnType<typeof useSortable>, 'attributes' | 'listeners'>;
  61. type Props = WithRouterProps & {
  62. api: Client;
  63. isEditingDashboard: boolean;
  64. location: Location;
  65. organization: Organization;
  66. selection: PageFilters;
  67. widget: Widget;
  68. widgetLimitReached: boolean;
  69. dashboardFilters?: DashboardFilters;
  70. draggableProps?: DraggableProps;
  71. hideToolbar?: boolean;
  72. index?: string;
  73. isEditingWidget?: boolean;
  74. isMobile?: boolean;
  75. isPreview?: boolean;
  76. isWidgetInvalid?: boolean;
  77. noDashboardsMEPProvider?: boolean;
  78. noLazyLoad?: boolean;
  79. onDataFetched?: (results: TableDataWithTitle[]) => void;
  80. onDelete?: () => void;
  81. onDuplicate?: () => void;
  82. onEdit?: () => void;
  83. onUpdate?: (widget: Widget | null) => void;
  84. renderErrorMessage?: (errorMessage?: string) => React.ReactNode;
  85. showContextMenu?: boolean;
  86. showStoredAlert?: boolean;
  87. tableItemLimit?: number;
  88. windowWidth?: number;
  89. };
  90. type State = {
  91. pageLinks?: string;
  92. seriesData?: Series[];
  93. seriesResultsType?: Record<string, AggregationOutputType>;
  94. tableData?: TableDataWithTitle[];
  95. totalIssuesCount?: string;
  96. };
  97. type SearchFilterKey = {key?: {value: string}};
  98. const ERROR_FIELDS = [
  99. 'error.handled',
  100. 'error.unhandled',
  101. 'error.mechanism',
  102. 'error.type',
  103. 'error.value',
  104. ];
  105. class WidgetCard extends Component<Props, State> {
  106. state: State = {};
  107. renderToolbar() {
  108. const {
  109. onEdit,
  110. onDelete,
  111. onDuplicate,
  112. draggableProps,
  113. hideToolbar,
  114. isEditingDashboard,
  115. isMobile,
  116. } = this.props;
  117. if (!isEditingDashboard) {
  118. return null;
  119. }
  120. return (
  121. <Toolbar
  122. onEdit={onEdit}
  123. onDelete={onDelete}
  124. onDuplicate={onDuplicate}
  125. draggableProps={draggableProps}
  126. hideToolbar={hideToolbar}
  127. isMobile={isMobile}
  128. />
  129. );
  130. }
  131. renderContextMenu() {
  132. const {
  133. widget,
  134. selection,
  135. organization,
  136. showContextMenu,
  137. isPreview,
  138. widgetLimitReached,
  139. onEdit,
  140. onDuplicate,
  141. onDelete,
  142. isEditingDashboard,
  143. router,
  144. location,
  145. index,
  146. } = this.props;
  147. const {seriesData, tableData, pageLinks, totalIssuesCount, seriesResultsType} =
  148. this.state;
  149. if (isEditingDashboard) {
  150. return null;
  151. }
  152. return (
  153. <WidgetCardContextMenu
  154. organization={organization}
  155. widget={widget}
  156. selection={selection}
  157. showContextMenu={showContextMenu}
  158. isPreview={isPreview}
  159. widgetLimitReached={widgetLimitReached}
  160. onDuplicate={onDuplicate}
  161. onEdit={onEdit}
  162. onDelete={onDelete}
  163. router={router}
  164. location={location}
  165. index={index}
  166. seriesData={seriesData}
  167. seriesResultsType={seriesResultsType}
  168. tableData={tableData}
  169. pageLinks={pageLinks}
  170. totalIssuesCount={totalIssuesCount}
  171. />
  172. );
  173. }
  174. setData = ({
  175. tableResults,
  176. timeseriesResults,
  177. totalIssuesCount,
  178. pageLinks,
  179. timeseriesResultsTypes,
  180. }: {
  181. pageLinks?: string;
  182. tableResults?: TableDataWithTitle[];
  183. timeseriesResults?: Series[];
  184. timeseriesResultsTypes?: Record<string, AggregationOutputType>;
  185. totalIssuesCount?: string;
  186. }) => {
  187. const {onDataFetched} = this.props;
  188. if (onDataFetched && tableResults) {
  189. onDataFetched(tableResults);
  190. }
  191. this.setState({
  192. seriesData: timeseriesResults,
  193. tableData: tableResults,
  194. totalIssuesCount,
  195. pageLinks,
  196. seriesResultsType: timeseriesResultsTypes,
  197. });
  198. };
  199. render() {
  200. const {
  201. api,
  202. organization,
  203. selection,
  204. widget,
  205. isMobile,
  206. renderErrorMessage,
  207. tableItemLimit,
  208. windowWidth,
  209. noLazyLoad,
  210. showStoredAlert,
  211. noDashboardsMEPProvider,
  212. dashboardFilters,
  213. isWidgetInvalid,
  214. location,
  215. } = this.props;
  216. if (widget.displayType === DisplayType.TOP_N) {
  217. const queries = widget.queries.map(query => ({
  218. ...query,
  219. // Use the last aggregate because that's where the y-axis is stored
  220. aggregates: query.aggregates.length
  221. ? [query.aggregates[query.aggregates.length - 1]]
  222. : [],
  223. }));
  224. widget.queries = queries;
  225. widget.limit = DEFAULT_RESULTS_LIMIT;
  226. }
  227. const hasSessionDuration = widget.queries.some(query =>
  228. query.aggregates.some(aggregate => aggregate.includes('session.duration'))
  229. );
  230. function conditionalWrapWithDashboardsMEPProvider(component: React.ReactNode) {
  231. if (noDashboardsMEPProvider) {
  232. return component;
  233. }
  234. return <DashboardsMEPProvider>{component}</DashboardsMEPProvider>;
  235. }
  236. // prettier-ignore
  237. const widgetContainsErrorFields = widget.queries.some(
  238. ({columns, aggregates, conditions}) =>
  239. ERROR_FIELDS.some(
  240. errorField =>
  241. columns.includes(errorField) ||
  242. aggregates.some(
  243. aggregate => parseFunction(aggregate)?.arguments.includes(errorField)
  244. ) ||
  245. parseSearch(conditions)?.some(
  246. filter => (filter as SearchFilterKey).key?.value === errorField
  247. )
  248. )
  249. );
  250. if (widget.widgetType === WidgetType.METRICS) {
  251. if (hasDDMFeature(organization)) {
  252. return (
  253. <MetricWidgetCard
  254. index={this.props.index}
  255. isEditingDashboard={this.props.isEditingDashboard}
  256. onEdit={this.props.onEdit}
  257. onDelete={this.props.onDelete}
  258. onDuplicate={this.props.onDuplicate}
  259. router={this.props.router}
  260. location={this.props.location}
  261. organization={organization}
  262. selection={selection}
  263. widget={widget}
  264. dashboardFilters={dashboardFilters}
  265. renderErrorMessage={renderErrorMessage}
  266. showContextMenu={this.props.showContextMenu}
  267. />
  268. );
  269. }
  270. }
  271. return (
  272. <ErrorBoundary
  273. customComponent={<ErrorCard>{t('Error loading widget data')}</ErrorCard>}
  274. >
  275. {conditionalWrapWithDashboardsMEPProvider(
  276. <Fragment>
  277. <VisuallyCompleteWithData
  278. id="DashboardList-FirstWidgetCard"
  279. hasData={
  280. ((this.state.tableData?.length || this.state.seriesData?.length) ?? 0) > 0
  281. }
  282. disabled={Number(this.props.index) !== 0}
  283. >
  284. <WidgetCardPanel isDragging={false}>
  285. <WidgetHeaderWrapper>
  286. <WidgetHeaderDescription>
  287. <WidgetTitleRow>
  288. <Tooltip
  289. title={widget.title}
  290. containerDisplayMode="grid"
  291. showOnlyOnOverflow
  292. >
  293. <WidgetTitle>{widget.title}</WidgetTitle>
  294. </Tooltip>
  295. {widget.thresholds &&
  296. hasThresholdMaxValue(widget.thresholds) &&
  297. this.state.tableData &&
  298. organization.features.includes('dashboard-widget-indicators') &&
  299. getColoredWidgetIndicator(
  300. widget.thresholds,
  301. this.state.tableData
  302. )}
  303. <ExtractedMetricsTag queryKey={widget} />
  304. <DisplayOnDemandWarnings widget={widget} />
  305. </WidgetTitleRow>
  306. {widget.description && (
  307. <Tooltip
  308. title={widget.description}
  309. containerDisplayMode="grid"
  310. showOnlyOnOverflow
  311. isHoverable
  312. >
  313. <WidgetDescription>{widget.description}</WidgetDescription>
  314. </Tooltip>
  315. )}
  316. </WidgetHeaderDescription>
  317. {this.renderContextMenu()}
  318. </WidgetHeaderWrapper>
  319. {hasSessionDuration && SESSION_DURATION_ALERT}
  320. {isWidgetInvalid ? (
  321. <Fragment>
  322. {renderErrorMessage?.('Widget query condition is invalid.')}
  323. <StyledErrorPanel>
  324. <IconWarning color="gray500" size="lg" />
  325. </StyledErrorPanel>
  326. </Fragment>
  327. ) : noLazyLoad ? (
  328. <WidgetCardChartContainer
  329. location={location}
  330. api={api}
  331. organization={organization}
  332. selection={selection}
  333. widget={widget}
  334. isMobile={isMobile}
  335. renderErrorMessage={renderErrorMessage}
  336. tableItemLimit={tableItemLimit}
  337. windowWidth={windowWidth}
  338. onDataFetched={this.setData}
  339. dashboardFilters={dashboardFilters}
  340. chartGroup={DASHBOARD_CHART_GROUP}
  341. />
  342. ) : (
  343. <LazyLoad once resize height={200}>
  344. <WidgetCardChartContainer
  345. location={location}
  346. api={api}
  347. organization={organization}
  348. selection={selection}
  349. widget={widget}
  350. isMobile={isMobile}
  351. renderErrorMessage={renderErrorMessage}
  352. tableItemLimit={tableItemLimit}
  353. windowWidth={windowWidth}
  354. onDataFetched={this.setData}
  355. dashboardFilters={dashboardFilters}
  356. chartGroup={DASHBOARD_CHART_GROUP}
  357. />
  358. </LazyLoad>
  359. )}
  360. {this.renderToolbar()}
  361. </WidgetCardPanel>
  362. </VisuallyCompleteWithData>
  363. {!organization.features.includes('performance-mep-bannerless-ui') && (
  364. <MEPConsumer>
  365. {metricSettingContext => {
  366. return (
  367. <DashboardsMEPConsumer>
  368. {({isMetricsData}) => {
  369. if (
  370. showStoredAlert &&
  371. isMetricsData === false &&
  372. widget.widgetType === WidgetType.DISCOVER &&
  373. metricSettingContext &&
  374. metricSettingContext.metricSettingState !==
  375. MEPState.TRANSACTIONS_ONLY
  376. ) {
  377. if (!widgetContainsErrorFields) {
  378. return (
  379. <StoredDataAlert showIcon>
  380. {tct(
  381. "Your selection is only applicable to [indexedData: indexed event data]. We've automatically adjusted your results.",
  382. {
  383. indexedData: (
  384. <ExternalLink href="https://docs.sentry.io/product/dashboards/widget-builder/#errors--transactions" />
  385. ),
  386. }
  387. )}
  388. </StoredDataAlert>
  389. );
  390. }
  391. }
  392. return null;
  393. }}
  394. </DashboardsMEPConsumer>
  395. );
  396. }}
  397. </MEPConsumer>
  398. )}
  399. </Fragment>
  400. )}
  401. </ErrorBoundary>
  402. );
  403. }
  404. }
  405. export default withApi(withOrganization(withPageFilters(withSentryRouter(WidgetCard))));
  406. function DisplayOnDemandWarnings(props: {widget: Widget}) {
  407. const organization = useOrganization();
  408. if (!hasOnDemandMetricWidgetFeature(organization)) {
  409. return null;
  410. }
  411. // prettier-ignore
  412. const widgetContainsHighCardinality = props.widget.queries.some(
  413. wq =>
  414. wq.onDemand?.some(
  415. d => d.extractionState === OnDemandExtractionState.DISABLED_HIGH_CARDINALITY
  416. )
  417. );
  418. // prettier-ignore
  419. const widgetReachedSpecLimit = props.widget.queries.some(
  420. wq =>
  421. wq.onDemand?.some(
  422. d => d.extractionState === OnDemandExtractionState.DISABLED_SPEC_LIMIT
  423. )
  424. );
  425. if (widgetContainsHighCardinality) {
  426. return (
  427. <Tooltip
  428. containerDisplayMode="inline-flex"
  429. title={t(
  430. 'This widget is using indexed data because it has a column with too many unique values.'
  431. )}
  432. >
  433. <IconWarning color="warningText" />
  434. </Tooltip>
  435. );
  436. }
  437. if (widgetReachedSpecLimit) {
  438. return (
  439. <Tooltip
  440. containerDisplayMode="inline-flex"
  441. title={t(
  442. "This widget is using indexed data because you've reached your organization limit for dynamically extracted metrics."
  443. )}
  444. >
  445. <IconWarning color="warningText" />
  446. </Tooltip>
  447. );
  448. }
  449. return null;
  450. }
  451. const ErrorCard = styled(Placeholder)`
  452. display: flex;
  453. align-items: center;
  454. justify-content: center;
  455. background-color: ${p => p.theme.alert.error.backgroundLight};
  456. border: 1px solid ${p => p.theme.alert.error.border};
  457. color: ${p => p.theme.alert.error.textLight};
  458. border-radius: ${p => p.theme.borderRadius};
  459. margin-bottom: ${space(2)};
  460. `;
  461. export const WidgetCardPanel = styled(Panel, {
  462. shouldForwardProp: prop => prop !== 'isDragging',
  463. })<{
  464. isDragging: boolean;
  465. }>`
  466. margin: 0;
  467. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  468. /* If a panel overflows due to a long title stretch its grid sibling */
  469. height: 100%;
  470. min-height: 96px;
  471. display: flex;
  472. flex-direction: column;
  473. `;
  474. const StoredDataAlert = styled(Alert)`
  475. margin-top: ${space(1)};
  476. margin-bottom: 0;
  477. `;
  478. const StyledErrorPanel = styled(ErrorPanel)`
  479. padding: ${space(2)};
  480. `;
  481. export const WidgetTitleRow = styled('span')`
  482. display: flex;
  483. align-items: center;
  484. gap: ${space(0.75)};
  485. `;
  486. export const WidgetDescription = styled('small')`
  487. ${p => p.theme.overflowEllipsis}
  488. color: ${p => p.theme.gray300};
  489. `;
  490. const WidgetTitle = styled(HeaderTitle)`
  491. ${p => p.theme.overflowEllipsis};
  492. font-weight: normal;
  493. `;
  494. const WidgetHeaderWrapper = styled('div')`
  495. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  496. min-height: 36px;
  497. width: 100%;
  498. display: flex;
  499. align-items: center;
  500. justify-content: space-between;
  501. `;
  502. const WidgetHeaderDescription = styled('div')`
  503. display: flex;
  504. flex-direction: column;
  505. gap: ${space(0.5)};
  506. `;