summaryrefslogtreecommitdiff
path: root/client/modalImage/modalImage.container.js
blob: 5479ca5fe7f0cec561ccfe0421af0ee253c3a833 (plain)
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
import React, { Component } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { ReactTabulator } from 'react-tabulator'

import { toArray, toTuples, domainFromUrl } from '../util'
import { Loader } from '../common'

import csv from 'parse-csv'

class ModalImage extends Component {
  state = {
    visible: false,
    images: [],
    index: 0,
  }
  
  componentDidMount() {
    const images = toArray(document.querySelectorAll('.image img'))
    // console.log(images)
    images.forEach((img, i) => {
      img.addEventListener('click', () => this.loadImage(i))
    })
    this.setState({ images })
    document.body.addEventListener('keydown', e => {
      if (document.activeElement && document.activeElement !== document.body) {
        return null
      }
      console.log(e.keyCode)
      switch (e.keyCode) {
        case 27: // esc
          this.close()
          break
        case 37: // left
          this.prev()
          break
        case 39: // right
          this.next()
          break
        default:
          break
      }
    })
  }

  loadImage(index) {
    const { images } = this.state
    if (!images.length) return
    if (index < 0 || index >= images.length) return
    this.setState({ visible: true, index })
  }

  prev() {
    const { index, images } = this.state
    if (!images.length) return
    this.setState({ index: (images.length + index - 1) % images.length })
  }

  next() {
    const { index, images } = this.state
    if (!images.length) return
    this.setState({ index: (index + 1) % images.length })
  }

  close() {
    this.setState({ visible: false })
  }

  render() {
    const { images, index, visible } = this.state
    if (!images.length) return null
    const img = images[index]
    let caption = null
    const sib = img.nextSibling
    if (sib && sib.classList.contains('caption')) {
      caption = sib.innerText
    }
    return (
      <div className={visible ? 'modal visible' : 'modal'}>
        <div className='inner'>
          <div className='centered'>
            <img src={img.src} />
            {caption && <div class='caption'>{caption}</div>}
          </div>
        </div>
        <div onClick={() => this.prev()}className='prev'><span>{'<'}</span></div>
        <div onClick={() => this.next()} className='next'><span>{'>'}</span></div>
        <div onClick={() => this.close()} className='close'><span>{'×'}</span></div>
      </div>
    )
  }
}
export default ModalImage