From d1341e2e563c014cd079b5a999ab56bc9f336a32 Mon Sep 17 00:00:00 2001 From: rdunk Date: Wed, 5 Feb 2025 01:47:35 +0000 Subject: [PATCH] fix(visual-editing): prevent snapshot overfetching --- packages/visual-editing/src/ui/Overlays.tsx | 40 ++++++++++++--------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/packages/visual-editing/src/ui/Overlays.tsx b/packages/visual-editing/src/ui/Overlays.tsx index 9ad9bcbd1..7bb7e242f 100644 --- a/packages/visual-editing/src/ui/Overlays.tsx +++ b/packages/visual-editing/src/ui/Overlays.tsx @@ -78,26 +78,33 @@ const DocumentReporter: FunctionComponent<{ perspective: ClientPerspective }> = (props) => { const {documentIds} = props - const actor = useOptimisticActor() + const [uniqueIds, setUniqueIds] = useState([]) - useEffect((): (() => void) => { - return observeDocumentIds(actor, documentIds) - }, [actor, documentIds]) + useEffect(() => { + setUniqueIds((prev) => { + const next = Array.from(new Set(documentIds)) + return prev.length === next.length && + prev.reduce((acc, prevId) => acc.filter((id) => id !== prevId), next)?.length === 0 + ? prev + : next + }) + }, [documentIds]) + const actor = useOptimisticActor() - return null -} -function observeDocumentIds(actor: ReturnType, documentIds: string[]) { - const uniqueIds = Array.from(new Set(documentIds)) - for (const id of uniqueIds) { - actor.send({type: 'observe', documentId: getDraftId(id)}) - actor.send({type: 'observe', documentId: getPublishedId(id)}) - } - return () => { + useEffect(() => { for (const id of uniqueIds) { - actor.send({type: 'unobserve', documentId: getDraftId(id)}) - actor.send({type: 'unobserve', documentId: getPublishedId(id)}) + actor.send({type: 'observe', documentId: getDraftId(id)}) + actor.send({type: 'observe', documentId: getPublishedId(id)}) } - } + return () => { + for (const id of uniqueIds) { + actor.send({type: 'unobserve', documentId: getDraftId(id)}) + actor.send({type: 'unobserve', documentId: getPublishedId(id)}) + } + } + }, [actor, uniqueIds]) + + return null } const OverlaysController: FunctionComponent<{ @@ -323,6 +330,7 @@ export const Overlays: FunctionComponent<{ }, [overlayEnabled]) const documentIds = useMemo(() => { + console.log('recalc documentIds') return elements.flatMap((element) => ('id' in element.sanity ? [element.sanity.id] : [])) }, [elements])