Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(lemon-ui): restore arrow navigation for portal menus (#107943)

Javier Bahamondes5e39a1e12b4f
diff --git a/.claude/commands/conventions.md b/.claude/commands/conventions.md
index c1e7b8c21953..b80ca3325973 100644
--- a/.claude/commands/conventions.md
+++ b/.claude/commands/conventions.md
@@ -52,6 +52,7 @@ Hence the explicit separation between the data and view layers.
- Before building new UI, read a few comparable scenes or components and model yours on the ones that follow these conventions. The codebase contains legacy that predates them — an existing violation is not license to repeat it. Conventions outrank precedent, and compliant precedent outranks invention.
- Extract a shared component once the same shape appears in several places and the call sites read as content, not markup. Keep new generics next to the feature that uses them, and promote to `lib/` only when a second feature needs them. Don't build wrappers with a single consumer, and don't add boolean variant props so one caller can switch half the component off — that's two components.
- Interactive elements are real `<button>`/`<a>` elements (`LemonButton` renders one) — never `onClick` on a `<div>`.
+ - With `focusBasedKeyboardNavigation` enabled, `LemonMenu` moves focus between its trigger and menu items with the arrow keys, including after the menu reopens. Custom triggers must forward `onFocus` and `onKeyDown` to preserve keyboard navigation and focus return.
- Loading, empty, and error are three different screens. Never show an empty state from data that hasn't resolved yet — branch on the loading state first.
- When renaming a feature, sweep code symbols completely — but analytics-facing strings (event names, property names and values, `data-attr` values) and persisted keys are a frozen API: leave them as-is, with a comment noting they're pinned.
- Scenes
diff --git a/docs/published/handbook/engineering/conventions/frontend-coding.md b/docs/published/handbook/engineering/conventions/frontend-coding.md
index f33cb23ccb08..2a41a24c5af5 100644
--- a/docs/published/handbook/engineering/conventions/frontend-coding.md
+++ b/docs/published/handbook/engineering/conventions/frontend-coding.md
@@ -41,6 +41,7 @@ Hence the explicit separation between the data and view layers.
- Before building new UI, read a few comparable scenes or components and model yours on the ones that follow these conventions. The codebase contains legacy that predates them — an existing violation is not license to repeat it. Conventions outrank precedent, and compliant precedent outranks invention.
- Extract a shared component once the same shape appears in several places and the call sites read as content, not markup. Keep new generics next to the feature that uses them, and promote to `lib/` only when a second feature needs them. Don't build wrappers with a single consumer, and don't add boolean variant props so one caller can switch half the component off — that's two components.
- Interactive elements are real `<button>`/`<a>` elements (`LemonButton` renders one) — never `onClick` on a `<div>`.
+ - With `focusBasedKeyboardNavigation` enabled, `LemonMenu` moves focus between its trigger and menu items with the arrow keys, including after the menu reopens. Custom triggers must forward `onFocus` and `onKeyDown` to preserve keyboard navigation and focus return.
- Loading, empty, and error are three different screens. Never show an empty state from data that hasn't resolved yet — branch on the loading state first.
- In `createSetupDetectionLogic`, return `null` when a setup check cannot answer. Like a thrown error, it preserves an existing setup status or shows the product scene if no answer exists yet. Return `unknown` when the scene itself should handle the result, such as showing an access-denied screen. Successful checks can still advance setup when data arrives.
- When renaming a feature, sweep code symbols completely — but analytics-facing strings (event names, property names and values, `data-attr` values) and persisted keys are a frozen API: leave them as-is, with a comment noting they're pinned.
diff --git a/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.test.tsx b/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.test.tsx
index 3b5089d569e6..aea402afe652 100644
--- a/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.test.tsx
@@ -2,7 +2,9 @@ import '@testing-library/jest-dom'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { useRef } from 'react'
+import { ButtonHTMLAttributes, forwardRef, useRef, useState } from 'react'
+
+import { FloatingContainerContext } from 'lib/hooks/useFloatingContainerContext'
import { LemonButton } from '../LemonButton'
import { LemonMenu } from './LemonMenu'
@@ -66,7 +68,7 @@ describe('LemonMenu', () => {
label: 'Change view',
closeOnClickInside: false,
closeParentPopoverOnClickInside: false,
- items: [{ label: 'Summary', onClick: onSelect }],
+ items: [{ label: 'Summary', onClick: onSelect }, { label: 'Details' }],
},
]}
>
@@ -78,7 +80,14 @@ describe('LemonMenu', () => {
await userEvent.click(screen.getByText('More actions'))
await userEvent.click(await screen.findByText('Change view'))
- await userEvent.click(await screen.findByText('Summary'))
+ const summary = (await screen.findByText('Summary')).closest('button')!
+ await userEvent.keyboard('{ArrowDown}')
+ expect(summary).toHaveFocus()
+ await userEvent.keyboard('{ArrowDown}')
+ expect(screen.getByText('Details').closest('button')).toHaveFocus()
+ await userEvent.keyboard('{ArrowUp}')
+ expect(summary).toHaveFocus()
+ await userEvent.click(summary)
expect(onSelect).toHaveBeenCalledTimes(1)
expect(screen.getByText('Change view')).toBeInTheDocument()
@@ -91,4 +100,157 @@ describe('LemonMenu', () => {
expect(screen.queryByText('Summary')).not.toBeInTheDocument()
})
})
+
+ it('moves focus past a closed submenu trigger to the next item', async () => {
+ render(
+ <LemonMenu items={[{ label: 'Change view', items: [{ label: 'Summary' }] }, { label: 'Export' }]}>
+ <LemonButton>More actions</LemonButton>
+ </LemonMenu>
+ )
+
+ await userEvent.click(screen.getByText('More actions'))
+ const changeView = (await screen.findByText('Change view')).closest('button')!
+ await userEvent.keyboard('{ArrowDown}')
+ expect(changeView).toHaveFocus()
+ await userEvent.keyboard('{ArrowDown}')
+ expect(screen.getByText('Export').closest('button')).toHaveFocus()
+ expect(screen.queryByText('Summary')).not.toBeInTheDocument()
+ })
+
+ it('starts arrow navigation from a clicked item', async () => {
+ render(
+ <LemonMenu
+ items={[{ items: [{ label: 'First' }, { label: 'Second' }, false] }, { items: [{ label: 'Third' }] }]}
+ closeOnClickInside={false}
+ >
+ <LemonButton>Open</LemonButton>
+ </LemonMenu>
+ )
+
+ await userEvent.click(screen.getByText('Open'))
+ const second = (await screen.findByText('Second')).closest('button')!
+ await userEvent.click(second)
+ await userEvent.keyboard('{ArrowDown}')
+ expect(screen.getByText('Third').closest('button')).toHaveFocus()
+ await userEvent.keyboard('{ArrowUp}')
+ expect(second).toHaveFocus()
+ })
+
+ it('accepts arrow keys from a button inside a wrapper trigger', async () => {
+ const WrappedButton = forwardRef<HTMLDivElement, ButtonHTMLAttributes<HTMLButtonElement>>(
+ function WrappedButton(props, ref) {
+ return (
+ <div ref={ref}>
+ <button type="button" disabled>
+ Unavailable
+ </button>
+ <button type="button" {...props} />
+ </div>
+ )
+ }
+ )
+ render(
+ <LemonMenu items={[{ label: 'First' }, { label: 'Second' }]}>
+ <WrappedButton>Open</WrappedButton>
+ </LemonMenu>
+ )
+
+ const trigger = screen.getByText('Open')
+ await userEvent.click(trigger)
+ const first = (await screen.findByText('First')).closest('button')
+ await userEvent.keyboard('{ArrowDown}')
+ expect(first).toHaveFocus()
+ await userEvent.keyboard('{ArrowUp}')
+ expect(trigger).toHaveFocus()
+ })
+
+ it('navigates to items added after the menu opens', async () => {
+ const { rerender } = render(
+ <LemonMenu items={[{ label: 'First' }]}>
+ <LemonButton>Open</LemonButton>
+ </LemonMenu>
+ )
+
+ await userEvent.click(screen.getByText('Open'))
+ await screen.findByText('First')
+ rerender(
+ <LemonMenu items={[{ label: 'First' }, { label: 'Second' }]}>
+ <LemonButton>Open</LemonButton>
+ </LemonMenu>
+ )
+ await userEvent.keyboard('{ArrowDown}{ArrowDown}')
+ expect(screen.getByText('Second').closest('button')).toHaveFocus()
+ })
+
+ it('navigates portal items inside a shadow root', async () => {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const shadowRoot = host.attachShadow({ mode: 'open' })
+ const container = shadowRoot.appendChild(document.createElement('div'))
+
+ function ShadowMenu(): JSX.Element {
+ const [floatingContainer, setFloatingContainer] = useState<HTMLDivElement | null>(null)
+ return (
+ <FloatingContainerContext.Provider value={floatingContainer}>
+ <LemonMenu items={[{ label: 'First' }, { label: 'Second' }]}>
+ <LemonButton>Open</LemonButton>
+ </LemonMenu>
+ <div ref={setFloatingContainer} />
+ </FloatingContainerContext.Provider>
+ )
+ }
+ const { getByText, findByText } = render(<ShadowMenu />, { container })
+
+ await userEvent.click(getByText('Open'))
+ const first = (await findByText('First')).closest('button')
+ await userEvent.keyboard('{ArrowDown}')
+ expect(shadowRoot.activeElement).toBe(first)
+ await userEvent.keyboard('{ArrowDown}')
+ expect(shadowRoot.activeElement).toBe(getByText('Second').closest('button'))
+ host.remove()
+ })
+
+ it.each([false, true])('navigates and reopens with startVisible=%s', async (startVisible) => {
+ render(
+ <div>
+ <LemonMenu
+ startVisible={startVisible}
+ items={[
+ { title: <div>Available sources</div>, items: [] },
+ { label: 'First' },
+ { label: 'Second' },
+ ]}
+ >
+ <LemonButton>Open</LemonButton>
+ </LemonMenu>
+ <button type="button">Outside</button>
+ </div>
+ )
+
+ const trigger = screen.getByText('Open').closest('button')!
+ for (let opening = 0; opening < 2; opening++) {
+ if (!startVisible || opening > 0) {
+ await userEvent.click(trigger)
+ }
+ const first = (await screen.findByText('First')).closest('button')!
+ if (startVisible && opening === 0) {
+ first.focus()
+ await userEvent.keyboard('{ArrowUp}')
+ expect(trigger).toHaveFocus()
+ }
+ const second = screen.getByText('Second').closest('button')!
+ await userEvent.keyboard('{ArrowDown}')
+ expect(first).toHaveFocus()
+ await userEvent.keyboard('{ArrowDown}')
+ expect(second).toHaveFocus()
+ await userEvent.keyboard('{ArrowUp}')
+ expect(first).toHaveFocus()
+ await userEvent.keyboard('{ArrowUp}')
+ expect(trigger).toHaveFocus()
+ await userEvent.keyboard('{ArrowDown}{ArrowDown}')
+ expect(second).toHaveFocus()
+ await userEvent.click(screen.getByText('Outside'))
+ await waitFor(() => expect(screen.queryByText('First')).not.toBeInTheDocument())
+ }
+ })
})
diff --git a/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.tsx b/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.tsx
index 0962cc09158d..d8cbc1f6c9db 100644
--- a/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.tsx
+++ b/frontend/src/lib/lemon-ui/LemonMenu/LemonMenu.tsx
@@ -108,7 +108,7 @@ export interface LemonMenuProps
| 'trigger'
>,
LemonMenuOverlayProps {
- /** Must support `ref` and `onKeyDown` for keyboard navigation. */
+ /** Must support `ref`, `onFocus`, and `onKeyDown` for keyboard navigation. */
children: React.ReactElement
/** Index of the active (e.g. selected) item, if there is a specific one. */
activeItemIndex?: number
@@ -133,11 +133,12 @@ export const LemonMenu = React.forwardRef<HTMLElement, LemonMenuProps>(function
},
ref
): JSX.Element {
- const { referenceRef, itemsRef } = useKeyboardNavigation<HTMLElement, HTMLButtonElement>(
- items.flatMap((item) => (item && isLemonMenuSection(item) ? item.items : item)).length,
- activeItemIndex,
- { enabled: focusBasedKeyboardNavigation }
- )
+ const { referenceRef, itemsRef, onTriggerFocus, onTriggerKeyDown, onItemsKeyDown } =
+ useKeyboardNavigation<HTMLButtonElement>(
+ items.flatMap((item) => (item && isLemonMenuSection(item) ? item.items : item)).length,
+ activeItemIndex,
+ { enabled: focusBasedKeyboardNavigation }
+ )
const _onVisibilityChange = useCallback(
(visible: boolean) => {
@@ -165,6 +166,7 @@ export const LemonMenu = React.forwardRef<HTMLElement, LemonMenuProps>(function
items={items}
tooltipPlacement={tooltipPlacement}
itemsRef={itemsRef}
+ onKeyDown={onItemsKeyDown}
/>
}
closeOnClickInside
@@ -172,7 +174,17 @@ export const LemonMenu = React.forwardRef<HTMLElement, LemonMenuProps>(function
onVisibilityChange={_onVisibilityChange}
{...dropdownProps}
>
- {cloneElement(children, { ref: triggerRef })}
+ {cloneElement(children, {
+ ref: triggerRef,
+ onFocus: (e: React.FocusEvent<HTMLElement>) => {
+ children.props.onFocus?.(e)
+ onTriggerFocus(e)
+ },
+ onKeyDown: (e: React.KeyboardEvent<HTMLElement>) => {
+ children.props.onKeyDown?.(e)
+ onTriggerKeyDown(e)
+ },
+ })}
</LemonDropdown>
)
})
@@ -182,6 +194,7 @@ export interface LemonMenuOverlayProps {
items: LemonMenuItems
tooltipPlacement?: TooltipProps['placement']
itemsRef?: React.RefObject<React.RefObject<HTMLButtonElement>[]>
+ onKeyDown?: React.KeyboardEventHandler<HTMLElement>
/** @default 'small' */
buttonSize?: 'xsmall' | 'small' | 'medium'
}
@@ -191,6 +204,7 @@ export function LemonMenuOverlay({
tooltipPlacement = 'right',
itemsRef,
buttonSize = 'small',
+ onKeyDown,
}: LemonMenuOverlayProps): JSX.Element {
const sectionsOrItems = useMemo(() => normalizeItems(items), [items])
@@ -200,6 +214,7 @@ export function LemonMenuOverlay({
buttonSize={buttonSize}
tooltipPlacement={tooltipPlacement}
itemsRef={itemsRef}
+ onKeyDown={onKeyDown}
/>
) : (
<LemonMenuItemList
@@ -207,6 +222,7 @@ export function LemonMenuOverlay({
buttonSize={buttonSize}
tooltipPlacement={tooltipPlacement}
itemsRef={itemsRef}
+ onKeyDown={onKeyDown}
itemIndexOffset={0}
/>
)
@@ -217,6 +233,7 @@ interface LemonMenuSectionListProps {
buttonSize: 'xsmall' | 'small' | 'medium'
tooltipPlacement: TooltipProps['placement'] | undefined
itemsRef: React.RefObject<React.RefObject<HTMLButtonElement>[]> | undefined
+ onKeyDown?: React.KeyboardEventHandler<HTMLElement>
}
export function LemonMenuSectionList({
@@ -224,11 +241,12 @@ export function LemonMenuSectionList({
buttonSize,
tooltipPlacement,
itemsRef,
+ onKeyDown,
}: LemonMenuSectionListProps): JSX.Element {
let rollingItemIndex = 0
return (
- <ul>
+ <ul onKeyDown={onKeyDown}>
{sections.map((section, i) => {
const sectionElement = (
<li key={section.key || i}>
@@ -267,6 +285,7 @@ interface LemonMenuItemListProps {
tooltipPlacement?: TooltipProps['placement'] | undefined
itemsRef?: React.RefObject<React.RefObject<HTMLButtonElement>[]> | undefined
itemIndexOffset?: number
+ onKeyDown?: React.KeyboardEventHandler<HTMLElement>
}
export function LemonMenuItemList({
@@ -275,9 +294,10 @@ export function LemonMenuItemList({
itemIndexOffset = 0,
tooltipPlacement = 'right',
itemsRef,
+ onKeyDown,
}: LemonMenuItemListProps): JSX.Element {
return (
- <ul className="deprecated-space-y-px">
+ <ul className="deprecated-space-y-px" onKeyDown={onKeyDown}>
{items.map((item, itemIndex) => (
<li key={item.key || itemIndex}>
<LemonMenuItemButton
diff --git a/frontend/src/lib/lemon-ui/LemonMenu/useKeyboardNavigation.ts b/frontend/src/lib/lemon-ui/LemonMenu/useKeyboardNavigation.ts
index 7890a01a6974..cb429610ddfc 100644
--- a/frontend/src/lib/lemon-ui/LemonMenu/useKeyboardNavigation.ts
+++ b/frontend/src/lib/lemon-ui/LemonMenu/useKeyboardNavigation.ts
@@ -1,61 +1,61 @@
-import { createRef, useEffect, useRef } from 'react'
+import { FocusEventHandler, KeyboardEvent, KeyboardEventHandler, createRef, useRef } from 'react'
-export function useKeyboardNavigation<R extends HTMLElement = HTMLElement, I extends HTMLElement = HTMLElement>(
+export function useKeyboardNavigation<I extends HTMLElement = HTMLElement>(
itemCount: number,
activeItemIndex: number = -1,
{ enabled = true } = {}
): {
- referenceRef: React.RefObject<R>
+ referenceRef: React.RefObject<HTMLElement>
itemsRef: React.RefObject<React.RefObject<I>[]>
- options?: { enabled: boolean }
+ onTriggerFocus: FocusEventHandler<HTMLElement>
+ onTriggerKeyDown: KeyboardEventHandler<HTMLElement>
+ onItemsKeyDown: KeyboardEventHandler<HTMLElement>
} {
- const focusedItemIndexRef = useRef(activeItemIndex)
- const referenceRef = useRef<R>(null)
+ const referenceRef = useRef<HTMLElement>(null)
+ const focusedTriggerRef = useRef<HTMLElement | null>(null)
const itemsRef = useRef(Array.from({ length: itemCount }, () => createRef<I>()))
-
- useEffect(() => {
- focusedItemIndexRef.current = activeItemIndex
- }, [activeItemIndex])
-
- function focus(itemIndex: number): void {
- if (itemIndex > -1) {
- itemsRef.current[itemIndex].current?.focus()
- } else {
- referenceRef.current?.focus()
- }
+ // A menu can gain items after its first render, for example when its data loads.
+ while (itemsRef.current.length < itemCount) {
+ itemsRef.current.push(createRef<I>())
}
- useEffect(() => {
- if (!enabled) {
+ function moveFocus(e: KeyboardEvent<HTMLElement>, fromIndex: number): void {
+ if (!enabled || e.defaultPrevented) {
return
}
-
- const handleKeyDown = (e: KeyboardEvent): void => {
- if (e.key === 'ArrowDown') {
- if (focusedItemIndexRef.current < itemCount - 1) {
- focusedItemIndexRef.current += 1
- focus(focusedItemIndexRef.current)
- e.preventDefault()
- }
- } else if (e.key === 'ArrowUp') {
- if (focusedItemIndexRef.current >= 0) {
- focusedItemIndexRef.current -= 1
- focus(focusedItemIndexRef.current)
- e.preventDefault()
- }
- }
- }
-
- const controller = new AbortController()
-
- referenceRef.current?.addEventListener('keydown', handleKeyDown, { signal: controller.signal })
- for (const item of itemsRef.current) {
- item?.current?.addEventListener('keydown', handleKeyDown, { signal: controller.signal })
+ let target: HTMLElement | null = null
+ if (e.key === 'ArrowDown') {
+ target = itemsRef.current.find((item, i) => i > fromIndex && item.current)?.current ?? null
+ } else if (e.key === 'ArrowUp' && fromIndex >= 0) {
+ target =
+ itemsRef.current.findLast((item, i) => i < fromIndex && item.current)?.current ??
+ focusedTriggerRef.current ??
+ referenceRef.current
}
- return () => {
- controller.abort()
+ if (target) {
+ target.focus()
+ e.preventDefault()
}
- }, [itemCount, enabled])
+ }
- return { referenceRef, itemsRef }
+ return {
+ referenceRef,
+ itemsRef,
+ onTriggerFocus: (e) => {
+ // The positioning ref can point at a wrapper, so remember the element that actually took focus.
+ focusedTriggerRef.current = e.target
+ },
+ onTriggerKeyDown: (e) => {
+ // A closed submenu leaves arrow keys to its parent menu.
+ if (itemsRef.current.some((item) => item.current)) {
+ moveFocus(e, activeItemIndex)
+ }
+ },
+ onItemsKeyDown: (e) => {
+ const itemIndex = itemsRef.current.findIndex((item) => item.current === e.target)
+ if (itemIndex >= 0) {
+ moveFocus(e, itemIndex)
+ }
+ },
+ }
}