File size: 10,290 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import { useDevOverlayContext } from '../../dev-overlay.browser'
import { useClickOutsideAndEscape } from '../components/errors/dev-tools-indicator/utils'
import {
  useLayoutEffect,
  useRef,
  createContext,
  useContext,
  type CSSProperties,
  type Dispatch,
  type SetStateAction,
} from 'react'
import { getIndicatorOffset } from '../utils/indicator-metrics'
import { INDICATOR_PADDING } from '../components/devtools-indicator/devtools-indicator'
import { usePanelRouterContext } from './context'
import { usePanelContext } from './panel-router'

interface C {
  closeMenu?: () => void
  selectedIndex: number
  setSelectedIndex: Dispatch<SetStateAction<number>>
}

export const MenuContext = createContext({} as C)

export function MenuItem({
  index,
  label,
  value,
  onClick,
  href,
  ...props
}: {
  index?: number
  title?: string
  label: string
  value: React.ReactNode
  href?: string
  onClick?: () => void
}) {
  const isInteractive =
    typeof onClick === 'function' || typeof href === 'string'
  const { closeMenu, selectedIndex, setSelectedIndex } = useContext(MenuContext)
  const selected = selectedIndex === index

  function click() {
    if (isInteractive) {
      onClick?.()
      closeMenu?.()
      if (href) {
        window.open(href, '_blank', 'noopener, noreferrer')
      }
    }
  }

  return (
    <div
      className="dev-tools-indicator-item"
      data-index={index}
      data-selected={selected}
      onClick={click}
      // Needs `onMouseMove` instead of enter to work together
      // with keyboard and mouse input
      onMouseMove={() => {
        if (isInteractive && index !== undefined && selectedIndex !== index) {
          setSelectedIndex(index)
        }
      }}
      onMouseLeave={() => setSelectedIndex(-1)}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          click()
        }
      }}
      role={isInteractive ? 'menuitem' : undefined}
      tabIndex={selected ? 0 : -1}
      {...props}
    >
      <span className="dev-tools-indicator-label">{label}</span>
      <span className="dev-tools-indicator-value">{value}</span>
    </div>
  )
}

export const DevtoolMenu = ({
  closeOnClickOutside = true,
  items,
}: {
  closeOnClickOutside?: boolean
  items: Array<
    | false
    | undefined
    | null
    | {
        onClick?: () => void
        title?: string
        label: string
        value: React.ReactNode
        attributes?: Record<string, string | boolean>
        footer?: boolean
      }
  >
}) => {
  const { state } = useDevOverlayContext()
  const { setPanel, triggerRef, setSelectedIndex, selectedIndex } =
    usePanelRouterContext()
  const { mounted } = usePanelContext()

  const [vertical, horizontal] = state.devToolsPosition.split('-', 2)

  const menuRef = useRef<HTMLDivElement>(null)

  useClickOutsideAndEscape(
    menuRef,
    triggerRef,
    closeOnClickOutside && mounted,
    (reason) => {
      switch (reason) {
        case 'escape': {
          setPanel(null)
          setSelectedIndex(-1)
          return
        }
        case 'outside': {
          if (!closeOnClickOutside) {
            return
          }
          setPanel(null)
          setSelectedIndex(-1)
          return
        }
        default: {
          return null!
        }
      }
    }
  )
  useLayoutEffect(() => {
    menuRef.current?.focus() // allows keydown to be captured
    selectMenuItem({
      index: selectedIndex === -1 ? 'first' : selectedIndex,
      menuRef,
      setSelectedIndex,
    })
    // eslint-disable-next-line react-hooks/react-compiler
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const indicatorOffset = getIndicatorOffset(state)

  const [indicatorVertical, indicatorHorizontal] = state.devToolsPosition.split(
    '-',
    2
  )

  const verticalOffset =
    vertical === indicatorVertical && horizontal === indicatorHorizontal
      ? indicatorOffset
      : INDICATOR_PADDING

  const positionStyle = {
    [vertical]: `${verticalOffset}px`,
    [horizontal]: `${INDICATOR_PADDING}px`,
    [vertical === 'top' ? 'bottom' : 'top']: 'auto',
    [horizontal === 'left' ? 'right' : 'left']: 'auto',
  } as CSSProperties
  const definedItems = items.filter((item) => !!item)
  const itemsAboveFooter = definedItems.filter((item) => !item.footer)
  const itemsBelowFooter = definedItems.filter((item) => item.footer)

  function onMenuKeydown(e: React.KeyboardEvent<HTMLDivElement | null>) {
    e.preventDefault()

    const clickableItems = definedItems.filter((item) => item.onClick)
    const totalClickableItems = clickableItems.length

    switch (e.key) {
      case 'ArrowDown':
        const next =
          selectedIndex >= totalClickableItems - 1 ? 0 : selectedIndex + 1
        selectMenuItem({ index: next, menuRef, setSelectedIndex })
        break
      case 'ArrowUp':
        const prev =
          selectedIndex <= 0 ? totalClickableItems - 1 : selectedIndex - 1
        selectMenuItem({ index: prev, menuRef, setSelectedIndex })
        break
      case 'Home':
        selectMenuItem({ index: 'first', menuRef, setSelectedIndex })
        break
      case 'End':
        selectMenuItem({ index: 'last', menuRef, setSelectedIndex })
        break
      case 'n':
        if (e.ctrlKey) {
          const nextCtrl =
            selectedIndex >= totalClickableItems - 1 ? 0 : selectedIndex + 1
          selectMenuItem({ index: nextCtrl, menuRef, setSelectedIndex })
        }
        break
      case 'p':
        if (e.ctrlKey) {
          const prevCtrl =
            selectedIndex <= 0 ? totalClickableItems - 1 : selectedIndex - 1
          selectMenuItem({ index: prevCtrl, menuRef, setSelectedIndex })
        }
        break
      default:
        break
    }
  }

  return (
    <div
      ref={menuRef}
      onKeyDown={onMenuKeydown}
      id="nextjs-dev-tools-menu"
      role="menu"
      dir="ltr"
      aria-orientation="vertical"
      aria-label="Next.js Dev Tools Items"
      tabIndex={-1}
      style={{
        outline: 0,
        WebkitFontSmoothing: 'antialiased',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'flex-start',
        background: 'var(--color-background-100)',

        backgroundClip: 'padding-box',
        boxShadow: 'var(--shadow-menu)',
        borderRadius: 'var(--rounded-xl)',
        position: 'fixed',
        fontFamily: 'var(--font-stack-sans)',
        zIndex: 'var(--top-z-index)',
        overflow: 'hidden',
        opacity: 1,
        minWidth: '248px',
        transition:
          'opacity var(--animate-out-duration-ms) var(--animate-out-timing-function)',
        border: '1px solid var(--color-gray-alpha-400)',
        ...positionStyle,
      }}
    >
      <MenuContext
        value={{
          selectedIndex,
          setSelectedIndex,
        }}
      >
        <div style={{ padding: '6px', width: '100%' }}>
          {itemsAboveFooter.map((item, index) => (
            <MenuItem
              key={item.label}
              title={item.title}
              label={item.label}
              value={item.value}
              onClick={item.onClick}
              index={
                item.onClick
                  ? getAdjustedIndex(itemsAboveFooter, index)
                  : undefined
              }
              {...item.attributes}
            />
          ))}
        </div>
        <div className="dev-tools-indicator-footer">
          {itemsBelowFooter.map((item, index) => (
            <MenuItem
              key={item.label}
              title={item.title}
              label={item.label}
              value={item.value}
              onClick={item.onClick}
              {...item.attributes}
              index={
                item.onClick
                  ? getAdjustedIndex(itemsBelowFooter, index) +
                    getClickableItemsCount(itemsAboveFooter)
                  : undefined
              }
            />
          ))}
        </div>
      </MenuContext>
    </div>
  )
}

export function getAdjustedIndex(
  items: Array<{ onClick?: () => void }>,
  targetIndex: number
): number {
  let adjustedIndex = 0

  for (let i = 0; i <= targetIndex && i < items.length; i++) {
    if (items[i].onClick) {
      if (i === targetIndex) {
        return adjustedIndex
      }
      adjustedIndex++
    }
  }

  return adjustedIndex
}

export function getClickableItemsCount(
  items: Array<{ onClick?: () => void }>
): number {
  return items.filter((item) => item.onClick).length
}

export function IssueCount({ children }: { children: number }) {
  return (
    <span
      className="dev-tools-indicator-issue-count"
      data-has-issues={children > 0}
    >
      <span className="dev-tools-indicator-issue-count-indicator" />
      {children}
    </span>
  )
}

export function ChevronRight() {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="none"
    >
      <path
        fill="#666"
        fillRule="evenodd"
        clipRule="evenodd"
        d="M5.50011 1.93945L6.03044 2.46978L10.8537 7.293C11.2442 7.68353 11.2442 8.31669 10.8537 8.70722L6.03044 13.5304L5.50011 14.0608L4.43945 13.0001L4.96978 12.4698L9.43945 8.00011L4.96978 3.53044L4.43945 3.00011L5.50011 1.93945Z"
      />
    </svg>
  )
}

export function selectMenuItem({
  index,
  menuRef,
  setSelectedIndex,
}: {
  index: number | 'first' | 'last'
  menuRef: React.RefObject<HTMLDivElement | null>
  setSelectedIndex: (index: number) => void
}) {
  if (index === 'first') {
    setTimeout(() => {
      const all = menuRef.current?.querySelectorAll('[role="menuitem"]')
      if (all) {
        const firstIndex = all[0].getAttribute('data-index')
        selectMenuItem({ index: Number(firstIndex), menuRef, setSelectedIndex })
      }
    })
    return
  }

  if (index === 'last') {
    setTimeout(() => {
      const all = menuRef.current?.querySelectorAll('[role="menuitem"]')
      if (all) {
        const lastIndex = all.length - 1
        selectMenuItem({ index: lastIndex, menuRef, setSelectedIndex })
      }
    })
    return
  }

  const el = menuRef.current?.querySelector(
    `[data-index="${index}"]`
  ) as HTMLElement

  if (el) {
    setSelectedIndex(index)
    el?.focus()
  }
}