Monorepo containing core modules of Zeichen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
1.9 KiB

  1. import * as Storage from '../services/Storage'
  2. const save = async ({ stateRef, router, id, setNotes, }) => {
  3. stateRef.current.updatedAt = new Date().toISOString()
  4. const newNote = await Storage.saveNote(stateRef.current)
  5. if (router.query.id !== id) {
  6. await router.replace(
  7. {
  8. pathname: '/notes/[id]',
  9. query: { id, },
  10. },
  11. undefined,
  12. {
  13. shallow: true,
  14. }
  15. )
  16. }
  17. setNotes(oldNotes => {
  18. let notes
  19. if (oldNotes.some((a) => a.id === id)) {
  20. notes = oldNotes.map(n => n.id === id ? newNote : n)
  21. } else {
  22. notes = [newNote, ...oldNotes]
  23. }
  24. return notes.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
  25. })
  26. }
  27. const triggerAutoSave = ({
  28. stateRef,
  29. timeoutRef,
  30. router,
  31. id,
  32. setNotes,
  33. }) => {
  34. if (timeoutRef.current !== null) {
  35. clearTimeout(timeoutRef.current)
  36. }
  37. timeoutRef.current = setTimeout(async () => {
  38. await save({ stateRef, router, id, setNotes, })
  39. timeoutRef.current = null
  40. }, 3000)
  41. }
  42. export const updateContent = ({
  43. stateRef,
  44. timeoutRef,
  45. router,
  46. id,
  47. setNotes,
  48. }) => e => {
  49. stateRef.current.content = e
  50. triggerAutoSave({
  51. stateRef,
  52. timeoutRef,
  53. router,
  54. id,
  55. setNotes,
  56. })
  57. }
  58. export const updateTitle = ({
  59. stateRef,
  60. timeoutRef,
  61. router,
  62. id,
  63. setNotes,
  64. setTitle,
  65. }) => e => {
  66. setTitle(stateRef.current.title = e.target.value)
  67. triggerAutoSave({
  68. stateRef,
  69. timeoutRef,
  70. router,
  71. id,
  72. setNotes,
  73. })
  74. }
  75. export const remove = ({
  76. setNotes,
  77. notes,
  78. router,
  79. }) => note => async () => {
  80. setNotes(notes.filter(n => n.id !== note.id))
  81. await router.replace(
  82. {
  83. pathname: '/notes',
  84. },
  85. undefined,
  86. {
  87. shallow: true,
  88. }
  89. )
  90. const result = await Storage.deleteNote(note)
  91. if (!result) {
  92. setNotes(notes)
  93. }
  94. }
  95. export const load = async ({ setNotes, }) => {
  96. const theNotes = await Storage.loadNotes()
  97. setNotes(theNotes)
  98. }