detail.tsx 32 KB

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