: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(shortcuts): stop Shortcut swallowing a wrapper's disabled guard (#91966)
posthog[bot]5a16f9febaff
diff --git a/frontend/src/lib/components/Shortcuts/Shortcut.test.tsx b/frontend/src/lib/components/Shortcuts/Shortcut.test.tsxnew file mode 100644index 000000000000..414ee6719c6a--- /dev/null+++ b/frontend/src/lib/components/Shortcuts/Shortcut.test.tsx@@ -0,0 +1,72 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'++import { AccessControlAction } from 'lib/components/AccessControlAction'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'++import { AccessControlLevel, AccessControlResourceType } from '~/types'++import { Shortcut } from './Shortcut'+import { keyBinds } from './shortcuts'++describe('Shortcut', () => {+ // RTL auto-cleanup is not enabled in this repo, so `screen` leaks between tests without this.+ afterEach(() => {+ cleanup()+ })++ // AccessControlAction injects disabledReason through Shortcut, which must forward it to the child.+ test.each([+ [AccessControlLevel.Viewer, false],+ [AccessControlLevel.Editor, true],+ ])('with %s access the button is clickable=%s', async (userAccessLevel, clickable) => {+ const onClick = jest.fn()++ render(+ <AccessControlAction+ resourceType={AccessControlResourceType.SessionRecording}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={userAccessLevel}+ >+ <Shortcut name="TestNew" keybind={[keyBinds.new]} intent="New" interaction="click">+ <LemonButton type="primary" onClick={onClick}>+ New+ </LemonButton>+ </Shortcut>+ </AccessControlAction>+ )++ await userEvent.click(screen.getByText('New'))++ expect(onClick).toHaveBeenCalledTimes(clickable ? 1 : 0)+ })++ // On the saved insights scene the child is a LemonDropdown, so the guard lands on the dropdown+ // rather than on the visible trigger.+ test.each([+ [AccessControlLevel.Viewer, false],+ [AccessControlLevel.Editor, true],+ ])('with %s access a wrapped dropdown opens its menu=%s', async (userAccessLevel, canOpen) => {+ render(+ <AccessControlAction+ resourceType={AccessControlResourceType.Insight}+ minAccessLevel={AccessControlLevel.Editor}+ userAccessLevel={userAccessLevel}+ >+ <Shortcut name="TestNewInsight" keybind={[keyBinds.new]} intent="New" interaction="click">+ <LemonDropdown overlay={<span>Create menu item</span>} placement="bottom-end">+ <LemonButton type="primary">New</LemonButton>+ </LemonDropdown>+ </Shortcut>+ </AccessControlAction>+ )++ await userEvent.click(screen.getByText('New'))++ const menuOpened = screen.queryByText('Create menu item') !== null+ expect(menuOpened).toBe(canOpen)+ })+})diff --git a/frontend/src/lib/components/Shortcuts/Shortcut.tsx b/frontend/src/lib/components/Shortcuts/Shortcut.tsxindex 19001ae307aa..4138d2a22a80 100644--- a/frontend/src/lib/components/Shortcuts/Shortcut.tsx+++ b/frontend/src/lib/components/Shortcuts/Shortcut.tsx@@ -21,19 +21,27 @@ interface ShortcutProps extends Omit<ShortcutType, 'ref' | 'keybind' | 'interactinteraction: 'click' | 'focus'/** If true, the keyboard shortcut will not be registered and tooltip keyboard shortcut will not be added to the childs tooltip */disabled?: boolean+ /** Reason the child is disabled, e.g. injected by AccessControlAction. Forwarded to the child. */+ disabledReason?: string | null}export const Shortcut = forwardRef<HTMLElement, ShortcutProps>(function Shortcut(- { children, name, keybind, intent, interaction, scope = 'global', disabled = false, priority = 0 },+ { children, name, keybind, intent, interaction, scope = 'global', disabled = false, disabledReason, priority = 0 },forwardedRef): ReactElement {+ const childProps = (isValidElement(children) ? children.props : {}) as Record<string, unknown>++ // A disabled control must not keep a live keybind, so this also gates registration below.+ const isDisabled =+ disabled || Boolean(disabledReason) || Boolean(childProps.disabled) || Boolean(childProps.disabledReason)+const { callbackRef } = useShortcut({name,keybind,intent,interaction,scope,- disabled,+ disabled: isDisabled,priority,})@@ -43,12 +51,11 @@ export const Shortcut = forwardRef<HTMLElement, ShortcutProps>(function Shortcutthrow new Error('Shortcut requires a single React element child')}- const childProps = children.props as Record<string, unknown>const keybindStrings = keybind.map((kb) => kb.join('+')).join(',')// Append keyboard shortcut to tooltip if child has onelet finalTooltip = childProps.tooltip- if (childProps.tooltip && !disabled) {+ if (childProps.tooltip && !isDisabled) {finalTooltip = (<>{childProps.tooltip}{' '}@@ -64,6 +71,8 @@ export const Shortcut = forwardRef<HTMLElement, ShortcutProps>(function Shortcutreturn cloneElement(children, {ref: mergedRef,+ disabled: isDisabled,+ disabledReason: disabledReason ?? (childProps.disabledReason as string | null | undefined),'data-shortcut-name': name,'data-shortcut-keybind': keybindStrings,'data-shortcut-intent': intent,diff --git a/frontend/src/lib/lemon-ui/LemonDropdown/LemonDropdown.tsx b/frontend/src/lib/lemon-ui/LemonDropdown/LemonDropdown.tsxindex 77707fe57d93..d35e0c2b2282 100644--- a/frontend/src/lib/lemon-ui/LemonDropdown/LemonDropdown.tsx+++ b/frontend/src/lib/lemon-ui/LemonDropdown/LemonDropdown.tsx@@ -19,6 +19,10 @@ export interface LemonDropdownProps extends Omit<PopoverProps, 'children' | 'vis/** @default 'click' */trigger?: 'click' | 'hover'hoverOpenDelayMs?: number+ /** Disabled state for the trigger, e.g. injected by an access-control guard. */+ disabled?: boolean+ /** Reason shown when the trigger is disabled. */+ disabledReason?: string | nullchildren: React.ReactElement<Record<string, any> & {onClick: MouseEventHandler@@ -42,6 +46,8 @@ export const LemonDropdown = React.forwardRef<HTMLDivElement, LemonDropdownPropshoverOpenDelayMs = 0,children,startVisible,+ disabled,+ disabledReason,...popoverProps},ref@@ -80,6 +86,10 @@ export const LemonDropdown = React.forwardRef<HTMLDivElement, LemonDropdownPropsonVisibilityChange?.(value)}+ // A guard clones these onto the dropdown, so merge them with whatever the trigger already has.+ const triggerDisabled = disabled || children.props.disabled+ const triggerDisabledReason = disabledReason ?? children.props.disabledReason+return (<Popoverref={ref}@@ -146,6 +156,9 @@ export const LemonDropdown = React.forwardRef<HTMLDivElement, LemonDropdownProps}},'aria-haspopup': 'true',+ disabled: triggerDisabled,+ // `disabledReason` is a LemonButton prop, so React warns if it reaches a plain element.+ ...(triggerDisabledReason != null ? { disabledReason: triggerDisabledReason } : {}),})}</Popover>)diff --git a/frontend/src/scenes/session-recordings/SessionRecordings.tsx b/frontend/src/scenes/session-recordings/SessionRecordings.tsxindex 0e8c8a1b5ff0..7d7ee731757f 100644--- a/frontend/src/scenes/session-recordings/SessionRecordings.tsx+++ b/frontend/src/scenes/session-recordings/SessionRecordings.tsx@@ -1,11 +1,13 @@import { BindLogic, useActions, useValues } from 'kea'import { router } from 'kea-router'+import posthog from 'posthog-js'import { useState } from 'react'import { IconDocument, IconGear, IconHeadset } from '@posthog/icons'import { LemonBadge, LemonButton, Link } from '@posthog/lemon-ui'import { PostHogCaptureOnViewed } from '@posthog/react'+import { isAccessDeniedError, shouldReportApiFailure } from 'lib/api-error'import { AccessControlAction } from 'lib/components/AccessControlAction'import { LiveRecordingsCount } from 'lib/components/LiveUserCount'import { Shortcut } from 'lib/components/Shortcuts/Shortcut'@@ -14,6 +16,7 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { lemonBannerLogic } from 'lib/lemon-ui/LemonBanner/lemonBannerLogic'import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'import { cn } from 'lib/utils/css-classes'@@ -53,6 +56,16 @@ function Header(): JSX.Element {try {await createPlaylist({ _create_in_folder: 'Unfiled/Replay playlists', type: 'collection' }, true)reportRecordingPlaylistCreated('new')+ } catch (error: any) {+ if (isAccessDeniedError(error)) {+ lemonToast.error('You do not have access to create collections.')+ } else {+ lemonToast.error('Could not create the collection. Please try again.')+ }+ // Not a kea loader, so initKea's report gate does not run. Apply the same gate here.+ if (shouldReportApiFailure(error)) {+ posthog.captureException(error)+ }} finally {setLoading(false)}