detail.tsx 41 KB

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