widgetViewerModal.tsx 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  1. import {Fragment, memo, useEffect, useMemo, useRef, useState} from 'react';
  2. // eslint-disable-next-line no-restricted-imports
  3. import {withRouter, WithRouterProps} from 'react-router';
  4. import {components} from 'react-select';
  5. import {css} from '@emotion/react';
  6. import styled from '@emotion/styled';
  7. import * as Sentry from '@sentry/react';
  8. import {truncate} from '@sentry/utils';
  9. import type {DataZoomComponentOption} from 'echarts';
  10. import {Location} from 'history';
  11. import cloneDeep from 'lodash/cloneDeep';
  12. import isEqual from 'lodash/isEqual';
  13. import trimStart from 'lodash/trimStart';
  14. import moment from 'moment';
  15. import {fetchTotalCount} from 'sentry/actionCreators/events';
  16. import {ModalRenderProps} from 'sentry/actionCreators/modal';
  17. import {Client} from 'sentry/api';
  18. import Alert from 'sentry/components/alert';
  19. import Button from 'sentry/components/button';
  20. import ButtonBar from 'sentry/components/buttonBar';
  21. import SelectControl from 'sentry/components/forms/selectControl';
  22. import Option from 'sentry/components/forms/selectOption';
  23. import GridEditable, {
  24. COL_WIDTH_UNDEFINED,
  25. GridColumnOrder,
  26. } from 'sentry/components/gridEditable';
  27. import Pagination from 'sentry/components/pagination';
  28. import QuestionTooltip from 'sentry/components/questionTooltip';
  29. import {parseSearch} from 'sentry/components/searchSyntax/parser';
  30. import HighlightQuery from 'sentry/components/searchSyntax/renderer';
  31. import {t, tct} from 'sentry/locale';
  32. import space from 'sentry/styles/space';
  33. import {Organization, PageFilters, SelectValue} from 'sentry/types';
  34. import {Series} from 'sentry/types/echarts';
  35. import {defined} from 'sentry/utils';
  36. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  37. import {getUtcDateString} from 'sentry/utils/dates';
  38. import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  39. import EventView from 'sentry/utils/discover/eventView';
  40. import {
  41. isAggregateField,
  42. isEquation,
  43. isEquationAlias,
  44. } from 'sentry/utils/discover/fields';
  45. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  46. import {decodeInteger, decodeList, decodeScalar} from 'sentry/utils/queryString';
  47. import useApi from 'sentry/utils/useApi';
  48. import withPageFilters from 'sentry/utils/withPageFilters';
  49. import {DisplayType, Widget, WidgetType} from 'sentry/views/dashboardsV2/types';
  50. import {
  51. eventViewFromWidget,
  52. getFieldsFromEquations,
  53. getNumEquations,
  54. getWidgetDiscoverUrl,
  55. getWidgetIssueUrl,
  56. getWidgetReleasesUrl,
  57. isCustomMeasurementWidget,
  58. } from 'sentry/views/dashboardsV2/utils';
  59. import WidgetCardChart, {
  60. AugmentedEChartDataZoomHandler,
  61. SLIDER_HEIGHT,
  62. } from 'sentry/views/dashboardsV2/widgetCard/chart';
  63. import {
  64. DashboardsMEPProvider,
  65. useDashboardsMEPContext,
  66. } from 'sentry/views/dashboardsV2/widgetCard/dashboardsMEPContext';
  67. import {GenericWidgetQueriesChildrenProps} from 'sentry/views/dashboardsV2/widgetCard/genericWidgetQueries';
  68. import IssueWidgetQueries from 'sentry/views/dashboardsV2/widgetCard/issueWidgetQueries';
  69. import ReleaseWidgetQueries from 'sentry/views/dashboardsV2/widgetCard/releaseWidgetQueries';
  70. import {WidgetCardChartContainer} from 'sentry/views/dashboardsV2/widgetCard/widgetCardChartContainer';
  71. import WidgetQueries from 'sentry/views/dashboardsV2/widgetCard/widgetQueries';
  72. import {decodeColumnOrder} from 'sentry/views/eventsV2/utils';
  73. import {WidgetViewerQueryField} from './widgetViewerModal/utils';
  74. import {
  75. renderDiscoverGridHeaderCell,
  76. renderGridBodyCell,
  77. renderIssueGridHeaderCell,
  78. renderReleaseGridHeaderCell,
  79. } from './widgetViewerModal/widgetViewerTableCell';
  80. export interface WidgetViewerModalOptions {
  81. organization: Organization;
  82. widget: Widget;
  83. onEdit?: () => void;
  84. pageLinks?: string;
  85. seriesData?: Series[];
  86. seriesResultsType?: string;
  87. tableData?: TableDataWithTitle[];
  88. totalIssuesCount?: string;
  89. }
  90. interface Props extends ModalRenderProps, WithRouterProps, WidgetViewerModalOptions {
  91. organization: Organization;
  92. selection: PageFilters;
  93. }
  94. const FULL_TABLE_ITEM_LIMIT = 20;
  95. const HALF_TABLE_ITEM_LIMIT = 10;
  96. const GEO_COUNTRY_CODE = 'geo.country_code';
  97. const HALF_CONTAINER_HEIGHT = 300;
  98. const EMPTY_QUERY_NAME = '(Empty Query Condition)';
  99. const shouldWidgetCardChartMemo = (prevProps, props) => {
  100. const selectionMatches = props.selection === prevProps.selection;
  101. const sortMatches =
  102. props.location.query[WidgetViewerQueryField.SORT] ===
  103. prevProps.location.query[WidgetViewerQueryField.SORT];
  104. const chartZoomOptionsMatches = isEqual(
  105. props.chartZoomOptions,
  106. prevProps.chartZoomOptions
  107. );
  108. const isNotTopNWidget =
  109. props.widget.displayType !== DisplayType.TOP_N && !defined(props.widget.limit);
  110. return selectionMatches && chartZoomOptionsMatches && (sortMatches || isNotTopNWidget);
  111. };
  112. // WidgetCardChartContainer and WidgetCardChart rerenders if selection was changed.
  113. // This is required because we want to prevent ECharts interactions from causing
  114. // unnecessary rerenders which can break legends and zoom functionality.
  115. const MemoizedWidgetCardChartContainer = memo(
  116. WidgetCardChartContainer,
  117. shouldWidgetCardChartMemo
  118. );
  119. const MemoizedWidgetCardChart = memo(WidgetCardChart, shouldWidgetCardChartMemo);
  120. async function fetchDiscoverTotal(
  121. api: Client,
  122. organization: Organization,
  123. location: Location,
  124. eventView: EventView
  125. ): Promise<string | undefined> {
  126. if (!eventView.isValid()) {
  127. return undefined;
  128. }
  129. try {
  130. const total = await fetchTotalCount(
  131. api,
  132. organization.slug,
  133. eventView.getEventsAPIPayload(location)
  134. );
  135. return total.toLocaleString();
  136. } catch (err) {
  137. Sentry.captureException(err);
  138. return undefined;
  139. }
  140. }
  141. function WidgetViewerModal(props: Props) {
  142. const {
  143. organization,
  144. widget,
  145. selection,
  146. location,
  147. Footer,
  148. Body,
  149. Header,
  150. closeModal,
  151. onEdit,
  152. router,
  153. routes,
  154. params,
  155. seriesData,
  156. tableData,
  157. totalIssuesCount,
  158. pageLinks: defaultPageLinks,
  159. seriesResultsType,
  160. } = props;
  161. const shouldShowSlider = organization.features.includes('widget-viewer-modal-minimap');
  162. // Get widget zoom from location
  163. // We use the start and end query params for just the initial state
  164. const start = decodeScalar(location.query[WidgetViewerQueryField.START]);
  165. const end = decodeScalar(location.query[WidgetViewerQueryField.END]);
  166. const isTableWidget = widget.displayType === DisplayType.TABLE;
  167. const locationPageFilter = useMemo(
  168. () =>
  169. start && end
  170. ? {
  171. ...selection,
  172. datetime: {start, end, period: null, utc: null},
  173. }
  174. : selection,
  175. [start, end, selection]
  176. );
  177. const [chartUnmodified, setChartUnmodified] = useState<boolean>(true);
  178. const [chartZoomOptions, setChartZoomOptions] = useState<DataZoomComponentOption>({
  179. start: 0,
  180. end: 100,
  181. });
  182. // We wrap the modalChartSelection in a useRef because we do not want to recalculate this value
  183. // (which would cause an unnecessary rerender on calculation) except for the initial load.
  184. // We use this for when a user visit a widget viewer url directly.
  185. const [modalTableSelection, setModalTableSelection] =
  186. useState<PageFilters>(locationPageFilter);
  187. const modalChartSelection = useRef(modalTableSelection);
  188. // Detect when a user clicks back and set the PageFilter state to match the location
  189. // We need to use useEffect to prevent infinite looping rerenders due to the setModalTableSelection call
  190. useEffect(() => {
  191. if (location.action === 'POP') {
  192. setModalTableSelection(locationPageFilter);
  193. if (start && end) {
  194. setChartZoomOptions({
  195. startValue: moment.utc(start).unix() * 1000,
  196. endValue: moment.utc(end).unix() * 1000,
  197. });
  198. } else {
  199. setChartZoomOptions({start: 0, end: 100});
  200. }
  201. }
  202. }, [end, location, locationPageFilter, start]);
  203. // Get legends toggle settings from location
  204. // We use the legend query params for just the initial state
  205. const [disabledLegends, setDisabledLegends] = useState<{[key: string]: boolean}>(
  206. decodeList(location.query[WidgetViewerQueryField.LEGEND]).reduce((acc, legend) => {
  207. acc[legend] = false;
  208. return acc;
  209. }, {})
  210. );
  211. const [totalResults, setTotalResults] = useState<string | undefined>();
  212. // Get query selection settings from location
  213. const selectedQueryIndex =
  214. decodeInteger(location.query[WidgetViewerQueryField.QUERY]) ?? 0;
  215. // Get pagination settings from location
  216. const page = decodeInteger(location.query[WidgetViewerQueryField.PAGE]) ?? 0;
  217. const cursor = decodeScalar(location.query[WidgetViewerQueryField.CURSOR]);
  218. // Get table column widths from location
  219. const widths = decodeList(location.query[WidgetViewerQueryField.WIDTH]);
  220. // Get table sort settings from location
  221. const sort = decodeScalar(location.query[WidgetViewerQueryField.SORT]);
  222. const sortedQueries = cloneDeep(
  223. sort ? widget.queries.map(query => ({...query, orderby: sort})) : widget.queries
  224. );
  225. // Top N widget charts (including widgets with limits) results rely on the sorting of the query
  226. // Set the orderby of the widget chart to match the location query params
  227. const primaryWidget =
  228. widget.displayType === DisplayType.TOP_N || widget.limit !== undefined
  229. ? {...widget, queries: sortedQueries}
  230. : widget;
  231. const api = useApi();
  232. // Create Table widget
  233. const tableWidget = {
  234. ...cloneDeep({...widget, queries: [sortedQueries[selectedQueryIndex]]}),
  235. displayType: DisplayType.TABLE,
  236. };
  237. const {aggregates, columns} = tableWidget.queries[0];
  238. const {orderby} = widget.queries[0];
  239. const order = orderby.startsWith('-');
  240. const rawOrderby = trimStart(orderby, '-');
  241. const fields = defined(tableWidget.queries[0].fields)
  242. ? tableWidget.queries[0].fields
  243. : [...columns, ...aggregates];
  244. // Some Discover Widgets (Line, Area, Bar) allow the user to specify an orderby
  245. // that is not explicitly selected as an aggregate or column. We need to explicitly
  246. // include the orderby in the table widget aggregates and columns otherwise
  247. // eventsv2 will complain about sorting on an unselected field.
  248. if (
  249. widget.widgetType === WidgetType.DISCOVER &&
  250. orderby &&
  251. !isEquationAlias(rawOrderby) &&
  252. !fields.includes(rawOrderby)
  253. ) {
  254. fields.push(rawOrderby);
  255. [tableWidget, primaryWidget].forEach(aggregatesAndColumns => {
  256. if (isAggregateField(rawOrderby) || isEquation(rawOrderby)) {
  257. aggregatesAndColumns.queries.forEach(query => {
  258. if (!query.aggregates.includes(rawOrderby)) {
  259. query.aggregates.push(rawOrderby);
  260. }
  261. });
  262. } else {
  263. aggregatesAndColumns.queries.forEach(query => {
  264. if (!query.columns.includes(rawOrderby)) {
  265. query.columns.push(rawOrderby);
  266. }
  267. });
  268. }
  269. });
  270. }
  271. // Need to set the orderby of the eventsv2 query to equation[index] format
  272. // since eventsv2 does not accept the raw equation as a valid sort payload
  273. if (isEquation(rawOrderby) && tableWidget.queries[0].orderby === orderby) {
  274. tableWidget.queries[0].orderby = `${order ? '-' : ''}equation[${
  275. getNumEquations(fields) - 1
  276. }]`;
  277. }
  278. // World Map view should always have geo.country in the table chart
  279. if (
  280. widget.displayType === DisplayType.WORLD_MAP &&
  281. !columns.includes(GEO_COUNTRY_CODE)
  282. ) {
  283. fields.unshift(GEO_COUNTRY_CODE);
  284. columns.unshift(GEO_COUNTRY_CODE);
  285. }
  286. // Default table columns for visualizations that don't have a column setting
  287. const shouldReplaceTableColumns =
  288. [
  289. DisplayType.AREA,
  290. DisplayType.LINE,
  291. DisplayType.BIG_NUMBER,
  292. DisplayType.BAR,
  293. ].includes(widget.displayType) &&
  294. widget.widgetType &&
  295. [WidgetType.DISCOVER, WidgetType.RELEASE].includes(widget.widgetType) &&
  296. !defined(widget.limit);
  297. // Updates fields by adding any individual terms from equation fields as a column
  298. if (!isTableWidget) {
  299. const equationFields = getFieldsFromEquations(fields);
  300. equationFields.forEach(term => {
  301. if (isAggregateField(term) && !aggregates.includes(term)) {
  302. aggregates.unshift(term);
  303. }
  304. if (!isAggregateField(term) && !columns.includes(term)) {
  305. columns.unshift(term);
  306. }
  307. });
  308. }
  309. // Add any group by columns into table fields if missing
  310. columns.forEach(column => {
  311. if (!fields.includes(column)) {
  312. fields.unshift(column);
  313. }
  314. });
  315. if (shouldReplaceTableColumns) {
  316. switch (widget.widgetType) {
  317. case WidgetType.DISCOVER:
  318. if (fields.length === 1) {
  319. tableWidget.queries[0].orderby =
  320. tableWidget.queries[0].orderby || `-${fields[0]}`;
  321. }
  322. fields.unshift('title');
  323. columns.unshift('title');
  324. break;
  325. case WidgetType.RELEASE:
  326. fields.unshift('release');
  327. columns.unshift('release');
  328. break;
  329. default:
  330. break;
  331. }
  332. }
  333. const eventView = eventViewFromWidget(
  334. tableWidget.title,
  335. tableWidget.queries[0],
  336. modalTableSelection,
  337. tableWidget.displayType
  338. );
  339. let columnOrder = decodeColumnOrder(
  340. fields.map(field => ({
  341. field,
  342. })),
  343. organization.features.includes('discover-frontend-use-events-endpoint')
  344. );
  345. const columnSortBy = eventView.getSorts();
  346. columnOrder = columnOrder.map((column, index) => ({
  347. ...column,
  348. width: parseInt(widths[index], 10) || -1,
  349. }));
  350. const queryOptions = sortedQueries.map(({name, conditions}, index) => {
  351. // Creates the highlighted query elements to be used in the Query Select
  352. const parsedQuery = !!!name && !!conditions ? parseSearch(conditions) : null;
  353. const getHighlightedQuery = (
  354. highlightedContainerProps: React.ComponentProps<typeof HighlightContainer>
  355. ) => {
  356. return parsedQuery !== null ? (
  357. <HighlightContainer {...highlightedContainerProps}>
  358. <HighlightQuery parsedQuery={parsedQuery} />
  359. </HighlightContainer>
  360. ) : undefined;
  361. };
  362. return {
  363. label: truncate(name || conditions, 120),
  364. value: index,
  365. getHighlightedQuery,
  366. };
  367. });
  368. const onResizeColumn = (columnIndex: number, nextColumn: GridColumnOrder) => {
  369. const newWidth = nextColumn.width ? Number(nextColumn.width) : COL_WIDTH_UNDEFINED;
  370. const newWidths: number[] = new Array(Math.max(columnIndex, widths.length)).fill(
  371. COL_WIDTH_UNDEFINED
  372. );
  373. widths.forEach((width, index) => (newWidths[index] = parseInt(width, 10)));
  374. newWidths[columnIndex] = newWidth;
  375. router.replace({
  376. pathname: location.pathname,
  377. query: {
  378. ...location.query,
  379. [WidgetViewerQueryField.WIDTH]: newWidths,
  380. },
  381. });
  382. };
  383. // Get discover result totals
  384. useEffect(() => {
  385. const getDiscoverTotals = async () => {
  386. if (widget.widgetType === WidgetType.DISCOVER) {
  387. setTotalResults(await fetchDiscoverTotal(api, organization, location, eventView));
  388. }
  389. };
  390. getDiscoverTotals();
  391. // Disabling this for now since this effect should only run on initial load and query index changes
  392. // Including all exhaustive deps would cause fetchDiscoverTotal on nearly every update
  393. // eslint-disable-next-line react-hooks/exhaustive-deps
  394. }, [selectedQueryIndex]);
  395. function onLegendSelectChanged({selected}: {selected: Record<string, boolean>}) {
  396. setDisabledLegends(selected);
  397. router.replace({
  398. pathname: location.pathname,
  399. query: {
  400. ...location.query,
  401. [WidgetViewerQueryField.LEGEND]: Object.keys(selected).filter(
  402. key => !selected[key]
  403. ),
  404. },
  405. });
  406. trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.toggle_legend', {
  407. organization,
  408. widget_type: widget.widgetType ?? WidgetType.DISCOVER,
  409. display_type: widget.displayType,
  410. });
  411. }
  412. const renderDiscoverTable = ({
  413. tableResults,
  414. loading,
  415. pageLinks,
  416. }: GenericWidgetQueriesChildrenProps) => {
  417. const links = parseLinkHeader(pageLinks ?? null);
  418. const isFirstPage = links.previous?.results === false;
  419. return (
  420. <Fragment>
  421. <GridEditable
  422. isLoading={loading}
  423. data={tableResults?.[0]?.data ?? []}
  424. columnOrder={columnOrder}
  425. columnSortBy={columnSortBy}
  426. grid={{
  427. renderHeadCell: renderDiscoverGridHeaderCell({
  428. ...props,
  429. widget: tableWidget,
  430. tableData: tableResults?.[0],
  431. onHeaderClick: () => {
  432. if (
  433. [DisplayType.TOP_N, DisplayType.TABLE].includes(widget.displayType) ||
  434. defined(widget.limit)
  435. ) {
  436. setChartUnmodified(false);
  437. }
  438. },
  439. }) as (column: GridColumnOrder, columnIndex: number) => React.ReactNode,
  440. renderBodyCell: renderGridBodyCell({
  441. ...props,
  442. tableData: tableResults?.[0],
  443. isFirstPage,
  444. }),
  445. onResizeColumn,
  446. }}
  447. location={location}
  448. />
  449. {(links?.previous?.results || links?.next?.results) && (
  450. <Pagination
  451. pageLinks={pageLinks}
  452. onCursor={newCursor => {
  453. router.replace({
  454. pathname: location.pathname,
  455. query: {
  456. ...location.query,
  457. [WidgetViewerQueryField.CURSOR]: newCursor,
  458. },
  459. });
  460. if (widget.displayType === DisplayType.TABLE) {
  461. setChartUnmodified(false);
  462. }
  463. trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.paginate', {
  464. organization,
  465. widget_type: WidgetType.DISCOVER,
  466. display_type: widget.displayType,
  467. });
  468. }}
  469. />
  470. )}
  471. </Fragment>
  472. );
  473. };
  474. const renderIssuesTable = ({
  475. tableResults,
  476. loading,
  477. pageLinks,
  478. totalCount,
  479. }: GenericWidgetQueriesChildrenProps) => {
  480. if (totalResults === undefined && totalCount) {
  481. setTotalResults(totalCount);
  482. }
  483. const links = parseLinkHeader(pageLinks ?? null);
  484. return (
  485. <Fragment>
  486. <GridEditable
  487. isLoading={loading}
  488. data={tableResults?.[0]?.data ?? []}
  489. columnOrder={columnOrder}
  490. columnSortBy={columnSortBy}
  491. grid={{
  492. renderHeadCell: renderIssueGridHeaderCell({
  493. location,
  494. organization,
  495. selection,
  496. widget: tableWidget,
  497. onHeaderClick: () => {
  498. setChartUnmodified(false);
  499. },
  500. }) as (column: GridColumnOrder, columnIndex: number) => React.ReactNode,
  501. renderBodyCell: renderGridBodyCell({
  502. location,
  503. organization,
  504. selection,
  505. widget: tableWidget,
  506. }),
  507. onResizeColumn,
  508. }}
  509. location={location}
  510. />
  511. {(links?.previous?.results || links?.next?.results) && (
  512. <Pagination
  513. pageLinks={pageLinks}
  514. onCursor={(nextCursor, _path, _query, delta) => {
  515. let nextPage = isNaN(page) ? delta : page + delta;
  516. let newCursor = nextCursor;
  517. // unset cursor and page when we navigate back to the first page
  518. // also reset cursor if somehow the previous button is enabled on
  519. // first page and user attempts to go backwards
  520. if (nextPage <= 0) {
  521. newCursor = undefined;
  522. nextPage = 0;
  523. }
  524. router.replace({
  525. pathname: location.pathname,
  526. query: {
  527. ...location.query,
  528. [WidgetViewerQueryField.CURSOR]: newCursor,
  529. [WidgetViewerQueryField.PAGE]: nextPage,
  530. },
  531. });
  532. if (widget.displayType === DisplayType.TABLE) {
  533. setChartUnmodified(false);
  534. }
  535. trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.paginate', {
  536. organization,
  537. widget_type: WidgetType.ISSUE,
  538. display_type: widget.displayType,
  539. });
  540. }}
  541. />
  542. )}
  543. </Fragment>
  544. );
  545. };
  546. const renderReleaseTable: ReleaseWidgetQueries['props']['children'] = ({
  547. tableResults,
  548. loading,
  549. pageLinks,
  550. }) => {
  551. const links = parseLinkHeader(pageLinks ?? null);
  552. const isFirstPage = links.previous?.results === false;
  553. return (
  554. <Fragment>
  555. <GridEditable
  556. isLoading={loading}
  557. data={tableResults?.[0]?.data ?? []}
  558. columnOrder={columnOrder}
  559. columnSortBy={columnSortBy}
  560. grid={{
  561. renderHeadCell: renderReleaseGridHeaderCell({
  562. ...props,
  563. widget: tableWidget,
  564. tableData: tableResults?.[0],
  565. onHeaderClick: () => {
  566. if (
  567. [DisplayType.TOP_N, DisplayType.TABLE].includes(widget.displayType) ||
  568. defined(widget.limit)
  569. ) {
  570. setChartUnmodified(false);
  571. }
  572. },
  573. }) as (column: GridColumnOrder, columnIndex: number) => React.ReactNode,
  574. renderBodyCell: renderGridBodyCell({
  575. ...props,
  576. tableData: tableResults?.[0],
  577. isFirstPage,
  578. }),
  579. onResizeColumn,
  580. }}
  581. location={location}
  582. />
  583. {!tableWidget.queries[0].orderby.match(/^-?release$/) &&
  584. (links?.previous?.results || links?.next?.results) && (
  585. <Pagination
  586. pageLinks={pageLinks}
  587. onCursor={newCursor => {
  588. router.replace({
  589. pathname: location.pathname,
  590. query: {
  591. ...location.query,
  592. [WidgetViewerQueryField.CURSOR]: newCursor,
  593. },
  594. });
  595. trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.paginate', {
  596. organization,
  597. widget_type: WidgetType.RELEASE,
  598. display_type: widget.displayType,
  599. });
  600. }}
  601. />
  602. )}
  603. </Fragment>
  604. );
  605. };
  606. const onZoom: AugmentedEChartDataZoomHandler = (evt, chart) => {
  607. // @ts-ignore getModel() is private but we need this to retrieve datetime values of zoomed in region
  608. const model = chart.getModel();
  609. const {seriesStart, seriesEnd} = evt;
  610. let startValue, endValue;
  611. startValue = model._payload.batch?.[0].startValue;
  612. endValue = model._payload.batch?.[0].endValue;
  613. const seriesStartTime = seriesStart ? new Date(seriesStart).getTime() : undefined;
  614. const seriesEndTime = seriesEnd ? new Date(seriesEnd).getTime() : undefined;
  615. // Slider zoom events don't contain the raw date time value, only the percentage
  616. // We use the percentage with the start and end of the series to calculate the adjusted zoom
  617. if (startValue === undefined || endValue === undefined) {
  618. if (seriesStartTime && seriesEndTime) {
  619. const diff = seriesEndTime - seriesStartTime;
  620. startValue = diff * model._payload.start * 0.01 + seriesStartTime;
  621. endValue = diff * model._payload.end * 0.01 + seriesStartTime;
  622. } else {
  623. return;
  624. }
  625. }
  626. setChartZoomOptions({startValue, endValue});
  627. const newStart = getUtcDateString(moment.utc(startValue));
  628. const newEnd = getUtcDateString(moment.utc(endValue));
  629. setModalTableSelection({
  630. ...modalTableSelection,
  631. datetime: {
  632. ...modalTableSelection.datetime,
  633. start: newStart,
  634. end: newEnd,
  635. period: null,
  636. },
  637. });
  638. router.push({
  639. pathname: location.pathname,
  640. query: {
  641. ...location.query,
  642. [WidgetViewerQueryField.START]: newStart,
  643. [WidgetViewerQueryField.END]: newEnd,
  644. },
  645. });
  646. trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.zoom', {
  647. organization,
  648. widget_type: widget.widgetType ?? WidgetType.DISCOVER,
  649. display_type: widget.displayType,
  650. });
  651. };
  652. function renderWidgetViewerTable() {
  653. switch (widget.widgetType) {
  654. case WidgetType.ISSUE:
  655. if (tableData && chartUnmodified && widget.displayType === DisplayType.TABLE) {
  656. return renderIssuesTable({
  657. tableResults: tableData,
  658. loading: false,
  659. errorMessage: undefined,
  660. pageLinks: defaultPageLinks,
  661. totalCount: totalIssuesCount,
  662. });
  663. }
  664. return (
  665. <IssueWidgetQueries
  666. api={api}
  667. organization={organization}
  668. widget={tableWidget}
  669. selection={modalTableSelection}
  670. limit={
  671. widget.displayType === DisplayType.TABLE
  672. ? FULL_TABLE_ITEM_LIMIT
  673. : HALF_TABLE_ITEM_LIMIT
  674. }
  675. cursor={cursor}
  676. >
  677. {renderIssuesTable}
  678. </IssueWidgetQueries>
  679. );
  680. case WidgetType.RELEASE:
  681. if (tableData && chartUnmodified && widget.displayType === DisplayType.TABLE) {
  682. return renderReleaseTable({
  683. tableResults: tableData,
  684. loading: false,
  685. pageLinks: defaultPageLinks,
  686. });
  687. }
  688. return (
  689. <ReleaseWidgetQueries
  690. api={api}
  691. organization={organization}
  692. widget={tableWidget}
  693. selection={modalTableSelection}
  694. limit={
  695. widget.displayType === DisplayType.TABLE
  696. ? FULL_TABLE_ITEM_LIMIT
  697. : HALF_TABLE_ITEM_LIMIT
  698. }
  699. cursor={cursor}
  700. >
  701. {renderReleaseTable}
  702. </ReleaseWidgetQueries>
  703. );
  704. case WidgetType.DISCOVER:
  705. default:
  706. if (tableData && chartUnmodified && widget.displayType === DisplayType.TABLE) {
  707. return renderDiscoverTable({
  708. tableResults: tableData,
  709. loading: false,
  710. pageLinks: defaultPageLinks,
  711. });
  712. }
  713. return (
  714. <WidgetQueries
  715. api={api}
  716. organization={organization}
  717. widget={tableWidget}
  718. selection={modalTableSelection}
  719. limit={
  720. widget.displayType === DisplayType.TABLE
  721. ? FULL_TABLE_ITEM_LIMIT
  722. : HALF_TABLE_ITEM_LIMIT
  723. }
  724. cursor={cursor}
  725. >
  726. {renderDiscoverTable}
  727. </WidgetQueries>
  728. );
  729. }
  730. }
  731. function renderWidgetViewer() {
  732. return (
  733. <Fragment>
  734. {widget.displayType !== DisplayType.TABLE && (
  735. <Container
  736. height={
  737. widget.displayType !== DisplayType.BIG_NUMBER
  738. ? HALF_CONTAINER_HEIGHT +
  739. (shouldShowSlider &&
  740. [
  741. DisplayType.AREA,
  742. DisplayType.LINE,
  743. DisplayType.BAR,
  744. DisplayType.TOP_N,
  745. ].includes(widget.displayType)
  746. ? SLIDER_HEIGHT
  747. : 0)
  748. : null
  749. }
  750. >
  751. {(!!seriesData || !!tableData) && chartUnmodified ? (
  752. <MemoizedWidgetCardChart
  753. timeseriesResults={seriesData}
  754. timeseriesResultsType={seriesResultsType}
  755. tableResults={tableData}
  756. errorMessage={undefined}
  757. loading={false}
  758. location={location}
  759. widget={widget}
  760. selection={selection}
  761. router={router}
  762. organization={organization}
  763. onZoom={onZoom}
  764. onLegendSelectChanged={onLegendSelectChanged}
  765. legendOptions={{selected: disabledLegends}}
  766. expandNumbers
  767. showSlider={shouldShowSlider}
  768. noPadding
  769. chartZoomOptions={chartZoomOptions}
  770. />
  771. ) : (
  772. <MemoizedWidgetCardChartContainer
  773. location={location}
  774. router={router}
  775. routes={routes}
  776. params={params}
  777. api={api}
  778. organization={organization}
  779. selection={modalChartSelection.current}
  780. // Top N charts rely on the orderby of the table
  781. widget={primaryWidget}
  782. onZoom={onZoom}
  783. onLegendSelectChanged={onLegendSelectChanged}
  784. legendOptions={{selected: disabledLegends}}
  785. expandNumbers
  786. showSlider={shouldShowSlider}
  787. noPadding
  788. chartZoomOptions={chartZoomOptions}
  789. />
  790. )}
  791. </Container>
  792. )}
  793. {widget.queries.length > 1 && (
  794. <Alert type="info" showIcon>
  795. {t(
  796. 'This widget was built with multiple queries. Table data can only be displayed for one query at a time. To edit any of the queries, edit the widget.'
  797. )}
  798. </Alert>
  799. )}
  800. {(widget.queries.length > 1 || widget.queries[0].conditions) && (
  801. <QueryContainer>
  802. <SelectControl
  803. value={selectedQueryIndex}
  804. options={queryOptions}
  805. onChange={(option: SelectValue<number>) => {
  806. router.replace({
  807. pathname: location.pathname,
  808. query: {
  809. ...location.query,
  810. [WidgetViewerQueryField.QUERY]: option.value,
  811. [WidgetViewerQueryField.PAGE]: undefined,
  812. [WidgetViewerQueryField.CURSOR]: undefined,
  813. },
  814. });
  815. trackAdvancedAnalyticsEvent(
  816. 'dashboards_views.widget_viewer.select_query',
  817. {
  818. organization,
  819. widget_type: widget.widgetType ?? WidgetType.DISCOVER,
  820. display_type: widget.displayType,
  821. }
  822. );
  823. }}
  824. components={{
  825. // Replaces the displayed selected value
  826. SingleValue: containerProps => {
  827. return (
  828. <components.SingleValue
  829. {...containerProps}
  830. // Overwrites some of the default styling that interferes with highlighted query text
  831. getStyles={() => ({
  832. wordBreak: 'break-word',
  833. flex: 1,
  834. display: 'flex',
  835. padding: `0 ${space(0.5)}`,
  836. })}
  837. >
  838. {queryOptions[selectedQueryIndex].getHighlightedQuery({
  839. display: 'block',
  840. }) ??
  841. (queryOptions[selectedQueryIndex].label || (
  842. <EmptyQueryContainer>{EMPTY_QUERY_NAME}</EmptyQueryContainer>
  843. ))}
  844. </components.SingleValue>
  845. );
  846. },
  847. // Replaces the dropdown options
  848. Option: containerProps => {
  849. const highlightedQuery = containerProps.data.getHighlightedQuery({
  850. display: 'flex',
  851. });
  852. return (
  853. <Option
  854. {...(highlightedQuery
  855. ? {
  856. ...containerProps,
  857. label: highlightedQuery,
  858. }
  859. : containerProps.label
  860. ? containerProps
  861. : {
  862. ...containerProps,
  863. label: (
  864. <EmptyQueryContainer>
  865. {EMPTY_QUERY_NAME}
  866. </EmptyQueryContainer>
  867. ),
  868. })}
  869. />
  870. );
  871. },
  872. // Hide the dropdown indicator if there is only one option
  873. ...(widget.queries.length < 2 ? {IndicatorsContainer: _ => null} : {}),
  874. }}
  875. isSearchable={false}
  876. isDisabled={widget.queries.length < 2}
  877. />
  878. {widget.queries.length === 1 && (
  879. <StyledQuestionTooltip
  880. title={t('To edit this query, you must edit the widget.')}
  881. size="sm"
  882. />
  883. )}
  884. </QueryContainer>
  885. )}
  886. {renderWidgetViewerTable()}
  887. </Fragment>
  888. );
  889. }
  890. return (
  891. <Fragment>
  892. <DashboardsMEPProvider>
  893. <Header closeButton>
  894. <h3>{widget.title}</h3>
  895. </Header>
  896. <Body>{renderWidgetViewer()}</Body>
  897. <Footer>
  898. <ResultsContainer>
  899. {renderTotalResults(totalResults, widget.widgetType)}
  900. <ButtonBar gap={1}>
  901. {onEdit && widget.id && (
  902. <Button
  903. type="button"
  904. onClick={() => {
  905. closeModal();
  906. onEdit();
  907. trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.edit', {
  908. organization,
  909. widget_type: widget.widgetType ?? WidgetType.DISCOVER,
  910. display_type: widget.displayType,
  911. });
  912. }}
  913. >
  914. {t('Edit Widget')}
  915. </Button>
  916. )}
  917. {widget.widgetType && (
  918. <OpenButton
  919. widget={primaryWidget}
  920. organization={organization}
  921. selection={modalTableSelection}
  922. selectedQueryIndex={selectedQueryIndex}
  923. />
  924. )}
  925. </ButtonBar>
  926. </ResultsContainer>
  927. </Footer>
  928. </DashboardsMEPProvider>
  929. </Fragment>
  930. );
  931. }
  932. interface OpenButtonProps {
  933. organization: Organization;
  934. selectedQueryIndex: number;
  935. selection: PageFilters;
  936. widget: Widget;
  937. }
  938. function OpenButton({
  939. widget,
  940. selection,
  941. organization,
  942. selectedQueryIndex,
  943. }: OpenButtonProps) {
  944. let openLabel: string;
  945. let path: string;
  946. const {isMetricsData} = useDashboardsMEPContext();
  947. switch (widget.widgetType) {
  948. case WidgetType.ISSUE:
  949. openLabel = t('Open in Issues');
  950. path = getWidgetIssueUrl(widget, selection, organization);
  951. break;
  952. case WidgetType.RELEASE:
  953. openLabel = t('Open in Releases');
  954. path = getWidgetReleasesUrl(widget, selection, organization);
  955. break;
  956. case WidgetType.DISCOVER:
  957. default:
  958. openLabel = t('Open in Discover');
  959. path = getWidgetDiscoverUrl(
  960. {...widget, queries: [widget.queries[selectedQueryIndex]]},
  961. selection,
  962. organization,
  963. 0,
  964. isMetricsData
  965. );
  966. break;
  967. }
  968. return (
  969. <Button
  970. to={path}
  971. priority="primary"
  972. type="button"
  973. disabled={isCustomMeasurementWidget(widget)}
  974. title={
  975. isCustomMeasurementWidget(widget)
  976. ? t('Widgets using custom performance metrics cannot be opened in Discover.')
  977. : undefined
  978. }
  979. onClick={() => {
  980. trackAdvancedAnalyticsEvent('dashboards_views.widget_viewer.open_source', {
  981. organization,
  982. widget_type: widget.widgetType ?? WidgetType.DISCOVER,
  983. display_type: widget.displayType,
  984. });
  985. }}
  986. >
  987. {openLabel}
  988. </Button>
  989. );
  990. }
  991. function renderTotalResults(totalResults?: string, widgetType?: WidgetType) {
  992. if (totalResults === undefined) {
  993. return <span />;
  994. }
  995. switch (widgetType) {
  996. case WidgetType.ISSUE:
  997. return (
  998. <span>
  999. {tct('[description:Total Issues:] [total]', {
  1000. description: <strong />,
  1001. total: totalResults === '1000' ? '1000+' : totalResults,
  1002. })}
  1003. </span>
  1004. );
  1005. case WidgetType.DISCOVER:
  1006. return (
  1007. <span>
  1008. {tct('[description:Total Events:] [total]', {
  1009. description: <strong />,
  1010. total: totalResults,
  1011. })}
  1012. </span>
  1013. );
  1014. default:
  1015. return <span />;
  1016. }
  1017. }
  1018. export const modalCss = css`
  1019. width: 100%;
  1020. max-width: 1200px;
  1021. `;
  1022. const Container = styled('div')<{height?: number | null}>`
  1023. height: ${p => (p.height ? `${p.height}px` : 'auto')};
  1024. position: relative;
  1025. padding-bottom: ${space(3)};
  1026. `;
  1027. const QueryContainer = styled('div')`
  1028. margin-bottom: ${space(2)};
  1029. position: relative;
  1030. `;
  1031. const StyledQuestionTooltip = styled(QuestionTooltip)`
  1032. position: absolute;
  1033. top: ${space(1.5)};
  1034. right: ${space(2)};
  1035. `;
  1036. const HighlightContainer = styled('span')<{display?: 'block' | 'flex'}>`
  1037. display: ${p => p.display};
  1038. gap: ${space(1)};
  1039. font-family: ${p => p.theme.text.familyMono};
  1040. font-size: ${p => p.theme.fontSizeSmall};
  1041. line-height: 2;
  1042. flex: 1;
  1043. `;
  1044. const ResultsContainer = styled('div')`
  1045. display: flex;
  1046. flex-grow: 1;
  1047. flex-direction: column;
  1048. gap: ${space(1)};
  1049. @media (min-width: ${p => p.theme.breakpoints.small}) {
  1050. align-items: center;
  1051. flex-direction: row;
  1052. justify-content: space-between;
  1053. }
  1054. `;
  1055. const EmptyQueryContainer = styled('span')`
  1056. color: ${p => p.theme.disabled};
  1057. `;
  1058. export default withRouter(withPageFilters(WidgetViewerModal));