# All files / src/_utils slotify.ts

95.65% Statements 22/23
75% Branches 3/4
100% Functions 4/4
94.11% Lines 16/17

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
    5819x

    19x

    10x
    28x
    28x

    28x

    10x
    27x

    27x

    61x

    27x
    4x

    23x

    23x
    23x

    10x

     import React from 'react'
    import { DivAttributes } from './types'

    type Ref = React.ForwardedRef<HTMLDivElement>

    type Slots = Record<
      string,
      {
        slotChildren: React.ReactNode | null
        slotProps: DivAttributes
        slotRef: Ref | null
      }
    >

    type ReactComponent =
      | React.FC
      | React.Component
      | React.ForwardRefExoticComponent<HTMLDivElement>

    export const slotify = (
      rawChildren: React.ReactNode,
      slotMap: Record<string, ReactComponent>
    ): Slots => {
      const serializedConfig = Object.entries(slotMap) as [string, ReactComponent][]
      const slots = serializedConfig.reduce((acc, [slotKey]) => {
        acc[slotKey] = {
          slotProps: {},
          slotChildren: null,
          slotRef: null,
        }
        return acc
      }, {} as Slots)

      React.Children.toArray(rawChildren).forEach((child) => {
        const slot = child as React.FunctionComponentElement<any>

        Iif (!slot || !slot.type) {
          return
        }
        const slotConfig = serializedConfig.find(([, type]) => slot.type === type)

        if (!slotConfig) {
          return
        }

        const [slotKey] = slotConfig

        const { children, ...props } = slot.props
        slots[slotKey] = {
          slotChildren: children,
          slotProps: props,
          slotRef: slot.ref as Ref,
        }
      })

      return slots
    }