|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- import * as Storage from '../services/Storage'
-
- const save = async ({ stateRef, router, id, setNotes, }) => {
- stateRef.current.updatedAt = new Date().toISOString()
- const newNote = await Storage.saveNote(stateRef.current)
- if (router.query.id !== id) {
- await router.replace(
- {
- pathname: '/notes/[id]',
- query: { id, },
- },
- undefined,
- {
- shallow: true,
- }
- )
- }
- setNotes(oldNotes => {
- let notes
- if (oldNotes.some((a) => a.id === id)) {
- notes = oldNotes.map(n => n.id === id ? newNote : n)
- } else {
- notes = [newNote, ...oldNotes]
- }
- return notes.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
- })
- }
-
- const triggerAutoSave = ({
- stateRef,
- timeoutRef,
- router,
- id,
- setNotes,
- }) => {
- if (timeoutRef.current !== null) {
- clearTimeout(timeoutRef.current)
- }
- timeoutRef.current = setTimeout(async () => {
- await save({ stateRef, router, id, setNotes, })
- timeoutRef.current = null
- }, 3000)
- }
-
- export const updateContent = ({
- stateRef,
- timeoutRef,
- router,
- id,
- setNotes,
- }) => e => {
- stateRef.current.content = e
- triggerAutoSave({
- stateRef,
- timeoutRef,
- router,
- id,
- setNotes,
- })
- }
-
- export const updateTitle = ({
- stateRef,
- timeoutRef,
- router,
- id,
- setNotes,
- setTitle,
- }) => e => {
- setTitle(stateRef.current.title = e.target.value)
- triggerAutoSave({
- stateRef,
- timeoutRef,
- router,
- id,
- setNotes,
- })
- }
-
- export const remove = ({
- setNotes,
- notes,
- router,
- }) => note => async () => {
- setNotes(notes.filter(n => n.id !== note.id))
- await router.replace(
- {
- pathname: '/notes',
- },
- undefined,
- {
- shallow: true,
- }
- )
- const result = await Storage.deleteNote(note)
- if (!result) {
- setNotes(notes)
- }
- }
-
- export const load = async ({ setNotes, }) => {
- const theNotes = await Storage.loadNotes()
- setNotes(theNotes)
- }
|