• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / gui / 1113439055

19 Dec 2023 09:01PM UTC coverage: 82.752% (-17.2%) from 99.964%
1113439055

Pull #4258

gitlab-ci

mender-test-bot
chore: Types update

Signed-off-by: Mender Test Bot <mender@northern.tech>
Pull Request #4258: chore: Types update

4326 of 6319 branches covered (0.0%)

8348 of 10088 relevant lines covered (82.75%)

189.39 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.67
/src/js/components/app.js
1
// Copyright 2015 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14
import React, { useCallback, useEffect, useState } from 'react';
15
import { useIdleTimer, workerTimers } from 'react-idle-timer';
16
import { Provider, useDispatch, useSelector } from 'react-redux';
17
import { BrowserRouter, useLocation, useNavigate } from 'react-router-dom';
18

19
import createCache from '@emotion/cache';
20
import { CacheProvider } from '@emotion/react';
21
import { CssBaseline } from '@mui/material';
22
import { ThemeProvider, createTheme } from '@mui/material/styles';
23
import withStyles from '@mui/styles/withStyles';
24
import { LocalizationProvider } from '@mui/x-date-pickers';
25
import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment';
26
import { makeStyles } from 'tss-react/mui';
27

28
import Cookies from 'universal-cookie';
29

30
import { parseEnvironmentInfo, setSnackbar } from '../actions/appActions';
31
import { logoutUser, setAccountActivationCode, setShowConnectingDialog } from '../actions/userActions';
32
import { getSessionInfo, maxSessionAge, updateMaxAge } from '../auth';
33
import SharedSnackbar from '../components/common/sharedsnackbar';
34
import { PrivateRoutes, PublicRoutes } from '../config/routes';
35
import { TIMEOUTS } from '../constants/appConstants';
36
import ErrorBoundary from '../errorboundary';
37
import { isDarkMode, toggle } from '../helpers';
38
import store from '../reducers';
39
import { getCurrentSession, getCurrentUser, getUserSettings } from '../selectors';
40
import { dark as darkTheme, light as lightTheme } from '../themes/Mender';
41
import Tracking from '../tracking';
42
import ConfirmDismissHelptips from './common/dialogs/confirmdismisshelptips';
43
import DeviceConnectionDialog from './common/dialogs/deviceconnectiondialog';
44
import Footer from './footer';
45
import Header from './header/header';
46
import LeftNav from './leftnav';
47
import SearchResult from './search-result';
48
import Uploads from './uploads';
49

50
const cache = createCache({ key: 'mui', prepend: true });
1✔
51

52
const activationPath = '/activate';
1✔
53
const trackingBlacklist = [/\/password\/.+/i];
1✔
54
const timeout = maxSessionAge * 1000; // 15 minutes idle time
1✔
55
const cookies = new Cookies();
1✔
56

57
const reducePalette =
58
  prefix =>
1✔
59
  (accu, [key, value]) => {
184✔
60
    if (value instanceof Object) {
800✔
61
      return {
176✔
62
        ...accu,
63
        ...Object.entries(value).reduce(reducePalette(`${prefix}-${key}`), {})
64
      };
65
    } else {
66
      accu[`${prefix}-${key}`] = value;
624✔
67
    }
68
    return accu;
624✔
69
  };
70

71
const cssVariables = ({ palette }) => {
1✔
72
  const muiVariables = Object.entries(palette).reduce(reducePalette('--mui'), {});
8✔
73
  return {
8✔
74
    '@global': {
75
      ':root': {
76
        ...muiVariables,
77
        '--mui-overlay': palette.grey[400]
78
      }
79
    }
80
  };
81
};
82

83
const WrappedBaseline = withStyles(cssVariables)(CssBaseline);
1✔
84

85
const useStyles = makeStyles()(() => ({
2✔
86
  public: {
87
    display: 'grid',
88
    gridTemplateRows: 'max-content 1fr max-content',
89
    height: '100vh',
90
    '.content': {
91
      alignSelf: 'center',
92
      justifySelf: 'center'
93
    }
94
  }
95
}));
96

97
export const AppRoot = () => {
1✔
98
  const [showSearchResult, setShowSearchResult] = useState(false);
8✔
99
  const navigate = useNavigate();
8✔
100
  const { pathname = '', hash } = useLocation();
8!
101

102
  const dispatch = useDispatch();
8✔
103
  const { id: currentUser } = useSelector(getCurrentUser);
8✔
104
  const showDismissHelptipsDialog = useSelector(state => !state.onboarding.complete && state.onboarding.showTipsDialog);
1,004✔
105
  const showDeviceConnectionDialog = useSelector(state => state.users.showConnectDeviceDialog);
1,004✔
106
  const snackbar = useSelector(state => state.app.snackbar);
1,004✔
107
  const trackingCode = useSelector(state => state.app.trackerCode);
1,004✔
108
  const { mode } = useSelector(getUserSettings);
8✔
109
  const { token: storedToken } = getSessionInfo();
8✔
110
  const { expiresAt, token = storedToken } = useSelector(getCurrentSession);
8✔
111

112
  const trackLocationChange = useCallback(
8✔
113
    pathname => {
114
      let page = pathname;
3✔
115
      // if we're on page whose path might contain sensitive device/ group/ deployment names etc. we sanitize the sent information before submission
116
      if (page.includes('=') && (page.startsWith('/devices') || page.startsWith('/deployments'))) {
3!
117
        const splitter = page.lastIndexOf('/');
×
118
        const filters = page.slice(splitter + 1);
×
119
        const keyOnlyFilters = filters.split('&').reduce((accu, item) => `${accu}:${item.split('=')[0]}&`, ''); // assume the keys to filter by are not as revealing as the values things are filtered by
×
120
        page = `${page.substring(0, splitter)}?${keyOnlyFilters.substring(0, keyOnlyFilters.length - 1)}`; // cut off the last & of the reduced filters string
×
121
      } else if (page.startsWith(activationPath)) {
3!
122
        dispatch(setAccountActivationCode(page.substring(activationPath.length + 1)));
×
123
        navigate('/settings/my-profile', { replace: true });
×
124
      } else if (trackingBlacklist.some(item => !!page.match(item))) {
3!
125
        return;
×
126
      }
127
      Tracking.pageview(page);
3✔
128
    },
129
    [dispatch, navigate]
130
  );
131

132
  useEffect(() => {
8✔
133
    dispatch(parseEnvironmentInfo());
3✔
134
    if (!trackingCode) {
3✔
135
      return;
1✔
136
    }
137
    if (!cookies.get('_ga')) {
2!
138
      Tracking.cookieconsent().then(({ trackingConsentGiven }) => {
2✔
139
        if (trackingConsentGiven) {
×
140
          Tracking.initialize(trackingCode);
×
141
          Tracking.pageview();
×
142
        }
143
      });
144
    } else {
145
      Tracking.initialize(trackingCode);
×
146
    }
147
  }, [dispatch, trackingCode]);
148

149
  useEffect(() => {
8✔
150
    if (!(trackingCode && cookies.get('_ga'))) {
4!
151
      return;
4✔
152
    }
153
    trackLocationChange(pathname);
×
154
  }, [pathname, trackLocationChange, trackingCode]);
155

156
  useEffect(() => {
8✔
157
    trackLocationChange(pathname);
3✔
158
    // the following is added to ensure backwards capability for hash containing routes & links (e.g. /ui/#/devices => /ui/devices)
159
    if (hash) {
3!
160
      navigate(hash.substring(1));
×
161
    }
162
  }, [hash, navigate, pathname, trackLocationChange]);
163

164
  const updateExpiryDate = useCallback(() => updateMaxAge({ expiresAt, token }), [expiresAt, token]);
8✔
165

166
  const onIdle = useCallback(() => {
8✔
167
    if (!!expiresAt && currentUser) {
2✔
168
      // logout user and warn
169
      return dispatch(logoutUser())
1✔
170
        .catch(updateExpiryDate)
171
        .then(() => {
172
          navigate('//'); // double / to ensure the logged out URL conforms to `/ui/` in order to not trigger a redirect and potentially use state
1✔
173
          // async snackbar setting to ensure the login screen has loaded as the snackbar might be cleared by other actions otherwise
174
          setTimeout(() => dispatch(setSnackbar('Your session has expired. You have been automatically logged out due to inactivity.')), TIMEOUTS.oneSecond);
1✔
175
        });
176
    }
177
  }, [currentUser, dispatch, expiresAt, navigate, updateExpiryDate]);
178

179
  useIdleTimer({ crossTab: true, onAction: updateExpiryDate, onActive: updateExpiryDate, onIdle, syncTimers: 400, timeout, timers: workerTimers });
8✔
180

181
  const onToggleSearchResult = () => setShowSearchResult(toggle);
8✔
182

183
  const theme = createTheme(isDarkMode(mode) ? darkTheme : lightTheme);
8!
184

185
  const { classes } = useStyles();
8✔
186

187
  return (
8✔
188
    <ThemeProvider theme={theme}>
189
      <WrappedBaseline enableColorScheme />
190
      <>
191
        {token ? (
8✔
192
          <div id="app">
193
            <Header mode={mode} />
194
            <LeftNav />
195
            <div className="rightFluid container">
196
              <ErrorBoundary>
197
                <SearchResult onToggleSearchResult={onToggleSearchResult} open={showSearchResult} />
198
                <PrivateRoutes />
199
              </ErrorBoundary>
200
            </div>
201
            {showDismissHelptipsDialog && <ConfirmDismissHelptips />}
4!
202
            {showDeviceConnectionDialog && <DeviceConnectionDialog onCancel={() => dispatch(setShowConnectingDialog(false))} />}
×
203
          </div>
204
        ) : (
205
          <div className={classes.public}>
206
            <PublicRoutes />
207
            <Footer />
208
          </div>
209
        )}
210
        <SharedSnackbar snackbar={snackbar} setSnackbar={message => dispatch(setSnackbar(message))} />
×
211
        <Uploads />
212
      </>
213
    </ThemeProvider>
214
  );
215
};
216

217
export const AppProviders = ({ basename = 'ui' }) => (
1!
218
  <React.StrictMode>
×
219
    <Provider store={store}>
220
      <CacheProvider value={cache}>
221
        <LocalizationProvider dateAdapter={AdapterMoment}>
222
          <ErrorBoundary>
223
            <BrowserRouter basename={basename}>
224
              <AppRoot />
225
            </BrowserRouter>
226
          </ErrorBoundary>
227
        </LocalizationProvider>
228
      </CacheProvider>
229
    </Provider>
230
  </React.StrictMode>
231
);
232

233
export default AppRoot;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc