index.tsx 18 KB

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