detail.tsx 39 KB

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