logo

pleroma-fe

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

drafts.js (2361B)


  1. import { storage } from 'src/lib/storage.js'
  2. export const defaultState = {
  3. drafts: {}
  4. }
  5. export const mutations = {
  6. addOrSaveDraft (state, { draft }) {
  7. state.drafts[draft.id] = draft
  8. },
  9. abandonDraft (state, { id }) {
  10. delete state.drafts[id]
  11. },
  12. loadDrafts (state, data) {
  13. state.drafts = data
  14. }
  15. }
  16. const storageKey = 'pleroma-fe-drafts'
  17. /*
  18. * Note: we do not use the persist state plugin because
  19. * it is not impossible for a user to have two windows at
  20. * the same time. The persist state plugin is just overriding
  21. * everything with the current state. This isn't good because
  22. * if a draft is created in one window and another draft is
  23. * created in another, the draft in the first window will just
  24. * be overriden.
  25. * Here, we can't guarantee 100% atomicity unless one uses
  26. * different keys, which will just pollute the whole storage.
  27. * It is indeed best to have backend support for this.
  28. */
  29. const getStorageData = async () => ((await storage.getItem(storageKey)) || {})
  30. const saveDraftToStorage = async (draft) => {
  31. const currentData = await getStorageData()
  32. currentData[draft.id] = JSON.parse(JSON.stringify(draft))
  33. await storage.setItem(storageKey, currentData)
  34. }
  35. const deleteDraftFromStorage = async (id) => {
  36. const currentData = await getStorageData()
  37. delete currentData[id]
  38. await storage.setItem(storageKey, currentData)
  39. }
  40. export const actions = {
  41. async addOrSaveDraft (store, { draft }) {
  42. const id = draft.id || (new Date().getTime()).toString()
  43. const draftWithId = { ...draft, id }
  44. store.commit('addOrSaveDraft', { draft: draftWithId })
  45. await saveDraftToStorage(draftWithId)
  46. return id
  47. },
  48. async abandonDraft (store, { id }) {
  49. store.commit('abandonDraft', { id })
  50. await deleteDraftFromStorage(id)
  51. },
  52. async loadDrafts (store) {
  53. const currentData = await getStorageData()
  54. store.commit('loadDrafts', currentData)
  55. }
  56. }
  57. export const getters = {
  58. draftsByTypeAndRefId (state) {
  59. return (type, refId) => {
  60. return Object.values(state.drafts).filter(draft => draft.type === type && draft.refId === refId)
  61. }
  62. },
  63. draftsArray (state) {
  64. return Object.values(state.drafts)
  65. },
  66. draftCount (state) {
  67. return Object.values(state.drafts).length
  68. }
  69. }
  70. const drafts = {
  71. state: defaultState,
  72. mutations,
  73. getters,
  74. actions
  75. }
  76. export default drafts