From 070b586648627b5acb89ac21804f7ffc1b80eb3b Mon Sep 17 00:00:00 2001 From: James Vaughan Date: Tue, 13 Aug 2024 15:22:04 -0700 Subject: [PATCH] Add hooks for using the project and an individual element --- src/ui/app.tsx | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/ui/app.tsx b/src/ui/app.tsx index 2b5b54b..7575aeb 100644 --- a/src/ui/app.tsx +++ b/src/ui/app.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useState, useSyncExternalStore } from "react" +import { useCallback, useState, useSyncExternalStore } from "react"; import { getGlobal } from "../global"; import stringify from "json-stringify-pretty-compact"; import { Project } from "../project"; @@ -44,6 +44,25 @@ function computeSnapshot(project: Project): StoreSnapshot { } } +function useProject(): StoreSnapshot { + return useSyncExternalStore(getGlobal().project.getStore().subscribeObjectChange, () => + computeSnapshot(getGlobal().project), + ); +} + +function useElement(elementId: ElementId): Element | null { + return useSyncExternalStore( + (onStoreChanged) => { + return getGlobal().project.subscribeElementChange((element) => { + if (element.id === elementId) { + onStoreChanged(); + } + }); + }, + () => getGlobal().project.getById(elementId), + ); +} + type ElementRowProps = { index: number, element: ElementRow, @@ -149,14 +168,7 @@ function ElementTree({ elements, selection, setSelection }: ElementTreeProps) { export function App() { const project = getGlobal().project; - - const [snapshot, setSnapshot] = useState(null); - useEffect(() => { - setSnapshot(computeSnapshot(project)); - return project.getStore().subscribeObjectChange((change) => { - setSnapshot(computeSnapshot(project)); - }) - }, [project]); + const snapshot = useProject(); const [selection, setSelection] = useState({}); const selected = Object.keys(selection)