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 (2088B)


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