From 86cf27aae67c152af9d9f5ed17b303c0c8ee73a9 Mon Sep 17 00:00:00 2001 From: Bela Bohlender Date: Fri, 20 Aug 2021 00:05:52 +0200 Subject: [PATCH] prevent readding boxes at the end of its parent --- src/Box.tsx | 16 +++++++++++----- src/Flex.tsx | 10 ++++++++-- src/context.ts | 3 ++- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/Box.tsx b/src/Box.tsx index 83ac4cc..95e27c5 100644 --- a/src/Box.tsx +++ b/src/Box.tsx @@ -192,18 +192,24 @@ export function Box({ setYogaProperties(node, flexProps, scaleFactor) }, [flexProps, node, scaleFactor]) - // Make child known to the parents yoga instance *before* it calculates layout useLayoutEffect(() => { - if (!group.current || !parent) return - - parent.insertChild(node, parent.getChildCount()) - registerBox(node, group.current, flexProps, centerAnchor) + if (!parent) return // Remove child on unmount return () => { parent.removeChild(node) unregisterBox(node) } + }, [node, parent]) + + // Make child known to the parents yoga instance *before* it calculates layout + useLayoutEffect(() => { + if (!group.current || !parent) return + + if (registerBox(node, group.current, flexProps, centerAnchor)) { + //newly registered node: add it to the parent + parent.insertChild(node, parent.getChildCount()) + } }, [node, parent, flexProps, centerAnchor, registerBox, unregisterBox]) // We need to reflow if props change diff --git a/src/Flex.tsx b/src/Flex.tsx index c173097..c4172f4 100644 --- a/src/Flex.tsx +++ b/src/Flex.tsx @@ -214,10 +214,16 @@ export function Flex({ const registerBox = useCallback( (node: YogaNode, group: Group, flexProps: R3FlexProps, centerAnchor: boolean = false) => { const i = boxesRef.current.findIndex((b) => b.node === node) + const boxItem = { group, node, flexProps, centerAnchor } if (i !== -1) { - boxesRef.current.splice(i, 1) + //node already contained: update box + boxesRef.current[i] = boxItem + return false + } else { + //node not contained: insert new box + boxesRef.current.push(boxItem) + return true } - boxesRef.current.push({ group, node, flexProps, centerAnchor }) }, [] ) diff --git a/src/context.ts b/src/context.ts index b016dc2..5c23be5 100644 --- a/src/context.ts +++ b/src/context.ts @@ -6,7 +6,7 @@ import { R3FlexProps } from './props' export interface SharedFlexContext { scaleFactor: number requestReflow(): void - registerBox(node: YogaNode, group: Group, flexProps: R3FlexProps, centerAnchor?: boolean): void + registerBox(node: YogaNode, group: Group, flexProps: R3FlexProps, centerAnchor?: boolean): boolean unregisterBox(node: YogaNode): void } @@ -17,6 +17,7 @@ const initialSharedFlexContext: SharedFlexContext = { }, registerBox() { console.warn('Flex not initialized! Please report') + return false }, unregisterBox() { console.warn('Flex not initialized! Please report')