detail.tsx 38 KB

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