Start sharing components as a team!Share components as a team!Join Bit to build your applications faster.Get Started Free

child-mapping

v0.86.0arrow_drop_down
v0.86.0
v0.85.0
v0.84.0
STATUS
Passing
DOWNLOADS
10,917
LICENSE
MIT
VISIBILITY
Public
PUBLISHED
9 months ago
SIZE
25 KB
Given `this.props.children`, return an object mapping key to child.
1 contributor
Use child-mapping in your project ?
Copied
npm i @bit/semantic-org.semantic-ui-react.utils.child-mapping
Set Bit as a scoped registryLearn more
npm config set '@bit:registry' https://node.bit.dev
Files
childMapping.js
61 Lines(35 sloc)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import _ from 'lodash'
import { Children, isValidElement } from 'react'

/**
 * Given `this.props.children`, return an object mapping key to child.
 *
 * @param {object} children Element's children
 * @return {object} Mapping of key to child
 */
export const getChildMapping = children => _.keyBy(_.filter(Children.toArray(children), isValidElement), 'key')

const getPendingKeys = (prev, next) => {
  const nextKeysPending = {}
  let pendingKeys = []

  _.forEach(_.keys(prev), (prevKey) => {
    if (!_.has(next, prevKey)) {
      pendingKeys.push(prevKey)
      return
    }

    if (pendingKeys.length) {
      nextKeysPending[prevKey] = pendingKeys
      pendingKeys = []
    }
  })

  return [nextKeysPending, pendingKeys]
}

const getValue = (key, prev, next) => (_.has(next, key) ? next[key] : prev[key])

/**
 * When you're adding or removing children some may be added or removed in the same render pass. We want to show *both*
 * since we want to simultaneously animate elements in and out. This function takes a previous set of keys and a new set
 * of keys and merges them with its best guess of the correct ordering.
 *
 * @param {object} prev Prev children as returned from `getChildMapping()`
 * @param {object} next Next children as returned from `getChildMapping()`
 * @return {object} A key set that contains all keys in `prev` and all keys in `next` in a reasonable order
 */
export const mergeChildMappings = (prev = {}, next = {}) => {
  const childMapping = {}
  const [nextKeysPending, pendingKeys] = getPendingKeys(prev, next)

  _.forEach(_.keys(next), (nextKey) => {
    if (_.has(nextKeysPending, nextKey)) {
      _.forEach(nextKeysPending[nextKey], (pendingKey) => {
        childMapping[pendingKey] = getValue(pendingKey, prev, next)
      })
    }

    childMapping[nextKey] = getValue(nextKey, prev, next)
  })

  _.forEach(pendingKeys, (pendingKey) => {
    childMapping[pendingKey] = getValue(pendingKey, prev, next)
  })

  return childMapping
}