From b43d34c0136552cd2d83258fb5523bb873177908 Mon Sep 17 00:00:00 2001 From: piotrruss Date: Mon, 16 Aug 2021 00:13:45 +0200 Subject: added import --- apps/Notes/components/Import.js | 104 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 102 insertions(+), 2 deletions(-) (limited to 'apps/Notes/components/Import.js') diff --git a/apps/Notes/components/Import.js b/apps/Notes/components/Import.js index 6182ca6..71c08d6 100644 --- a/apps/Notes/components/Import.js +++ b/apps/Notes/components/Import.js @@ -1,10 +1,85 @@ +import React, {useState} from 'react' +import fetchJson from 'lib/fetchJson' +import useNotes from '../hooks/useNotes' +import {faCheck, faTimes} from '@fortawesome/free-solid-svg-icons' +import {FontAwesomeIcon} from '@fortawesome/react-fontawesome' + const Import = ({action, setAction}) => { + const [files, setFiles] = useState() + const [done, setDone] = useState([]) + const {mutateNotes} = useNotes() + + const state = i => done[i] && + + const readFileAsText = (file) => new Promise((resolve,reject) => { + let fr = new FileReader() + + fr.onload = () => resolve(fr.result) + fr.onerror = () => reject(fr) + + fr.readAsText(file) + }) + + const handleImport = async e => { + e.preventDefault(); + + Array.from(files).forEach(async (file, i) => { + const title = file.name.replace(/\.[^/.]+$/, "") + const content = await readFileAsText(file); + + try { + const notes = await fetchJson('/api/notes', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({title, content}), + }) + if (i === files.length - 1) await mutateNotes(notes) + setDone((prev) => ({...prev, [i]: 1})) + } catch (e) { + setDone((prev) => ({...prev, [i]: 0})) + } + }) + } + + const handleChange = e => { + setFiles(e.currentTarget.files) + setDone([]) + } + return (
{ setAction('') }}>Back
-
From txt
-
From JSON
+
+
+
+ Import new notes: +
+ +
+ {files && ( + <> +

Notes to import:

+
    + {[...files].map((f, i) =>
  • {f.name} {state(i)}
  • )} +
+ { + done.length === 0 + ? + :

Import finished.

Go back to notes list or choose other notes to import.

+ } + + )} +
) -- cgit v1.2.3