Zeichen's app for both server and client.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Note.ts 1.9 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. }