aboutsummaryrefslogtreecommitdiffstats
path: root/apps/Notes/components/Export.js
blob: f281d1adb11e31edd013449c99fa2c7ec9977ae3 (plain) (blame)
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
import styles from '../Notes.module.scss'
import React, {useState} from 'react'
import useNotes from '../hooks/useNotes'
import fetchJson from 'lib/fetchJson'
import JSZip from 'jszip'
import saveFile from 'helpers/saveFile'
import filename from '../helpers/fileName'
// import {state, color, handleImport, handleChange} from '../helpers/import'

const Export = ({setAction}) => {
  const {notes} = useNotes()
  const [ids, setIds] = useState(notes.map(n => n.noteId))
  // const [files, setFiles] = useState()
  // const [done, setDone] = useState([])

  const handleSelect = id => {
    ids.includes(id)
      ? setIds(ids.filter(i => i !== id))
      : setIds([...ids, id])
  }

  const handleSelectAll = e => {
    if (e.target.checked) {
      setIds(notes.map(n => n.noteId))
    } else {
      setIds([])
    }
  }

  const handleExport = e => {
    e.preventDefault()
    const zip = new JSZip()

    Promise.all(ids.map(async id => {
      const title = notes.find(n => n.noteId === id).title
      const {content} = await fetchJson(`/api/note/${id}`)
      zip.folder('notes').file(filename(title), content, {binary: true})
    })).then(() => {
      zip.generateAsync({type:"blob"})
        .then(c => saveFile(c, 'notes.zip', 'application/zip'))
    })
  }

  if (!notes) return null

  return (
    <section>
      <div className='window__submenu'>
        <div onClick={() => {setAction('')}}>Back</div>
      </div>
      <div className={`window__scroll ${styles.export}`}>
        <h3>Click to export your notes:</h3>
        <input
          className="window__button"
          type="submit"
          value="Export"
          onClick={handleExport}
        />
        <p>Notes to export:</p>
        <div className={`${styles.export__select}`}>
          <input type="checkbox" name='selectAll' onChange={handleSelectAll} checked={notes.length === ids.length} />
          <label htmlFor='selectAll'>Select all</label>
        </div>
        {notes.map(note => (
          <div key={note.noteId}>
            <input
              type="checkbox"
              name={note.noteId}
              value={note.noteId}
              checked={ids.includes(note.noteId)}
              onChange={() => handleSelect(note.noteId)}
            />
            <label htlmfor={note.noteId}>
              {note.title}
            </label><br/>
          </div>
        ))}
      </div>
    </section>
  )
}

export default Export