detail.tsx 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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 isEditingDashboard() {
  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.isEditingDashboard || 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.isEditingDashboard
  586. ? this.onUpdateWidget
  587. : this.handleUpdateWidgetList,
  588. })
  589. : children;
  590. }
  591. renderDefaultDashboardDetail() {
  592. const {organization, dashboard, dashboards, params, router, location} = this.props;
  593. const {modifiedDashboard, dashboardState, widgetLimitReached} = this.state;
  594. const {dashboardId} = params;
  595. return (
  596. <PageFiltersContainer
  597. disablePersistence
  598. defaultSelection={{
  599. datetime: {
  600. start: null,
  601. end: null,
  602. utc: false,
  603. period: DEFAULT_STATS_PERIOD,
  604. },
  605. }}
  606. >
  607. <Layout.Page withPadding>
  608. <OnDemandControlProvider location={location}>
  609. <MetricsResultsMetaProvider>
  610. <NoProjectMessage organization={organization}>
  611. <StyledPageHeader>
  612. <Layout.Title>
  613. <DashboardTitle
  614. dashboard={modifiedDashboard ?? dashboard}
  615. onUpdate={this.setModifiedDashboard}
  616. isEditingDashboard={this.isEditingDashboard}
  617. />
  618. </Layout.Title>
  619. <Controls
  620. organization={organization}
  621. dashboards={dashboards}
  622. onEdit={this.onEdit}
  623. onCancel={this.onCancel}
  624. onCommit={this.onCommit}
  625. onAddWidget={this.onAddWidget}
  626. onDelete={this.onDelete(dashboard)}
  627. dashboardState={dashboardState}
  628. widgetLimitReached={widgetLimitReached}
  629. />
  630. </StyledPageHeader>
  631. <HookHeader organization={organization} />
  632. <FiltersBar
  633. filters={{}} // Default Dashboards don't have filters set
  634. location={location}
  635. hasUnsavedChanges={false}
  636. isEditingDashboard={false}
  637. isPreview={false}
  638. onDashboardFilterChange={this.handleChangeFilter}
  639. />
  640. <MetricsCardinalityProvider
  641. organization={organization}
  642. location={location}
  643. >
  644. <MetricsDataSwitcher
  645. organization={organization}
  646. eventView={EventView.fromLocation(location)}
  647. location={location}
  648. >
  649. {metricsDataSide => (
  650. <MEPSettingProvider
  651. location={location}
  652. forceTransactions={metricsDataSide.forceTransactionsOnly}
  653. >
  654. <Dashboard
  655. paramDashboardId={dashboardId}
  656. dashboard={modifiedDashboard ?? dashboard}
  657. organization={organization}
  658. isEditingDashboard={this.isEditingDashboard}
  659. widgetLimitReached={widgetLimitReached}
  660. onUpdate={this.onUpdateWidget}
  661. handleUpdateWidgetList={this.handleUpdateWidgetList}
  662. handleAddCustomWidget={this.handleAddCustomWidget}
  663. isPreview={this.isPreview}
  664. router={router}
  665. location={location}
  666. />
  667. </MEPSettingProvider>
  668. )}
  669. </MetricsDataSwitcher>
  670. </MetricsCardinalityProvider>
  671. </NoProjectMessage>
  672. </MetricsResultsMetaProvider>
  673. </OnDemandControlProvider>
  674. </Layout.Page>
  675. </PageFiltersContainer>
  676. );
  677. }
  678. getBreadcrumbLabel() {
  679. const {dashboardState} = this.state;
  680. let label = this.dashboardTitle;
  681. if (dashboardState === DashboardState.CREATE) {
  682. label = t('Create Dashboard');
  683. } else if (this.isPreview) {
  684. label = t('Preview Dashboard');
  685. }
  686. return label;
  687. }
  688. renderDashboardDetail() {
  689. const {
  690. api,
  691. organization,
  692. dashboard,
  693. dashboards,
  694. params,
  695. router,
  696. location,
  697. newWidget,
  698. onSetNewWidget,
  699. onDashboardUpdate,
  700. projects,
  701. } = this.props;
  702. const {modifiedDashboard, dashboardState, widgetLimitReached, seriesData, setData} =
  703. this.state;
  704. const {dashboardId} = params;
  705. const hasUnsavedFilters =
  706. dashboard.id !== 'default-overview' &&
  707. dashboardState !== DashboardState.CREATE &&
  708. hasUnsavedFilterChanges(dashboard, location);
  709. const eventView = generatePerformanceEventView(location, projects, {}, organization);
  710. const isDashboardUsingTransaction = dashboard.widgets.some(
  711. isWidgetUsingTransactionName
  712. );
  713. return (
  714. <SentryDocumentTitle title={dashboard.title} orgSlug={organization.slug}>
  715. <PageFiltersContainer
  716. disablePersistence
  717. defaultSelection={{
  718. datetime: {
  719. start: null,
  720. end: null,
  721. utc: false,
  722. period: DEFAULT_STATS_PERIOD,
  723. },
  724. }}
  725. >
  726. <Layout.Page>
  727. <OnDemandControlProvider location={location}>
  728. <MetricsResultsMetaProvider>
  729. <NoProjectMessage organization={organization}>
  730. <Layout.Header>
  731. <Layout.HeaderContent>
  732. <Breadcrumbs
  733. crumbs={[
  734. {
  735. label: t('Dashboards'),
  736. to: `/organizations/${organization.slug}/dashboards/`,
  737. },
  738. {
  739. label: this.getBreadcrumbLabel(),
  740. },
  741. ]}
  742. />
  743. <Layout.Title>
  744. <DashboardTitle
  745. dashboard={modifiedDashboard ?? dashboard}
  746. onUpdate={this.setModifiedDashboard}
  747. isEditingDashboard={this.isEditingDashboard}
  748. />
  749. </Layout.Title>
  750. </Layout.HeaderContent>
  751. <Layout.HeaderActions>
  752. <Controls
  753. organization={organization}
  754. dashboards={dashboards}
  755. hasUnsavedFilters={hasUnsavedFilters}
  756. onEdit={this.onEdit}
  757. onCancel={this.onCancel}
  758. onCommit={this.onCommit}
  759. onAddWidget={this.onAddWidget}
  760. onDelete={this.onDelete(dashboard)}
  761. dashboardState={dashboardState}
  762. widgetLimitReached={widgetLimitReached}
  763. />
  764. </Layout.HeaderActions>
  765. </Layout.Header>
  766. <Layout.Body>
  767. <Layout.Main fullWidth>
  768. <MetricsCardinalityProvider
  769. organization={organization}
  770. location={location}
  771. >
  772. <MetricsDataSwitcher
  773. organization={organization}
  774. eventView={eventView}
  775. location={location}
  776. >
  777. {metricsDataSide => (
  778. <MEPSettingProvider
  779. location={location}
  780. forceTransactions={metricsDataSide.forceTransactionsOnly}
  781. >
  782. {isDashboardUsingTransaction ? (
  783. <MetricsDataSwitcherAlert
  784. organization={organization}
  785. eventView={eventView}
  786. projects={projects}
  787. location={location}
  788. router={router}
  789. source={DiscoverQueryPageSource.DISCOVER}
  790. {...metricsDataSide}
  791. />
  792. ) : null}
  793. <FiltersBar
  794. filters={(modifiedDashboard ?? dashboard).filters}
  795. location={location}
  796. hasUnsavedChanges={hasUnsavedFilters}
  797. isEditingDashboard={
  798. dashboardState !== DashboardState.CREATE &&
  799. this.isEditingDashboard
  800. }
  801. isPreview={this.isPreview}
  802. onDashboardFilterChange={this.handleChangeFilter}
  803. onCancel={() => {
  804. resetPageFilters(dashboard, location);
  805. this.setState({
  806. modifiedDashboard: {
  807. ...(modifiedDashboard ?? dashboard),
  808. filters: dashboard.filters,
  809. },
  810. });
  811. }}
  812. onSave={() => {
  813. const newModifiedDashboard = {
  814. ...cloneDashboard(modifiedDashboard ?? dashboard),
  815. ...getCurrentPageFilters(location),
  816. filters:
  817. getDashboardFiltersFromURL(location) ??
  818. (modifiedDashboard ?? dashboard).filters,
  819. };
  820. updateDashboard(
  821. api,
  822. organization.slug,
  823. newModifiedDashboard
  824. ).then(
  825. (newDashboard: DashboardDetails) => {
  826. if (onDashboardUpdate) {
  827. onDashboardUpdate(newDashboard);
  828. this.setState({
  829. modifiedDashboard: null,
  830. });
  831. }
  832. addSuccessMessage(t('Dashboard filters updated'));
  833. browserHistory.replace(
  834. normalizeUrl({
  835. pathname: `/organizations/${organization.slug}/dashboard/${newDashboard.id}/`,
  836. query: omit(
  837. location.query,
  838. Object.values(DashboardFilterKeys)
  839. ),
  840. })
  841. );
  842. },
  843. // `updateDashboard` does its own error handling
  844. () => undefined
  845. );
  846. }}
  847. />
  848. <WidgetViewerContext.Provider value={{seriesData, setData}}>
  849. <Dashboard
  850. paramDashboardId={dashboardId}
  851. dashboard={modifiedDashboard ?? dashboard}
  852. organization={organization}
  853. isEditingDashboard={this.isEditingDashboard}
  854. widgetLimitReached={widgetLimitReached}
  855. onUpdate={this.onUpdateWidget}
  856. handleUpdateWidgetList={this.handleUpdateWidgetList}
  857. handleAddCustomWidget={this.handleAddCustomWidget}
  858. router={router}
  859. location={location}
  860. newWidget={newWidget}
  861. onSetNewWidget={onSetNewWidget}
  862. isPreview={this.isPreview}
  863. />
  864. </WidgetViewerContext.Provider>
  865. </MEPSettingProvider>
  866. )}
  867. </MetricsDataSwitcher>
  868. </MetricsCardinalityProvider>
  869. </Layout.Main>
  870. </Layout.Body>
  871. </NoProjectMessage>
  872. </MetricsResultsMetaProvider>
  873. </OnDemandControlProvider>
  874. </Layout.Page>
  875. </PageFiltersContainer>
  876. </SentryDocumentTitle>
  877. );
  878. }
  879. render() {
  880. const {organization} = this.props;
  881. if (this.isWidgetBuilderRouter) {
  882. return this.renderWidgetBuilder();
  883. }
  884. if (organization.features.includes('dashboards-edit')) {
  885. return this.renderDashboardDetail();
  886. }
  887. return this.renderDefaultDashboardDetail();
  888. }
  889. }
  890. const StyledPageHeader = styled('div')`
  891. display: grid;
  892. grid-template-columns: minmax(0, 1fr);
  893. grid-row-gap: ${space(2)};
  894. align-items: center;
  895. margin-bottom: ${space(2)};
  896. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  897. grid-template-columns: minmax(0, 1fr) max-content;
  898. grid-column-gap: ${space(2)};
  899. height: 40px;
  900. }
  901. `;
  902. export default withProjects(withApi(withOrganization(DashboardDetail)));