detail.tsx 34 KB

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