-
Notifications
You must be signed in to change notification settings - Fork 13.9k
/
DashboardPage.tsx
261 lines (240 loc) · 8.39 KB
/
DashboardPage.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { createContext, lazy, FC, useEffect, useMemo, useRef } from 'react';
import { Global } from '@emotion/react';
import { useHistory } from 'react-router-dom';
import { t, useTheme } from '@superset-ui/core';
import { useDispatch, useSelector } from 'react-redux';
import { createSelector } from '@reduxjs/toolkit';
import { useToasts } from 'src/components/MessageToasts/withToasts';
import Loading from 'src/components/Loading';
import {
useDashboard,
useDashboardCharts,
useDashboardDatasets,
} from 'src/hooks/apiResources';
import { hydrateDashboard } from 'src/dashboard/actions/hydrate';
import { setDatasources } from 'src/dashboard/actions/datasources';
import injectCustomCss from 'src/dashboard/util/injectCustomCss';
import {
getAllActiveFilters,
getRelevantDataMask,
} from 'src/dashboard/util/activeAllDashboardFilters';
import { getActiveFilters } from 'src/dashboard/util/activeDashboardFilters';
import { LocalStorageKeys, setItem } from 'src/utils/localStorageHelpers';
import { URL_PARAMS } from 'src/constants';
import { getUrlParam } from 'src/utils/urlUtils';
import { setDatasetsStatus } from 'src/dashboard/actions/dashboardState';
import {
getFilterValue,
getPermalinkValue,
} from 'src/dashboard/components/nativeFilters/FilterBar/keyValue';
import DashboardContainer from 'src/dashboard/containers/Dashboard';
import { nanoid } from 'nanoid';
import { RootState } from '../types';
import {
chartContextMenuStyles,
filterCardPopoverStyle,
focusStyle,
headerStyles,
chartHeaderStyles,
} from '../styles';
import SyncDashboardState, {
getDashboardContextLocalStorage,
} from '../components/SyncDashboardState';
export const DashboardPageIdContext = createContext('');
const DashboardBuilder = lazy(
() =>
import(
/* webpackChunkName: "DashboardContainer" */
/* webpackPreload: true */
'src/dashboard/components/DashboardBuilder/DashboardBuilder'
),
);
const originalDocumentTitle = document.title;
type PageProps = {
idOrSlug: string;
};
// TODO: move to Dashboard.jsx when it's refactored to functional component
const selectRelevantDatamask = createSelector(
(state: RootState) => state.dataMask, // the first argument accesses relevant data from global state
dataMask => getRelevantDataMask(dataMask, 'ownState'), // the second parameter conducts the transformation
);
// TODO: move to Dashboard.jsx when it's refactored to functional component
const selectActiveFilters = createSelector(
(state: RootState) => ({
// eslint-disable-next-line camelcase
chartConfiguration: state.dashboardInfo.metadata?.chart_configuration,
nativeFilters: state.nativeFilters.filters,
dataMask: state.dataMask,
allSliceIds: state.dashboardState.sliceIds,
}),
({ chartConfiguration, nativeFilters, dataMask, allSliceIds }) => ({
...getActiveFilters(),
...getAllActiveFilters({
// eslint-disable-next-line camelcase
chartConfiguration,
nativeFilters,
dataMask,
allSliceIds,
}),
}),
);
export const DashboardPage: FC<PageProps> = ({ idOrSlug }: PageProps) => {
const theme = useTheme();
const dispatch = useDispatch();
const history = useHistory();
const dashboardPageId = useMemo(() => nanoid(), []);
const hasDashboardInfoInitiated = useSelector<RootState, Boolean>(
({ dashboardInfo }) =>
dashboardInfo && Object.keys(dashboardInfo).length > 0,
);
const { addDangerToast } = useToasts();
const { result: dashboard, error: dashboardApiError } =
useDashboard(idOrSlug);
const { result: charts, error: chartsApiError } =
useDashboardCharts(idOrSlug);
const {
result: datasets,
error: datasetsApiError,
status,
} = useDashboardDatasets(idOrSlug);
const isDashboardHydrated = useRef(false);
const error = dashboardApiError || chartsApiError;
const readyToRender = Boolean(dashboard && charts);
const { dashboard_title, css, id = 0 } = dashboard || {};
useEffect(() => {
// mark tab id as redundant when user closes browser tab - a new id will be
// generated next time user opens a dashboard and the old one won't be reused
const handleTabClose = () => {
const dashboardsContexts = getDashboardContextLocalStorage();
setItem(LocalStorageKeys.DashboardExploreContext, {
...dashboardsContexts,
[dashboardPageId]: {
...dashboardsContexts[dashboardPageId],
isRedundant: true,
},
});
};
window.addEventListener('beforeunload', handleTabClose);
return () => {
window.removeEventListener('beforeunload', handleTabClose);
};
}, [dashboardPageId]);
useEffect(() => {
dispatch(setDatasetsStatus(status));
}, [dispatch, status]);
useEffect(() => {
// eslint-disable-next-line consistent-return
async function getDataMaskApplied() {
const permalinkKey = getUrlParam(URL_PARAMS.permalinkKey);
const nativeFilterKeyValue = getUrlParam(URL_PARAMS.nativeFiltersKey);
const isOldRison = getUrlParam(URL_PARAMS.nativeFilters);
let dataMask = nativeFilterKeyValue || {};
// activeTabs is initialized with undefined so that it doesn't override
// the currently stored value when hydrating
let activeTabs: string[] | undefined;
if (permalinkKey) {
const permalinkValue = await getPermalinkValue(permalinkKey);
if (permalinkValue) {
({ dataMask, activeTabs } = permalinkValue.state);
}
} else if (nativeFilterKeyValue) {
dataMask = await getFilterValue(id, nativeFilterKeyValue);
}
if (isOldRison) {
dataMask = isOldRison;
}
if (readyToRender) {
if (!isDashboardHydrated.current) {
isDashboardHydrated.current = true;
}
dispatch(
hydrateDashboard({
history,
dashboard,
charts,
activeTabs,
dataMask,
}),
);
}
return null;
}
if (id) getDataMaskApplied();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [readyToRender]);
useEffect(() => {
if (dashboard_title) {
document.title = dashboard_title;
}
return () => {
document.title = originalDocumentTitle;
};
}, [dashboard_title]);
useEffect(() => {
if (typeof css === 'string') {
// returning will clean up custom css
// when dashboard unmounts or changes
return injectCustomCss(css);
}
return () => {};
}, [css]);
useEffect(() => {
if (datasetsApiError) {
addDangerToast(
t('Error loading chart datasources. Filters may not work correctly.'),
);
} else {
dispatch(setDatasources(datasets));
}
}, [addDangerToast, datasets, datasetsApiError, dispatch]);
const relevantDataMask = useSelector(selectRelevantDatamask);
const activeFilters = useSelector(selectActiveFilters);
if (error) throw error; // caught in error boundary
return (
<>
<Global
styles={[
filterCardPopoverStyle(theme),
headerStyles(theme),
chartContextMenuStyles(theme),
focusStyle(theme),
chartHeaderStyles(theme),
]}
/>
{readyToRender && hasDashboardInfoInitiated ? (
<>
<SyncDashboardState dashboardPageId={dashboardPageId} />
<DashboardPageIdContext.Provider value={dashboardPageId}>
<DashboardContainer
activeFilters={activeFilters}
ownDataCharts={relevantDataMask}
>
<DashboardBuilder />
</DashboardContainer>
</DashboardPageIdContext.Provider>
</>
) : (
<Loading />
)}
</>
);
};
export default DashboardPage;