detail.tsx 41 KB

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