diff options
| author | Henry Jameson <me@hjkos.com> | 2021-03-08 19:42:24 +0200 |
|---|---|---|
| committer | Henry Jameson <me@hjkos.com> | 2021-03-08 19:42:24 +0200 |
| commit | bd5b62b1071d6424f82477dca2f0d374f709a596 (patch) | |
| tree | 4e5cd4823256facf4b61da40ade66457e9368a7f /src/services/export_import | |
| parent | 4baa397ed02f5deab4d5548dd89bbfb07c8a3d80 (diff) | |
changed importexport into a service instead of component for simplicity
Diffstat (limited to 'src/services/export_import')
| -rw-r--r-- | src/services/export_import/export_import.js | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/src/services/export_import/export_import.js b/src/services/export_import/export_import.js new file mode 100644 index 00000000..0bf9eadc --- /dev/null +++ b/src/services/export_import/export_import.js @@ -0,0 +1,57 @@ +export const newExporter = ({ + filename = 'data', + getExportedObject +}) => ({ + exportData () { + const stringified = JSON.stringify(getExportedObject(), null, 2) // Pretty-print and indent with 2 spaces + + // Create an invisible link with a data url and simulate a click + const e = document.createElement('a') + e.setAttribute('download', `${filename}.json`) + e.setAttribute('href', 'data:application/json;base64,' + window.btoa(stringified)) + e.style.display = 'none' + + document.body.appendChild(e) + e.click() + document.body.removeChild(e) + } +}) + +export const newImporter = ({ + onImport, + onImportFailure, + validator = () => true +}) => ({ + importData () { + const filePicker = document.createElement('input') + filePicker.setAttribute('type', 'file') + filePicker.setAttribute('accept', '.json') + console.log(1) + + filePicker.addEventListener('change', event => { + if (event.target.files[0]) { + // eslint-disable-next-line no-undef + const reader = new FileReader() + reader.onload = ({ target }) => { + try { + const parsed = JSON.parse(target.result) + const validationResult = validator(parsed) + if (validationResult === true) { + onImport(parsed) + } else { + onImportFailure({ validationResult }) + } + } catch (error) { + onImportFailure({ error }) + } + } + console.log(2) + reader.readAsText(event.target.files[0]) + } + }) + + document.body.appendChild(filePicker) + filePicker.click() + document.body.removeChild(filePicker) + } +}) |
