Skip to content

Commit

Permalink
refactor(structure): announce presence throttled
Browse files Browse the repository at this point in the history
When we introduced presence in the PortableTextInput, we risk calling the presence updates very often.
There should be no reason for not doing this throttled, as long as we have leading true.
  • Loading branch information
skogsmaskin authored and hermanwikner committed Apr 26, 2024
1 parent 4cd93f6 commit 1f8fc66
Showing 1 changed file with 21 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from '@sanity/types'
import {useToast} from '@sanity/ui'
import {fromString as pathFromString, resolveKeyedPath} from '@sanity/util/paths'
import {omit} from 'lodash'
import {omit, throttle} from 'lodash'
import {memo, useCallback, useEffect, useMemo, useRef, useState} from 'react'
import deepEquals from 'react-fast-compare'
import {
Expand Down Expand Up @@ -548,15 +548,8 @@ export const DocumentPaneProvider = memo((props: DocumentPaneProviderProps) => {
[formStateRef],
)

const handleFocus = useCallback(
const updatePresence = useCallback(
(nextFocusPath: Path, payload?: OnPathFocusPayload) => {
setFocusPath(nextFocusPath)
if (!deepEquals(focusPathRef.current, nextFocusPath)) {
setOpenPath(nextFocusPath.slice(0, -1))
focusPathRef.current = nextFocusPath
onFocusPath?.(nextFocusPath)
}

presenceStore.setLocation([
{
type: 'document',
Expand All @@ -567,7 +560,25 @@ export const DocumentPaneProvider = memo((props: DocumentPaneProviderProps) => {
},
])
},
[documentId, onFocusPath, presenceStore, setOpenPath],
[documentId, presenceStore],
)

const updatePresenceThrottled = useMemo(
() => throttle(updatePresence, 1000, {leading: true, trailing: true}),
[updatePresence],
)

const handleFocus = useCallback(
(nextFocusPath: Path, payload?: OnPathFocusPayload) => {
setFocusPath(nextFocusPath)
if (!deepEquals(focusPathRef.current, nextFocusPath)) {
setOpenPath(nextFocusPath.slice(0, -1))
focusPathRef.current = nextFocusPath
onFocusPath?.(nextFocusPath)
}
updatePresenceThrottled(nextFocusPath, payload)
},
[onFocusPath, setOpenPath, updatePresenceThrottled],
)

const documentPane: DocumentPaneContextValue = useMemo(
Expand Down

0 comments on commit 1f8fc66

Please sign in to comment.