-
Notifications
You must be signed in to change notification settings - Fork 637
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
93 additions
and
76 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
import { useCallback, useEffect, useMemo } from "react"; | ||
import { useMeasure as useMeasureBase, useRectState } from "~/shared/dom-hooks"; | ||
import { type PubsubMap, useSubscribeAll } from "~/shared/pubsub"; | ||
|
||
const useTreeChange = (onChange: () => void, enabled: boolean) => { | ||
const callback = useMemo(() => { | ||
if (!enabled) { | ||
return () => null; | ||
} | ||
return (type: keyof PubsubMap) => { | ||
if ( | ||
type === "updateProps" || | ||
type === "deleteProp" || | ||
type === "insertInstance" || | ||
type === "deleteInstance" || | ||
type === "reparentInstance" || | ||
type === "updateStyle" || | ||
type.startsWith("previewStyle:") | ||
) { | ||
onChange(); | ||
} | ||
}; | ||
}, [onChange, enabled]); | ||
|
||
useSubscribeAll(callback); | ||
}; | ||
|
||
// A version of useMeasure capable of measuring inlined elements, but works only within canvas. | ||
export const useMeasure = (element: HTMLElement | undefined) => { | ||
const { canObserve, rect: baseRect } = useMeasureBase(element); | ||
|
||
const [rect, setRect] = useRectState(); | ||
|
||
const handleChange = useCallback(() => { | ||
setRect(element && element.getBoundingClientRect()); | ||
}, [element, setRect]); | ||
|
||
useTreeChange(handleChange, canObserve === false); | ||
|
||
useEffect(() => { | ||
if (canObserve === false) { | ||
handleChange(); | ||
} | ||
}, [handleChange, canObserve]); | ||
|
||
return canObserve ? baseRect : rect; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters