detail.tsx 50 KB

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