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(navigation): keep submenus open on the diagonal to them (#84105)

Adam Leith87dd3117092c
diff --git a/frontend/src/lib/components/Account/NewAccountMenu.tsx b/frontend/src/lib/components/Account/NewAccountMenu.tsx
index b585770d4307..b0e30049b134 100644
--- a/frontend/src/lib/components/Account/NewAccountMenu.tsx
+++ b/frontend/src/lib/components/Account/NewAccountMenu.tsx
@@ -21,6 +21,7 @@ import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { DropdownMenuSeparator } from 'lib/ui/DropdownMenu/DropdownMenu'
import { Label } from 'lib/ui/Label/Label'
import { MenuOpenIndicator } from 'lib/ui/Menus/Menus'
+import { useSubmenuSafeTriangle } from 'lib/ui/Menus/useSubmenuSafeTriangle'
import { cn } from 'lib/utils/css-classes'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { billingLogic } from 'scenes/billing/billingLogic'
@@ -66,6 +67,8 @@ export function NewAccountMenu({ isLayoutNavCollapsed }: AccountMenuProps): JSX.
const { guardAvailableFeature } = useValues(upgradeModalLogic)
const { showCreateProjectModal } = useActions(globalModalsLogic)
const { showCreateOrganizationModal } = useActions(globalModalsLogic)
+ const projectSubmenu = useSubmenuSafeTriangle()
+ const organizationSubmenu = useSubmenuSafeTriangle()
const projectNameStartsWithEmoji = currentTeam?.name?.match(/^\p{Extended_Pictographic}/u) !== null
const projectNameWithoutFirstEmoji = projectNameStartsWithEmoji
@@ -166,6 +169,7 @@ export function NewAccountMenu({ isLayoutNavCollapsed }: AccountMenuProps): JSX.
<Menu.SubmenuRoot>
<Menu.SubmenuTrigger
openOnHover={false}
+ ref={projectSubmenu.triggerRef}
render={
<ButtonPrimitive
menuItem
@@ -189,7 +193,10 @@ export function NewAccountMenu({ isLayoutNavCollapsed }: AccountMenuProps): JSX.
className="z-[var(--z-popover)]"
collisionPadding={{ top: 50, bottom: 50 }}
>
- <Menu.Popup className="primitive-menu-content w-min max-w-[var(--available-width)]">
+ <Menu.Popup
+ ref={projectSubmenu.popupRef}
+ className="primitive-menu-content w-min max-w-[var(--available-width)]"
+ >
{/* We need to add a div here to prevent the keydown event from bubbling up to the menu. */}
<div onKeyDown={(e) => e.stopPropagation()}>
<ProjectSwitcher dialog={false} />
@@ -265,6 +272,7 @@ export function NewAccountMenu({ isLayoutNavCollapsed }: AccountMenuProps): JSX.
<Menu.SubmenuRoot>
<Menu.SubmenuTrigger
openOnHover={false}
+ ref={organizationSubmenu.triggerRef}
render={
<ButtonPrimitive
menuItem
@@ -294,7 +302,10 @@ export function NewAccountMenu({ isLayoutNavCollapsed }: AccountMenuProps): JSX.
className="z-[var(--z-popover)]"
collisionPadding={{ top: 50, bottom: 50 }}
>
- <Menu.Popup className="primitive-menu-content w-min max-w-[var(--available-width)]">
+ <Menu.Popup
+ ref={organizationSubmenu.popupRef}
+ className="primitive-menu-content w-min max-w-[var(--available-width)]"
+ >
{/* We need to add a div here to prevent the keydown event from bubbling up to the menu. */}
<div onKeyDown={(e) => e.stopPropagation()}>
<OrgSwitcher dialog={false} />
diff --git a/frontend/src/lib/components/Menus/ThemeMenu.tsx b/frontend/src/lib/components/Menus/ThemeMenu.tsx
index da1bb8de5180..f75d4d984811 100644
--- a/frontend/src/lib/components/Menus/ThemeMenu.tsx
+++ b/frontend/src/lib/components/Menus/ThemeMenu.tsx
@@ -8,6 +8,7 @@ import { Link } from 'lib/lemon-ui/Link/Link'
import { themeLogic } from 'lib/logic/themeLogic'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
import { MenuOpenIndicator } from 'lib/ui/Menus/Menus'
+import { useSubmenuSafeTriangle } from 'lib/ui/Menus/useSubmenuSafeTriangle'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -17,6 +18,7 @@ export function ThemeMenu(): JSX.Element {
const { themeMode } = useValues(userLogic)
const { updateUser } = useActions(userLogic)
const { customCssEnabled } = useValues(themeLogic)
+ const themeSubmenu = useSubmenuSafeTriangle()
function handleThemeChange(theme: UserTheme): void {
updateUser({ theme_mode: theme })
@@ -26,6 +28,7 @@ export function ThemeMenu(): JSX.Element {
<Menu.SubmenuRoot>
<Menu.SubmenuTrigger
openOnHover={false}
+ ref={themeSubmenu.triggerRef}
render={
<ButtonPrimitive menuItem data-attr="more-menu-theme-button">
<IconPalette />
@@ -39,7 +42,7 @@ export function ThemeMenu(): JSX.Element {
/>
<Menu.Portal>
<Menu.Positioner className="z-[var(--z-popover)]" collisionPadding={{ top: 50, bottom: 50 }}>
- <Menu.Popup className="primitive-menu-content">
+ <Menu.Popup ref={themeSubmenu.popupRef} className="primitive-menu-content">
<div className="primitive-menu-content-inner flex flex-col gap-px p-1">
<Menu.Item
onClick={() => handleThemeChange('light')}
diff --git a/frontend/src/lib/ui/Menus/safeTriangle.test.ts b/frontend/src/lib/ui/Menus/safeTriangle.test.ts
new file mode 100644
index 000000000000..5cbae5167115
--- /dev/null
+++ b/frontend/src/lib/ui/Menus/safeTriangle.test.ts
@@ -0,0 +1,64 @@
+import { isPointInSafeTriangle, Point, Rect } from './safeTriangle'
+
+describe('safeTriangle', () => {
+ // A submenu sitting to the right of its trigger, the way Base UI places one by default.
+ const submenuOnTheRight: Rect = { left: 200, right: 400, top: 100, bottom: 300 }
+ const anchorLeftOfSubmenu: Point = { x: 100, y: 110 }
+
+ const cases: [string, Point, Point, Rect, boolean][] = [
+ [
+ 'keeps a point on the diagonal to the far corner',
+ { x: 150, y: 200 },
+ anchorLeftOfSubmenu,
+ submenuOnTheRight,
+ true,
+ ],
+ [
+ 'keeps a point straight ahead of the anchor',
+ { x: 150, y: 110 },
+ anchorLeftOfSubmenu,
+ submenuOnTheRight,
+ true,
+ ],
+ [
+ 'drops a point past the diagonal to the far corner',
+ { x: 150, y: 260 },
+ anchorLeftOfSubmenu,
+ submenuOnTheRight,
+ false,
+ ],
+ [
+ 'drops a point heading away from the submenu',
+ { x: 150, y: 50 },
+ anchorLeftOfSubmenu,
+ submenuOnTheRight,
+ false,
+ ],
+ ['drops a point behind the anchor', { x: 50, y: 110 }, anchorLeftOfSubmenu, submenuOnTheRight, false],
+ [
+ 'keeps a point heading to a submenu on the left',
+ { x: 450, y: 200 },
+ { x: 500, y: 110 },
+ { left: 200, right: 400, top: 100, bottom: 300 },
+ true,
+ ],
+ [
+ 'keeps a point heading to a submenu below',
+ { x: 250, y: 250 },
+ { x: 210, y: 50 },
+ { left: 100, right: 400, top: 300, bottom: 500 },
+ true,
+ ],
+ [
+ 'drops a point whose anchor faces no edge',
+ { x: 250, y: 250 },
+ { x: 250, y: 200 },
+ { left: 100, right: 400, top: 100, bottom: 300 },
+ false,
+ ],
+ ]
+
+ it.each(cases)('%s', (_name, point, anchor, rect, expected) => {
+ expect(isPointInSafeTriangle(point, anchor, rect)).toBe(expected)
+ })
+})
diff --git a/frontend/src/lib/ui/Menus/safeTriangle.ts b/frontend/src/lib/ui/Menus/safeTriangle.ts
new file mode 100644
index 000000000000..e0d3aa1499ac
--- /dev/null
+++ b/frontend/src/lib/ui/Menus/safeTriangle.ts
@@ -0,0 +1,67 @@
+export interface Point {
+ x: number
+ y: number
+}
+
+/** The parts of a `DOMRect` the safe triangle needs. */
+export interface Rect {
+ left: number
+ right: number
+ top: number
+ bottom: number
+}
+
+/** Widens the target edge, where the triangle is at its narrowest and least forgiving. */
+const EDGE_TOLERANCE_PX = 12
+
+/**
+ * Whether `point` sits in the triangle spanned by `anchor` and the edge of `rect` facing it — the
+ * wedge a pointer travelling from `anchor` towards any part of `rect` stays inside.
+ */
+export function isPointInSafeTriangle(point: Point, anchor: Point, rect: Rect): boolean {
+ const edge = facingEdge(anchor, rect)
+ return edge !== null && isPointInTriangle(point, anchor, edge[0], edge[1])
+}
+
+/** The two corners of the `rect` edge that faces `anchor`, or null when `anchor` faces no edge. */
+function facingEdge(anchor: Point, rect: Rect): [Point, Point] | null {
+ if (anchor.x <= rect.left) {
+ return [
+ { x: rect.left, y: rect.top - EDGE_TOLERANCE_PX },
+ { x: rect.left, y: rect.bottom + EDGE_TOLERANCE_PX },
+ ]
+ }
+ if (anchor.x >= rect.right) {
+ return [
+ { x: rect.right, y: rect.top - EDGE_TOLERANCE_PX },
+ { x: rect.right, y: rect.bottom + EDGE_TOLERANCE_PX },
+ ]
+ }
+ if (anchor.y <= rect.top) {
+ return [
+ { x: rect.left - EDGE_TOLERANCE_PX, y: rect.top },
+ { x: rect.right + EDGE_TOLERANCE_PX, y: rect.top },
+ ]
+ }
+ if (anchor.y >= rect.bottom) {
+ return [
+ { x: rect.left - EDGE_TOLERANCE_PX, y: rect.bottom },
+ { x: rect.right + EDGE_TOLERANCE_PX, y: rect.bottom },
+ ]
+ }
+ return null
+}
+
+function isPointInTriangle(point: Point, a: Point, b: Point, c: Point): boolean {
+ const ab = crossProductSign(point, a, b)
+ const bc = crossProductSign(point, b, c)
+ const ca = crossProductSign(point, c, a)
+ const hasNegative = ab < 0 || bc < 0 || ca < 0
+ const hasPositive = ab > 0 || bc > 0 || ca > 0
+ // A point inside the triangle sits on the same side of all three edges.
+ return !(hasNegative && hasPositive)
+}
+
+function crossProductSign(point: Point, from: Point, to: Point): number {
+ return (point.x - to.x) * (from.y - to.y) - (from.x - to.x) * (point.y - to.y)
+}
diff --git a/frontend/src/lib/ui/Menus/useSubmenuSafeTriangle.ts b/frontend/src/lib/ui/Menus/useSubmenuSafeTriangle.ts
new file mode 100644
index 000000000000..2d14ce5f7d62
--- /dev/null
+++ b/frontend/src/lib/ui/Menus/useSubmenuSafeTriangle.ts
@@ -0,0 +1,88 @@
+import { useCallback, useEffect, useMemo, useRef } from 'react'
+
+import { isPointInSafeTriangle, Point } from './safeTriangle'
+
+/** A pointer that pauses this long is no longer travelling to the submenu, whatever the wedge says. */
+const MAX_STALL_MS = 200
+
+export interface SubmenuSafeTriangle {
+ /** Attach to `Menu.SubmenuTrigger`. */
+ triggerRef: (element: HTMLElement | null) => void
+ /** Attach to the submenu's `Menu.Popup`. */
+ popupRef: (element: HTMLElement | null) => void
+}
+
+/**
+ * Keeps a submenu open while the pointer travels diagonally from its trigger to the submenu itself.
+ *
+ * Base UI only does this for submenus that open on hover; one that opens on click closes as soon as
+ * the pointer grazes another item of the parent menu, which is most of the diagonal path. Blocking
+ * the mouse move before it reaches those items keeps the path from registering as a hover.
+ */
+export function useSubmenuSafeTriangle(): SubmenuSafeTriangle {
+ const triggerElement = useRef<HTMLElement | null>(null)
+ const popupElement = useRef<HTMLElement | null>(null)
+ const anchor = useRef<{ point: Point; movedAt: number } | null>(null)
+ const detach = useRef<(() => void) | null>(null)
+
+ const handleMouseMove = useCallback((event: MouseEvent): void => {
+ const trigger = triggerElement.current
+ const popup = popupElement.current
+ if (!trigger || !popup) {
+ return
+ }
+
+ const point = { x: event.clientX, y: event.clientY }
+ // Going by the event target rather than the trigger's rect matters on the boundary pixel,
+ // which reads as inside the rect while the move already belongs to the item below.
+ if (trigger.contains(event.target as Node)) {
+ // The last point the pointer held on the trigger is where the wedge starts.
+ anchor.current = { point, movedAt: event.timeStamp }
+ return
+ }
+
+ const from = anchor.current
+ if (!from) {
+ return
+ }
+ if (
+ event.timeStamp - from.movedAt < MAX_STALL_MS &&
+ isPointInSafeTriangle(point, from.point, popup.getBoundingClientRect())
+ ) {
+ from.movedAt = event.timeStamp
+ event.stopPropagation()
+ return
+ }
+ anchor.current = null
+ }, [])
+
+ // Listening on the parent menu rather than the document keeps every other mouse move untouched.
+ const listenOnParentMenu = useCallback((): void => {
+ detach.current?.()
+ detach.current = null
+ anchor.current = null
+
+ const parentMenu = popupElement.current ? triggerElement.current?.closest<HTMLElement>('[role="menu"]') : null
+ if (!parentMenu) {
+ return
+ }
+ parentMenu.addEventListener('mousemove', handleMouseMove, true)
+ detach.current = () => parentMenu.removeEventListener('mousemove', handleMouseMove, true)
+ }, [handleMouseMove])
+
+ useEffect(() => () => detach.current?.(), [])
+
+ return useMemo(
+ () => ({
+ triggerRef: (element: HTMLElement | null): void => {
+ triggerElement.current = element
+ listenOnParentMenu()
+ },
+ popupRef: (element: HTMLElement | null): void => {
+ popupElement.current = element
+ listenOnParentMenu()
+ },
+ }),
+ [listenOnParentMenu]
+ )
+}