All files / src/react-components shared.js

100% Statements 32/32
100% Branches 18/18
100% Functions 13/13
100% Lines 31/31

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                                                                                  11x 11x       11x       11x   1x                           12x   11x             1x   12x   1x               11x                                   1x                                             2x   1x             111x       36x                   7x                                   1x                                                                                     32x 32x 32x         32x   7x   5x         1x                       42x 42x   34x   8x   1x   7x                
/*
 * 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 { Route } from 'react-router-dom';
import type { Location } from 'react-router-dom';
import { MainContainer, PageTitle } from './layout';
import { withRouter } from 'react-router';
import RoutingAssistant from '../routing';
import * as OfflinePluginRuntime from 'offline-plugin/runtime';
 
type NotFoundProps = {|
    root?: boolean | null
|};
 
/**
 * The component that renders our 404 message.
 */
class NotFound extends React.PureComponent<NotFoundProps, {| hasCheckedForUpdates: boolean |}>
{
    constructor(props: NotFoundProps) //eslint-disable-line require-jsdoc
    {
        super(props);
        this.state = {
            hasCheckedForUpdates: false
        };
 
        OfflinePluginRuntime.update();
        // Yes, this is basically cheating, but it does give the site a bit more
        // feedback. We can't actually know if the OfflinePluginRuntime is checking for
        // updates (or is done updating), so we pretend we know by using a timeout.
        setTimeout( () =>
        {
            this.setState({hasCheckedForUpdates: true});
        },15000);
    }
 
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        let content: React.Node | string;
        /*
         * Display "updating" message if we haven't yet checked for updates
         * *AND* we're not running react-snap. Under react-snap we will want to
         * display the real message regardless, so that 404 preview images
         * display correctly.
         */
        if(!this.state.hasCheckedForUpdates && navigator.userAgent !== "ReactSnap")
        {
            content = <div>
                <div className="spinner-border" role="status">
                </div>&nbsp;Ser etter oppdateringer til Pleiar.no i tilfelle denne sida finnes i en nyere versjon…
            </div>;
        }
        else
        {
            content = "Siden du prøvde å besøke finnes ikke. Prøv å finne det du leter etter ved å bruke menyen over.";
        }
        if(this.props.root)
        {
            return <MainContainer app="404">
                <PageTitle title="404: fil ikke funnet" />
                <h3>404 feil: fil ikke funnet</h3>
                {content}
            </MainContainer>;
        }
        else
        {
            return <div>
                <h3>404 feil: fil ikke funnet</h3>
                {content}
                </div>;
        }
    }
}
 
/**
 * A 404 handler. Should be the last element of a `<Switch></Switch>`-block. Will
 * slurp up anything that hasn't been handled by any of the `Route`s above it and
 * display a 404 message.
 */
class Handle404 extends React.Component<{|root?: boolean | null|}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        return <Route path="*" render={() => {return <NotFound root={this.props.root} />; }} />;
    }
}
 
/**
 * Props for ScrollToTopHelper
 */
type ScrollToTopHelperProps = {|
    location: Location
|};
 
/**
 * A helper component that calls `window.scrollTo(0,0)` whenever the URL
 * is updated. This is needed because the browser won't on its own scroll
 * to the top. Note that his element accepts no children.
 */
class ScrollToTopHelper extends React.Component<ScrollToTopHelperProps>
{
    /**
     * We do the actual scrolling in componentDidUpdate.
     */
    componentDidUpdate(prevProps: ScrollToTopHelperProps)
    {
        if (this.props.location.pathname !== prevProps.location.pathname && !RoutingAssistant.isManagedChange())
        {
            window.scrollTo(0, 0);
        }
    }
 
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        return null;
    }
}
 
const ScrollToTopHelperWithRouter: React.AbstractComponent<{| |}> = withRouter(ScrollToTopHelper);
 
/**
 * The component rendered while `ConditionalRender` waits for its condition to resolve.
 */
class ConditionalRenderLoading extends React.PureComponent<{||}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        return <MainContainer app="loading">
            <div className="text-center loading">
                <div className="spinner-border" role="status">
                    <span className="sr-only">Laster resultater ...</span>
                </div>
            </div>
        </MainContainer>;
    }
}
 
/**
 * The component rendered if `ConditionalRender` is rejected.
 */
class ConditionalRenderRejected extends React.PureComponent<{| reason: string|}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        return <MainContainer app="loading">
            <div className="text-center loading">
                Mislyktes i å laste nødvendig data: {this.props.reason}<br />
                Prøv igjen senere.
            </div>
        </MainContainer>;
    }
}
 
// eslint-disable-next-line flowtype/require-exact-type
type ConditionalRenderProps = {
    component: React.ComponentType<*>,
    test: () => boolean,
    resolve: () => Promise<null>
};
type ConditionalRenderState = {|
    resolved: boolean,
    rejected: boolean,
    rejectReason?: string
|};
/**
 * ConditionalRender is a component that can be used to wrap another component
 * that depends on some state that we might not have. It accepts a `component`, which
 * is the component to be rendered when the data is present, a `test` function, whose
 * return value will be used as the initial state, and a `resolve` function.
 *
 * The `test` function is run once, during construction. If it returns true,
 * then ConditionalRender will assume that the data is already present and
 * always render `component`. This is used to avoid having to flash a loading
 * message if we're just going to resolve it miliseconds later because we
 * already have the data. If it is false, then it will run `resolve`, and
 * render ConditionalRenderLoading. Once the promise returned from `resolve` is
 * resolved it will render `component` unconditionally.
 *
 * A `ConditionalRender` can only resolve once. So once it has been resolved, it
 * will stay resolved, even if its props change. So you need a completely new
 * instance of `ConditionalRender` if you want to check a different condition,
 * you can't just update an existing instance.
 */
class ConditionalRender extends React.Component<ConditionalRenderProps, ConditionalRenderState>
{
    constructor(props: ConditionalRenderProps) // eslint-disable-line require-jsdoc
    {
        const { test: testFunction, resolve } = props;
        super(props);
        this.state = {
            resolved: testFunction(),
            rejected: false
        };
 
        if(this.state.resolved !== true)
        {
            resolve().then( () =>
            {
                this.setState({
                    resolved: true
                });
            }).catch( (reason) =>
            {
                this.setState({
                    rejected: true,
                    rejectReason: reason
                });
            });
        }
    }
 
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        // eslint-disable-next-line no-unused-vars
        const { component: RenderComponent, test, resolve, ...additionalProps } = this.props;
        if(this.state.resolved)
        {
            return <RenderComponent {...additionalProps} />;
        }
        else if(this.state.rejected && this.state.rejectReason !== undefined)
        {
            return <ConditionalRenderRejected reason={this.state.rejectReason} />;
        }
        return <ConditionalRenderLoading />;
    }
}
 
// Testing-only exports
export { ScrollToTopHelper as ScrollToTopHelperRaw, ConditionalRenderLoading, ConditionalRenderRejected };
// Public exports
export { NotFound, Handle404, ScrollToTopHelperWithRouter as ScrollToTopHelper, ConditionalRender };