NoriginMedia / react-spatial-navigation

DEPRECATED. HOC-based Spatial Navigation. NEW Hooks version is available here: https://github.com/NoriginMedia/norigin-spatial-navigation
MIT License
226 stars 64 forks source link

Select closest elements #71

Closed thiagoteles closed 4 years ago

thiagoteles commented 4 years ago

Hello,

I have this code

` const KeyOne = ({ value, focused }: any) => { return ( <View style={focused ? styles.focused : {}}>

{value}
        </View>
    )
}

const KeyRow = ({ children, focused }: any) => {
    return (
        <View style={focused ? styles.focused : {}}>
            <Text style={styles.keyRow}>{children}</Text>
        </View>
    )
}

const Container = ({ children, focused }: any) => {
    return (
        <div>{children}</div>
    )
}

const FocusableKeyOne = withFocusable()(KeyOne);
const FocusableRow = withFocusable()(KeyRow);
const FocusableContainer = withFocusable()(Container);

return (

    <FocusableContainer>
        <FocusableRow focusKey={'ROW-1'}>
            <FocusableKeyOne focusKey={'KEY-1'} value={"1"} />
            <FocusableKeyOne focusKey={'KEY-2'} value={"2"} />
            <FocusableKeyOne focusKey={'KEY-3'} value={"3"} />
        </FocusableRow>
        <FocusableRow focusKey={'ROW-2'}>
            <FocusableKeyOne focusKey={'KEY-4'} value={"4"} />
            <FocusableKeyOne focusKey={'KEY-5'} value={"5"} />
            <FocusableKeyOne focusKey={'KEY-6'} value={"6"} />
        </FocusableRow>
        <FocusableRow focusKey={'ROW-3'}>
            <FocusableKeyOne focusKey={'KEY-7'} value={"7"} />
            <FocusableKeyOne focusKey={'KEY-8'} value={"8"} />
            <FocusableKeyOne focusKey={'KEY-9'} value={"9"} />
        </FocusableRow>
    </FocusableContainer>
)

`

Its produces a small virtual keyboard like that:

image

But when Im on number 6 for example, and press UP the focus goes to 1. When Im on number 8 for example and press UP the focus goes to 6.

I dont know what a reson due a framework dont get the closest value based on key pressed.

Someone can help me please?

asgvard commented 4 years ago

Hi,

You group keys by 3 into a Row, so when you go up from number 6, first it focuses second Row. Then the Row propagates focus down to the first child which is number one. The case with going up from 8 to 6 is because it remembers last focused child in that Row and focuses 6. Please read the docs and the article, especially about “forgetLastFocusedChild” and how is focus propagated down from parents to children. In your case you don’t need to make Row focusable. This creates nested level in your focusable tree that causes these issues. Also always try to use debug and visualDebug mode first, it tells you exactly where the focus goes and why, including coordinates calculations.