All files / src/react-components handbook.js

99.15% Statements 117/118
95.52% Branches 64/67
100% Functions 15/15
99.15% Lines 116/117

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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470                                                                                                13x 13x 13x   37x 37x   17x   20x   8x   12x   10x       2x     11x                                         9x 9x                             96x 96x   63x       33x 33x   72x   33x   17x   33x   96x               6x 6x 6x   19x   3x   16x         6x               3x 3x 3x   7x   3x               8x 8x 8x 8x 8x 8x 8x   4x   4x   1x   8x   5x   8x   2x       6x   8x                                             123x                 3x       3x   2x 2x   1x               123x   123x 123x   583x         123x               2x                                             442x 442x 442x 442x 442x   200x 200x   242x   204x 204x   38x   38x   442x                               434x 434x                           246x 246x 246x 246x 246x   8x       238x   200x   238x   196x   238x   38x     246x                                                       123x   123x 123x   1x       122x       123x               123x   45x   78x                           120x   120x 120x 120x   119x 119x   115x 115x       4x 4x   2x       2x           1x 1x   120x                                
/*
 * Part of Pleiar.no - a collection of tools for nurses
 *
 * Copyright (C) Fagforbundet 2019-2020
 * Copyright (C) Eskild Hustvedt 2017-2018
 *
 * 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 { MainContainer, PageTitle } from './layout';
import { Row, Col } from 'reactstrap';
import { Markdown } from './markdown';
import { NotFound } from './shared';
import { withRouter } from 'react-router';
import { Link, Redirect } from 'react-router-dom';
// $FlowIssue[cannot-resolve-module] react-select+flow temporarily broken, tracked as https://github.com/JedWatson/react-select/issues/3612
import Select from 'react-select';
import slug from '../helper.slugs.js';
import { HandbookEntry, HandbookIndex } from '../data.handbook';
import type { QuickRefEntry } from '../data.quickref';
import { RequiresAuth } from './auth';
import SimpleAccordion from './shared/simple-accordion';
import type { ReactSelectOnChangeValue }  from '../types/libs.js';
 
/**
 * A rendering component that can render a `HandbookEntry` with a
 * searchSnippet, which is an array of `searchSnippetComponent`s that
 * `helper.lunrSnippet` has built.
 */
class HandbookLikeSearchResult extends React.PureComponent<{|entry: HandbookEntry | QuickRefEntry, prefix: string, readmore: string |}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const { entry, prefix, readmore } = this.props;
        const result = [];
        for(let componentI: number = 0; componentI < entry.searchSnippet.length; componentI++)
        {
            const component = entry.searchSnippet[componentI];
            if(component.type === "normal")
            {
                result.push(<span key={componentI}>{component.str}</span>);
            }
            else if(component.type === "highlight")
            {
                result.push(<b key={componentI}>{component.str}</b>);
            }
            else if(component.type === "delimiter")
            {
                result.push(<i className="handbookDelimiter" key={componentI}> (…) </i>);
            }
            else
            {
                throw('Unknown string type: '+component.type);
            }
        }
        return <Row className="handbookSearchEntry">
            <Col>
                <Link to={entry.url} className="linkWrapper">
                    <div className="handbookSearchTitle likeLink" target="_blank">{prefix}: {entry.title}</div>
                    {result}. <span className="likeLink">{readmore}.</span>
                </Link>
            </Col>
        </Row>;
    }
}
 
/**
 * A rendering component that can render a `HandbookEntry` with a
 * searchSnippet, which is an array of `searchSnippetComponent`s that
 * `helper.lunrSnippet` has built.
 */
class HandbookSearchResult extends React.PureComponent<{|entry: HandbookEntry |}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const { entry } = this.props;
        return <HandbookLikeSearchResult entry={entry} prefix="Håndbok" readmore="Les mer i håndboken" />;
    }
}
 
/**
 * The Pleiar.no handbook index/list renderer
 */
class HandbookIndexRenderer extends React.PureComponent<{| index?: HandbookIndex, title?: string, skipToplevelArticles?: boolean, alwaysOpen?: boolean, plainList?: boolean |}>
{
    /**
     * Recursively goes over the entire Handbook* tree and renders
     * them
     */
    recursiveRender (entry: HandbookEntry | HandbookIndex, suppressTitle: ?boolean): Array<React.Node>
    {
        const rendered = [];
        if(entry instanceof HandbookEntry)
        {
            rendered.push(<li key={entry.path.join('/')} className="topSection"><Link to={entry.url}>{entry.title}</Link></li>);
        }
        else
        {
            let children: Array<React.Node> = [];
            for(const child of entry.tree)
            {
                children = children.concat( this.recursiveRender( child ) );
            }
            if(!suppressTitle)
            {
                rendered.push(<li key={entry.path.join('/')} className="topSection"><Link to={entry.url}>{entry.title}</Link></li>);
            }
            rendered.push(<ul key={'sub-'+entry.path.join('/')}>{children}</ul>);
        }
        return rendered;
    }
 
    /**
     * Renders the index using a SimpleAccordion
     */
    renderWithAccordion (index: HandbookIndex, skipToplevelArticles: ?boolean, alwaysOpen: ?boolean): React.Node
    {
        const result = [];
        const rootChildren = index.tree;
        for(const child of rootChildren)
        {
            if(skipToplevelArticles === true && child instanceof HandbookEntry)
            {
                continue;
            }
            result.push({
                header: child.title,
                render: this.recursiveRender(child,true)
            });
        }
        return <SimpleAccordion key="idx-accordion" elements={result} alwaysOpen={ alwaysOpen === true } />;
    }
 
    /**
     * Renders the index as a basic <ul> list
     */
    renderAsUlList (index: HandbookIndex): React.Node
    {
        const result = [];
        const rootChildren = index.tree;
        for(const child of rootChildren)
        {
            result.push(this.recursiveRender(child,false));
        }
        return <ul key="hiUlList">
            {result}
        </ul>;
    }
 
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        let index: ?HandbookIndex            = this.props.index;
        const title: ?string                 = this.props.title;
        const skipToplevelArticles: ?boolean = this.props.skipToplevelArticles;
        const alwaysOpen: ?boolean           = this.props.alwaysOpen;
        const render                         = [];
        const plainList                      = this.props.plainList === true;
        if(title === null || title === undefined)
        {
            render.push(<h1 key="header">Håndbok</h1>);
        }
        else if(title.length > 0)
        {
            render.push(<h1 key="header">Håndbok: {title}</h1>);
        }
        if (index === undefined || index === null)
        {
            index = new HandbookIndex();
        }
        if(plainList)
        {
            render.push(this.renderAsUlList(index));
        }
        else
        {
            render.push(this.renderWithAccordion(index, skipToplevelArticles, alwaysOpen));
        }
        return <div className="handbookIndex">
                {render}
            </div>;
    }
}
 
/**
 * Props for `HandbookTocRender`
 */
type HandbookTocRenderProps = {| toc: Array<string> |};
 
type HandbookNavLinkRenderMode = 'nav' | 'back';
 
type HandbookNavLinkType = "next" | "previous" | "toplevel";
 
/**
 * Renders the `<Select />` box that can be used to jump between headers
 * on a handbook page
 */
class HandbookTocRender extends React.Component<HandbookTocRenderProps>
{
    constructor (props: HandbookTocRenderProps) // eslint-disable-line require-jsdoc
    {
        super(props);
    }
 
    /**
     * Handles scrolling to a header.
     * This is bound to this instance of `HandbookTocRender` in the `constructor`.
     */
    onChange (target: ReactSelectOnChangeValue)
    {
        Iif(Array.isArray(target))
        {
            return;
        }
        if(target !== undefined && target !== null)
        {
            const scrollTo = document.getElementById(target.value);
            if(scrollTo)
            {
                window.scrollTo(0, scrollTo.offsetTop);
            }
        }
    }
 
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        slug.reset();
 
        const options = [];
        for(const entry of this.props.toc)
        {
            options.push({
                label: entry,
                value: slug.get(entry)
            });
        }
        return <Select
                    options={options}
					isClearable={false}
                    value={null}
                    noResultsText="Ingen resultater funnet"
                    placeholder="Hopp til…"
					isSearchable={true}
                    autoFocus={false}
                    onChange={ (v: ReactSelectOnChangeValue) => this.onChange(v) }
                    classNamePrefix="react-select"
                    className="reactSelect"
				/>;
    }
}
 
/**
 * A navigation link in the handbook that links to the previous or next section
 * (page).  Also does some magic to render shorter link text (with only "next"
 * or "previous") on mobile, where space is limited.
 *
 * @param url The Url to render
 * @param title The title to render
 * @param type The type of rendering (next or previous)
 * @param [genericNext] (optional) Override the generic text for Next
 * @param [genericPrevious] (optional) Override the generic text for Previous
 */
class HandbookNavLinkRaw extends React.PureComponent<{| url: string, title: string, type: HandbookNavLinkType, genericNext?: string, genericPrevious?: string |}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const { url, title, type, genericNext, genericPrevious } = this.props;
        let prefix      : ?string = null;
        let postfix     : ?string = null;
        let genericText : ?string = null;
        if(type === "next")
        {
            postfix = "\u00A0»";
            genericText = genericNext ? genericNext : "Neste";
        }
        else if(type == "previous")
        {
            prefix = "«\u00A0";
            genericText = genericPrevious ? genericPrevious : "Forrige";
        }
        else Eif(type == "toplevel")
        {
            genericText = "↑";
        }
        return <Link to={url}>{prefix}<span className="d-md-none">{genericText}</span><span className="d-none d-md-inline">{title}</span>{postfix}</Link>;
    }
}
 
/**
 * A variant of @{link HandbookNavLinkRaw} that takes a @{link HandbookEntry}
 * instead of raw `url` and `title` parameters.
 *
 * @param {HandbookEntry} entry The HandbookEntry being rendered
 * @param type The type of rendering (next or previous)
 */
class HandbookNavLink extends React.PureComponent<{| entry: HandbookEntry | HandbookIndex, type: HandbookNavLinkType |}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const { entry, type } = this.props;
        return <HandbookNavLinkRaw url={entry.url} title={entry.title} type={type} />;
    }
}
 
/**
 * Renders a set of `HandbookNavLink`s. One for previous, one for next.
 * Usually there will be two `HandbookNavLinks` on any page, one at the top,
 * one at the bottom.
 */
class HandbookNavLinks extends React.PureComponent<{|entry: HandbookEntry, navBackLink?: string, navMode?: HandbookNavLinkRenderMode, hideToplevelLink?: boolean |}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const { entry, navMode, navBackLink, hideToplevelLink } = this.props;
        let previous : React.Node = null;
        let next     : React.Node = null;
        let toplevel : React.Node = null;
        if(navMode && navMode === "back" && navBackLink)
        {
            previous = <HandbookNavLinkRaw type="previous" url={navBackLink} title="Tilbake" genericPrevious="Tilbake" />;
        }
        else
        {
            if(entry.next)
            {
                next = <HandbookNavLink type="next" entry={entry.next} />;
            }
            if(entry.previous)
            {
                previous = <HandbookNavLink type="previous" entry={entry.previous} />;
            }
            if(hideToplevelLink !== true && entry.toplevelParent.displayIndexLink === true)
            {
                toplevel = <HandbookNavLink type="toplevel" entry={entry.toplevelParent} />;
            }
        }
        return <Row className="handbook-nav">
            <Col className="previous">
                {previous}
            </Col>
            <Col className="toplevel">
                {toplevel}
            </Col>
            <Col className="next">
                {next}
            </Col>
        </Row>;
    }
}
 
/**
 * Renders a single section in the handbook. Will 404 if the chapter or
 * section isn't found. Will redirect to the first section in a chapter if
 * only a chapter is provided.
 *
 * @param {HandbookEntry} entry The HandbookEntry to render
 * @param navMode The nav link mode (nav or back)
 * @param navBackLink The URL to link to in navMode=back
 */
class HandbookRender extends React.PureComponent<{|entry: HandbookEntry, navMode?: HandbookNavLinkRenderMode, navBackLink?: string |}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const { entry, navMode, navBackLink } = this.props;
        let toc : ?React.Node;
        let mediumWidth: number = 8;
        if (entry.hideTOC)
        {
            mediumWidth = 12;
        }
        else
        {
            toc = <Col md="4" className="order-md-12 conditionallySticky">
                <HandbookTocRender toc={entry.toc} />
            </Col>;
        }
        const article = <Row>
                {toc}
                <Col md={mediumWidth} xl="8" className="order-md-1">
                    <HandbookNavLinks entry={entry} navMode={navMode} navBackLink={navBackLink} />
                    <Markdown content={entry.content} permitSpecialNodes={true} />
                    <HandbookNavLinks entry={entry} navMode={navMode} navBackLink={navBackLink} hideToplevelLink={true} />
                </Col>
            </Row>;
        if(entry.public)
        {
            return article;
        }
        return <RequiresAuth type="article" title={entry.title}>
            {article}
        </RequiresAuth>;
    }
}
 
/**
 * The handbook app component. Renders pages or the index.
 */
class Handbook extends React.Component<{|match: {| params: {| handbookPath?: string|}|}|}>
{
    // eslint-disable-next-line require-jsdoc
    render(): React.Node
    {
        const match = this.props.match;
        let subComponent: React.Node;
        let small: boolean = false;
        let title: string = "Handbok";
        if(match.params.handbookPath)
        {
            const entry = new HandbookEntry( match.params.handbookPath );
            if(entry.exists)
            {
                subComponent = <HandbookRender entry={entry} />;
                title += ' - '+entry.toplevelParent.title;
            }
            else
            {
                const index = new HandbookIndex( match.params.handbookPath );
                if(index.exists)
                {
                    subComponent = <Redirect to={index.firstChild.url} />;
                }
                else
                {
                    subComponent = <NotFound root={false} />;
                }
            }
        }
        else
        {
            subComponent = <HandbookIndexRenderer />;
            small = true;
        }
        return  <MainContainer app="handbook" small={small}>
            <Row>
                <Col>
                    <PageTitle title={title} />
                    {subComponent}
                </Col>
            </Row>
        </MainContainer>;
    }
}
 
// Public exports
export default (withRouter(Handbook): React.AbstractComponent<{| |}>);
export { HandbookSearchResult, HandbookLikeSearchResult, HandbookRender, HandbookIndexRenderer };
// Testing exports
export { Handbook as HandbookUnconnected, HandbookNavLinks, HandbookNavLink, HandbookTocRender,  HandbookNavLinkRaw };