# All files / src/Tabs Tabs.tsx

97.22% Statements 105/108
88.88% Branches 56/63
90.47% Functions 19/21
96.55% Lines 84/87

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
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    3033x
    3x

    3x
    3x

    3x

    3x
    3x
    3x
    3x
    3x

    3x

    3x
    1880x
    1880x

    1899x
    1898x
    1898x
    1898x
    1898x
    1898x
    1898x
    1898x
    1898x
    1898x
    1898x
    1898x
    1898x

    1898x

    1898x

    1898x

    1898x

    1898x
    588x
    588x

    1898x

    1898x

    3x

    3x

    6x
    6x

    6x

    6x
    4x
    4x
    4x

    6x

    10x
    10x

    3x
    189x
    188x

    188x
    188x

    188x

    188x

    142x

    142x

    1308x

    1308x
    1308x

    142x

    142x

    188x

    188x

    2466x

    188x

    188x
    224x

    188x

    2466x
    2466x

    579x
    579x
    579x
    579x

    579x
    44x
    44x
    44x

    2x

    3x

    3x

    3x

    3x

     import { CaretDown, CaretUp } from '@procore/core-icons/dist'
    import React from 'react'

    import { useButton } from '@react-aria/button'
    import { MenuImperative } from '../MenuImperative/MenuImperative'
    import { MenuRef, Selection } from '../MenuImperative/MenuImperative.types'
    import {
      OverlayTrigger,
      useOverlayTriggerContext,
    } from '../OverlayTrigger/OverlayTrigger'
    import { useI18nContext } from '../_hooks/I18n'
    import { useResize } from '../_hooks/Resize'
    import { addSubcomponents } from '../_utils/addSubcomponents'
    import { getBoundingRect } from '../_utils/dom'
    import { mergeRefs } from '../_utils/mergeRefs'
    import {
      DivAttributes,
      NavAttributes,
      Props,
      SpanAttributes,
    } from '../_utils/types'
    import {
      StyledDropdownTab,
      StyledDropdownTabInner,
      StyledLink,
      StyledOverlay,
      StyledTab,
      StyledTabInner,
      StyledTabList,
      StyledTabs,
    } from './Tabs.styles'
    import {
      BaseTabProps,
      TabDropdownProps,
      TabProps,
      TabRef,
      TabRole,
      TabRoleType,
      TabsProps,
    } from './Tabs.types'

    function noop() {}

    export const Link = React.forwardRef<HTMLSpanElement, SpanAttributes & Props>(
      function Link({ children, ...props }, ref) {
        return (
          <StyledLink ref={ref} {...props}>
            {children}
          </StyledLink>
        )
      }
    )

    /**

     We use tabs to navigate between different, but related content.
     Tabs are commonly used on tool landing pages and on item detail pages.

     @since 10.19.0

     @see [Storybook](https://procore.github.io/core/core-react/latest/?path=/story/demos-tabs--demo)

     @see [Design Guidelines](https://design.procore.com/tabs)

     */

    function TabInternal(
      {
        as,
        disabled,
        role,
        active = false,
        children,
        onBlur,
        onFocus,
        onMount = noop,
        onUnmount = noop,
        overflowing = false,
        dropdown = false,
        variant = '',
        ...props
      }: TabProps<TabRoleType>,
      ref: TabRef<TabRoleType>
    ) {
      const { onPress } = props as TabProps<'button'>

      const { buttonProps } = useButton(
        {
          ...props,
          onBlur: onBlur as (e: React.FocusEvent) => void,
          onFocus: onFocus as (e: React.FocusEvent) => void,
          elementType: role === 'link' ? 'a' : role === 'button' ? 'button' : 'div',
          isDisabled: disabled,
          onPress,
          type: 'button',
        },
        ref as any // TODO fix polymorphic type
      )

      const a11yProps =
        role === 'button'
          ? {
              ...buttonProps,
              'aria-current': active,
              as: as || 'button',
              $clickable: !disabled,
            }
          : role === 'link'
          ? {
              ...buttonProps,
              'aria-current': active,
              as: as || 'a',
              $clickable: !disabled,
            }
          : role === 'tab'
          ? { role: 'tab', onBlur, onFocus }
          : { onBlur, onFocus }

      const innerRef = React.useRef<HTMLDivElement>(null)

      React.useEffect(() => {
        onMount(innerRef.current)
        return onUnmount
      }, [])

      const validChild = React.isValidElement(children)

      return (
        // @ts-ignore
        <StyledTab ref={mergeRefs(ref, innerRef)} {...a11yProps} {...props}>
          <StyledTabInner active={active || variant === 'active'} dark={props.dark}>
            {validChild
              ? React.cloneElement(children as React.ReactElement<any, any>, {
                  'aria-current': active || variant === 'active' ? true : undefined,
                })
              : children}
          </StyledTabInner>
        </StyledTab>
      )
    }

    export const Tab = React.forwardRef(TabInternal) as <Role extends TabRole>(
      props:
        | TabProps<Role>
        | (BaseTabProps & { ref?: React.ComponentPropsWithRef<'div'>['ref'] })
    ) => ReturnType<typeof TabInternal>

    export const MoreMenu = React.forwardRef<
      HTMLDivElement,
      DivAttributes & TabDropdownProps
    >(function MoreMenu({ children, id }, ref) {
      const ctx = useOverlayTriggerContext()

      const menuRef = React.useRef<MenuRef | null>(null)

      React.useEffect(function () {
        menuRef.current?.el?.focus()
        menuRef.current?.highlightFirst()
        menuRef.current?.highlightSelected()
      }, [])

      function onSelect(selection: Selection) {
        ctx.hide(selection.event)
      }

      return (
        <StyledOverlay ref={ref}>
          <MenuImperative id={id} role="menu" ref={menuRef} onSelect={onSelect}>
            <MenuImperative.Options>
              {React.Children.map(children, (child, i) => {
                if (React.isValidElement<BaseTabProps>(child)) {
                  return (
                    <MenuImperative.Item
                      item={null}
                      key={i}
                      selected={child.props.active}
                    >
                      {React.cloneElement(child as any, { ref: null })}
                    </MenuImperative.Item>
                  )
                }
              })}
            </MenuImperative.Options>
          </MenuImperative>
        </StyledOverlay>
      )
    })

    const Tabs_ = React.forwardRef<HTMLDivElement, NavAttributes & TabsProps>(
      function Tabs({ children, className, dark = false, qa, ...props }, ref) {
        const i18n = useI18nContext()

        const [moreMenuIsShown, setMoreMenuIsShown] = React.useState(false)
        const [tabElements, setTabElements] = React.useState<
          (HTMLDivElement | null)[]
        >([])
        const [cutoffIndex, setCutoffIndex] = React.useState(0)

        const containerRef = React.useRef<HTMLDivElement>(null)

        function recalculate() {
          const container = getBoundingRect(containerRef.current!)

          const { subtotals } = tabElements.reduce(
            (acc, el) => {
              Iif (!el) {
                return acc
              }
              const rect = getBoundingRect(el)
              return {
                subtotals: [...acc.subtotals, acc.total + rect.width],
                total: acc.total + rect.width,
              }
            },
            { subtotals: new Array(), total: 0 }
          )

          const index = subtotals.findIndex((val: number) => val >= container.width)

          setCutoffIndex(index)
        }

        useResize({ onResize: recalculate })

        React.useEffect(recalculate)

        const filtered = React.Children.toArray(children).filter((child) => child)

        const overflowing = filtered.slice(cutoffIndex - 1)

        const isOverflowingActive = React.Children.toArray(overflowing).some(
          (child) => React.isValidElement(child) && child.props.active
        )

        return (
          <StyledTabs ref={ref} dark={dark} index={cutoffIndex} {...props}>
            <StyledTabList ref={containerRef}>
              {filtered.map((child, i) => {
                if (React.isValidElement(child))
                  return React.cloneElement(child, {
                    dark,
                    onMount: (el: HTMLDivElement) => {
                      setTabElements((elements) => {
                        const oldElements = [...elements]
                        oldElements[i] = el
                        return oldElements
                      })
                    },
                    onUnmount: () => {
                      setTabElements((elements) => {
                        const oldElements = [...elements]
                        oldElements[i] = null
                        return oldElements
                      })
                    },
                  } as any) // TODO fix type
              })}

              <OverlayTrigger
                autoFocus
                beforeShow={() => setMoreMenuIsShown(true)}
                afterHide={() => setMoreMenuIsShown(false)}
                trigger="click"
                passA11yPropsToOverlay
                placement="bottom-right"
                overlay={<MoreMenu>{overflowing}</MoreMenu>}
                ref={ref}
                role="menu"
              >
                <StyledDropdownTab aria-hidden={!overflowing.length} as="button">
                  <StyledDropdownTabInner active={isOverflowingActive} dark={dark}>
                    <StyledLink data-qa={qa?.more}>
                      {i18n.t('core.tabs.more')}
                    </StyledLink>
                    {moreMenuIsShown ? (
                      <CaretUp size="sm" />
                    ) : (
                      <CaretDown size="sm" />
                    )}
                  </StyledDropdownTabInner>
                </StyledDropdownTab>
              </OverlayTrigger>
            </StyledTabList>
          </StyledTabs>
        )
      }
    )

    Tabs_.displayName = 'Tabs'

    Link.displayName = 'Tabs.Link'

    // @ts-ignore
    Tab.displayName = 'Tabs.Tab'

    export const Tabs = addSubcomponents(
      {
        Link,
        Tab,
      },
      Tabs_
    )