123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671 |
- import {cloneElement, Component, isValidElement} from 'react';
- import type {Layout as RGLLayout} from 'react-grid-layout';
- import {browserHistory, PlainRoute, RouteComponentProps} from 'react-router';
- import styled from '@emotion/styled';
- import isEqual from 'lodash/isEqual';
- import {
- createDashboard,
- deleteDashboard,
- updateDashboard,
- } from 'sentry/actionCreators/dashboards';
- import {addSuccessMessage} from 'sentry/actionCreators/indicator';
- import {openDashboardWidgetLibraryModal} from 'sentry/actionCreators/modal';
- import {Client} from 'sentry/api';
- import Breadcrumbs from 'sentry/components/breadcrumbs';
- import HookOrDefault from 'sentry/components/hookOrDefault';
- import * as Layout from 'sentry/components/layouts/thirds';
- import NoProjectMessage from 'sentry/components/noProjectMessage';
- import GlobalSelectionHeader from 'sentry/components/organizations/globalSelectionHeader';
- import {t} from 'sentry/locale';
- import {PageContent} from 'sentry/styles/organization';
- import space from 'sentry/styles/space';
- import {Organization} from 'sentry/types';
- import {trackAnalyticsEvent} from 'sentry/utils/analytics';
- import withApi from 'sentry/utils/withApi';
- import withOrganization from 'sentry/utils/withOrganization';
- import {getDashboardLayout, saveDashboardLayout} from './gridLayout/utils';
- import Controls from './controls';
- import Dashboard, {assignTempId, constructGridItemKey} from './dashboard';
- import {DEFAULT_STATS_PERIOD, EMPTY_DASHBOARD} from './data';
- import DashboardTitle from './title';
- import {
- DashboardDetails,
- DashboardListItem,
- DashboardState,
- MAX_WIDGETS,
- Widget,
- } from './types';
- import {cloneDashboard} from './utils';
- const UNSAVED_MESSAGE = t('You have unsaved changes, are you sure you want to leave?');
- const HookHeader = HookOrDefault({hookName: 'component:dashboards-header'});
- type RouteParams = {
- orgId: string;
- dashboardId?: string;
- widgetId?: number;
- };
- type Props = RouteComponentProps<RouteParams, {}> & {
- api: Client;
- organization: Organization;
- initialState: DashboardState;
- dashboard: DashboardDetails;
- dashboards: DashboardListItem[];
- route: PlainRoute;
- onDashboardUpdate?: (updatedDashboard: DashboardDetails) => void;
- newWidget?: Widget;
- };
- type State = {
- dashboardState: DashboardState;
- modifiedDashboard: DashboardDetails | null;
- widgetToBeUpdated?: Widget;
- layout: RGLLayout[];
- widgetLimitReached: boolean;
- };
- class DashboardDetail extends Component<Props, State> {
- state: State = {
- dashboardState: this.props.initialState,
- modifiedDashboard: this.updateModifiedDashboard(this.props.initialState),
- layout: getDashboardLayout(this.props.organization.id, this.props.dashboard.id),
- widgetLimitReached: this.props.dashboard.widgets.length >= MAX_WIDGETS,
- };
- componentDidMount() {
- const {route, router} = this.props;
- this.checkStateRoute();
- router.setRouteLeaveHook(route, this.onRouteLeave);
- window.addEventListener('beforeunload', this.onUnload);
- }
- componentDidUpdate(prevProps: Props) {
- if (prevProps.location.pathname !== this.props.location.pathname) {
- this.checkStateRoute();
- }
- }
- componentWillUnmount() {
- window.removeEventListener('beforeunload', this.onUnload);
- }
- checkStateRoute() {
- const {router, organization, params} = this.props;
- const {dashboardId} = params;
- const dashboardDetailsRoute = `/organizations/${organization.slug}/dashboard/${dashboardId}/`;
- if (this.isWidgetBuilderRouter && !this.isEditing) {
- router.replace(dashboardDetailsRoute);
- }
- if (location.pathname === dashboardDetailsRoute && !!this.state.widgetToBeUpdated) {
- this.onSetWidgetToBeUpdated(undefined);
- }
- }
- updateRouteAfterSavingWidget() {
- if (this.isWidgetBuilderRouter) {
- const {router, organization, params} = this.props;
- const {dashboardId} = params;
- if (dashboardId) {
- router.replace(`/organizations/${organization.slug}/dashboard/${dashboardId}/`);
- return;
- }
- router.replace(`/organizations/${organization.slug}/dashboards/new/`);
- }
- }
- updateModifiedDashboard(dashboardState: DashboardState) {
- const {dashboard} = this.props;
- switch (dashboardState) {
- case DashboardState.CREATE:
- return cloneDashboard(EMPTY_DASHBOARD);
- case DashboardState.EDIT:
- return cloneDashboard(dashboard);
- default: {
- return null;
- }
- }
- }
- get isEditing() {
- const {dashboardState} = this.state;
- return [
- DashboardState.EDIT,
- DashboardState.CREATE,
- DashboardState.PENDING_DELETE,
- ].includes(dashboardState);
- }
- get isWidgetBuilderRouter() {
- const {location, params, organization} = this.props;
- const {dashboardId} = params;
- const newWidgetRoutes = [
- `/organizations/${organization.slug}/dashboards/new/widget/new/`,
- `/organizations/${organization.slug}/dashboard/${dashboardId}/widget/new/`,
- ];
- return newWidgetRoutes.includes(location.pathname) || this.isWidgetBuilderEditRouter;
- }
- get isWidgetBuilderEditRouter() {
- const {location, params, organization} = this.props;
- const {dashboardId, widgetId} = params;
- const widgetEditRoutes = [
- `/organizations/${organization.slug}/dashboards/new/widget/${widgetId}/edit/`,
- `/organizations/${organization.slug}/dashboard/${dashboardId}/widget/${widgetId}/edit/`,
- ];
- return widgetEditRoutes.includes(location.pathname);
- }
- get dashboardTitle() {
- const {dashboard} = this.props;
- const {modifiedDashboard} = this.state;
- return modifiedDashboard ? modifiedDashboard.title : dashboard.title;
- }
- onEdit = () => {
- const {dashboard} = this.props;
- trackAnalyticsEvent({
- eventKey: 'dashboards2.edit.start',
- eventName: 'Dashboards2: Edit start',
- organization_id: parseInt(this.props.organization.id, 10),
- });
- this.setState({
- dashboardState: DashboardState.EDIT,
- modifiedDashboard: cloneDashboard(dashboard),
- });
- };
- onRouteLeave = () => {
- if (
- ![DashboardState.VIEW, DashboardState.PENDING_DELETE].includes(
- this.state.dashboardState
- )
- ) {
- return UNSAVED_MESSAGE;
- }
- return undefined;
- };
- onUnload = (event: BeforeUnloadEvent) => {
- if (
- [DashboardState.VIEW, DashboardState.PENDING_DELETE].includes(
- this.state.dashboardState
- )
- ) {
- return;
- }
- event.preventDefault();
- event.returnValue = UNSAVED_MESSAGE;
- };
- onDelete = (dashboard: State['modifiedDashboard']) => () => {
- const {api, organization, location} = this.props;
- if (!dashboard?.id) {
- return;
- }
- const previousDashboardState = this.state.dashboardState;
- this.setState({dashboardState: DashboardState.PENDING_DELETE}, () => {
- deleteDashboard(api, organization.slug, dashboard.id)
- .then(() => {
- addSuccessMessage(t('Dashboard deleted'));
- trackAnalyticsEvent({
- eventKey: 'dashboards2.delete',
- eventName: 'Dashboards2: Delete',
- organization_id: parseInt(this.props.organization.id, 10),
- });
- browserHistory.replace({
- pathname: `/organizations/${organization.slug}/dashboards/`,
- query: location.query,
- });
- })
- .catch(() => {
- this.setState({
- dashboardState: previousDashboardState,
- });
- });
- });
- };
- onCancel = () => {
- const {organization, dashboard, location, params} = this.props;
- if (params.dashboardId) {
- trackAnalyticsEvent({
- eventKey: 'dashboards2.edit.cancel',
- eventName: 'Dashboards2: Edit cancel',
- organization_id: parseInt(this.props.organization.id, 10),
- });
- this.setState({
- dashboardState: DashboardState.VIEW,
- modifiedDashboard: null,
- layout: getDashboardLayout(organization.id, dashboard.id),
- });
- return;
- }
- trackAnalyticsEvent({
- eventKey: 'dashboards2.create.cancel',
- eventName: 'Dashboards2: Create cancel',
- organization_id: parseInt(this.props.organization.id, 10),
- });
- browserHistory.replace({
- pathname: `/organizations/${organization.slug}/dashboards/`,
- query: location.query,
- });
- };
- handleAddLibraryWidgets = (widgets: Widget[]) => {
- const {organization, dashboard, api, onDashboardUpdate, location} = this.props;
- const {dashboardState, modifiedDashboard} = this.state;
- const newModifiedDashboard = {
- ...cloneDashboard(modifiedDashboard || dashboard),
- widgets: widgets.map(assignTempId),
- };
- this.setState({
- modifiedDashboard: newModifiedDashboard,
- widgetLimitReached: widgets.length >= MAX_WIDGETS,
- });
- if ([DashboardState.CREATE, DashboardState.EDIT].includes(dashboardState)) {
- return;
- }
- updateDashboard(api, organization.slug, newModifiedDashboard).then(
- (newDashboard: DashboardDetails) => {
- if (onDashboardUpdate) {
- onDashboardUpdate(newDashboard);
- }
- addSuccessMessage(t('Dashboard updated'));
- if (dashboard && newDashboard.id !== dashboard.id) {
- browserHistory.replace({
- pathname: `/organizations/${organization.slug}/dashboard/${newDashboard.id}/`,
- query: {
- ...location.query,
- },
- });
- return;
- }
- },
- () => undefined
- );
- };
- onAddWidget = () => {
- const {organization, dashboard} = this.props;
- this.setState({
- modifiedDashboard: cloneDashboard(dashboard),
- });
- openDashboardWidgetLibraryModal({
- organization,
- dashboard,
- onAddWidget: (widgets: Widget[]) => this.handleAddLibraryWidgets(widgets),
- });
- };
- /**
- * Saves a dashboard layout where the layout keys are replaced with the IDs of new widgets.
- *
- * If there are more widgets than layout objects, these widgets will be treated as
- * new and will get default positioning. This happens when saving in mobile
- * view because we don't update the desktop layout to account for the new widget.
- *
- * Throws an error if we end up in a state where we're trying to save more layouts
- * than we have widgets.
- */
- saveLayoutWithNewWidgets = (organizationId, dashboardId, newWidgets) => {
- const {layout} = this.state;
- if (layout.length > newWidgets.length) {
- throw new Error('Expected layouts to have less length than widgets');
- }
- const newLayout = layout.map((widgetLayout, index) => ({
- ...widgetLayout,
- i: constructGridItemKey(newWidgets[index]),
- }));
- saveDashboardLayout(organizationId, dashboardId, newLayout);
- this.setState({layout: newLayout});
- };
- onCommit = () => {
- const {api, organization, location, dashboard, onDashboardUpdate} = this.props;
- const {layout, modifiedDashboard, dashboardState} = this.state;
- switch (dashboardState) {
- case DashboardState.CREATE: {
- if (modifiedDashboard) {
- createDashboard(api, organization.slug, modifiedDashboard).then(
- (newDashboard: DashboardDetails) => {
- if (organization.features.includes('dashboard-grid-layout')) {
- this.saveLayoutWithNewWidgets(
- organization.id,
- newDashboard.id,
- newDashboard.widgets
- );
- }
- addSuccessMessage(t('Dashboard created'));
- trackAnalyticsEvent({
- eventKey: 'dashboards2.create.complete',
- eventName: 'Dashboards2: Create complete',
- organization_id: parseInt(organization.id, 10),
- });
- this.setState({
- dashboardState: DashboardState.VIEW,
- });
- // redirect to new dashboard
- browserHistory.replace({
- pathname: `/organizations/${organization.slug}/dashboard/${newDashboard.id}/`,
- query: {
- ...location.query,
- },
- });
- },
- () => undefined
- );
- }
- break;
- }
- case DashboardState.EDIT: {
- // TODO(nar): This should only fire when there are changes to the layout
- // and the dashboard can be successfully saved
- if (organization.features.includes('dashboard-grid-layout')) {
- saveDashboardLayout(organization.id, dashboard.id, layout);
- }
- // only update the dashboard if there are changes
- if (modifiedDashboard) {
- if (isEqual(dashboard, modifiedDashboard)) {
- this.setState({
- dashboardState: DashboardState.VIEW,
- modifiedDashboard: null,
- });
- return;
- }
- updateDashboard(api, organization.slug, modifiedDashboard).then(
- (newDashboard: DashboardDetails) => {
- if (onDashboardUpdate) {
- onDashboardUpdate(newDashboard);
- }
- if (organization.features.includes('dashboard-grid-layout')) {
- this.saveLayoutWithNewWidgets(
- organization.id,
- newDashboard.id,
- newDashboard.widgets
- );
- }
- addSuccessMessage(t('Dashboard updated'));
- trackAnalyticsEvent({
- eventKey: 'dashboards2.edit.complete',
- eventName: 'Dashboards2: Edit complete',
- organization_id: parseInt(organization.id, 10),
- });
- this.setState({
- dashboardState: DashboardState.VIEW,
- modifiedDashboard: null,
- });
- if (dashboard && newDashboard.id !== dashboard.id) {
- browserHistory.replace({
- pathname: `/organizations/${organization.slug}/dashboard/${newDashboard.id}/`,
- query: {
- ...location.query,
- },
- });
- return;
- }
- },
- () => undefined
- );
- return;
- }
- this.setState({
- dashboardState: DashboardState.VIEW,
- modifiedDashboard: null,
- });
- break;
- }
- case DashboardState.VIEW:
- default: {
- this.setState({
- dashboardState: DashboardState.VIEW,
- modifiedDashboard: null,
- });
- break;
- }
- }
- };
- setModifiedDashboard = (dashboard: DashboardDetails) => {
- this.setState({
- modifiedDashboard: dashboard,
- });
- };
- onSetWidgetToBeUpdated = (widget?: Widget) => {
- this.setState({widgetToBeUpdated: widget});
- };
- onLayoutChange = (layout: RGLLayout[]) => {
- this.setState({layout});
- };
- onUpdateWidget = (widgets: Widget[]) => {
- this.setState(
- (state: State) => ({
- ...state,
- widgetToBeUpdated: undefined,
- widgetLimitReached: widgets.length >= MAX_WIDGETS,
- modifiedDashboard: {
- ...(state.modifiedDashboard || this.props.dashboard),
- widgets,
- },
- }),
- this.updateRouteAfterSavingWidget
- );
- };
- renderWidgetBuilder(dashboard: DashboardDetails) {
- const {children} = this.props;
- const {modifiedDashboard, widgetToBeUpdated} = this.state;
- return isValidElement(children)
- ? cloneElement(children, {
- dashboard: modifiedDashboard ?? dashboard,
- onSave: this.onUpdateWidget,
- widget: widgetToBeUpdated,
- })
- : children;
- }
- renderDefaultDashboardDetail() {
- const {organization, dashboard, dashboards, params, router, location} = this.props;
- const {layout, modifiedDashboard, dashboardState, widgetLimitReached} = this.state;
- const {dashboardId} = params;
- return (
- <GlobalSelectionHeader
- skipLoadLastUsed={organization.features.includes('global-views')}
- defaultSelection={{
- datetime: {
- start: null,
- end: null,
- utc: false,
- period: DEFAULT_STATS_PERIOD,
- },
- }}
- >
- <PageContent>
- <NoProjectMessage organization={organization}>
- <StyledPageHeader>
- <DashboardTitle
- dashboard={modifiedDashboard ?? dashboard}
- onUpdate={this.setModifiedDashboard}
- isEditing={this.isEditing}
- />
- <Controls
- organization={organization}
- dashboards={dashboards}
- onEdit={this.onEdit}
- onCancel={this.onCancel}
- onCommit={this.onCommit}
- onAddWidget={this.onAddWidget}
- onDelete={this.onDelete(dashboard)}
- dashboardState={dashboardState}
- widgetLimitReached={widgetLimitReached}
- />
- </StyledPageHeader>
- <HookHeader organization={organization} />
- <Dashboard
- paramDashboardId={dashboardId}
- dashboard={modifiedDashboard ?? dashboard}
- organization={organization}
- isEditing={this.isEditing}
- widgetLimitReached={widgetLimitReached}
- onUpdate={this.onUpdateWidget}
- onSetWidgetToBeUpdated={this.onSetWidgetToBeUpdated}
- handleAddLibraryWidgets={this.handleAddLibraryWidgets}
- router={router}
- location={location}
- layout={layout}
- onLayoutChange={this.onLayoutChange}
- />
- </NoProjectMessage>
- </PageContent>
- </GlobalSelectionHeader>
- );
- }
- renderDashboardDetail() {
- const {organization, dashboard, dashboards, params, router, location, newWidget} =
- this.props;
- const {layout, modifiedDashboard, dashboardState, widgetLimitReached} = this.state;
- const {dashboardId} = params;
- return (
- <GlobalSelectionHeader
- skipLoadLastUsed={organization.features.includes('global-views')}
- defaultSelection={{
- datetime: {
- start: null,
- end: null,
- utc: false,
- period: DEFAULT_STATS_PERIOD,
- },
- }}
- >
- <StyledPageContent>
- <NoProjectMessage organization={organization}>
- <Layout.Header>
- <Layout.HeaderContent>
- <Breadcrumbs
- crumbs={[
- {
- label: t('Dashboards'),
- to: `/organizations/${organization.slug}/dashboards/`,
- },
- {
- label:
- dashboardState === DashboardState.CREATE
- ? t('Create Dashboard')
- : organization.features.includes('dashboards-edit') &&
- dashboard.id === 'default-overview'
- ? 'Default Dashboard'
- : this.dashboardTitle,
- },
- ]}
- />
- <Layout.Title>
- <DashboardTitle
- dashboard={modifiedDashboard ?? dashboard}
- onUpdate={this.setModifiedDashboard}
- isEditing={this.isEditing}
- />
- </Layout.Title>
- </Layout.HeaderContent>
- <Layout.HeaderActions>
- <Controls
- organization={organization}
- dashboards={dashboards}
- onEdit={this.onEdit}
- onCancel={this.onCancel}
- onCommit={this.onCommit}
- onAddWidget={this.onAddWidget}
- onDelete={this.onDelete(dashboard)}
- dashboardState={dashboardState}
- widgetLimitReached={widgetLimitReached}
- />
- </Layout.HeaderActions>
- </Layout.Header>
- <Layout.Body>
- <Layout.Main fullWidth>
- <Dashboard
- paramDashboardId={dashboardId}
- dashboard={modifiedDashboard ?? dashboard}
- organization={organization}
- isEditing={this.isEditing}
- widgetLimitReached={widgetLimitReached}
- onUpdate={this.onUpdateWidget}
- handleAddLibraryWidgets={this.handleAddLibraryWidgets}
- onSetWidgetToBeUpdated={this.onSetWidgetToBeUpdated}
- router={router}
- location={location}
- newWidget={newWidget}
- layout={layout}
- onLayoutChange={this.onLayoutChange}
- />
- </Layout.Main>
- </Layout.Body>
- </NoProjectMessage>
- </StyledPageContent>
- </GlobalSelectionHeader>
- );
- }
- render() {
- const {organization, dashboard} = this.props;
- if (this.isEditing && this.isWidgetBuilderRouter) {
- return this.renderWidgetBuilder(dashboard);
- }
- if (organization.features.includes('dashboards-edit')) {
- return this.renderDashboardDetail();
- }
- return this.renderDefaultDashboardDetail();
- }
- }
- const StyledPageHeader = styled('div')`
- display: grid;
- grid-template-columns: minmax(0, 1fr);
- grid-row-gap: ${space(2)};
- align-items: center;
- font-size: ${p => p.theme.headerFontSize};
- color: ${p => p.theme.textColor};
- margin-bottom: ${space(2)};
- @media (min-width: ${p => p.theme.breakpoints[1]}) {
- grid-template-columns: minmax(0, 1fr) max-content;
- grid-column-gap: ${space(2)};
- height: 40px;
- }
- `;
- const StyledPageContent = styled(PageContent)`
- padding: 0;
- `;
- export default withApi(withOrganization(DashboardDetail));
|