index.tsx 14 KB

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