<commit_before>/* global window */
import React, { useState, useEffect, useRef } from 'react'
import { connect } from 'react-redux'
import { Input, Icon, Spin, Collapse, Button, Select, Form, Checkbox, Tooltip } from 'antd'
import { cloneDeep } from 'lodash'
import moment from 'moment'
import SVGInline from 'react-svg-inline'
import { useTranslation } from 'react-i18next'
import classNames from 'classnames'
import { resultTypes, indicatorTypes } from '../../utils/constants'
import './styles.scss'
import ProjectInitHandler from '../editor/project-init-handler'
import api from '../../utils/api'
import approvedSvg from '../../images/status-approved.svg'
import pendingSvg from '../../images/status-pending.svg'
import Timeline from './timeline'
import Update from './update'
import EditUpdate from './edit-update'
import DsgOverview from './dsg-overview'

const { Panel } = Collapse
const Aux = node => node.children

const ExpandIcon = ({ isActive }) => (
  <div className={classNames('expander', { isActive })}>
    <Icon type="down" />
  </div>
)

const Results = ({ results = [], isFetched, userRdr, match: { params: { id } }, ...props}) => {
  const { t } = useTranslation()
  const [src, setSrc] = useState('')
  const [selectedPeriods, setSelectedPeriods] = useState([])
  const [filterBarVisible, setFilterBarVisible] = useState(true)
  const [activeResultKey, setActiveResultKey] = useState()
  const [periodFilter, setPeriodFilter] = useState(null)
  const [allChecked, setAllChecked] = useState(false)
  const sidebarUlRef = useRef()
  const mainContentRef = useRef()
  const periodSetters = useRef({})
  const filteredResults = results.filter(it => {
    return it.indicators.filter(ind => src.length === 0 || ind.title.toLowerCase().indexOf(src.toLowerCase()) !== -1).length > 0
  })
  const toggleSelectedPeriod = (period, indicatorId) => {
    if(selectedPeriods.findIndex(it => it.id === period.id) === -1){
      setSelectedPeriods([...selectedPeriods, {id: period.id, indicatorId, locked: period.locked}])
    } else {
      setSelectedPeriods(selectedPeriods.filter(it => it.id !== period.id))
    }
  }
  const toggleSelectAll = () => {
    let allPeriods = []
    results.forEach(res => {
      res.indicators.forEach(ind => {
        allPeriods = [
          ...allPeriods,
          ...ind.periods.filter(it => {
            if (!periodFilter) return true
            const dates = periodFilter.split('-')
            return it.periodStart === dates[0] && it.periodEnd === dates[1]
          }).map(it => ({ id: it.id, locked: it.locked, indicatorId: ind.id }))
        ]
      })
    })
    if(selectedPeriods.length < allPeriods.length){
      setSelectedPeriods(allPeriods)
      setAllChecked(true)
    } else {
      setSelectedPeriods([])
      setAllChecked(false)
    }
  }
  const selectedLocked = selectedPeriods.filter(it => it.locked)
  const selectedUnlocked = selectedPeriods.filter(it => !it.locked)
  const handleChangeResult = (key) => {
    setActiveResultKey(key)
    if(!key) return
    const sidebarIndex = filteredResults.findIndex(it => it.id === results[key].id)
    if(sidebarIndex > -1){
      if (Math.abs(sidebarUlRef.current.scrollTop - sidebarUlRef.current.children[sidebarIndex].offsetTop) > 500){
        sidebarUlRef.current.scroll({ top: sidebarUlRef.current.children[sidebarIndex].offsetTop - 62, behavior: 'smooth' })
      }
    }
  }
  const handleJumpToIndicator = (result, indicator) => () => {
    const resIndex = results.findIndex(it => it.id === result.id)
    if(resIndex > -1){
      // console.log(mainContentRef.current.getElementsByClassName('results-list')[0].children[resIndex])
      const $resultsList = mainContentRef.current.getElementsByClassName('results-list')[0]
      const resultIsActive = $resultsList.children[resIndex].classList.contains('ant-collapse-item-active')
      if (resultIsActive === false){
        mainContentRef.current.getElementsByClassName('results-list')[0].children[resIndex].children[0].click()
      }
      const indIndex = results[resIndex].indicators.findIndex(it => it.id === indicator.id)
      if(indIndex > -1){
        setTimeout(() => {
          const $indicator = $resultsList.children[resIndex].getElementsByClassName('indicators-list')[0].children[indIndex]
          if ($indicator.classList.contains('ant-collapse-item-active') === false){
            $indicator.children[0].click()
          }
          window.scroll({ top: $indicator.offsetTop - 119, behavior: 'smooth' })
        }, resultIsActive ? 0 : 500)
      }
    }
  }
  const periodOpts = []
  results.forEach(res => {
    res.indicators.forEach(ind => {
      ind.periods.forEach(per => {
        const item = {start: per.periodStart, end: per.periodEnd}
        if(periodOpts.findIndex(it => it.start === item.start && it.end === item.end) === -1){
          periodOpts.push(item)
        }
      })
    })
  })
  const handlePeriodFilter = (value) => {
    setPeriodFilter(value)
  }
  const updatePeriodsLock = (periods, locked) => {
    let indicatorIds = periods.map(it => it.indicatorId);
    indicatorIds = indicatorIds.filter((it, ind) => indicatorIds.indexOf(it) === ind)
    indicatorIds.forEach(indicatorId => {
      const subset = periods.filter(it => it.indicatorId === indicatorId)
      if(periodSetters.current[indicatorId]) periodSetters.current[indicatorId](subset, locked)
    })
    setSelectedPeriods(selectedPeriods.map(it => ({...it, locked})))<commit_msg>[#3998] set locked requests<commit_after>/* global window */
import React, { useState, useEffect, useRef } from 'react'
import { connect } from 'react-redux'
import { Input, Icon, Spin, Collapse, Button, Select, Form, Checkbox, Tooltip } from 'antd'
import { cloneDeep } from 'lodash'
import moment from 'moment'
import SVGInline from 'react-svg-inline'
import { useTranslation } from 'react-i18next'
import classNames from 'classnames'
import { resultTypes, indicatorTypes } from '../../utils/constants'
import './styles.scss'
import ProjectInitHandler from '../editor/project-init-handler'
import api from '../../utils/api'
import approvedSvg from '../../images/status-approved.svg'
import pendingSvg from '../../images/status-pending.svg'
import Timeline from './timeline'
import Update from './update'
import EditUpdate from './edit-update'
import DsgOverview from './dsg-overview'

const { Panel } = Collapse
const Aux = node => node.children

const ExpandIcon = ({ isActive }) => (
  <div className={classNames('expander', { isActive })}>
    <Icon type="down" />
  </div>
)

const Results = ({ results = [], isFetched, userRdr, match: { params: { id } }, ...props}) => {
  const { t } = useTranslation()
  const [src, setSrc] = useState('')
  const [selectedPeriods, setSelectedPeriods] = useState([])
  const [filterBarVisible, setFilterBarVisible] = useState(true)
  const [activeResultKey, setActiveResultKey] = useState()
  const [periodFilter, setPeriodFilter] = useState(null)
  const [allChecked, setAllChecked] = useState(false)
  const sidebarUlRef = useRef()
  const mainContentRef = useRef()
  const periodSetters = useRef({})
  const filteredResults = results.filter(it => {
    return it.indicators.filter(ind => src.length === 0 || ind.title.toLowerCase().indexOf(src.toLowerCase()) !== -1).length > 0
  })
  const toggleSelectedPeriod = (period, indicatorId) => {
    if(selectedPeriods.findIndex(it => it.id === period.id) === -1){
      setSelectedPeriods([...selectedPeriods, {id: period.id, indicatorId, locked: period.locked}])
    } else {
      setSelectedPeriods(selectedPeriods.filter(it => it.id !== period.id))
    }
  }
  const toggleSelectAll = () => {
    let allPeriods = []
    results.forEach(res => {
      res.indicators.forEach(ind => {
        allPeriods = [
          ...allPeriods,
          ...ind.periods.filter(it => {
            if (!periodFilter) return true
            const dates = periodFilter.split('-')
            return it.periodStart === dates[0] && it.periodEnd === dates[1]
          }).map(it => ({ id: it.id, locked: it.locked, indicatorId: ind.id }))
        ]
      })
    })
    if(selectedPeriods.length < allPeriods.length){
      setSelectedPeriods(allPeriods)
      setAllChecked(true)
    } else {
      setSelectedPeriods([])
      setAllChecked(false)
    }
  }
  const selectedLocked = selectedPeriods.filter(it => it.locked)
  const selectedUnlocked = selectedPeriods.filter(it => !it.locked)
  const handleChangeResult = (key) => {
    setActiveResultKey(key)
    if(!key) return
    const sidebarIndex = filteredResults.findIndex(it => it.id === results[key].id)
    if(sidebarIndex > -1){
      if (Math.abs(sidebarUlRef.current.scrollTop - sidebarUlRef.current.children[sidebarIndex].offsetTop) > 500){
        sidebarUlRef.current.scroll({ top: sidebarUlRef.current.children[sidebarIndex].offsetTop - 62, behavior: 'smooth' })
      }
    }
  }
  const handleJumpToIndicator = (result, indicator) => () => {
    const resIndex = results.findIndex(it => it.id === result.id)
    if(resIndex > -1){
      // console.log(mainContentRef.current.getElementsByClassName('results-list')[0].children[resIndex])
      const $resultsList = mainContentRef.current.getElementsByClassName('results-list')[0]
      const resultIsActive = $resultsList.children[resIndex].classList.contains('ant-collapse-item-active')
      if (resultIsActive === false){
        mainContentRef.current.getElementsByClassName('results-list')[0].children[resIndex].children[0].click()
      }
      const indIndex = results[resIndex].indicators.findIndex(it => it.id === indicator.id)
      if(indIndex > -1){
        setTimeout(() => {
          const $indicator = $resultsList.children[resIndex].getElementsByClassName('indicators-list')[0].children[indIndex]
          if ($indicator.classList.contains('ant-collapse-item-active') === false){
            $indicator.children[0].click()
          }
          window.scroll({ top: $indicator.offsetTop - 119, behavior: 'smooth' })
        }, resultIsActive ? 0 : 500)
      }
    }
  }
  const periodOpts = []
  results.forEach(res => {
    res.indicators.forEach(ind => {
      ind.periods.forEach(per => {
        const item = {start: per.periodStart, end: per.periodEnd}
        if(periodOpts.findIndex(it => it.start === item.start && it.end === item.end) === -1){
          periodOpts.push(item)
        }
      })
    })
  })
  const handlePeriodFilter = (value) => {
    setPeriodFilter(value)
  }
  const updatePeriodsLock = (periods, locked) => {
    // TODO rethink request architecture
    let indicatorIds = periods.map(it => it.indicatorId);
    indicatorIds = indicatorIds.filter((it, ind) => indicatorIds.indexOf(it) === ind)
    indicatorIds.forEach(indicatorId => {
      const subset = periods.filter(it => it.indicatorId === indicatorId)
      if(periodSetters.current[indicatorId]) periodSetters.current[indicatorId](subset, locked)
    })
    setSelectedPeriods(selectedPeriods.map(it => ({...it, locked})))
    periods.forEach(period => {
      api.patch(`/indicator_period/${period.id}/`, { locked })
    })
{'fraction_non_alphanumeric': 0.15340960273849202, 'fraction_numerical': 0.005765246374200522, 'mean_word_length': 3.4748085449415558, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 86, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3510367', 'n_tokens_mistral': 3380, 'n_tokens_neox': 3368, 'n_words': 675}