Skip to content

Commit

Permalink
fix(performance): allow Synchronizer to be compiled
Browse files Browse the repository at this point in the history
  • Loading branch information
stipsan committed Nov 1, 2024
1 parent b586f24 commit 8e49bea
Showing 1 changed file with 20 additions and 22 deletions.
42 changes: 20 additions & 22 deletions packages/editor/src/editor/components/Synchronizer.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {Patch} from '@portabletext/patches'
import type {PortableTextBlock} from '@sanity/types'
import {throttle} from 'lodash'
import {useCallback, useEffect, useMemo, useRef} from 'react'
import {useCallback, useEffect, useRef} from 'react'
import {Editor} from 'slate'
import {useSlate} from 'slate-react'
import {useEffectEvent} from 'use-effect-event'
Expand Down Expand Up @@ -69,26 +69,6 @@ export function Synchronizer(props: SynchronizerProps) {
IS_PROCESSING_LOCAL_CHANGES.set(slateEditor, false)
}, [editorActor, slateEditor, getValue])

const onFlushPendingPatchesThrottled = useMemo(() => {
return throttle(
() => {
// If the editor is normalizing (each operation) it means that it's not in the middle of a bigger transform,
// and we can flush these changes immediately.
if (Editor.isNormalizing(slateEditor)) {
onFlushPendingPatches()
return
}
// If it's in the middle of something, try again.
onFlushPendingPatchesThrottled()
},
FLUSH_PATCHES_THROTTLED_MS,
{
leading: false,
trailing: true,
},
)
}, [onFlushPendingPatches, slateEditor])

// Flush pending patches immediately on unmount
useEffect(() => {
return () => {
Expand All @@ -106,6 +86,24 @@ export function Synchronizer(props: SynchronizerProps) {

// Subscribe to, and handle changes from the editor
useEffect(() => {
const onFlushPendingPatchesThrottled = throttle(
() => {
// If the editor is normalizing (each operation) it means that it's not in the middle of a bigger transform,
// and we can flush these changes immediately.
if (Editor.isNormalizing(slateEditor)) {
onFlushPendingPatches()
return
}
// If it's in the middle of something, try again.
onFlushPendingPatchesThrottled()
},
FLUSH_PATCHES_THROTTLED_MS,
{
leading: false,
trailing: true,
},
)

debug('Subscribing to editor changes')
const sub = editorActor.on('*', (event) => {
switch (event.type) {
Expand Down Expand Up @@ -161,7 +159,7 @@ export function Synchronizer(props: SynchronizerProps) {
debug('Unsubscribing to changes')
sub.unsubscribe()
}
}, [handleChange, editorActor, onFlushPendingPatchesThrottled, slateEditor])
}, [editorActor, handleChange, onFlushPendingPatches, slateEditor])

// Sync the value when going online
const handleOnline = useCallback(() => {
Expand Down

0 comments on commit 8e49bea

Please sign in to comment.