All files / src/react-components external-resources.js

100% Statements 61/61
100% Branches 28/28
100% Functions 21/21
100% Lines 59/59

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 296 297 298 299 300 301 302 303 304 305                                                                                                  64x   19x   45x                       17x 17x 17x   85x 85x   85x   68x     85x       17x                       64x 64x                                                                   5x                   5x 5x   2x   1x       1x         3x   5x                 17x 17x 17x   10x 10x   1x   6x   4x   6x           7x   35x   19x   4x 4x   3x         15x     35x     17x           17x 17x 17x   4x     17x           1x     3x   1x                                     20x     16x             5x     5x       4x                                 7x 7x     20x     18x       5x     1x                      
/*
 * Part of Pleiar.no - a collection of tools for nurses
 *
 * Copyright (C) Eskild Hustvedt 2018
 t 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 { connect } from 'react-redux';
import { PageTitle } from './layout';
import { Row, Col, Input, Label, InputGroup, InputGroupAddon, InputGroupText } from 'reactstrap';
import { setExtRSearchString, toggleOnlyNorwegian } from '../actions/external-resources';
import data from '../../data/datasett/external-resources.json';
import XCircle from 'react-feather/dist/icons/x-circle';
import PleiarSearcher from '../searcher';
import { InfiniteScrollSearchResultRenderer, RequiresPleiarSearcher } from './global-search';
import RoutingAssistant from '../routing';
import { getValueFromLiteralOrEvent } from '../helper.general';
import device from '../helper.device';
import { ExternalLink } from './shared/links';
import type { lunrResult } from '../types/libs';
import type { ExternalResourcesEntry as ExternalResourcesEntryType } from '../types/data';
import type { onSyncSignature } from '../routing';
import type { Location } from 'react-router-dom';
 
/**
 * Displays a line containing the language of an `ExternalResourcesEntry`, if
 * that language is not Norsk.
 */
class LanguageInformation extends React.PureComponent<{|language: string|}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        if(this.props.language !== "Norsk")
        {
            return <div className="externalLanguage">Språk: {this.props.language}</div>;
        }
        return '';
    }
}
 
/**
 * Renders a list of suggested search phrases
 */
class SearchSuggestions extends React.PureComponent<{|onSearchUpdate: (string) => mixed|}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const words = [ 'Legemiddel','Seksualitet','Kreft','Blodprøver','Forsking' ];
        const result = [];
        for(let i: number = 0; i < words.length; i++)
        {
            const word = words[i];
            let addon: string = '';
 
            if ( (i+1) < words.length)
            {
                addon += ', ';
            }
 
            result.push(<span key={i} className="externalKeyword" onClick={() => { this.props.onSearchUpdate(word);} }>
                <span className="likeLink">{word}</span>{addon}
                </span>);
        }
        return result;
    }
}
 
/**
 * Renders a single entry in the external resources list
 */
class ExternalResourcesEntry extends React.PureComponent<{| entry: ExternalResourcesEntryType |}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const dataEntry = this.props.entry;
        return <Row key={dataEntry.url} className="externalEntry">
            <Col>
                <ExternalLink basicStyle={true} href={dataEntry.url} className="linkWrapper">
                    <div className="externalTitle likeLink" target="_blank">{dataEntry.title}</div>
                    <div className="externalURL">{dataEntry.url}</div>
                    <LanguageInformation language={dataEntry.language} />
                    {dataEntry.description}
                </ExternalLink>
            </Col>
        </Row>;
    }
}
 
/**
 * The props for `ExternalResources`
 */
type ExternalResourcesProps = {|
    search: string,
    location?: Location,
    onSearchUpdate: (string) => void,
    onlyNorwegian: boolean,
    onOnlyNorwegianToggle: () => void,
    onPageUpdate: (number) => void
|};
 
/**
 * Renders the full external resources page. Complete with a search field and
 * infinite scroll.
 */
class ExternalResources extends React.Component<ExternalResourcesProps>
{
    constructor (props: ExternalResourcesProps) // eslint-disable-line require-jsdoc
 
    {
        super(props);
    }
 
    /**
     * Callback, called when either the user types or clicks on a link that
     * updates the search value. This gets bound to this instance of
     * `ExternalResources` in the `constructor`
     */
    onChanged (str: string | SyntheticEvent<HTMLInputElement>,forcedPush?: boolean)
    {
        str = getValueFromLiteralOrEvent(str);
        if(str == "")
        {
            if(forcedPush)
            {
                RoutingAssistant.push('/andresider');
            }
            else
            {
                RoutingAssistant.replace('/andresider');
            }
        }
        else
        {
            RoutingAssistant.generateReplace('/andresider',str,"auto");
        }
        this.props.onSearchUpdate(str);
    }
 
    /**
     * Performs a search and returns the result. Also handles applying a reducer
     * that limits results to only Norwegian if the `onlyNorwegian` prop is true.
     */
    getResources (): Array<lunrResult>
    {
        const search = this.props.search;
        let results: Array<lunrResult> = [];
        if(search === null || search === "" || !/\w/.test(search))
        {
            results = data;
            if(this.props.onlyNorwegian)
            {
                results = data.reduce( (acc, value) =>
                {
                    if(value.language === "Norsk")
                    {
                        acc.push(value);
                    }
                    return acc;
                }, []);
            }
        }
        else
        {
            results = PleiarSearcher.safePartialSearch(search,(accumulator: Array<lunrResult>,result: lunrResult) =>
            {
                if(result.ref.indexOf("external") === 0)
                {
                    if(this.props.onlyNorwegian)
                    {
                        const entry = PleiarSearcher.getResultFromRef( result.ref );
                        if(entry && entry.externalResources && entry.externalResources.language === "Norsk")
                        {
                            accumulator.push(result);
                        }
                    }
                    else
                    {
                        accumulator.push(result);
                    }
                }
                return accumulator;
            });
        }
        return results;
    }
 
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const entries = this.getResources();
        let autoFocus: boolean = true;
        if(device.isTouchScreen())
        {
            autoFocus = false;
        }
 
        return  <Row>
            <Col lg={{offset:2,size:8}}>
                <PageTitle title="Andre sider" />
                <h3>Andre sider</h3>
                <div>Her kan du finne andre nettstader som kan vere nyttige for pleiepersonell og studentar. Lista er relativt lang, så det enkleste er å søke.<br /><br />Nokre forslag til søkjeord:&nbsp;
                    {/* FIXME */}
                    <SearchSuggestions onSearchUpdate={(e,force) => this.onChanged(e,force)} />
                </div>
                <InputGroup>
                    <Input autoFocus={autoFocus} placeholder="Søk" value={this.props.search} onChange={(e,force) => this.onChanged(e,force) } name="search" />
                    <InputGroupAddon addonType="append">
                        <InputGroupText className="clearSearchField" onClick={ () => { this.onChanged('', true); } }>
                            <XCircle />
                        </InputGroupText>
                    </InputGroupAddon>
                </InputGroup>
                <Row>
                    <Col className="align-self-center form-inline">
                        <Label check>
                            <Input name="onlyNorwegian" type="checkbox" checked={this.props.onlyNorwegian} onChange={this.props.onOnlyNorwegianToggle} /> Vis kun sider/kjelder på Norsk
                        </Label>
                    </Col>
                </Row>
                <hr />
                <InfiniteScrollSearchResultRenderer result={entries} search={this.props.search} type="externalResources" suggestGlobalSearch={true} searchPathPrefix="/andresider" location={this.props.location} />
            </Col>
        </Row>;
    }
}
 
const ExternalResourcesContainer = connect(
    (state) =>
    {
        return {
            search: state.externalResources.search,
            onlyNorwegian: state.externalResources.onlyNorwegian,
        };
    },
    (dispatch) =>
    {
        return {
            onSearchUpdate(val: string)
            {
                dispatch(setExtRSearchString(val));
            },
            onOnlyNorwegianToggle ()
            {
                dispatch(toggleOnlyNorwegian());
            },
        };
    }
)(ExternalResources);
 
type ExternalResourcesContainerProps = {| onRouteSync: onSyncSignature |};
/**
 * This is a wrapper around ExternalResources. It wraps it in a
 * RequiresPleiarSearcher component to ensure PleiarSearcher is initialized
 * once ExternalResources starts rendering.
 */
class ExternalResourcesWrapper extends React.Component<ExternalResourcesContainerProps>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const { onRouteSync, ...moreProps } = this.props;
        return <RequiresPleiarSearcher component={ExternalResourcesContainer} onRouteSync={onRouteSync} app="external" {...moreProps} />;
    }
}
const ExternalResourcesWrapperContainer: React.AbstractComponent<{| |}> = connect<ExternalResourcesContainerProps,{||},_,ExternalResourcesContainerProps,_,_>(
    () =>
    {
        return {};
    },
    (dispatch): ExternalResourcesContainerProps =>
    {
        return {
            onRouteSync(search)
            {
                dispatch(setExtRSearchString(search));
            },
        };
    }
)(ExternalResourcesWrapper);
 
// Public exports
export default ExternalResourcesWrapperContainer;
export { ExternalResourcesEntry };
// Testing exports
export { ExternalResources as ExternalResourcesContainerRaw };