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

Optimization of `getNextFocusKey` method #40

Closed yarikleto closed 4 years ago

yarikleto commented 5 years ago

This method recursively finds a focusable child without his own focusable children.

If the preferredChildFocusKey and lastFocusedChildKey are "disabled", we need to select at least something.

// getNextFocusKey method

/**
 * Otherwise, trying to focus something by coordinates
*/
  const sortedXChildren = sortBy(children, (child) => child.layout.left);
  const sortedYChildren = sortBy(sortedXChildren, (child) => child.layout.top);
  const {focusKey: childKey} = first(sortedYChildren);

  this.log('getNextFocusKey', 'childKey will be focused', childKey);

  return this.getNextFocusKey(childKey);

Here, we try to find a component closer to (x: 0, y: 0). It's O(2n)

const [{focusKey: childKey}] = sortBy(
  children, ({layout}) => Math.abs(layout.left) + Math.abs(layout.top)
);

It's the same. O(n).

Or we can just pick a first child. It's very fast :)

const [{focusKey: childKey}] = children
asgvard commented 5 years ago

Although this is not a huge bottleneck, it looks like a nice optimisation with single sortBy way. Picking first child seems a bit random though. Could you submit a PR please?

yarikleto commented 5 years ago

Thank you for your answer. OK

asgvard commented 4 years ago

Merged, will be published soon :)

yarikleto commented 4 years ago

🥳