detail.tsx 37 KB

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