All files / src/react-components main.js

100% Statements 44/44
86.49% Branches 32/37
100% Functions 9/9
100% Lines 44/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295                                                                                                                                                          126x 126x     126x                 129x   3x     126x   126x       1x       3x   1x       1x   1x             2x                               129x   129x   129x 129x     129x   3x     1x 1x           129x     1x   1x   1x         129x                                                                   8x       1x       7x     8x   8x                                               8x 8x         7x   1x               6x               1x   7x           7x   1x   1x           7x   2x   1x                  
/*
 * Part of Pleiar.no - a collection of tools for nurses
 *
 * Copyright (C) Eskild Hustvedt 2017-2018
 * Copyright (C) Fagforbundet 2019
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
 
// @flow
import * as React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import pleiarStore from '../reducers/root';
import Menu from './menu';
import About from './about';
import Handbook from './handbook';
import QuickRef from './quickref';
import ExternalResources from './external-resources';
import Dictionary from './dictionary';
import GlobalSearch from './global-search';
import Covid19 from './covid19';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { Alert } from 'reactstrap';
import OfflinePluginRuntime from 'offline-plugin/runtime';
import FrontPage from './frontpage';
import { Handle404, ScrollToTopHelper } from './shared';
import { RoutingAssistantInit } from '../routing.js';
import { applyBrowserWorkaroundsIfNeeded } from '../workarounds';
import Tools from './tools';
import { Authenticator } from './auth';
import PleiarSearcher from '../searcher';
import { appInstall } from '../mobile-appinstall';
import device from '../helper.device';
import { ExternalLink } from './shared/links';
import QuizModule from './elearn';
 
import type { Store as ReduxStore } from 'redux';
import type { pleiarReduxState } from '../reducers/root';
 
// Let flow know about our GIT_REVISION and PLEIAR_ENV globals (from webpack)
declare var GIT_REVISION:string;
declare var PLEIAR_ENV:string;
 
/**
 * Props for Pleiar
 */
type PleiarProps = {| store: ReduxStore<pleiarReduxState,{||}>, baseState?: pleiarReduxState |};
/**
 * State for Pleiar
 */
type PleiarState = {| updateIsAvailable: boolean |};
 
/**
 * The root handler. Renders the menu and passes control off to the rendering
 * component.
 */
class Pleiar extends React.Component<PleiarProps, PleiarState>
{
    offlineInstalled: boolean;
 
    constructor(props: PleiarProps) // eslint-disable-line require-jsdoc
 
    {
        super(props);
        this.state = {
            updateIsAvailable: false
        };
        this.offlineInstalled = false;
    }
 
    /**
     * This function starts our service worker/OfflinePluginRuntime.
     * It sets updateIsAvailable when/if an update becomes available.
     */
    offlineManager ()
    {
        if(this.offlineInstalled)
        {
            return;
        }
        // Silently prevent us from executing multiple times
        this.offlineInstalled = true;
        // Install service worker
        OfflinePluginRuntime.install({
            onUpdateReady: () =>
            {
                // Tells to new SW to take control immediately
                OfflinePluginRuntime.applyUpdate();
            },
            onUpdated: () =>
            {
                if(window.location.pathname == '/' || JSON.stringify(this.props.baseState) == JSON.stringify(this.props.store.getState()))
                {
                    window.location.reload();
                    // We set a timeout so that IF the reload should for some reason take forever
                    // or fail, we display the "update available" message. Otherwise this just
                    // causes the app to needlessly flash just before repainting the new version.
                    setTimeout( () =>
                    {
                        this.setState({
                            updateIsAvailable: true
                        });
                    },4000);
                }
                else
                {
                    this.setState({
                        updateIsAvailable: true
                    });
                }
            }
        });
    }
 
    /**
     * React rendering method
     */
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        // This is the "notification line". Contains elements to render either
        // the "updates available" or "this is the staging instance" lines.
        const notificationLine = [];
        // Initialize the offline plugin (unless we're running under react-snap)
        Eif(navigator.userAgent !== "ReactSnap")
        {
            this.offlineManager();
            appInstall.init();
        }
        // If we have an update available, render information about it
        if(this.state.updateIsAvailable)
        {
            notificationLine.push( <Alert color="success text-center" key="updateAvailable">
                Pleiar.no har verta oppdatert. <span className="likeLink" onClick={(ev) =>
                {
                    ev.preventDefault();
                    window.location.reload();
                }}>Trykk her</span> for å ta i bruk den nye versjonen (det du holder på med vil gå tapt).
            </Alert> );
        }
        // If we're the staging server, tell the user about it and provide a link
        // to production in case they're here by mistake.
        if(PLEIAR_ENV === "staging")
        {
            let link: ?React.Node;
            Eif(navigator.userAgent !== "ReactSnap")
            {
                link = <ExternalLink sameWindow={true} href="https://www.pleiar.no/">{device.isAppMode() ? 'og installerer ' : 'Gå til '}den vanlige versjonen.</ExternalLink>;
            }
            notificationLine.push(<Alert color="warning" className="text-center" key="staging">
                    Dette er utviklingsversjonen av Pleiar.no. Den er berre til testing og kan vere ustabil. {device.isAppMode() ? 'Vi anbefaler at du avinstallerer denne appen ':''} {link}
                </Alert>);
        }
 
        return <BrowserRouter>
                <Provider store={this.props.store}>
                    <ScrollToTopHelper />
                    <RoutingAssistantInit />
                    <div>
                        <Menu />
                        {notificationLine}
                        <Switch>
                            <Route exact path="/" component={FrontPage} />
                            <Route path="/om" component={About} />
                            <Route path="/verktoy" component={Tools} />
                            <Route path="/auth" component={Authenticator} />
                            <Route path="/covid19" component={Covid19} />
                            <Route path="/andresider/:query?/:renderElements?/:filter?" component={ExternalResources} />
                            <Route path="/ordliste/:query?/:renderElements?/:filter?" component={Dictionary} />
                            <Route path="/sok/:query?/:renderElements?/:filter?" component={GlobalSearch} />
                            <Route path="/handbok/:handbookPath*" component={Handbook} />
                            <Route path="/oppslag/:quickrefPath*" component={QuickRef} />
                            <Route path="/elaering/:learningSet?" component={QuizModule} />
                            <Handle404 root={true} />
                        </Switch>
                    </div>
                </Provider>
            </BrowserRouter>;
    }
}
 
/**
 * The main initialization function.
 */
function main ()
{
    // Create the react store
    let store: ReduxStore<pleiarReduxState,{||}>;
    if (PLEIAR_ENV !== "production")
    {
        // In non-production environments, allow the redux devtools to hook into
        // our store.
        store = createStore(pleiarStore,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
    }
    else
    {
        store = createStore(pleiarStore);
    }
 
    const baseState = store.getState();
 
    const root = document.getElementById("root");
    /*
     * This is here because there are cases (such as search results or other
     * content that we dynamically generate) where the prerendered version will
     * differ so hugely from the one that we will render client-side that react
     * won't be able to hydrate() properly.
     *
     * This happens when the server rendered a 404 page, and we're going to
     * render something completely different. At this point we don't actually
     * know if we're going to render something completely different, so we err
     * on the side of caution and just render everything from scratch.
     *
     * There is an actual bug this works around. When hydrating a 404-tree
     * which gets turned into something other than 404, it won't properly
     * update the dom, and will leave some of the 404 elements in there, namely
     * the app-404 class and the spinning loader.  The result of that is that
     * pages won't be styled properly (because the app- class isn't modified)
     * *and*, even more importantly, the entire content of the page will be
     * spinning around (literally), because react ends up rendering it all as a
     * child of the div with class=spinner-border.
     *
     * Tl;dr: if we're on a 404 page, we don't call hydrate() even if we have
     * prerendered content. Otherwise we will spin in circles forever.
     */
    const is404 = document.getElementsByClassName('app-404').length > 0;
    if(root)
    {
        // If root already has children and the pre-rednered content isn't a
        // 404 page, then we use the hydrate() method to attach to the
        // existing, pre-rendered static version of the page
        if(root.hasChildNodes() && !is404)
        {
            ReactDOM.hydrate(
                <Pleiar store={store} baseState={baseState} />,
                root
            );
        }
        // Otherwise, initialize react as normal
        else
        {
            ReactDOM.render(
                <Pleiar store={store} baseState={baseState} />,
                root
            );
        }
    }
    else
    {
        throw('No root element to render into, aborting');
    }
    applyBrowserWorkaroundsIfNeeded();
 
    /*
     * We want to pre-initialize PleiarSearcher to make the experience smoother.
     * We wait one second and then initialize it if it hasn't been already.
     */
    setTimeout( () =>
    {
        Eif (!PleiarSearcher.hasInitialized())
        {
            PleiarSearcher.initialize();
        }
    },1000);
    /*
     * Request persistent storage when in app mode
     */
    if(device.isAppMode())
    {
		if (window.navigator.storage && window.navigator.storage.persist && typeof(window.navigator.storage.persist) === 'function')
        {
            window.navigator.storage.persist();
        }
    }
}
 
// Used in production, imported in index.js
export { main };
// Used in development/testing
export { Pleiar, OfflinePluginRuntime };