# All files / src/MenuImperative sensors.ts

83.45% Statements 111/133
67.88% Branches 186/274
96.15% Functions 25/26
83.96% Lines 110/131

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
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321

    36x

    36x
    36x

    36x
    36x

    36x

    99x

    36x
    29x

    71x

    71x
    9x

    62x

    10x

    8x

    8x

    2x

    2x

    2x

    2x

    19x

    17x

    17x

    2x
    1x

    1x
    1x

    8x
    8x

    8x

    8x

    194x
    194x

    36x

    66x
    66x
    66x
    66x

    2x
    2x
    2x

    2x
    2x
    2x

    2x

    2x

    145x

    130x
    25x

    105x
    97x

    97x

    97x
    97x

    97x

    97x
    82x

    8x

    10x
    10x
    10x
    10x
    4x

    6x

    10x

    10x
    10x
    10x
    1x

    9x

    142x
    71x

    14x
    8x

    12x
    6x
    6x
    6x

    6x

    20x
    9x
    9x
    9x

    11x

    66x

    43x
    43x
    12x
    12x
    31x
    20x
    20x
    11x
    2x
    2x

    2x

    2x

    9x

    26x

    191x

    200x

    69x

    191x
    191x

    14x
    7x

    7x

    6x
    3x

    3x

     import React from 'react'
    import { SensorAPI, SnapDragActions } from 'react-beautiful-dnd'
    import { scrollIntoView } from '../_utils/scrollIntoView'
    import { Selection } from './MenuImperative.types'

    function noop() {}

    const MOUSE_ENTER = 'mouseenter'
    const MOUSE_LEAVE = 'mouseleave'

    const menuItemsWrapperAttributeName = 'data-core-menuimperative-items-wrapper'
    export const menuItemsWrapperAttribute = {
      [menuItemsWrapperAttributeName]: 'true',
    }

    const isItem = (element: Element | null) => element?.hasAttribute('data-value')

    function isGroup(el: HTMLElement) {
      return JSON.parse(el.dataset.group || 'false')
    }

    const isWrapper = (element: Element | null) =>
      element?.getAttribute(menuItemsWrapperAttributeName) === 'true'

    function getFirstItem(menu: Element | null) {
      const firstItem = menu?.querySelector<HTMLElement>('[data-value]:first-child')

      if (firstItem && isGroup(firstItem)) {
        return getNextItem(firstItem)
      }

      return firstItem
    }

    function getPrevItem(item: Element): HTMLElement | null {
      if (item.previousElementSibling) {
        // LocationFilter in data-table has div-wrapper around some items
        Iif (isWrapper(item.previousElementSibling)) {
          return getLastItem(item.previousElementSibling) as HTMLElement
        }

        return item.previousElementSibling as HTMLElement
      }

      Iif (isWrapper(item?.parentElement)) {
        return item?.parentElement?.previousElementSibling as HTMLElement
      }

      if (item?.parentElement?.getAttribute('data-droppable') === 'true') {
        const prevDroppableItems =
          item?.parentElement?.previousElementSibling?.querySelectorAll<HTMLElement>(
            '[data-group="false"]'
          )
        return prevDroppableItems?.length
          ? prevDroppableItems[prevDroppableItems.length - 1]
          : null
      }

      return null
    }

    function getNextItem(item: Element): HTMLElement | null {
      if (item.nextElementSibling) {
        // LocationFilter in data-table has div-wrapper around some items
        Iif (isWrapper(item.nextElementSibling)) {
          return getFirstItem(item.previousElementSibling) as HTMLElement
        }
        return item.nextElementSibling as HTMLElement
      }

      if (isWrapper(item?.parentElement)) {
        return item?.parentElement?.nextElementSibling as HTMLElement
      }

      if (item?.parentElement?.getAttribute('data-droppable') === 'true') {
        return item?.parentElement?.nextElementSibling?.querySelector(
          '[data-group="false"]'
        ) as HTMLElement
      }

      return null
    }

    function getLastItem(menu: Element | null) {
      const items = menu?.querySelectorAll<HTMLElement>('[data-value]')
      const lastItem = items?.[items.length - 1]

      Iif (lastItem && isGroup(lastItem)) {
        return getPrevItem(lastItem)
      }

      return lastItem
    }

    function updateHighlightedAttribute(
      item: Element | null | undefined,
      highlight: boolean
    ) {
      item?.setAttribute('data-highlighted', highlight ? 'true' : 'false')
      item?.dispatchEvent(new MouseEvent(highlight ? MOUSE_ENTER : MOUSE_LEAVE))
    }

    export function createSensors(
      ref: React.RefObject<HTMLDivElement>,
      circular: boolean,
      onChangeActiveDescendant: (
        id: string | undefined,
        menuRef: Element | null
      ) => void
    ) {
      let highlightedItem: HTMLElement | null = null
      let dragAndDropApi: SensorAPI | null = null
      let currentDrag: SnapDragActions | null = null
      let onSelect: (selection: Selection) => any = noop

      function select(
        event:
          | React.MouseEvent<HTMLElement, MouseEvent>
          | React.KeyboardEvent<HTMLElement>
      ) {
        if (ref.current && highlightedItem) {
          const disabled = JSON.parse(highlightedItem?.dataset.disabled || 'false')
          Iif (disabled) return

          const item = JSON.parse(highlightedItem?.dataset.value || 'null')
          const selected = JSON.parse(highlightedItem?.dataset.selected || 'false')
          const restoreFocus = highlightedItem?.dataset.restorefocus
            ? JSON.parse(highlightedItem?.dataset.restorefocus)
            : undefined

          Iif (highlightedItem.tagName === 'A') {
            highlightedItem.click()
          }

          onSelect?.({
            event,
            item,
            group: false,
            action: selected ? 'unselected' : 'selected',
            ...(restoreFocus === undefined ? {} : { restoreFocus }),
          })
        }
      }

      function highlightItem(
        item: HTMLElement | null | undefined,
        shouldScroll: boolean = true
      ) {
        // performance improvement, highlightItem is called onMouseMove for Item
        if (item === highlightedItem) {
          return
        }

        if (item) {
          updateHighlightedAttribute(highlightedItem, false)

          // TODO add localized screenreader instructions for the item
          updateHighlightedAttribute(item, true)

          const id = item.getAttribute('id') ?? undefined
          onChangeActiveDescendant(id, ref.current)

          highlightedItem = item

          if (shouldScroll) {
            scrollIntoView(-1, item)
          }
        } else {
          onChangeActiveDescendant('', ref.current)
        }
      }

      function getPrevHighlightableItem(
        currentItem: HTMLElement
      ): HTMLElement | null | undefined {
        const prev = getPrevItem(currentItem)
        if (prev) {
          if (isItem(prev)) {
            if (isGroup(prev)) {
              return getPrevHighlightableItem(prev)
            } else {
              return prev
            }
          }
        } else IEif (circular) {
          return getLastItem(ref.current)
        }

        return prev
      }

      function getNextHighlightableItem(
        currentItem: HTMLElement
      ): HTMLElement | null | undefined {
        const next = getNextItem(currentItem)

        if (next) {
          if (isItem(next)) {
            if (isGroup(next)) {
              return getNextHighlightableItem(next)
            }
            return next
          }
        } else IEif (circular) {
          return getFirstItem(ref.current)
        }
      }

      function highlightFirstItem(shouldScroll: boolean = true) {
        highlightItem(getFirstItem(ref.current), shouldScroll)
      }

      function highlightLastItem(shouldScroll: boolean = true) {
        highlightItem(getLastItem(ref.current), shouldScroll)
      }

      function highlightPrevItem() {
        if (highlightedItem && ref.current?.contains(highlightedItem)) {
          const prev = getPrevHighlightableItem(highlightedItem)
          if (prev) {
            highlightItem(prev)
          }
        } else {
          highlightLastItem()
        }
      }

      function highlightNextItem() {
        if (highlightedItem && ref.current?.contains(highlightedItem)) {
          const next = getNextHighlightableItem(highlightedItem)
          if (next) {
            highlightItem(next)
          }
        } else {
          highlightFirstItem()
        }
      }

      return {
        handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
          if (ref.current) {
            if (event.key === 'ArrowUp' || event.key === 'Up') {
              event.preventDefault()
              currentDrag?.isActive() ? currentDrag.moveUp() : highlightPrevItem()
            } else if (event.key === 'ArrowDown' || event.key === 'Down') {
              event.preventDefault()
              currentDrag?.isActive() ? currentDrag.moveDown() : highlightNextItem()
            } else if (event.key === 'Enter') {
              event.preventDefault()
              Iif (event.ctrlKey || event.metaKey) {
                const draggableId = highlightedItem?.getAttribute(
                  'data-rbd-draggable-id'
                )
                Iif (draggableId) {
                  const preDrag = dragAndDropApi?.tryGetLock(draggableId)
                  Iif (preDrag) {
                    currentDrag = preDrag.snapLift()
                  }
                }
              } else Iif (currentDrag?.isActive()) {
                currentDrag.drop()
              } else {
                select(event)
              }
            } else Iif (event.key === 'Escape' && currentDrag?.isActive()) {
              currentDrag.cancel()
            }
          }
        },
        handleItemHover(el?: HTMLDivElement) {
          highlightItem(el, false)
        },
        useKeyboardSensor(api: SensorAPI) {
          dragAndDropApi = api
        },

        updateSelectCallback(callback: (selection: Selection) => any) {
          onSelect = callback
        },

        highlight: highlightItem,

        highlighted() {
          return JSON.parse(highlightedItem?.dataset.value || 'null')
        },

        highlightFirst: highlightFirstItem,
        highlightLast: highlightLastItem,
        rehighlightCurrent() {
          // Rehighlights an item that may have lost its styling due to the re-render of the list items
          const draggableId = highlightedItem?.getAttribute('data-rbd-draggable-id')
          Iif (draggableId) {
            const newItem = ref.current?.querySelector<HTMLElement>(
              `[data-rbd-draggable-id="${draggableId.replace(/"/g, '\\"')}"]`
            )
            highlightItem(newItem)
          }
        },

        highlightSelected(shouldScroll: boolean = true) {
          const selectedItem = ref.current?.querySelector<HTMLElement>(
            '[data-selected="true"]'
          )

          highlightItem(selectedItem, shouldScroll)
        },

        highlightSuggested(shouldScroll: boolean = true) {
          const suggestedItem = ref.current?.querySelector<HTMLElement>(
            '[data-suggested="true"]'
          )

          highlightItem(suggestedItem, shouldScroll)
        },

        prev: highlightPrevItem,
        next: highlightNextItem,
        select,
      }
    }