logo

pleroma-fe

My custom branche(s) on git.pleroma.social/pleroma/pleroma-fe git clone https://anongit.hacktivis.me/git/pleroma-fe.git/

export_import.js (1644B)


  1. import utf8 from 'utf8'
  2. export const newExporter = ({
  3. filename = 'data',
  4. getExportedObject
  5. }) => ({
  6. exportData () {
  7. const stringified = utf8.encode(JSON.stringify(getExportedObject(), null, 2)) // Pretty-print and indent with 2 spaces
  8. // Create an invisible link with a data url and simulate a click
  9. const e = document.createElement('a')
  10. e.setAttribute('download', `${filename}.json`)
  11. e.setAttribute('href', 'data:application/json;base64,' + window.btoa(stringified))
  12. e.style.display = 'none'
  13. document.body.appendChild(e)
  14. e.click()
  15. document.body.removeChild(e)
  16. }
  17. })
  18. export const newImporter = ({
  19. onImport,
  20. onImportFailure,
  21. validator = () => true
  22. }) => ({
  23. importData () {
  24. const filePicker = document.createElement('input')
  25. filePicker.setAttribute('type', 'file')
  26. filePicker.setAttribute('accept', '.json')
  27. filePicker.addEventListener('change', event => {
  28. if (event.target.files[0]) {
  29. // eslint-disable-next-line no-undef
  30. const reader = new FileReader()
  31. reader.onload = ({ target }) => {
  32. try {
  33. const parsed = JSON.parse(target.result)
  34. const validationResult = validator(parsed)
  35. if (validationResult === true) {
  36. onImport(parsed)
  37. } else {
  38. onImportFailure({ validationResult })
  39. }
  40. } catch (error) {
  41. onImportFailure({ error })
  42. }
  43. }
  44. reader.readAsText(event.target.files[0])
  45. }
  46. })
  47. document.body.appendChild(filePicker)
  48. filePicker.click()
  49. document.body.removeChild(filePicker)
  50. }
  51. })