# All files / src/Tree Tree.hooks.ts

92% Statements 92/100
77.27% Branches 17/22
90.9% Functions 30/33
91.91% Lines 91/99

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    2575x
    5x
    5x
    5x

    31x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x
    26x

    26x

    11x

    26x
    4x

    26x

    3x
    4x

    26x
    26x
    26x
    26x

    26x
    1x

    1x
    2x

    1x

    26x
    1x

    26x

    15x
    15x
    15x

    15x

    26x
    26x
    26x
    75x

    26x
    26x
    26x
    26x

    26x

    1x

    26x
    26x
    26x
    26x
    26x
    26x

    26x

    26x

    1x
    1x
    1x

    26x
    5x

    26x
    1x

    26x

    26x

    13x

    13x

    26x

    11x

    11x
    4x

    7x

    7x

    26x

    4x
    4x

    26x
    7x

    26x

    26x
    16x

    26x

    18x

    26x
    8x

    26x

    34x

    34x

    34x

    2x

     import React from 'react'
    import { useListNavigation } from '../_hooks/ListNavigation'
    import { useSet } from '../_hooks/useSet'
    import { isRootNode } from './Tree'
    import { LevelWise, Node, UseTreeProps } from './Tree.types'

    export function useTree<T extends Node = Node>({
      rootNodes,
      expanded,
      selected,
      selectionLimit,
      onSelect,
      multiple,
      autoExpandParent,
      getChildren,
      getParentId,
      onCollapse,
      onExpand,
    }: UseTreeProps<T>) {
      type VisibleNode = T & LevelWise
      type TreeNode = VisibleNode & {
        items?: (TreeNode | VisibleNode)[]
      }

      const getNodes = React.useCallback(
        (nodes: T[], node: T): T[] => {
          return [...nodes, node, ...getChildren(node).reduce(getNodes, [])]
        },
        [getChildren]
      )

      const nodes = React.useMemo(() => {
        return rootNodes.map((el: T) => getNodes([], el)).flat()
      }, [rootNodes, getNodes])

      const getNodeById = React.useCallback(
        (nodeId: T['id']): T =>
          nodes.find((item: T) => {
            return item.id === nodeId
          }) as T,
        [nodes]
      )

      const {
        has: isLoading,
        add: startLoading,
        remove: stopLoading,
      } = useSet<T['id']>()

      const handleExpand = React.useCallback(
        async (nodeId: T['id']) => {
          try {
            startLoading(nodeId)
            await onExpand(getNodeById(nodeId))
          } finally {
            stopLoading(nodeId)
          }
        },
        [getNodeById, onExpand, startLoading, stopLoading]
      )

      const handleCollapse = React.useCallback(
        (nodeId: T['id']) => onCollapse(getNodeById(nodeId)),
        [getNodeById, onCollapse]
      )

      const getExpandedIds: (nodeIds: T['id'][], currentNode: T) => T['id'][] =
        React.useCallback(
          (nodeIds, currentNode) => {
            const parentId = getParentId(currentNode)
            if (
              rootNodes.find((rootNode) => parentId === rootNode.id) ||
              isRootNode(parentId)
            ) {
              return [...nodeIds, currentNode.id, parentId]
            } else E{
              return getExpandedIds(
                [...nodeIds, currentNode.id],
                getNodeById(parentId)
              )
            }
          },
          [getNodeById, getParentId, rootNodes]
        )

      const expandedIds = React.useMemo(() => {
        if (autoExpandParent) {
          return nodes
            .filter((node) => expanded.concat(selected).includes(node.id))
            .reduce(getExpandedIds, [])
        }
        return expanded
      }, [autoExpandParent, expanded, getExpandedIds, nodes, selected])

      const {
        has: isExpanded,
        toggle: toggleExpanded,
        setCollection: setExpanded,
      } = useSet<T['id']>({
        initialValue: new Set(expandedIds),
        onAdd: handleExpand,
        onRemove: handleCollapse,
      })

      const handleChange = React.useCallback(
        (selectedNodes: Set<T['id']>) =>
          onSelect(Array.from(selectedNodes).map(getNodeById)),
        [getNodeById, onSelect]
      )

      const {
        collection: selectedIds,
        has: isSelected,
        add: addSelected,
        remove: removeSelected,
        setCollection: setSelected,
      } = useSet<T['id']>({
        initialValue: new Set(selected),
        onChange: handleChange,
      })

      const toggleSingleSelected = React.useCallback(
        (nodeId: T['id']) => {
          setSelected(new Set([nodeId]))
        },
        [setSelected]
      )

      const toggleSelected = React.useCallback(
        (nodeId: T['id']) => {
          if (!isSelected(nodeId)) {
            if (selectedIds.size < selectionLimit) {
              addSelected(nodeId)
            }
          } else E{
            removeSelected(nodeId)
          }
        },
        [addSelected, isSelected, removeSelected, selectedIds.size, selectionLimit]
      )

      const toggleSelection = React.useMemo(
        () => (multiple ? toggleSelected : toggleSingleSelected),
        [multiple, toggleSelected, toggleSingleSelected]
      )

      const handleSelection = React.useCallback(
        (node: T) => toggleSelection(node.id),
        [toggleSelection]
      )

      const listNavigation = useListNavigation({
        circular: false,
        initialIndex: 0,
        size: 0,
      })

      const getSelectableItems = React.useCallback(
        (visibleNodes: TreeNode[], node: TreeNode): TreeNode[] => {
          const visibleItems =
            isExpanded(node.id) && !isLoading(node.id) && node.items
              ? node.items.reduce(getSelectableItems, [])
              : []
          return [...visibleNodes, node, ...visibleItems]
        },
        [isExpanded, isLoading]
      )

      const getChildrenNodes = React.useCallback(
        (nodes: TreeNode[], node: T, level: number): TreeNode[] => {
          const children = getChildren(node)

          if (children.length > 0) {
            return [
              ...nodes,
              {
                ...node,
                level,
                items: children.reduce(
                  (acc, curr) => getChildrenNodes(acc, curr, level + 1),
                  [] as TreeNode[]
                ),
              },
            ]
          } else {
            return [...nodes, { ...node, level }]
          }
        },
        [getChildren]
      )

      const nodesTree = React.useMemo(
        () =>
          Array.isArray(rootNodes)
            ? rootNodes.map((el: T) => getChildrenNodes([], el, 0)).flat()
            : [],
        [rootNodes, getChildrenNodes]
      )

      const visibleNodes = React.useMemo(
        () => nodesTree.reduce(getSelectableItems, []),
        [getSelectableItems, nodesTree]
      )

      const highlight = React.useCallback(
        (node: T) => {
          const index = visibleNodes.findIndex(
            (visibleNode: T) => visibleNode.id === node.id
          )
          Iif (index !== -1) {
            listNavigation.set(index)
          }
        },
        [listNavigation, visibleNodes]
      )

      React.useEffect(() => {
        listNavigation.setSize(visibleNodes.length)
      }, [listNavigation, visibleNodes.length])

      const isHighlighted = React.useCallback(
        (node: T) =>
          visibleNodes[listNavigation.index] &&
          visibleNodes[listNavigation.index].id === node.id,
        [listNavigation.index, visibleNodes]
      )

      const highlightedNode = React.useMemo(() => {
        return visibleNodes[listNavigation.index]
      }, [listNavigation.index, visibleNodes])

      return {
        nodes: visibleNodes,
        isExpanded: React.useCallback(
          (node: T) => isExpanded(node.id),
          [isExpanded]
        ),
        isSelected: React.useCallback(
          (node: T) => isSelected(node.id),
          [isSelected]
        ),
        isLoading: React.useCallback((node: T) => isLoading(node.id), [isLoading]),
        highlightedNode,
        isHighlighted,
        highlight,
        handleSelection,
        handleExpansion: React.useCallback(
          (node: T) => toggleExpanded(node.id),
          [toggleExpanded]
        ),
        setSelected,
        setExpanded,
        isFileLimitReached: selectedIds.size >= selectionLimit,
        listNavigation,
      }
    }