index.tsx 16 KB

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