index.tsx 14 KB

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