Skip to content

Commit

Permalink
refactor: extract useYDocUpdates hook in PreviewPanel component
Browse files Browse the repository at this point in the history
  • Loading branch information
lawvs committed Sep 10, 2024
1 parent 02a18da commit 8a769f7
Showing 1 changed file with 24 additions and 17 deletions.
41 changes: 24 additions & 17 deletions src/components/preview-panel.tsx
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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<Path>([]);
const [target, setTarget] = useState<unknown>(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);
Expand All @@ -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<Path>([]);
const [target, setTarget] = useState<unknown>(null);

const filterMap = useFilterMap();
const filterEnable = useIsFilterEnabled();
const inspectDepth = filterEnable ? 1 : 3;
const jsonViewerValue = filterEnable ? filterMap : yDoc;

useYDocUpdates(yDoc);

return (
<div className="flex flex-1 flex-col">
Expand Down

0 comments on commit 8a769f7

Please sign in to comment.