All files / src/components version-selector.js

0% Statements 0/28
0% Branches 0/10
0% Functions 0/10
0% Lines 0/28

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                                                                                                                                           
import React from 'react';
import { Location } from '@reach/router'
import navItems from '../nav.yml';
 
const versionMatch = /^\/cli\/(v\d+)\/(.*)/;
 
function find(items, path) {
    let results = new Array()
 
    items.forEach((item) => {
        var matches = versionMatch.exec(item.url);
 
        if (matches && matches[2] === path) {
            results.push(matches[1]);
        }
        else if (item.children) {
            results = results.concat(find(item.children, path));
        }
    });
 
    return results;
}
 
function getVersionsFor(path) {
    let versions = new Array()
 
    navItems.forEach((root) => {
        if (root.url === '/cli') {
            root.children.forEach((category) => {
                find(category.children, path).forEach((version) => {
                    versions = versions.concat({ url: version, title: category.title });
                });
            });
        }
    });
 
    return versions;
}
 
function VersionSelector(props) {
    return (
        <Location>
        {({location}) => {
            var matches = versionMatch.exec(location.pathname);
 
            if (!matches) {
                return;
            }
 
            const currentVersion = matches[1];
            const currentPath = matches[2];
            const availableVersions = getVersionsFor(currentPath);
 
            let options = new Array();
            let defaultOption;
 
            availableVersions.forEach((v) => {
                options.push(<option value={v.url}>{v.title}</option>);
            });
 
            return (
                <select value={currentVersion} onChange={(event) => { window.location = "/cli/" + event.target.value + "/" + currentPath }}>{options}</select>
            );
        }}
        </Location>
    );
}
 
export default VersionSelector