detail.tsx 36 KB

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