detail.tsx 50 KB

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