orgDashboards.tsx 6.4 KB

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