index.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. const widgetContainsErrorFields = widget.queries.some(
  237. ({columns, aggregates, conditions}) =>
  238. ERROR_FIELDS.some(
  239. errorField =>
  240. columns.includes(errorField) ||
  241. aggregates.some(aggregate =>
  242. parseFunction(aggregate)?.arguments.includes(errorField)
  243. ) ||
  244. parseSearch(conditions)?.some(
  245. filter => (filter as SearchFilterKey).key?.value === errorField
  246. )
  247. )
  248. );
  249. if (widget.widgetType === WidgetType.METRICS) {
  250. if (hasDDMFeature(organization)) {
  251. return (
  252. <MetricWidgetCard
  253. index={this.props.index}
  254. isEditingDashboard={this.props.isEditingDashboard}
  255. onEdit={this.props.onEdit}
  256. onDelete={this.props.onDelete}
  257. onDuplicate={this.props.onDuplicate}
  258. router={this.props.router}
  259. location={this.props.location}
  260. organization={organization}
  261. selection={selection}
  262. widget={widget}
  263. dashboardFilters={dashboardFilters}
  264. renderErrorMessage={renderErrorMessage}
  265. />
  266. );
  267. }
  268. }
  269. return (
  270. <ErrorBoundary
  271. customComponent={<ErrorCard>{t('Error loading widget data')}</ErrorCard>}
  272. >
  273. {conditionalWrapWithDashboardsMEPProvider(
  274. <Fragment>
  275. <VisuallyCompleteWithData
  276. id="DashboardList-FirstWidgetCard"
  277. hasData={
  278. ((this.state.tableData?.length || this.state.seriesData?.length) ?? 0) > 0
  279. }
  280. disabled={Number(this.props.index) !== 0}
  281. >
  282. <WidgetCardPanel isDragging={false}>
  283. <WidgetHeaderWrapper>
  284. <WidgetHeaderDescription>
  285. <WidgetTitleRow>
  286. <Tooltip
  287. title={widget.title}
  288. containerDisplayMode="grid"
  289. showOnlyOnOverflow
  290. >
  291. <WidgetTitle>{widget.title}</WidgetTitle>
  292. </Tooltip>
  293. {widget.thresholds &&
  294. hasThresholdMaxValue(widget.thresholds) &&
  295. this.state.tableData &&
  296. organization.features.includes('dashboard-widget-indicators') &&
  297. getColoredWidgetIndicator(
  298. widget.thresholds,
  299. this.state.tableData
  300. )}
  301. <ExtractedMetricsTag queryKey={widget} />
  302. <DisplayOnDemandWarnings widget={widget} />
  303. </WidgetTitleRow>
  304. {widget.description && (
  305. <Tooltip
  306. title={widget.description}
  307. containerDisplayMode="grid"
  308. showOnlyOnOverflow
  309. isHoverable
  310. >
  311. <WidgetDescription>{widget.description}</WidgetDescription>
  312. </Tooltip>
  313. )}
  314. </WidgetHeaderDescription>
  315. {this.renderContextMenu()}
  316. </WidgetHeaderWrapper>
  317. {hasSessionDuration && SESSION_DURATION_ALERT}
  318. {isWidgetInvalid ? (
  319. <Fragment>
  320. {renderErrorMessage?.('Widget query condition is invalid.')}
  321. <StyledErrorPanel>
  322. <IconWarning color="gray500" size="lg" />
  323. </StyledErrorPanel>
  324. </Fragment>
  325. ) : noLazyLoad ? (
  326. <WidgetCardChartContainer
  327. location={location}
  328. api={api}
  329. organization={organization}
  330. selection={selection}
  331. widget={widget}
  332. isMobile={isMobile}
  333. renderErrorMessage={renderErrorMessage}
  334. tableItemLimit={tableItemLimit}
  335. windowWidth={windowWidth}
  336. onDataFetched={this.setData}
  337. dashboardFilters={dashboardFilters}
  338. chartGroup={DASHBOARD_CHART_GROUP}
  339. />
  340. ) : (
  341. <LazyLoad once resize height={200}>
  342. <WidgetCardChartContainer
  343. location={location}
  344. api={api}
  345. organization={organization}
  346. selection={selection}
  347. widget={widget}
  348. isMobile={isMobile}
  349. renderErrorMessage={renderErrorMessage}
  350. tableItemLimit={tableItemLimit}
  351. windowWidth={windowWidth}
  352. onDataFetched={this.setData}
  353. dashboardFilters={dashboardFilters}
  354. chartGroup={DASHBOARD_CHART_GROUP}
  355. />
  356. </LazyLoad>
  357. )}
  358. {this.renderToolbar()}
  359. </WidgetCardPanel>
  360. </VisuallyCompleteWithData>
  361. {!organization.features.includes('performance-mep-bannerless-ui') && (
  362. <MEPConsumer>
  363. {metricSettingContext => {
  364. return (
  365. <DashboardsMEPConsumer>
  366. {({isMetricsData}) => {
  367. if (
  368. showStoredAlert &&
  369. isMetricsData === false &&
  370. widget.widgetType === WidgetType.DISCOVER &&
  371. metricSettingContext &&
  372. metricSettingContext.metricSettingState !==
  373. MEPState.TRANSACTIONS_ONLY
  374. ) {
  375. if (!widgetContainsErrorFields) {
  376. return (
  377. <StoredDataAlert showIcon>
  378. {tct(
  379. "Your selection is only applicable to [indexedData: indexed event data]. We've automatically adjusted your results.",
  380. {
  381. indexedData: (
  382. <ExternalLink href="https://docs.sentry.io/product/dashboards/widget-builder/#errors--transactions" />
  383. ),
  384. }
  385. )}
  386. </StoredDataAlert>
  387. );
  388. }
  389. }
  390. return null;
  391. }}
  392. </DashboardsMEPConsumer>
  393. );
  394. }}
  395. </MEPConsumer>
  396. )}
  397. </Fragment>
  398. )}
  399. </ErrorBoundary>
  400. );
  401. }
  402. }
  403. export default withApi(withOrganization(withPageFilters(withSentryRouter(WidgetCard))));
  404. function DisplayOnDemandWarnings(props: {widget: Widget}) {
  405. const organization = useOrganization();
  406. if (!hasOnDemandMetricWidgetFeature(organization)) {
  407. return null;
  408. }
  409. const widgetContainsHighCardinality = props.widget.queries.some(wq =>
  410. wq.onDemand?.some(
  411. d => d.extractionState === OnDemandExtractionState.DISABLED_HIGH_CARDINALITY
  412. )
  413. );
  414. const widgetReachedSpecLimit = props.widget.queries.some(wq =>
  415. wq.onDemand?.some(
  416. d => d.extractionState === OnDemandExtractionState.DISABLED_SPEC_LIMIT
  417. )
  418. );
  419. if (widgetContainsHighCardinality) {
  420. return (
  421. <Tooltip
  422. containerDisplayMode="inline-flex"
  423. title={t(
  424. 'This widget is using indexed data because it has a column with too many unique values.'
  425. )}
  426. >
  427. <IconWarning color="warningText" />
  428. </Tooltip>
  429. );
  430. }
  431. if (widgetReachedSpecLimit) {
  432. return (
  433. <Tooltip
  434. containerDisplayMode="inline-flex"
  435. title={t(
  436. "This widget is using indexed data because you've reached your organization limit for dynamically extracted metrics."
  437. )}
  438. >
  439. <IconWarning color="warningText" />
  440. </Tooltip>
  441. );
  442. }
  443. return null;
  444. }
  445. const ErrorCard = styled(Placeholder)`
  446. display: flex;
  447. align-items: center;
  448. justify-content: center;
  449. background-color: ${p => p.theme.alert.error.backgroundLight};
  450. border: 1px solid ${p => p.theme.alert.error.border};
  451. color: ${p => p.theme.alert.error.textLight};
  452. border-radius: ${p => p.theme.borderRadius};
  453. margin-bottom: ${space(2)};
  454. `;
  455. export const WidgetCardPanel = styled(Panel, {
  456. shouldForwardProp: prop => prop !== 'isDragging',
  457. })<{
  458. isDragging: boolean;
  459. }>`
  460. margin: 0;
  461. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  462. /* If a panel overflows due to a long title stretch its grid sibling */
  463. height: 100%;
  464. min-height: 96px;
  465. display: flex;
  466. flex-direction: column;
  467. `;
  468. const StoredDataAlert = styled(Alert)`
  469. margin-top: ${space(1)};
  470. margin-bottom: 0;
  471. `;
  472. const StyledErrorPanel = styled(ErrorPanel)`
  473. padding: ${space(2)};
  474. `;
  475. export const WidgetTitleRow = styled('span')`
  476. display: flex;
  477. align-items: center;
  478. gap: ${space(0.75)};
  479. `;
  480. export const WidgetDescription = styled('small')`
  481. ${p => p.theme.overflowEllipsis}
  482. color: ${p => p.theme.gray300};
  483. `;
  484. const WidgetTitle = styled(HeaderTitle)`
  485. ${p => p.theme.overflowEllipsis};
  486. font-weight: normal;
  487. `;
  488. const WidgetHeaderWrapper = styled('div')`
  489. padding: ${space(2)} ${space(1)} 0 ${space(3)};
  490. min-height: 36px;
  491. width: 100%;
  492. display: flex;
  493. align-items: center;
  494. justify-content: space-between;
  495. `;
  496. const WidgetHeaderDescription = styled('div')`
  497. display: flex;
  498. flex-direction: column;
  499. gap: ${space(0.5)};
  500. `;