detail.tsx 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. import {cloneElement, Component, isValidElement} from 'react';
  2. import type {PlainRoute, RouteComponentProps} from 'react-router';
  3. import {browserHistory} from 'react-router';
  4. import styled from '@emotion/styled';
  5. import cloneDeep from 'lodash/cloneDeep';
  6. import isEqual from 'lodash/isEqual';
  7. import isEqualWith from 'lodash/isEqualWith';
  8. import omit from 'lodash/omit';
  9. import {
  10. createDashboard,
  11. deleteDashboard,
  12. updateDashboard,
  13. } from 'sentry/actionCreators/dashboards';
  14. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  15. import {openWidgetViewerModal} from 'sentry/actionCreators/modal';
  16. import type {Client} from 'sentry/api';
  17. import {Breadcrumbs} from 'sentry/components/breadcrumbs';
  18. import HookOrDefault from 'sentry/components/hookOrDefault';
  19. import * as Layout from 'sentry/components/layouts/thirds';
  20. import {
  21. isWidgetViewerPath,
  22. WidgetViewerQueryField,
  23. } from 'sentry/components/modals/widgetViewerModal/utils';
  24. import NoProjectMessage from 'sentry/components/noProjectMessage';
  25. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  26. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  27. import {USING_CUSTOMER_DOMAIN} from 'sentry/constants';
  28. import {t} from 'sentry/locale';
  29. import {space} from 'sentry/styles/space';
  30. import type {Organization, PageFilters, Project} from 'sentry/types';
  31. import {defined} from 'sentry/utils';
  32. import {trackAnalytics} from 'sentry/utils/analytics';
  33. import EventView from 'sentry/utils/discover/eventView';
  34. import {MetricsCardinalityProvider} from 'sentry/utils/performance/contexts/metricsCardinality';
  35. import {MetricsResultsMetaProvider} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
  36. import {MEPSettingProvider} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  37. import {OnDemandControlProvider} from 'sentry/utils/performance/contexts/onDemandControl';
  38. import withApi from 'sentry/utils/withApi';
  39. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  40. import withOrganization from 'sentry/utils/withOrganization';
  41. import withPageFilters from 'sentry/utils/withPageFilters';
  42. import withProjects from 'sentry/utils/withProjects';
  43. import {defaultMetricWidget} from 'sentry/views/dashboards/metrics/utils';
  44. import {
  45. cloneDashboard,
  46. getCurrentPageFilters,
  47. getDashboardFiltersFromURL,
  48. hasUnsavedFilterChanges,
  49. isWidgetUsingTransactionName,
  50. openWidgetPreviewModal,
  51. resetPageFilters,
  52. } from 'sentry/views/dashboards/utils';
  53. import {DataSet} from 'sentry/views/dashboards/widgetBuilder/utils';
  54. import {MetricsDashboardContextProvider} from 'sentry/views/dashboards/widgetCard/metricsContext';
  55. import {MetricsDataSwitcherAlert} from 'sentry/views/performance/landing/metricsDataSwitcherAlert';
  56. import {generatePerformanceEventView} from '../performance/data';
  57. import {MetricsDataSwitcher} from '../performance/landing/metricsDataSwitcher';
  58. import {DiscoverQueryPageSource} from '../performance/utils';
  59. import type {WidgetViewerContextProps} from './widgetViewer/widgetViewerContext';
  60. import {WidgetViewerContext} from './widgetViewer/widgetViewerContext';
  61. import Controls from './controls';
  62. import Dashboard from './dashboard';
  63. import {DEFAULT_STATS_PERIOD} from './data';
  64. import FiltersBar from './filtersBar';
  65. import {
  66. assignDefaultLayout,
  67. assignTempId,
  68. calculateColumnDepths,
  69. generateWidgetsAfterCompaction,
  70. getDashboardLayout,
  71. } from './layoutUtils';
  72. import DashboardTitle from './title';
  73. import type {
  74. DashboardDetails,
  75. DashboardFilters,
  76. DashboardListItem,
  77. Widget,
  78. } from './types';
  79. import {
  80. DashboardFilterKeys,
  81. DashboardState,
  82. DashboardWidgetSource,
  83. MAX_WIDGETS,
  84. WidgetType,
  85. } from './types';
  86. const UNSAVED_MESSAGE = t('You have unsaved changes, are you sure you want to leave?');
  87. export const UNSAVED_FILTERS_MESSAGE = t(
  88. 'You have unsaved dashboard filters. You can save or discard them.'
  89. );
  90. const HookHeader = HookOrDefault({hookName: 'component:dashboards-header'});
  91. type RouteParams = {
  92. dashboardId?: string;
  93. templateId?: string;
  94. widgetId?: number | string;
  95. widgetIndex?: number;
  96. };
  97. type Props = RouteComponentProps<RouteParams, {}> & {
  98. api: Client;
  99. dashboard: DashboardDetails;
  100. dashboards: DashboardListItem[];
  101. initialState: DashboardState;
  102. organization: Organization;
  103. projects: Project[];
  104. route: PlainRoute;
  105. selection: PageFilters;
  106. children?: React.ReactNode;
  107. newWidget?: Widget;
  108. onDashboardUpdate?: (updatedDashboard: DashboardDetails) => void;
  109. onSetNewWidget?: () => void;
  110. };
  111. type State = {
  112. dashboardState: DashboardState;
  113. modifiedDashboard: DashboardDetails | null;
  114. widgetLimitReached: boolean;
  115. } & WidgetViewerContextProps;
  116. class DashboardDetail extends Component<Props, State> {
  117. state: State = {
  118. dashboardState: this.props.initialState,
  119. modifiedDashboard: this.updateModifiedDashboard(this.props.initialState),
  120. widgetLimitReached: this.props.dashboard.widgets.length >= MAX_WIDGETS,
  121. setData: data => {
  122. this.setState(data);
  123. },
  124. };
  125. componentDidMount() {
  126. const {route, router} = this.props;
  127. router.setRouteLeaveHook(route, this.onRouteLeave);
  128. window.addEventListener('beforeunload', this.onUnload);
  129. this.checkIfShouldMountWidgetViewerModal();
  130. }
  131. componentDidUpdate(prevProps: Props) {
  132. this.checkIfShouldMountWidgetViewerModal();
  133. if (prevProps.initialState !== this.props.initialState) {
  134. // Widget builder can toggle Edit state when saving
  135. this.setState({dashboardState: this.props.initialState});
  136. }
  137. }
  138. componentWillUnmount() {
  139. window.removeEventListener('beforeunload', this.onUnload);
  140. }
  141. checkIfShouldMountWidgetViewerModal() {
  142. const {
  143. params: {widgetId, dashboardId},
  144. organization,
  145. dashboard,
  146. location,
  147. router,
  148. } = this.props;
  149. const {seriesData, tableData, pageLinks, totalIssuesCount, seriesResultsType} =
  150. this.state;
  151. if (isWidgetViewerPath(location.pathname)) {
  152. const widget =
  153. defined(widgetId) &&
  154. (dashboard.widgets.find(({id}) => {
  155. // This ternary exists because widgetId is in some places typed as string, while
  156. // in other cases it is typed as number. Instead of changing the type everywhere,
  157. // we check for both cases at runtime as I am not sure which is the correct type.
  158. return typeof widgetId === 'number' ? id === String(widgetId) : id === widgetId;
  159. }) ??
  160. dashboard.widgets[widgetId]);
  161. if (widget) {
  162. openWidgetViewerModal({
  163. organization,
  164. widget,
  165. seriesData,
  166. seriesResultsType,
  167. tableData,
  168. pageLinks,
  169. totalIssuesCount,
  170. dashboardFilters: getDashboardFiltersFromURL(location) ?? dashboard.filters,
  171. onMetricWidgetEdit: (updatedWidget: Widget) => {
  172. const widgets = [...dashboard.widgets];
  173. const widgetIndex = dashboard.widgets.indexOf(widget);
  174. widgets[widgetIndex] = {...widgets[widgetIndex], ...updatedWidget};
  175. this.handleUpdateWidgetList(widgets);
  176. },
  177. onClose: () => {
  178. // Filter out Widget Viewer Modal query params when exiting the Modal
  179. const query = omit(location.query, Object.values(WidgetViewerQueryField));
  180. router.push({
  181. pathname: location.pathname.replace(/widget\/[0-9]+\/$/, ''),
  182. query,
  183. });
  184. },
  185. onEdit: () => {
  186. const widgetIndex = dashboard.widgets.indexOf(widget);
  187. if (dashboardId) {
  188. router.push(
  189. normalizeUrl({
  190. pathname: `/organizations/${organization.slug}/dashboard/${dashboardId}/widget/${widgetIndex}/edit/`,
  191. query: {
  192. ...location.query,
  193. source: DashboardWidgetSource.DASHBOARDS,
  194. },
  195. })
  196. );
  197. return;
  198. }
  199. },
  200. });
  201. trackAnalytics('dashboards_views.widget_viewer.open', {
  202. organization,
  203. widget_type: widget.widgetType ?? WidgetType.DISCOVER,
  204. display_type: widget.displayType,
  205. });
  206. } else {
  207. // Replace the URL if the widget isn't found and raise an error in toast
  208. router.replace(
  209. normalizeUrl({
  210. pathname: `/organizations/${organization.slug}/dashboard/${dashboard.id}/`,
  211. query: location.query,
  212. })
  213. );
  214. addErrorMessage(t('Widget not found'));
  215. }
  216. }
  217. }
  218. updateModifiedDashboard(dashboardState: DashboardState) {
  219. const {dashboard} = this.props;
  220. switch (dashboardState) {
  221. case DashboardState.PREVIEW:
  222. case DashboardState.CREATE:
  223. case DashboardState.EDIT:
  224. return cloneDashboard(dashboard);
  225. default: {
  226. return null;
  227. }
  228. }
  229. }
  230. get isPreview() {
  231. const {dashboardState} = this.state;
  232. return DashboardState.PREVIEW === dashboardState;
  233. }
  234. get isEditingDashboard() {
  235. const {dashboardState} = this.state;
  236. return [
  237. DashboardState.EDIT,
  238. DashboardState.CREATE,
  239. DashboardState.PENDING_DELETE,
  240. ].includes(dashboardState);
  241. }
  242. get isWidgetBuilderRouter() {
  243. const {location, params, organization} = this.props;
  244. const {dashboardId, widgetIndex} = params;
  245. const widgetBuilderRoutes = [
  246. `/organizations/${organization.slug}/dashboards/new/widget/new/`,
  247. `/organizations/${organization.slug}/dashboard/${dashboardId}/widget/new/`,
  248. `/organizations/${organization.slug}/dashboards/new/widget/${widgetIndex}/edit/`,
  249. `/organizations/${organization.slug}/dashboard/${dashboardId}/widget/${widgetIndex}/edit/`,
  250. ];
  251. if (USING_CUSTOMER_DOMAIN) {
  252. // TODO: replace with url generation later on.
  253. widgetBuilderRoutes.push(
  254. ...[
  255. `/dashboards/new/widget/new/`,
  256. `/dashboard/${dashboardId}/widget/new/`,
  257. `/dashboards/new/widget/${widgetIndex}/edit/`,
  258. `/dashboard/${dashboardId}/widget/${widgetIndex}/edit/`,
  259. ]
  260. );
  261. }
  262. return widgetBuilderRoutes.includes(location.pathname);
  263. }
  264. get dashboardTitle() {
  265. const {dashboard} = this.props;
  266. const {modifiedDashboard} = this.state;
  267. return modifiedDashboard ? modifiedDashboard.title : dashboard.title;
  268. }
  269. onEdit = () => {
  270. const {dashboard, organization} = this.props;
  271. trackAnalytics('dashboards2.edit.start', {organization});
  272. this.setState({
  273. dashboardState: DashboardState.EDIT,
  274. modifiedDashboard: cloneDashboard(dashboard),
  275. });
  276. };
  277. onRouteLeave = () => {
  278. const {dashboard} = this.props;
  279. const {modifiedDashboard} = this.state;
  280. if (
  281. ![
  282. DashboardState.VIEW,
  283. DashboardState.PENDING_DELETE,
  284. DashboardState.PREVIEW,
  285. ].includes(this.state.dashboardState) &&
  286. !isEqual(modifiedDashboard, dashboard)
  287. ) {
  288. return UNSAVED_MESSAGE;
  289. }
  290. return undefined;
  291. };
  292. onUnload = (event: BeforeUnloadEvent) => {
  293. const {dashboard} = this.props;
  294. const {modifiedDashboard} = this.state;
  295. if (
  296. [
  297. DashboardState.VIEW,
  298. DashboardState.PENDING_DELETE,
  299. DashboardState.PREVIEW,
  300. ].includes(this.state.dashboardState) ||
  301. isEqual(modifiedDashboard, dashboard)
  302. ) {
  303. return;
  304. }
  305. event.preventDefault();
  306. event.returnValue = UNSAVED_MESSAGE;
  307. };
  308. onDelete = (dashboard: State['modifiedDashboard']) => () => {
  309. const {api, organization, location} = this.props;
  310. if (!dashboard?.id) {
  311. return;
  312. }
  313. const previousDashboardState = this.state.dashboardState;
  314. this.setState({dashboardState: DashboardState.PENDING_DELETE}, () => {
  315. deleteDashboard(api, organization.slug, dashboard.id)
  316. .then(() => {
  317. addSuccessMessage(t('Dashboard deleted'));
  318. trackAnalytics('dashboards2.delete', {organization});
  319. browserHistory.replace({
  320. pathname: `/organizations/${organization.slug}/dashboards/`,
  321. query: location.query,
  322. });
  323. })
  324. .catch(() => {
  325. this.setState({
  326. dashboardState: previousDashboardState,
  327. });
  328. });
  329. });
  330. };
  331. onCancel = () => {
  332. const {organization, dashboard, location, params} = this.props;
  333. const {modifiedDashboard} = this.state;
  334. let hasDashboardChanged = !isEqual(modifiedDashboard, dashboard);
  335. // If a dashboard has every layout undefined, then ignore the layout field
  336. // when checking equality because it is a dashboard from before the grid feature
  337. const isLegacyLayout = dashboard.widgets.every(({layout}) => !defined(layout));
  338. if (isLegacyLayout) {
  339. hasDashboardChanged = !isEqual(
  340. {
  341. ...modifiedDashboard,
  342. widgets: modifiedDashboard?.widgets.map(widget => omit(widget, 'layout')),
  343. },
  344. {...dashboard, widgets: dashboard.widgets.map(widget => omit(widget, 'layout'))}
  345. );
  346. }
  347. // Don't confirm preview cancellation regardless of dashboard state
  348. if (hasDashboardChanged && !this.isPreview) {
  349. // Ignore no-alert here, so that the confirm on cancel matches onUnload & onRouteLeave
  350. /* eslint no-alert:0 */
  351. if (!confirm(UNSAVED_MESSAGE)) {
  352. return;
  353. }
  354. }
  355. if (params.dashboardId) {
  356. trackAnalytics('dashboards2.edit.cancel', {organization});
  357. this.setState({
  358. dashboardState: DashboardState.VIEW,
  359. modifiedDashboard: null,
  360. });
  361. return;
  362. }
  363. trackAnalytics('dashboards2.create.cancel', {organization});
  364. browserHistory.replace(
  365. normalizeUrl({
  366. pathname: `/organizations/${organization.slug}/dashboards/`,
  367. query: location.query,
  368. })
  369. );
  370. };
  371. handleChangeFilter = (activeFilters: DashboardFilters) => {
  372. const {dashboard, location} = this.props;
  373. const {modifiedDashboard} = this.state;
  374. const newModifiedDashboard = modifiedDashboard || dashboard;
  375. if (
  376. Object.keys(activeFilters).every(
  377. key => !newModifiedDashboard.filters?.[key] && activeFilters[key].length === 0
  378. )
  379. ) {
  380. return;
  381. }
  382. const filterParams: DashboardFilters = {};
  383. Object.keys(activeFilters).forEach(key => {
  384. filterParams[key] = activeFilters[key].length ? activeFilters[key] : '';
  385. });
  386. if (
  387. !isEqualWith(activeFilters, dashboard.filters, (a, b) => {
  388. // This is to handle the case where dashboard filters has release:[] and the new filter is release:""
  389. if (a.length === 0 && b.length === 0) {
  390. return a === b;
  391. }
  392. return undefined;
  393. })
  394. ) {
  395. browserHistory.push({
  396. ...location,
  397. query: {
  398. ...location.query,
  399. ...filterParams,
  400. },
  401. });
  402. }
  403. };
  404. handleUpdateWidgetList = (widgets: Widget[]) => {
  405. const {organization, dashboard, api, onDashboardUpdate, location} = this.props;
  406. const {modifiedDashboard} = this.state;
  407. // Use the new widgets for calculating layout because widgets has
  408. // the most up to date information in edit state
  409. const currentLayout = getDashboardLayout(widgets);
  410. const layoutColumnDepths = calculateColumnDepths(currentLayout);
  411. const newModifiedDashboard = {
  412. ...cloneDashboard(modifiedDashboard || dashboard),
  413. widgets: assignDefaultLayout(widgets, layoutColumnDepths),
  414. };
  415. this.setState({
  416. modifiedDashboard: newModifiedDashboard,
  417. widgetLimitReached: widgets.length >= MAX_WIDGETS,
  418. });
  419. if (this.isEditingDashboard || this.isPreview) {
  420. return null;
  421. }
  422. return updateDashboard(api, organization.slug, newModifiedDashboard).then(
  423. (newDashboard: DashboardDetails) => {
  424. if (onDashboardUpdate) {
  425. onDashboardUpdate(newDashboard);
  426. this.setState({
  427. modifiedDashboard: null,
  428. });
  429. }
  430. addSuccessMessage(t('Dashboard updated'));
  431. if (dashboard && newDashboard.id !== dashboard.id) {
  432. browserHistory.replace(
  433. normalizeUrl({
  434. pathname: `/organizations/${organization.slug}/dashboard/${newDashboard.id}/`,
  435. query: {
  436. ...location.query,
  437. },
  438. })
  439. );
  440. }
  441. return newDashboard;
  442. },
  443. // `updateDashboard` does its own error handling
  444. () => undefined
  445. );
  446. };
  447. handleAddCustomWidget = (widget: Widget) => {
  448. const {dashboard} = this.props;
  449. const {modifiedDashboard} = this.state;
  450. const newModifiedDashboard = modifiedDashboard || dashboard;
  451. this.onUpdateWidget([...newModifiedDashboard.widgets, widget]);
  452. };
  453. handleAddMetricWidget = (layout?: Widget['layout']) => {
  454. const {dashboard, router, location} = this.props;
  455. const widgetCopy = cloneDeep(
  456. assignTempId({
  457. layout,
  458. ...defaultMetricWidget(),
  459. })
  460. );
  461. const nextList = generateWidgetsAfterCompaction([...dashboard.widgets, widgetCopy]);
  462. this.onUpdateWidget(nextList);
  463. if (!this.isEditingDashboard) {
  464. this.handleUpdateWidgetList(nextList)?.then((newDashboard?: DashboardDetails) => {
  465. if (!newDashboard) {
  466. return;
  467. }
  468. const lastWidget = newDashboard?.widgets[newDashboard.widgets.length - 1];
  469. openWidgetPreviewModal(router, location, lastWidget);
  470. });
  471. }
  472. };
  473. onAddWidget = (dataset: DataSet) => {
  474. const {
  475. organization,
  476. dashboard,
  477. router,
  478. location,
  479. params: {dashboardId},
  480. } = this.props;
  481. if (dataset === DataSet.METRICS) {
  482. this.handleAddMetricWidget();
  483. return;
  484. }
  485. this.setState(
  486. {
  487. modifiedDashboard: cloneDashboard(dashboard),
  488. },
  489. () => {
  490. if (dashboardId) {
  491. router.push(
  492. normalizeUrl({
  493. pathname: `/organizations/${organization.slug}/dashboard/${dashboardId}/widget/new/`,
  494. query: {
  495. ...location.query,
  496. source: DashboardWidgetSource.DASHBOARDS,
  497. dataset,
  498. },
  499. })
  500. );
  501. }
  502. }
  503. );
  504. };
  505. onCommit = () => {
  506. const {api, organization, location, dashboard, onDashboardUpdate} = this.props;
  507. const {modifiedDashboard, dashboardState} = this.state;
  508. switch (dashboardState) {
  509. case DashboardState.PREVIEW:
  510. case DashboardState.CREATE: {
  511. if (modifiedDashboard) {
  512. if (this.isPreview) {
  513. trackAnalytics('dashboards_manage.templates.add', {
  514. organization,
  515. dashboard_id: dashboard.id,
  516. dashboard_title: dashboard.title,
  517. was_previewed: true,
  518. });
  519. }
  520. const newModifiedDashboard = {
  521. ...cloneDashboard(modifiedDashboard),
  522. ...getCurrentPageFilters(location),
  523. filters: getDashboardFiltersFromURL(location) ?? modifiedDashboard.filters,
  524. };
  525. createDashboard(
  526. api,
  527. organization.slug,
  528. newModifiedDashboard,
  529. this.isPreview
  530. ).then(
  531. (newDashboard: DashboardDetails) => {
  532. addSuccessMessage(t('Dashboard created'));
  533. trackAnalytics('dashboards2.create.complete', {organization});
  534. this.setState(
  535. {
  536. dashboardState: DashboardState.VIEW,
  537. },
  538. () => {
  539. // redirect to new dashboard
  540. browserHistory.replace(
  541. normalizeUrl({
  542. pathname: `/organizations/${organization.slug}/dashboard/${newDashboard.id}/`,
  543. query: {
  544. query: omit(location.query, Object.values(DashboardFilterKeys)),
  545. },
  546. })
  547. );
  548. }
  549. );
  550. },
  551. () => undefined
  552. );
  553. }
  554. break;
  555. }
  556. case DashboardState.EDIT: {
  557. // only update the dashboard if there are changes
  558. if (modifiedDashboard) {
  559. if (isEqual(dashboard, modifiedDashboard)) {
  560. this.setState({
  561. dashboardState: DashboardState.VIEW,
  562. modifiedDashboard: null,
  563. });
  564. return;
  565. }
  566. updateDashboard(api, organization.slug, modifiedDashboard).then(
  567. (newDashboard: DashboardDetails) => {
  568. if (onDashboardUpdate) {
  569. onDashboardUpdate(newDashboard);
  570. }
  571. addSuccessMessage(t('Dashboard updated'));
  572. trackAnalytics('dashboards2.edit.complete', {organization});
  573. this.setState(
  574. {
  575. dashboardState: DashboardState.VIEW,
  576. modifiedDashboard: null,
  577. },
  578. () => {
  579. if (dashboard && newDashboard.id !== dashboard.id) {
  580. browserHistory.replace(
  581. normalizeUrl({
  582. pathname: `/organizations/${organization.slug}/dashboard/${newDashboard.id}/`,
  583. query: {
  584. ...location.query,
  585. },
  586. })
  587. );
  588. }
  589. }
  590. );
  591. },
  592. // `updateDashboard` does its own error handling
  593. () => undefined
  594. );
  595. return;
  596. }
  597. this.setState({
  598. dashboardState: DashboardState.VIEW,
  599. modifiedDashboard: null,
  600. });
  601. break;
  602. }
  603. case DashboardState.VIEW:
  604. default: {
  605. this.setState({
  606. dashboardState: DashboardState.VIEW,
  607. modifiedDashboard: null,
  608. });
  609. break;
  610. }
  611. }
  612. };
  613. setModifiedDashboard = (dashboard: DashboardDetails) => {
  614. this.setState({
  615. modifiedDashboard: dashboard,
  616. });
  617. };
  618. onUpdateWidget = (widgets: Widget[]) => {
  619. this.setState((state: State) => ({
  620. ...state,
  621. widgetLimitReached: widgets.length >= MAX_WIDGETS,
  622. modifiedDashboard: {
  623. ...(state.modifiedDashboard || this.props.dashboard),
  624. widgets,
  625. },
  626. }));
  627. };
  628. renderWidgetBuilder() {
  629. const {children, dashboard} = this.props;
  630. const {modifiedDashboard} = this.state;
  631. return isValidElement(children)
  632. ? cloneElement<any>(children, {
  633. dashboard: modifiedDashboard ?? dashboard,
  634. onSave: this.isEditingDashboard
  635. ? this.onUpdateWidget
  636. : this.handleUpdateWidgetList,
  637. })
  638. : children;
  639. }
  640. renderDefaultDashboardDetail() {
  641. const {organization, dashboard, dashboards, params, router, location} = this.props;
  642. const {modifiedDashboard, dashboardState, widgetLimitReached} = this.state;
  643. const {dashboardId} = params;
  644. return (
  645. <PageFiltersContainer
  646. disablePersistence
  647. defaultSelection={{
  648. datetime: {
  649. start: null,
  650. end: null,
  651. utc: false,
  652. period: DEFAULT_STATS_PERIOD,
  653. },
  654. }}
  655. >
  656. <Layout.Page withPadding>
  657. <OnDemandControlProvider location={location}>
  658. <MetricsDashboardContextProvider>
  659. <MetricsResultsMetaProvider>
  660. <NoProjectMessage organization={organization}>
  661. <StyledPageHeader>
  662. <Layout.Title>
  663. <DashboardTitle
  664. dashboard={modifiedDashboard ?? dashboard}
  665. onUpdate={this.setModifiedDashboard}
  666. isEditingDashboard={this.isEditingDashboard}
  667. />
  668. </Layout.Title>
  669. <Controls
  670. organization={organization}
  671. dashboards={dashboards}
  672. onEdit={this.onEdit}
  673. onCancel={this.onCancel}
  674. onCommit={this.onCommit}
  675. onAddWidget={this.onAddWidget}
  676. onDelete={this.onDelete(dashboard)}
  677. dashboardState={dashboardState}
  678. widgetLimitReached={widgetLimitReached}
  679. />
  680. </StyledPageHeader>
  681. <HookHeader organization={organization} />
  682. <FiltersBar
  683. filters={{}} // Default Dashboards don't have filters set
  684. location={location}
  685. hasUnsavedChanges={false}
  686. isEditingDashboard={false}
  687. isPreview={false}
  688. onDashboardFilterChange={this.handleChangeFilter}
  689. />
  690. <MetricsCardinalityProvider
  691. organization={organization}
  692. location={location}
  693. >
  694. <MetricsDataSwitcher
  695. organization={organization}
  696. eventView={EventView.fromLocation(location)}
  697. location={location}
  698. >
  699. {metricsDataSide => (
  700. <MEPSettingProvider
  701. location={location}
  702. forceTransactions={metricsDataSide.forceTransactionsOnly}
  703. >
  704. <Dashboard
  705. paramDashboardId={dashboardId}
  706. dashboard={modifiedDashboard ?? dashboard}
  707. organization={organization}
  708. isEditingDashboard={this.isEditingDashboard}
  709. widgetLimitReached={widgetLimitReached}
  710. onUpdate={this.onUpdateWidget}
  711. handleUpdateWidgetList={this.handleUpdateWidgetList}
  712. handleAddCustomWidget={this.handleAddCustomWidget}
  713. handleAddMetricWidget={this.handleAddMetricWidget}
  714. isPreview={this.isPreview}
  715. router={router}
  716. location={location}
  717. />
  718. </MEPSettingProvider>
  719. )}
  720. </MetricsDataSwitcher>
  721. </MetricsCardinalityProvider>
  722. </NoProjectMessage>
  723. </MetricsResultsMetaProvider>
  724. </MetricsDashboardContextProvider>
  725. </OnDemandControlProvider>
  726. </Layout.Page>
  727. </PageFiltersContainer>
  728. );
  729. }
  730. getBreadcrumbLabel() {
  731. const {dashboardState} = this.state;
  732. let label = this.dashboardTitle;
  733. if (dashboardState === DashboardState.CREATE) {
  734. label = t('Create Dashboard');
  735. } else if (this.isPreview) {
  736. label = t('Preview Dashboard');
  737. }
  738. return label;
  739. }
  740. renderDashboardDetail() {
  741. const {
  742. api,
  743. organization,
  744. dashboard,
  745. dashboards,
  746. params,
  747. router,
  748. location,
  749. newWidget,
  750. onSetNewWidget,
  751. onDashboardUpdate,
  752. projects,
  753. } = this.props;
  754. const {modifiedDashboard, dashboardState, widgetLimitReached, seriesData, setData} =
  755. this.state;
  756. const {dashboardId} = params;
  757. const hasUnsavedFilters =
  758. dashboard.id !== 'default-overview' &&
  759. dashboardState !== DashboardState.CREATE &&
  760. hasUnsavedFilterChanges(dashboard, location);
  761. const eventView = generatePerformanceEventView(location, projects, {}, organization);
  762. const isDashboardUsingTransaction = dashboard.widgets.some(
  763. isWidgetUsingTransactionName
  764. );
  765. return (
  766. <SentryDocumentTitle title={dashboard.title} orgSlug={organization.slug}>
  767. <PageFiltersContainer
  768. disablePersistence
  769. defaultSelection={{
  770. datetime: {
  771. start: null,
  772. end: null,
  773. utc: false,
  774. period: DEFAULT_STATS_PERIOD,
  775. },
  776. }}
  777. >
  778. <Layout.Page>
  779. <OnDemandControlProvider location={location}>
  780. <MetricsDashboardContextProvider>
  781. <MetricsResultsMetaProvider>
  782. <NoProjectMessage organization={organization}>
  783. <Layout.Header>
  784. <Layout.HeaderContent>
  785. <Breadcrumbs
  786. crumbs={[
  787. {
  788. label: t('Dashboards'),
  789. to: `/organizations/${organization.slug}/dashboards/`,
  790. },
  791. {
  792. label: this.getBreadcrumbLabel(),
  793. },
  794. ]}
  795. />
  796. <Layout.Title>
  797. <DashboardTitle
  798. dashboard={modifiedDashboard ?? dashboard}
  799. onUpdate={this.setModifiedDashboard}
  800. isEditingDashboard={this.isEditingDashboard}
  801. />
  802. </Layout.Title>
  803. </Layout.HeaderContent>
  804. <Layout.HeaderActions>
  805. <Controls
  806. organization={organization}
  807. dashboards={dashboards}
  808. hasUnsavedFilters={hasUnsavedFilters}
  809. onEdit={this.onEdit}
  810. onCancel={this.onCancel}
  811. onCommit={this.onCommit}
  812. onAddWidget={this.onAddWidget}
  813. onDelete={this.onDelete(dashboard)}
  814. dashboardState={dashboardState}
  815. widgetLimitReached={widgetLimitReached}
  816. />
  817. </Layout.HeaderActions>
  818. </Layout.Header>
  819. <Layout.Body>
  820. <Layout.Main fullWidth>
  821. <MetricsCardinalityProvider
  822. organization={organization}
  823. location={location}
  824. >
  825. <MetricsDataSwitcher
  826. organization={organization}
  827. eventView={eventView}
  828. location={location}
  829. >
  830. {metricsDataSide => (
  831. <MEPSettingProvider
  832. location={location}
  833. forceTransactions={metricsDataSide.forceTransactionsOnly}
  834. >
  835. {isDashboardUsingTransaction ? (
  836. <MetricsDataSwitcherAlert
  837. organization={organization}
  838. eventView={eventView}
  839. projects={projects}
  840. location={location}
  841. router={router}
  842. source={DiscoverQueryPageSource.DISCOVER}
  843. {...metricsDataSide}
  844. />
  845. ) : null}
  846. <FiltersBar
  847. filters={(modifiedDashboard ?? dashboard).filters}
  848. location={location}
  849. hasUnsavedChanges={hasUnsavedFilters}
  850. isEditingDashboard={
  851. dashboardState !== DashboardState.CREATE &&
  852. this.isEditingDashboard
  853. }
  854. isPreview={this.isPreview}
  855. onDashboardFilterChange={this.handleChangeFilter}
  856. onCancel={() => {
  857. resetPageFilters(dashboard, location);
  858. this.setState({
  859. modifiedDashboard: {
  860. ...(modifiedDashboard ?? dashboard),
  861. filters: dashboard.filters,
  862. },
  863. });
  864. }}
  865. onSave={() => {
  866. const newModifiedDashboard = {
  867. ...cloneDashboard(modifiedDashboard ?? dashboard),
  868. ...getCurrentPageFilters(location),
  869. filters:
  870. getDashboardFiltersFromURL(location) ??
  871. (modifiedDashboard ?? dashboard).filters,
  872. };
  873. updateDashboard(
  874. api,
  875. organization.slug,
  876. newModifiedDashboard
  877. ).then(
  878. (newDashboard: DashboardDetails) => {
  879. addSuccessMessage(t('Dashboard filters updated'));
  880. const navigateToDashboard = () => {
  881. browserHistory.replace(
  882. normalizeUrl({
  883. pathname: `/organizations/${organization.slug}/dashboard/${newDashboard.id}/`,
  884. query: omit(
  885. location.query,
  886. Object.values(DashboardFilterKeys)
  887. ),
  888. })
  889. );
  890. };
  891. if (onDashboardUpdate) {
  892. onDashboardUpdate(newDashboard);
  893. this.setState(
  894. {
  895. modifiedDashboard: null,
  896. },
  897. () => {
  898. // Wait for modifiedDashboard state to update before navigating
  899. navigateToDashboard();
  900. }
  901. );
  902. return;
  903. }
  904. navigateToDashboard();
  905. },
  906. // `updateDashboard` does its own error handling
  907. () => undefined
  908. );
  909. }}
  910. />
  911. <WidgetViewerContext.Provider
  912. value={{seriesData, setData}}
  913. >
  914. <Dashboard
  915. paramDashboardId={dashboardId}
  916. dashboard={modifiedDashboard ?? dashboard}
  917. organization={organization}
  918. isEditingDashboard={this.isEditingDashboard}
  919. widgetLimitReached={widgetLimitReached}
  920. onUpdate={this.onUpdateWidget}
  921. handleUpdateWidgetList={this.handleUpdateWidgetList}
  922. handleAddCustomWidget={this.handleAddCustomWidget}
  923. handleAddMetricWidget={this.handleAddMetricWidget}
  924. router={router}
  925. location={location}
  926. newWidget={newWidget}
  927. onSetNewWidget={onSetNewWidget}
  928. isPreview={this.isPreview}
  929. />
  930. </WidgetViewerContext.Provider>
  931. </MEPSettingProvider>
  932. )}
  933. </MetricsDataSwitcher>
  934. </MetricsCardinalityProvider>
  935. </Layout.Main>
  936. </Layout.Body>
  937. </NoProjectMessage>
  938. </MetricsResultsMetaProvider>
  939. </MetricsDashboardContextProvider>
  940. </OnDemandControlProvider>
  941. </Layout.Page>
  942. </PageFiltersContainer>
  943. </SentryDocumentTitle>
  944. );
  945. }
  946. render() {
  947. const {organization} = this.props;
  948. if (this.isWidgetBuilderRouter) {
  949. return this.renderWidgetBuilder();
  950. }
  951. if (organization.features.includes('dashboards-edit')) {
  952. return this.renderDashboardDetail();
  953. }
  954. return this.renderDefaultDashboardDetail();
  955. }
  956. }
  957. const StyledPageHeader = styled('div')`
  958. display: grid;
  959. grid-template-columns: minmax(0, 1fr);
  960. grid-row-gap: ${space(2)};
  961. align-items: center;
  962. margin-bottom: ${space(2)};
  963. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  964. grid-template-columns: minmax(0, 1fr) max-content;
  965. grid-column-gap: ${space(2)};
  966. height: 40px;
  967. }
  968. `;
  969. export default withPageFilters(withProjects(withApi(withOrganization(DashboardDetail))));