Skip to content
Snippets Groups Projects
chart.js 6.68 KiB
Newer Older
import React, { Component } from 'react'
import { View, FlatList } from 'react-native'
import range from 'date-range'
import { LocalDate } from 'js-joda'
import { makeYAxisLabels, normalizeToScale, makeHorizontalGrid } from './y-axis'
import nfpLines from './nfp-lines'
import DayColumn from './day-column'
import { getCycleDay, getCycleDaysSortedByDate, getAmountOfCycleDays } from '../../db'
import styles from './styles'
import { scaleObservable } from '../../local-storage'
import config from '../../config'
import { AppText } from '../app-text'
Julia Friesel's avatar
Julia Friesel committed
export default class CycleChart extends Component {
    this.renderColumn = ({item, index}) => {
      return (
        <DayColumn
          index={index}
          navigate={this.props.navigate}
          symptomHeight={this.symptomHeight}
          columnHeight={this.columnHeight}
          chartHeight={this.state.chartHeight}
          symptomRowSymptoms={this.symptomRowSymptoms}
    this.cycleDaysSortedByDate = getCycleDaysSortedByDate()
  onLayout = ({ nativeEvent }) => {
    if (this.state.chartHeight) return
    const height = nativeEvent.layout.height
    this.setState({ chartHeight: height })
    this.reCalculateChartInfo = () => {
      // how many symptoms need to be displayed on the chart's upper symptom row?
      this.symptomRowSymptoms = [
        'bleeding',
        'mucus',
        'cervix',
        'sex',
        'desire',
        'pain',
        'note'
      ].filter((symptomName) => {
        return this.cycleDaysSortedByDate.some(cycleDay => {
          return cycleDay[symptomName]
        })
      })

      this.xAxisHeight = this.state.chartHeight * config.xAxisHeightPercentage
      const remainingHeight = this.state.chartHeight - this.xAxisHeight
      this.symptomHeight = config.symptomHeightPercentage * remainingHeight
      this.symptomRowHeight = this.symptomRowSymptoms.length * this.symptomHeight
      this.columnHeight = remainingHeight - this.symptomRowHeight

      const chartSymptoms = [...this.symptomRowSymptoms]
      if (this.cycleDaysSortedByDate.some(day => day.temperature)) {
        chartSymptoms.push('temperature')
      }

      const columnData = this.makeColumnInfo(nfpLines(), chartSymptoms)
      this.setState({ columns: columnData })
    this.cycleDaysSortedByDate.addListener(this.reCalculateChartInfo)
    this.removeObvListener = scaleObservable(this.reCalculateChartInfo, false)
  }

  componentWillUnmount() {
    this.cycleDaysSortedByDate.removeListener(this.reCalculateChartInfo)
    this.removeObvListener()
  makeColumnInfo(getFhmAndLtlInfo, chartSymptoms) {
    let amountOfCycleDays = getAmountOfCycleDays()
    // if there's not much data yet, we want to show at least 30 days on the chart
    if (amountOfCycleDays < 30) {
      amountOfCycleDays = 30
    } else {
      // we don't want the chart to end abruptly before the first data day
      amountOfCycleDays += 5
    }
    const jsDates = getTodayAndPreviousDays(amountOfCycleDays)
    const xAxisDates = jsDates.map(jsDate => {
      return LocalDate.of(
        jsDate.getFullYear(),
        jsDate.getMonth() + 1,
        jsDate.getDate()
      ).toString()
    })
    const columns = xAxisDates.map(dateString => {
      const cycleDay = getCycleDay(dateString)
tina's avatar
tina committed
      const symptoms = chartSymptoms.reduce((acc, symptom) => {
        if (symptom === 'bleeding' ||
          symptom === 'temperature' ||
          symptom === 'mucus' ||
          symptom === 'desire' ||
          symptom === 'note'
        ) {
          acc[symptom] = cycleDay[symptom] && cycleDay[symptom].value
tina's avatar
tina committed
        } else if (symptom === 'cervix') {
          acc.cervix = cycleDay.cervix &&
            (cycleDay.cervix.opening + cycleDay.cervix.firmness)
tina's avatar
tina committed
        } else if (symptom === 'sex') {
          // solo = 1 + partner = 2
          acc.sex = cycleDay.sex && (cycleDay.sex.solo + cycleDay.sex.partner)
tina's avatar
tina committed
        } else if (symptom === 'pain') {
          // is any pain documented?
          acc.pain = cycleDay.pain &&
            Object.values(cycleDay.pain).some(x => x === true)
tina's avatar
tina committed
        }
        acc[`${symptom}Exclude`] = cycleDay[symptom] && cycleDay[symptom].exclude
        return acc
      }, {})

      const temp = symptoms.temperature
      if (temp) {
        column.y = normalizeToScale(temp, this.columnHeight)

      const fhmAndLtl = getFhmAndLtlInfo(dateString, temp, this.columnHeight)
      return Object.assign(column, symptoms, fhmAndLtl)
    })

    return columns.map((col, i) => {
      const info = getInfoForNeighborColumns(i, columns)
      return Object.assign(col, info)
    })
  }

  render() {
    return (
      <View
        onLayout={this.onLayout}
        style={{ flexDirection: 'row', flex: 1 }}
      >
Julia Friesel's avatar
Julia Friesel committed
        {!this.state.chartLoaded &&
          <View style={{width: '100%', justifyContent: 'center', alignItems: 'center'}}>
            <AppText>Loading...</AppText>
Julia Friesel's avatar
Julia Friesel committed
          </View>
        }

        {this.state.chartHeight && this.state.chartLoaded &&
            style={[styles.yAxis, {
              height: this.columnHeight,
              marginTop: this.symptomRowHeight
            {makeYAxisLabels(this.columnHeight)}
        {this.state.chartHeight && this.state.chartLoaded &&
          makeHorizontalGrid(this.columnHeight, this.symptomRowHeight)
        }

        {this.state.chartHeight &&
          <FlatList
Julia Friesel's avatar
Julia Friesel committed
            horizontal={true}
            inverted={true}
            showsHorizontalScrollIndicator={false}
            data={this.state.columns}
            renderItem={this.renderColumn}
            keyExtractor={item => item.dateString}
            initialNumToRender={15}
            maxToRenderPerBatch={5}
Julia Friesel's avatar
Julia Friesel committed
            onLayout={() => this.setState({chartLoaded: true})}
function getTodayAndPreviousDays(n) {
Julia Friesel's avatar
Julia Friesel committed
  const today = new Date()
  today.setHours(0)
  today.setMinutes(0)
  today.setSeconds(0)
  today.setMilliseconds(0)
Julia Friesel's avatar
Julia Friesel committed
  const earlierDate = new Date(today - (range.DAY * n))
Julia Friesel's avatar
Julia Friesel committed

Julia Friesel's avatar
Julia Friesel committed
  return range(earlierDate, today).reverse()
Julia Friesel's avatar
Julia Friesel committed
}

function getInfoForNeighborColumns(index, cols) {
Julia Friesel's avatar
Julia Friesel committed
  const ret = {
    rightY: null,
    rightTemperatureExclude: null,
    leftY: null,
    leftTemperatureExclude: null
  }
Julia Friesel's avatar
Julia Friesel committed
  const right = index > 0 ? cols[index - 1] : undefined
  const left = index < cols.length - 1 ? cols[index + 1] : undefined
  if (right && right.y) {
    ret.rightY = right.y
    ret.rightTemperatureExclude = right.temperatureExclude
  }
  if (left && left.y) {
    ret.leftY = left.y
    ret.leftTemperatureExclude = left.temperatureExclude
  }
  return ret