From ef55138e691d1651f05fcfdd45d9d46d8c5effcd Mon Sep 17 00:00:00 2001 From: Michael Bashurov Date: Mon, 23 Aug 2021 16:45:34 +0300 Subject: [PATCH] Added useCenterAnchor hook It allows to read centerAnchor prop on a Box, which is useful when positioning something absolutely inside a Box --- src/Box.tsx | 8 ++++---- src/context.ts | 1 + src/hooks.ts | 13 ++++++++++--- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/Box.tsx b/src/Box.tsx index 83ac4cc..51850e3 100644 --- a/src/Box.tsx +++ b/src/Box.tsx @@ -4,7 +4,7 @@ import Yoga from 'yoga-layout-prebuilt' import { ReactThreeFiber, useFrame } from '@react-three/fiber' import { setYogaProperties, rmUndefFromObj } from './util' -import { boxContext, flexContext } from './context' +import { boxContext, flexContext, SharedBoxContext } from './context' import { R3FlexProps } from './props' import { useReflow, useContext } from './hooks' @@ -75,7 +75,7 @@ export function Box({ ...props }: { centerAnchor?: boolean - children: React.ReactNode | ((width: number, height: number) => React.ReactNode) + children: React.ReactNode | ((width: number, height: number, centerAnchor?: boolean) => React.ReactNode) } & R3FlexProps & Omit, 'children'>) { // must memoize or the object literal will cause every dependent of flexProps to rerender everytime @@ -225,12 +225,12 @@ export function Box({ } }) - const sharedBoxContext = useMemo(() => ({ node, size }), [node, size]) + const sharedBoxContext = useMemo(() => ({ node, size, centerAnchor }), [node, size, centerAnchor]) return ( - {typeof children === 'function' ? children(size[0], size[1]) : children} + {typeof children === 'function' ? children(size[0], size[1], centerAnchor) : children} ) diff --git a/src/context.ts b/src/context.ts index b016dc2..04ed578 100644 --- a/src/context.ts +++ b/src/context.ts @@ -28,6 +28,7 @@ export const flexContext = createContext(initialSharedFlexCon export interface SharedBoxContext { node: YogaNode | null size: [number, number] + centerAnchor?: boolean } const initialSharedBoxContext: SharedBoxContext = { diff --git a/src/hooks.ts b/src/hooks.ts index d8ecf59..17ded20 100644 --- a/src/hooks.ts +++ b/src/hooks.ts @@ -1,4 +1,4 @@ -import { useCallback, useContext as useContextImpl } from 'react' +import { useCallback, useContext as useContextImpl, useMemo } from 'react' import { Mesh, Vector3 } from 'three' import { flexContext, boxContext } from './context' @@ -15,9 +15,16 @@ export function useReflow() { return requestReflow } +/** + * @returns [width, height, centerAnchor] + */ export function useFlexSize() { - const { size } = useContext(boxContext) - return size + const { + size: [width, height], + centerAnchor, + } = useContext(boxContext) + const value = useMemo(() => [width, height, centerAnchor] as const, [width, height, centerAnchor]) + return value } export function useFlexNode() {