From 8a769f787329daa78ab31f619ee68e14e4d9f2d0 Mon Sep 17 00:00:00 2001 From: lawvs <18554747+lawvs@users.noreply.github.com> Date: Tue, 10 Sep 2024 16:03:18 +0800 Subject: [PATCH] refactor: extract useYDocUpdates hook in PreviewPanel component --- src/components/preview-panel.tsx | 41 +++++++++++++++++++------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/src/components/preview-panel.tsx b/src/components/preview-panel.tsx index 8c4992e..848a449 100644 --- a/src/components/preview-panel.tsx +++ b/src/components/preview-panel.tsx @@ -1,6 +1,7 @@ import { JsonViewer, Path } from "@textea/json-viewer"; import { Bug } from "lucide-react"; import { useEffect, useState } from "react"; +import * as Y from "yjs"; import { yDataType } from "../data-types"; import { useConfig, @@ -14,25 +15,10 @@ import { DeleteDialog } from "./delete-dialog"; import { useTheme } from "./theme-provider"; import { Button } from "./ui/button"; -export function PreviewPanel() { - const { resolvedTheme } = useTheme(); - const [yDoc] = useYDoc(); - const [config] = useConfig(); - const [addDialogOpen, setAddDialogOpen] = useState(false); - const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); - const [path, setPath] = useState([]); - const [target, setTarget] = useState(null); - - const filterMap = useFilterMap(); - const filterEnable = useIsFilterEnabled(); - const inspectDepth = filterEnable ? 1 : 3; - const jsonViewerValue = filterEnable ? filterMap : yDoc; - +function useYDocUpdates(yDoc: Y.Doc) { const [, setCount] = useState(0); + useEffect(() => { - if (!yDoc) { - return; - } const callback = () => { // Force re-render setCount((count) => count + 1); @@ -45,8 +31,29 @@ export function PreviewPanel() { }); return () => { yDoc.off("update", callback); + yDoc.off("subdocs", callback); + yDoc.subdocs.forEach((subDoc) => { + subDoc.off("update", callback); + }); }; }, [yDoc]); +} + +export function PreviewPanel() { + const { resolvedTheme } = useTheme(); + const [yDoc] = useYDoc(); + const [config] = useConfig(); + const [addDialogOpen, setAddDialogOpen] = useState(false); + const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); + const [path, setPath] = useState([]); + const [target, setTarget] = useState(null); + + const filterMap = useFilterMap(); + const filterEnable = useIsFilterEnabled(); + const inspectDepth = filterEnable ? 1 : 3; + const jsonViewerValue = filterEnable ? filterMap : yDoc; + + useYDocUpdates(yDoc); return (