index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. import {useContext, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {LegendComponentOption} from 'echarts';
  4. import type {Location} from 'history';
  5. import type {Client} from 'sentry/api';
  6. import type {BadgeProps} from 'sentry/components/badge/badge';
  7. import ErrorBoundary from 'sentry/components/errorBoundary';
  8. import {isWidgetViewerPath} from 'sentry/components/modals/widgetViewerModal/utils';
  9. import Panel from 'sentry/components/panels/panel';
  10. import PanelAlert from 'sentry/components/panels/panelAlert';
  11. import Placeholder from 'sentry/components/placeholder';
  12. import {t} from 'sentry/locale';
  13. import {space} from 'sentry/styles/space';
  14. import type {PageFilters} from 'sentry/types/core';
  15. import type {Series} from 'sentry/types/echarts';
  16. import type {WithRouterProps} from 'sentry/types/legacyReactRouter';
  17. import type {Organization} from 'sentry/types/organization';
  18. import {defined} from 'sentry/utils';
  19. import {getFormattedDate} from 'sentry/utils/dates';
  20. import type {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  21. import type {AggregationOutputType} from 'sentry/utils/discover/fields';
  22. import {hasOnDemandMetricWidgetFeature} from 'sentry/utils/onDemandMetrics/features';
  23. import {useExtractionStatus} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
  24. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  25. import useOrganization from 'sentry/utils/useOrganization';
  26. import withApi from 'sentry/utils/withApi';
  27. import withOrganization from 'sentry/utils/withOrganization';
  28. import withPageFilters from 'sentry/utils/withPageFilters';
  29. // eslint-disable-next-line no-restricted-imports
  30. import withSentryRouter from 'sentry/utils/withSentryRouter';
  31. import {DASHBOARD_CHART_GROUP} from 'sentry/views/dashboards/dashboard';
  32. import {useDiscoverSplitAlert} from 'sentry/views/dashboards/discoverSplitAlert';
  33. import {MetricWidgetCard} from 'sentry/views/dashboards/metrics/widgetCard';
  34. import type {DashboardFilters, Widget} from '../types';
  35. import {DisplayType, OnDemandExtractionState, WidgetType} from '../types';
  36. import {DEFAULT_RESULTS_LIMIT} from '../widgetBuilder/utils';
  37. import type WidgetLegendSelectionState from '../widgetLegendSelectionState';
  38. import {BigNumberWidget} from '../widgets/bigNumberWidget/bigNumberWidget';
  39. import type {Meta} from '../widgets/common/types';
  40. import {WidgetFrame} from '../widgets/common/widgetFrame';
  41. import {WidgetViewerContext} from '../widgetViewer/widgetViewerContext';
  42. import {useDashboardsMEPContext} from './dashboardsMEPContext';
  43. import WidgetCardChartContainer from './widgetCardChartContainer';
  44. import {getMenuOptions, useIndexedEventsWarning} from './widgetCardContextMenu';
  45. import {WidgetCardDataLoader} from './widgetCardDataLoader';
  46. const SESSION_DURATION_INGESTION_STOP_DATE = new Date('2023-01-12');
  47. export const SESSION_DURATION_ALERT_TEXT = t(
  48. 'session.duration is no longer being recorded as of %s. Data in this widget may be incomplete.',
  49. getFormattedDate(SESSION_DURATION_INGESTION_STOP_DATE, 'MMM D, YYYY')
  50. );
  51. export const SESSION_DURATION_ALERT = (
  52. <PanelAlert type="warning">{SESSION_DURATION_ALERT_TEXT}</PanelAlert>
  53. );
  54. type Props = WithRouterProps & {
  55. api: Client;
  56. isEditingDashboard: boolean;
  57. location: Location;
  58. organization: Organization;
  59. selection: PageFilters;
  60. widget: Widget;
  61. widgetLegendState: WidgetLegendSelectionState;
  62. widgetLimitReached: boolean;
  63. dashboardFilters?: DashboardFilters;
  64. hasEditAccess?: boolean;
  65. index?: string;
  66. isEditingWidget?: boolean;
  67. isMobile?: boolean;
  68. isPreview?: boolean;
  69. isWidgetInvalid?: boolean;
  70. legendOptions?: LegendComponentOption;
  71. onDataFetched?: (results: TableDataWithTitle[]) => void;
  72. onDelete?: () => void;
  73. onDuplicate?: () => void;
  74. onEdit?: () => void;
  75. onLegendSelectChanged?: () => void;
  76. onSetTransactionsDataset?: () => void;
  77. onUpdate?: (widget: Widget | null) => void;
  78. onWidgetSplitDecision?: (splitDecision: WidgetType) => void;
  79. renderErrorMessage?: (errorMessage?: string) => React.ReactNode;
  80. shouldResize?: boolean;
  81. showContextMenu?: boolean;
  82. showStoredAlert?: boolean;
  83. tableItemLimit?: number;
  84. windowWidth?: number;
  85. };
  86. type Data = {
  87. pageLinks?: string;
  88. tableResults?: TableDataWithTitle[];
  89. timeseriesResults?: Series[];
  90. timeseriesResultsTypes?: Record<string, AggregationOutputType>;
  91. totalIssuesCount?: string;
  92. };
  93. function WidgetCard(props: Props) {
  94. const [data, setData] = useState<Data>();
  95. const {setData: setWidgetViewerData} = useContext(WidgetViewerContext);
  96. const onDataFetched = (newData: Data) => {
  97. if (props.onDataFetched && newData.tableResults) {
  98. props.onDataFetched(newData.tableResults);
  99. }
  100. setData(newData);
  101. };
  102. const {
  103. api,
  104. organization,
  105. selection,
  106. widget,
  107. isMobile,
  108. renderErrorMessage,
  109. tableItemLimit,
  110. windowWidth,
  111. dashboardFilters,
  112. isWidgetInvalid,
  113. location,
  114. onWidgetSplitDecision,
  115. shouldResize,
  116. onLegendSelectChanged,
  117. onSetTransactionsDataset,
  118. legendOptions,
  119. widgetLegendState,
  120. } = props;
  121. if (widget.displayType === DisplayType.TOP_N) {
  122. const queries = widget.queries.map(query => ({
  123. ...query,
  124. // Use the last aggregate because that's where the y-axis is stored
  125. aggregates: query.aggregates.length
  126. ? [query.aggregates[query.aggregates.length - 1]]
  127. : [],
  128. }));
  129. widget.queries = queries;
  130. widget.limit = DEFAULT_RESULTS_LIMIT;
  131. }
  132. const hasSessionDuration = widget.queries.some(query =>
  133. query.aggregates.some(aggregate => aggregate.includes('session.duration'))
  134. );
  135. const {isMetricsData} = useDashboardsMEPContext();
  136. const extractionStatus = useExtractionStatus({queryKey: widget});
  137. const indexedEventsWarning = useIndexedEventsWarning();
  138. const onDemandWarning = useOnDemandWarning({widget});
  139. const discoverSplitAlert = useDiscoverSplitAlert({widget, onSetTransactionsDataset});
  140. const sessionDurationWarning = hasSessionDuration ? SESSION_DURATION_ALERT_TEXT : null;
  141. if (widget.widgetType === WidgetType.METRICS) {
  142. return (
  143. <MetricWidgetCard
  144. index={props.index}
  145. isEditingDashboard={props.isEditingDashboard}
  146. onEdit={props.onEdit}
  147. onDelete={props.onDelete}
  148. onDuplicate={props.onDuplicate}
  149. router={props.router}
  150. location={props.location}
  151. organization={organization}
  152. selection={selection}
  153. widget={widget}
  154. dashboardFilters={dashboardFilters}
  155. renderErrorMessage={renderErrorMessage}
  156. showContextMenu={props.showContextMenu}
  157. />
  158. );
  159. }
  160. const onFullScreenViewClick = () => {
  161. if (!isWidgetViewerPath(location.pathname)) {
  162. setWidgetViewerData({
  163. pageLinks: data?.pageLinks,
  164. seriesData: data?.timeseriesResults,
  165. tableData: data?.tableResults,
  166. seriesResultsType: data?.timeseriesResultsTypes,
  167. totalIssuesCount: data?.totalIssuesCount,
  168. });
  169. props.router.push({
  170. pathname: `${location.pathname}${
  171. location.pathname.endsWith('/') ? '' : '/'
  172. }widget/${props.index}/`,
  173. query: location.query,
  174. });
  175. }
  176. };
  177. const onDemandExtractionBadge: BadgeProps | undefined =
  178. extractionStatus === 'extracted'
  179. ? {
  180. text: t('Extracted'),
  181. }
  182. : extractionStatus === 'not-extracted'
  183. ? {
  184. text: t('Not Extracted'),
  185. }
  186. : undefined;
  187. const indexedDataBadge: BadgeProps | undefined = indexedEventsWarning
  188. ? {
  189. text: t('Indexed'),
  190. }
  191. : undefined;
  192. const badges = [indexedDataBadge, onDemandExtractionBadge].filter(
  193. Boolean
  194. ) as BadgeProps[];
  195. const warnings = [onDemandWarning, discoverSplitAlert, sessionDurationWarning].filter(
  196. Boolean
  197. ) as string[];
  198. const actionsDisabled = Boolean(props.isPreview);
  199. const actionsMessage = actionsDisabled
  200. ? t('This is a preview only. To edit, you must add this dashboard.')
  201. : undefined;
  202. const actions = props.showContextMenu
  203. ? getMenuOptions(
  204. organization,
  205. selection,
  206. widget,
  207. Boolean(isMetricsData),
  208. props.widgetLimitReached,
  209. props.hasEditAccess,
  210. props.onDelete,
  211. props.onDuplicate,
  212. props.onEdit
  213. )
  214. : [];
  215. const widgetQueryError = isWidgetInvalid
  216. ? t('Widget query condition is invalid.')
  217. : undefined;
  218. return (
  219. <ErrorBoundary
  220. customComponent={<ErrorCard>{t('Error loading widget data')}</ErrorCard>}
  221. >
  222. <VisuallyCompleteWithData
  223. id="DashboardList-FirstWidgetCard"
  224. hasData={
  225. ((data?.tableResults?.length || data?.timeseriesResults?.length) ?? 0) > 0
  226. }
  227. disabled={Number(props.index) !== 0}
  228. >
  229. {widget.displayType === DisplayType.BIG_NUMBER ? (
  230. <WidgetCardDataLoader
  231. widget={widget}
  232. selection={selection}
  233. dashboardFilters={dashboardFilters}
  234. onDataFetched={onDataFetched}
  235. onWidgetSplitDecision={onWidgetSplitDecision}
  236. tableItemLimit={tableItemLimit}
  237. >
  238. {({loading, errorMessage, tableResults}) => {
  239. // Big Number widgets only support one query, so we take the first query's results and meta
  240. const tableData = tableResults?.[0]?.data;
  241. const tableMeta = tableResults?.[0]?.meta as Meta | undefined;
  242. const fields = Object.keys(tableMeta?.fields ?? {});
  243. let field = fields[0];
  244. let selectedField = field;
  245. if (defined(widget.queries[0].selectedAggregate)) {
  246. const index = widget.queries[0].selectedAggregate;
  247. selectedField = widget.queries[0].aggregates[index];
  248. if (fields.includes(selectedField)) {
  249. field = selectedField;
  250. }
  251. }
  252. const value = tableData?.[0]?.[selectedField];
  253. return (
  254. <BigNumberWidget
  255. title={widget.title}
  256. description={widget.description}
  257. badgeProps={badges}
  258. warnings={warnings}
  259. actionsDisabled={actionsDisabled}
  260. actionsMessage={actionsMessage}
  261. actions={actions}
  262. onFullScreenViewClick={onFullScreenViewClick}
  263. isLoading={loading}
  264. thresholds={widget.thresholds ?? undefined}
  265. value={value}
  266. field={field}
  267. meta={tableMeta}
  268. error={widgetQueryError || errorMessage || undefined}
  269. preferredPolarity="-"
  270. />
  271. );
  272. }}
  273. </WidgetCardDataLoader>
  274. ) : (
  275. <WidgetFrame
  276. title={widget.title}
  277. description={widget.description}
  278. badgeProps={badges}
  279. warnings={warnings}
  280. actionsDisabled={actionsDisabled}
  281. error={widgetQueryError}
  282. actionsMessage={actionsMessage}
  283. actions={actions}
  284. onFullScreenViewClick={onFullScreenViewClick}
  285. >
  286. <WidgetCardChartContainer
  287. location={location}
  288. api={api}
  289. organization={organization}
  290. selection={selection}
  291. widget={widget}
  292. isMobile={isMobile}
  293. renderErrorMessage={renderErrorMessage}
  294. tableItemLimit={tableItemLimit}
  295. windowWidth={windowWidth}
  296. onDataFetched={onDataFetched}
  297. dashboardFilters={dashboardFilters}
  298. chartGroup={DASHBOARD_CHART_GROUP}
  299. onWidgetSplitDecision={onWidgetSplitDecision}
  300. shouldResize={shouldResize}
  301. onLegendSelectChanged={onLegendSelectChanged}
  302. legendOptions={legendOptions}
  303. widgetLegendState={widgetLegendState}
  304. />
  305. </WidgetFrame>
  306. )}
  307. </VisuallyCompleteWithData>
  308. </ErrorBoundary>
  309. );
  310. }
  311. export default withApi(withOrganization(withPageFilters(withSentryRouter(WidgetCard))));
  312. function useOnDemandWarning(props: {widget: Widget}): string | null {
  313. const organization = useOrganization();
  314. if (!hasOnDemandMetricWidgetFeature(organization)) {
  315. return null;
  316. }
  317. // prettier-ignore
  318. const widgetContainsHighCardinality = props.widget.queries.some(
  319. wq =>
  320. wq.onDemand?.some(
  321. d => d.extractionState === OnDemandExtractionState.DISABLED_HIGH_CARDINALITY
  322. )
  323. );
  324. // prettier-ignore
  325. const widgetReachedSpecLimit = props.widget.queries.some(
  326. wq =>
  327. wq.onDemand?.some(
  328. d => d.extractionState === OnDemandExtractionState.DISABLED_SPEC_LIMIT
  329. )
  330. );
  331. if (widgetContainsHighCardinality) {
  332. return t(
  333. 'This widget is using indexed data because it has a column with too many unique values.'
  334. );
  335. }
  336. if (widgetReachedSpecLimit) {
  337. return t(
  338. "This widget is using indexed data because you've reached your organization limit for dynamically extracted metrics."
  339. );
  340. }
  341. return null;
  342. }
  343. const ErrorCard = styled(Placeholder)`
  344. display: flex;
  345. align-items: center;
  346. justify-content: center;
  347. background-color: ${p => p.theme.alert.error.backgroundLight};
  348. border: 1px solid ${p => p.theme.alert.error.border};
  349. color: ${p => p.theme.alert.error.textLight};
  350. border-radius: ${p => p.theme.borderRadius};
  351. margin-bottom: ${space(2)};
  352. `;
  353. export const WidgetCardContextMenuContainer = styled('div')`
  354. opacity: 1;
  355. transition: opacity 0.1s;
  356. `;
  357. export const WidgetCardPanel = styled(Panel, {
  358. shouldForwardProp: prop => prop !== 'isDragging',
  359. })<{
  360. isDragging: boolean;
  361. }>`
  362. margin: 0;
  363. visibility: ${p => (p.isDragging ? 'hidden' : 'visible')};
  364. /* If a panel overflows due to a long title stretch its grid sibling */
  365. height: 100%;
  366. min-height: 96px;
  367. display: flex;
  368. flex-direction: column;
  369. &:not(:hover):not(:focus-within) {
  370. ${WidgetCardContextMenuContainer} {
  371. opacity: 0;
  372. ${p => p.theme.visuallyHidden}
  373. }
  374. }
  375. :hover {
  376. background-color: ${p => p.theme.surface200};
  377. transition:
  378. background-color 100ms linear,
  379. box-shadow 100ms linear;
  380. box-shadow: ${p => p.theme.dropShadowLight};
  381. }
  382. `;
  383. export const WidgetTitleRow = styled('span')`
  384. display: flex;
  385. align-items: center;
  386. gap: ${space(0.75)};
  387. `;
  388. export const WidgetDescription = styled('small')`
  389. ${p => p.theme.overflowEllipsis}
  390. color: ${p => p.theme.gray300};
  391. `;