orgDashboards.tsx 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import {browserHistory} from 'react-router';
  2. import {Location} from 'history';
  3. import isEmpty from 'lodash/isEmpty';
  4. import isEqual from 'lodash/isEqual';
  5. import {Client} from 'sentry/api';
  6. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  7. import NotFound from 'sentry/components/errors/notFound';
  8. import * as Layout from 'sentry/components/layouts/thirds';
  9. import LoadingIndicator from 'sentry/components/loadingIndicator';
  10. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  11. import {t} from 'sentry/locale';
  12. import {Organization} from 'sentry/types';
  13. import withRouteAnalytics, {
  14. WithRouteAnalyticsProps,
  15. } from 'sentry/utils/routeAnalytics/withRouteAnalytics';
  16. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  17. import {assignTempId} from './layoutUtils';
  18. import {DashboardDetails, DashboardListItem} from './types';
  19. import {hasSavedPageFilters} from './utils';
  20. type OrgDashboardsChildrenProps = {
  21. dashboard: DashboardDetails | null;
  22. dashboards: DashboardListItem[];
  23. error: boolean;
  24. onDashboardUpdate: (updatedDashboard: DashboardDetails) => void;
  25. };
  26. type Props = WithRouteAnalyticsProps & {
  27. api: Client;
  28. children: (props: OrgDashboardsChildrenProps) => React.ReactNode;
  29. location: Location;
  30. organization: Organization;
  31. params: {orgId: string; dashboardId?: string};
  32. };
  33. type State = {
  34. // endpoint response
  35. dashboards: DashboardListItem[] | null;
  36. /**
  37. * The currently selected dashboard.
  38. */
  39. selectedDashboard: DashboardDetails | null;
  40. } & DeprecatedAsyncComponent['state'];
  41. class OrgDashboards extends DeprecatedAsyncComponent<Props, State> {
  42. state: State = {
  43. // AsyncComponent state
  44. loading: true,
  45. reloading: false,
  46. error: false,
  47. errors: {},
  48. dashboards: [],
  49. selectedDashboard: null,
  50. };
  51. componentDidUpdate(prevProps: Props) {
  52. if (!isEqual(prevProps.params.dashboardId, this.props.params.dashboardId)) {
  53. this.remountComponent();
  54. }
  55. }
  56. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  57. const {organization, params} = this.props;
  58. const url = `/organizations/${organization.slug}/dashboards/`;
  59. const endpoints: ReturnType<DeprecatedAsyncComponent['getEndpoints']> = [
  60. ['dashboards', url],
  61. ];
  62. if (params.dashboardId) {
  63. endpoints.push(['selectedDashboard', `${url}${params.dashboardId}/`]);
  64. this.props.setEventNames('dashboards2.view', 'Dashboards2: View dashboard');
  65. this.props.setRouteAnalyticsParams({
  66. dashboard_id: params.dashboardId,
  67. });
  68. }
  69. return endpoints;
  70. }
  71. onDashboardUpdate(updatedDashboard: DashboardDetails) {
  72. this.setState({selectedDashboard: updatedDashboard});
  73. }
  74. getDashboards(): DashboardListItem[] {
  75. const {dashboards} = this.state;
  76. return Array.isArray(dashboards) ? dashboards : [];
  77. }
  78. onRequestSuccess({stateKey, data}) {
  79. const {params, organization, location} = this.props;
  80. if (params.dashboardId || stateKey === 'selectedDashboard') {
  81. const queryParamFilters = new Set([
  82. 'project',
  83. 'environment',
  84. 'statsPeriod',
  85. 'start',
  86. 'end',
  87. 'utc',
  88. 'release',
  89. ]);
  90. if (
  91. stateKey === 'selectedDashboard' &&
  92. // Only redirect if there are saved filters and none of the filters
  93. // appear in the query params
  94. hasSavedPageFilters(data) &&
  95. isEmpty(
  96. Object.keys(location.query).filter(unsavedQueryParam =>
  97. queryParamFilters.has(unsavedQueryParam)
  98. )
  99. )
  100. ) {
  101. browserHistory.replace({
  102. ...location,
  103. query: {
  104. ...location.query,
  105. project: data.projects,
  106. environment: data.environment,
  107. statsPeriod: data.period,
  108. start: data.start,
  109. end: data.end,
  110. utc: data.utc,
  111. },
  112. });
  113. }
  114. return;
  115. }
  116. // If we don't have a selected dashboard, and one isn't going to arrive
  117. // we can redirect to the first dashboard in the list.
  118. const dashboardId = data.length ? data[0].id : 'default-overview';
  119. browserHistory.replace(
  120. normalizeUrl({
  121. pathname: `/organizations/${organization.slug}/dashboard/${dashboardId}/`,
  122. query: {
  123. ...location.query,
  124. },
  125. })
  126. );
  127. }
  128. renderLoading() {
  129. return (
  130. <Layout.Page withPadding>
  131. <LoadingIndicator />
  132. </Layout.Page>
  133. );
  134. }
  135. renderBody() {
  136. const {children} = this.props;
  137. const {selectedDashboard, error} = this.state;
  138. let dashboard = selectedDashboard;
  139. // Ensure there are always tempIds for grid layout
  140. // This is needed because there are cases where the dashboard
  141. // renders before the onRequestSuccess setState is processed
  142. // and will caused stacked widgets because of missing tempIds
  143. dashboard = selectedDashboard
  144. ? {
  145. ...selectedDashboard,
  146. widgets: selectedDashboard.widgets.map(assignTempId),
  147. }
  148. : null;
  149. return children({
  150. error,
  151. dashboard,
  152. dashboards: this.getDashboards(),
  153. onDashboardUpdate: (updatedDashboard: DashboardDetails) =>
  154. this.onDashboardUpdate(updatedDashboard),
  155. });
  156. }
  157. renderError(error: Error) {
  158. const notFound = Object.values(this.state.errors).find(
  159. resp => resp && resp.status === 404
  160. );
  161. if (notFound) {
  162. return <NotFound />;
  163. }
  164. return super.renderError(error, true);
  165. }
  166. renderComponent() {
  167. const {organization, location} = this.props;
  168. const {loading, selectedDashboard} = this.state;
  169. if (!organization.features.includes('dashboards-basic')) {
  170. // Redirect to Dashboards v1
  171. browserHistory.replace(
  172. normalizeUrl({
  173. pathname: `/organizations/${organization.slug}/dashboards/`,
  174. query: {
  175. ...location.query,
  176. },
  177. })
  178. );
  179. return null;
  180. }
  181. if (
  182. loading &&
  183. selectedDashboard &&
  184. hasSavedPageFilters(selectedDashboard) &&
  185. isEmpty(location.query)
  186. ) {
  187. // Block dashboard from rendering if the dashboard has filters and
  188. // the URL does not contain filters yet. The filters can either match the
  189. // saved filters, or can be different (i.e. sharing an unsaved state)
  190. return this.renderLoading();
  191. }
  192. return (
  193. <SentryDocumentTitle title={t('Dashboards')} orgSlug={organization.slug}>
  194. {super.renderComponent() as React.ReactChild}
  195. </SentryDocumentTitle>
  196. );
  197. }
  198. }
  199. export default withRouteAnalytics(OrgDashboards);