All files / src/pages/TagCreator index.js

92.98% Statements 106/114
82.86% Branches 29/35
91.67% Functions 22/24
92.73% Lines 102/110

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                                          61x                                       61x 10x 10x 10x 10x 10x 10x       61x 1140x 1140x 568x   1140x       61x 1140x 1140x 1140x 1140x 1140x 1140x 1140x 1140x 1140x 1140x 1140x 1140x 1140x 1140x 1140x   1140x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     1140x 12x 12x   2893x 11x 11x     12x         1140x 40x 40x 30x   40x 30x 10x     30x         1140x 26x 3x 3x         1140x 404x 10x       1140x 12x     1140x 10x 2x   8x     8x       8x 8x     1140x   1140x 10x   10x 10x 10x   10x       10x 10x       10x 10x 10x                           1140x 8x 14x 8x     1140x           1140x 18x               1140x 24x                     1140x 1140x   924x                         20x               40x                     8x                                 8x                     140x                         1140x                                  
 
import React, { useState,useEffect,useRef } from 'react';
import {
  useQueryParam,
  StringParam,
  ArrayParam,
  withDefault,
} from 'use-query-params';
import axios from 'axios';
import Box from '@material-ui/core/Box'
import Container from '@material-ui/core/Container';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import { GenericHeaderSection } from '../../components/'
import { AffiliationQuestionSection } from "./AffilationQuestionSection";
import { OrgNameSection,OrganizationSelectorSection,OrgChange } from './Organization'
import { ProjectRepositorySection,ProjectRepositoryInput } from './ProjectRepository'
import { AddTopicTagSection,AddTagsQuestion,NewTags,CopyPasteTags,AddMoreTags,CurrentTopicTagSection } from './TopicTagSection'
import useTheme from '@material-ui/core/styles/useTheme';
import TagGeneratorInstructions from '../../components/TagGeneratorInstructions'
import { makeStyles } from '@material-ui/core/styles'
const useStyles = makeStyles((theme) => ({
  containerPadding: {
    paddingLeft:'100px',
    [theme.breakpoints.down('sm')]: {
      paddingLeft:'40px',
    },
    [theme.breakpoints.down('xs')]: {
      padding:'0px 16px',
    },
  },
}))
 
/**
 * By removing matched text, we allow leeway in entering repository URL,
 * including how it might be pasted from GitHub. All these would work:
 * https://github.com/civictechindex/CTI-website-frontend.git
 * git@github.com:civictechindex/CTI-website-frontend.git
 * github.com/civictechindex/CTI-website-frontend
 * civictechindex / CTI-website-frontend
 */
const getRepositoryUrlPath = (repositoryUrl) => {
  let result = repositoryUrl.replace(/ /g, '')
  const prefix = /^(?:https?:\/\/)?github\.com\/|git@github\.com:/
  const suffix = /\.git$/
  result = result.replace(prefix, '')
  result = result.replace(suffix, '')
  return result
}
 
// checks if URL is deifferent
const usePrevious =(refValue) => {
  const ref = useRef();
  useEffect(() => {
    ref.current = refValue;
  });
  return ref.current;
}
 
// eslint-disable-next-line max-lines-per-function
const TagCreator = () => {
  const theme = useTheme();
  const classes = useStyles()
  const [displayState, setDisplayState] = useQueryParam('displayState',withDefault(StringParam,''));
  const [value, setValue] = useQueryParam('value',withDefault(StringParam,''));
  const [orgName, setOrgName] = useQueryParam('orgName',withDefault(StringParam,''));
  const [changeValue, setChangeValue] = useQueryParam('changeValue',withDefault(StringParam,''));
  const [repositoryUrl, setRepositoryUrl] = useQueryParam('repositoryUrl',withDefault(StringParam,''));
  const [repositoryName, setRepositoryName] = useQueryParam('repositoryName',withDefault(StringParam,''));
  const [topicSearchError, setTopicSearchError] = useState('');
  const [tagsToAdd, setTagsToAdd] = useQueryParam('tagsToAdd',withDefault(ArrayParam,[]));
  const [currentTags, setCurrentTags] = useQueryParam('currentTags',withDefault(ArrayParam,[]));
  const [userTags, setUserTags] = useQueryParam('userTags',withDefault(ArrayParam,[]));
  const [orgTags, setOrgTags] = useQueryParam('orgTags',withDefault(ArrayParam,[]));
  const [options, setOptions] = useState([]);
  const breadCrumbLinks = [{ href: '/home', name: 'Home' }, { href: '/join-index', name: 'Join the Index' }]
 
  const resetForm = () => {
    setValue('')
    setOrgName('')
    setRepositoryUrl('')
    setRepositoryName('')
    setTopicSearchError('')
    setTagsToAdd([])
    setCurrentTags([])
    setUserTags([])
    setOrgTags([])
    setChangeValue('')
    setDisplayState('')
  }
 
  useEffect(() => {
    let active = true;
    axios.get(`${process.env.REACT_APP_API_URL}/api/organizations/`)
      .then(res => {
        const orgs = (res.data).map((org) => org.name)
        Eif (active) {
          setOptions(["",...orgs]);
        }
      })
    return () => {
      active = false;
    };
  }, []);
 
  useEffect(() => {
    const civicName = []
    if (!currentTags.includes("civictechindex")) {
      civicName.push("civictechindex")
    }
    if (orgTags.length !== 0 && currentTags.length !== 0){
      const result = orgTags.filter(ot => !currentTags.includes(ot))
      setTagsToAdd([...civicName,...result,...userTags])
    }
    else {
      setTagsToAdd([...civicName,...orgTags,...userTags])
    }
  },[orgTags, currentTags, setTagsToAdd, userTags])
 
 
  useEffect(() => {
    if (value === 'no'){
      setOrgName('')
      setOrgTags([])
    }
  },[setOrgName, setOrgTags, value])
 
 
  const handleEnter = (event) => {
    if (event.key === 'Enter') {
      handleSubmit();
    }
  }
 
  const handleChange = (event) => {
    setValue(event.target.value)
  }
 
  const handleChangeProjectRepository = () =>{
    if (changeValue === 'TopicTag'){
      setDisplayState('TopicTag')
    }
    else Iif (changeValue === 'GenerateTags'){
      setDisplayState('GenerateTags')
    }
    else Iif (changeValue === 'CopyPasteTags'){
      setDisplayState('CopyPasteTags')
    }
    else {
      setChangeValue('TopicTag')
      setDisplayState('TopicTag')
    }
  }
  const prevRefUrl = usePrevious(repositoryUrl)
 
  const handleSubmit = (event) => {
    const urlPath = getRepositoryUrlPath(repositoryUrl)
    // Setting Repository Name
    const patt = /[a-z]+\//g
    const repName = urlPath.replace(patt, '')
    setRepositoryName(repName)
    // Return error message if no url present
    Iif (urlPath.length === 0){
      return setTopicSearchError(<p style={{ color: 'red' }}>Please enter a URL</p>);
    }
    // Fetches Tags from API only if URL is changed
    Eif (prevRefUrl !== repositoryUrl){
      axios.get('https://api.github.com/repos/' + urlPath + '/topics', {
        headers: { Accept: "application/vnd.github.mercy-preview+json" },
      })
        .then(res => {
          setTopicSearchError()
          setCurrentTags(res.data.names)
          handleChangeProjectRepository()
        }).catch(e => {
        /*
         * This should store the error state.
         * Component should check for error state and resolve the correct response.
         */
          console.log(e);
          setTopicSearchError(<p style={{ color: 'red' }}>Cannot find repository. Please check the name and try again</p>)
        })
    }
    else {
      handleChangeProjectRepository()
    }
  }
  const handleChangeChip = (chips) =>{
    let chipsArr = []
    chipsArr = chips.map(chip => chip.toLowerCase().trim().replaceAll(" ", "-"))
    setUserTags(chipsArr)
  }
 
  const linkStyles = {
    fontWeight: '400',
    color: theme.palette.secondary.main,
  }
 
 
  const OrgProjSection = () => {
    return (
      <>
        <OrgNameSection setDisplayState={setDisplayState} orgName={orgName} linkStyles={linkStyles} />
        <ProjectRepositorySection repositoryUrl={repositoryUrl} setDisplayState={setDisplayState} linkStyles={linkStyles}/>
      </>
    )
  }
 
  const RadioYes = ({ value,setOrgName }) =>{
    return (
      <Grid container id='container-affiliated'>
        <OrganizationSelectorSection orgName={orgName} setOrgName={setOrgName} options={options}/>
        <OrgChange value={value} orgName={orgName} setOrgName={setOrgName} setOrgTags={setOrgTags}
          changeValue={changeValue} setDisplayState={setDisplayState} linkStyles={linkStyles}/>
      </Grid>
    )
  }
 
 
  // eslint-disable-next-line complexity
  const renderCurrentState = () => {
    switch (displayState) {
    case "ProjectUrl":
      return (
        <>
          <OrgNameSection setDisplayState={setDisplayState} orgName={orgName} linkStyles={linkStyles}/>
          <ProjectRepositoryInput
            repositoryUrl={repositoryUrl}
            handleEnter={handleEnter}
            setRepositoryUrl={setRepositoryUrl}
            topicSearchError={topicSearchError}
            setTopicSearchError={setTopicSearchError}
            handleSubmit={handleSubmit}/>
        </>
      )
    case "TopicTag":
      return (
        <>
          <OrgProjSection/>
          <CurrentTopicTagSection currentTags={currentTags} repositoryName={repositoryName}/>
          <AddTagsQuestion setDisplayState={setDisplayState} setChangeValue={setChangeValue} resetForm={resetForm}/>
        </>
      )
    case "AddTopicTags":
      return (
        <>
          <CurrentTopicTagSection currentTags={currentTags} repositoryName={repositoryName}/>
          <AddTopicTagSection
            setDisplayState={setDisplayState}
            setChangeValue={setChangeValue}
            resetForm={resetForm}
            handleChangeChip={handleChangeChip}/>
        </>
      )
    case "GenerateTags":
      return (
        <>
          <OrgProjSection/>
          <CurrentTopicTagSection currentTags={currentTags} repositoryName={repositoryName}/>
          <NewTags tagsToAdd={tagsToAdd}
            setDisplayState={setDisplayState}
            setChangeValue={setChangeValue}
            resetForm={resetForm}
            linkStyles={linkStyles}/>
        </>
      )
    case "AddMoreTags":
      return (
        <AddMoreTags userTags={userTags} setDisplayState={setDisplayState}
          resetForm={resetForm} handleChangeChip={handleChangeChip} changeValue={changeValue} />
      )
    case "CopyPasteTags":
      return (
        <>
          <OrgProjSection/>
          <CurrentTopicTagSection currentTags={currentTags} repositoryName={repositoryName}/>
          <CopyPasteTags tagsToAdd={tagsToAdd} setDisplayState={setDisplayState}
            repositoryName={repositoryName}
            repositoryUrl={repositoryUrl}
            linkStyles={linkStyles}/>
        </>
      )
    default:
      return (
        <>
          <AffiliationQuestionSection value={value} handleChange={handleChange}
            question={'Are you affiliated with an organization?'} />
          {(value === 'yes')?<RadioYes value={value} setOrgName={setOrgName}/>:null}
          {(value === 'no')?<OrgChange  value={value} orgName={orgName} setOrgName={setOrgName} setOrgTags={setOrgTags}
            changeValue={changeValue} setDisplayState={setDisplayState}/>:null}
        </>
      )
    }
 
  }
 
  return (
    <Box>
      <GenericHeaderSection mainTitle ="Tag Generator" breadCrumbLinks ={breadCrumbLinks} lg='320px' md='304px' sm='304px' subText>
        <Typography variant='h6' color='textSecondary' style={{ fontWeight:'500' , textAlign:'center' }} >Join the Civic Tech Index by submitting your open-source project.<br /> This process takes less than one minute to complete.</Typography>
      </GenericHeaderSection>
 
      <Box className='containerGray' style={{ paddingBottom:'30px' }} >
        <Container className={classes.containerPadding} >
          {renderCurrentState()}
        </Container>
      </Box>
      {(displayState === 'CopyPasteTags')?<TagGeneratorInstructions/>:null}
    </Box>
  )
}
 
export default TagCreator