# All files / src/FileSelect/TreeSource TreeSource.tsx

13.09% Statements 11/84
0% Branches 0/16
0% Functions 0/21
18.33% Lines 11/60

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
    1793x
    3x
    3x
    3x

    3x

    3x
    3x

    3x

    3x

    3x

    3x

     import React from 'react'
    import { areEqual } from 'react-window'
    import { Spinner } from '../../Spinner/Spinner'
    import { Tree } from '../../Tree/Tree'
    import { Node as TreeNode, TreeNodeId } from '../../Tree/Tree.types'
    import { useResizeObserver } from '../../_hooks/ResizeObserver'
    import { DivAttributes } from '../../_utils/types'
    import { useFileSelectContext } from '../FileSelect'
    import { StyledFileTreeSpinner } from './TreeSource.styles'
    import { FileTreeProps, TreeSourceRef } from './TreeSource.types'

    const topPadding = 24

    function noop() {}

    /**
     * `innerElementType` and `outerElementType` elements are needed to create top padding.
     * Be aware that because of virtualization, it is not a trivial task.
     * 1. First of all, we pass height to the `Tree` component without padding, it is needed for correct work of keyboard navigation.
     * 2. Then we counterbalance height in outerElementType component (by adding padding to the height).
     * 3. The last step - make padding using the shift of a relatively positioned element.
     */
    const innerElementType = React.memo(
      React.forwardRef<HTMLDivElement, any>(
        ({ style, children, ...props }, ref) => (
          <div
            ref={ref}
            style={{
              ...style,
              position: 'relative',
              top: `${topPadding}px`,
              height: `${parseFloat(style.height) - topPadding}px`,
            }}
            {...props}
          >
            {children}
          </div>
        )
      ),
      areEqual
    )

    const outerElementType = React.memo(
      React.forwardRef<HTMLDivElement, any>(
        ({ style, children, ...props }, ref) => (
          <div
            ref={ref}
            style={{
              ...style,
              height: `${parseFloat(style.height) + topPadding}px`,
            }}
            {...props}
          >
            {children}
          </div>
        )
      ),
      areEqual
    )

    export const TreeSource = React.forwardRef<
      TreeSourceRef,
      FileTreeProps & Omit<DivAttributes, 'onChange'>
    >(
      (
        {
          sourceId,
          title,
          icon,
          options,
          isLoading = false,
          onChange = noop,
          onExpand = () => Promise.resolve(),
          ...props
        },
        ref
      ) => {
        const {
          maxFileNumber,
          register,
          currentSource,
          onChange: onSourceChange,
          onResetValue,
        } = useFileSelectContext()

        const [value, setValue] = React.useState<TreeNode[]>([])
        const [expandedItems, setExpandedNodes] = React.useState<TreeNodeId[]>([])

        React.useEffect(() => {
          onSourceChange(sourceId, value)
        }, [value])

        React.useEffect(() => {
          const unregister = register(sourceId, {
            title,
            icon,
          })
          const unsubscribe = onResetValue(() => {
            setValue([])
          })
          return () => {
            unsubscribe()
            unregister()
          }
        }, [])

        const selectedFiles = React.useMemo(
          () => value.map((item: TreeNode) => item.id),
          [value]
        )

        const _onChange = (files: TreeNode[]) => {
          setValue(files)
          onChange(files)
        }

        const _onExpand = async (node: TreeNode) => {
          await onExpand(node)
          setExpandedNodes((prev) => [...prev, node.id])
        }

        const _onCollapse = (node: TreeNode) => {
          setExpandedNodes((prev) => prev.filter((nodeId) => nodeId !== node.id))
        }

        const [containerSize, setContainerSize] = React.useState({
          width: 0,
          height: 0,
        })

        const handleContainerResize = React.useCallback(
          (entries: ResizeObserverEntry[]) => {
            Iif (entries[0]) {
              const { clientHeight: height, clientWidth: width } = entries[0].target
              setContainerSize({ width, height })
            }
          },
          [setContainerSize]
        )

        const setResizeObserverTarget = useResizeObserver(handleContainerResize)

        React.useImperativeHandle(ref, () => ({
          setExpandedNodes,
          setValue,
        }))

        Iif (currentSource !== sourceId) {
          return null
        }

        return !isLoading ? (
          <Tree
            {...props}
            ref={(instance) => {
              Iif (instance?.rootEl) {
                setResizeObserverTarget(instance.rootEl)
              }
            }}
            options={options}
            onSelect={_onChange}
            onExpand={_onExpand}
            onCollapse={_onCollapse}
            expanded={expandedItems}
            selected={selectedFiles}
            selectionLimit={maxFileNumber + value.length}
            visibleHeight={containerSize.height - topPadding}
            innerElementType={innerElementType}
            outerElementType={outerElementType}
            autoExpandParent={false}
          />
        ) : (
          <StyledFileTreeSpinner>
            <Spinner />
          </StyledFileTreeSpinner>
        )
      }
    )