diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index 4052006f0c0a..0da3c0e188f7 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -945,11 +945,6 @@ "count": 1 } }, - "static/app/components/profiling/flamegraph/callTreeTable.tsx": { - "@sentry/scraps/prefer-primitives": { - "count": 2 - } - }, "static/app/components/profiling/flamegraph/collapsibleTimeline.tsx": { "@sentry/scraps/prefer-primitives": { "count": 1 diff --git a/static/app/components/core/table/table.spec.tsx b/static/app/components/core/table/table.spec.tsx index 67d6fe1f7714..aab7f07bc4ca 100644 --- a/static/app/components/core/table/table.spec.tsx +++ b/static/app/components/core/table/table.spec.tsx @@ -56,6 +56,13 @@ describe('Table', () => { expect(within(table).getAllByRole('cell')).toHaveLength(3); }); + it('takes a more specific role when given one', () => { + render(); + + expect(screen.getByRole('treegrid', {name: 'Tree'})).toBeInTheDocument(); + expect(screen.queryByRole('table')).not.toBeInTheDocument(); + }); + it.each([ { name: 'sizes declared widths and lets the last column absorb slack', diff --git a/static/app/components/core/table/table.tsx b/static/app/components/core/table/table.tsx index f671303c5170..2360add96caa 100644 --- a/static/app/components/core/table/table.tsx +++ b/static/app/components/core/table/table.tsx @@ -264,12 +264,12 @@ export function Table({ return ( column.hidden ? [index] : [] )} ref={gridRef} - role="table" style={template ? {...props.style, gridTemplateColumns: template} : props.style} > {children} diff --git a/static/app/components/profiling/flamegraph/aggregateFlamegraphTreeTable.spec.tsx b/static/app/components/profiling/flamegraph/aggregateFlamegraphTreeTable.spec.tsx new file mode 100644 index 000000000000..935dd1dfc625 --- /dev/null +++ b/static/app/components/profiling/flamegraph/aggregateFlamegraphTreeTable.spec.tsx @@ -0,0 +1,98 @@ +import {render, screen, userEvent, within} from 'sentry-test/reactTestingLibrary'; + +import {AggregateFlamegraphTreeTable} from 'sentry/components/profiling/flamegraph/aggregateFlamegraphTreeTable'; +import {trackAnalytics} from 'sentry/utils/analytics'; +import {CanvasPoolManager, CanvasScheduler} from 'sentry/utils/profiling/canvasScheduler'; +import {FlamegraphStateProvider} from 'sentry/utils/profiling/flamegraph/flamegraphStateProvider/flamegraphContextProvider'; +import {FlamegraphThemeProvider} from 'sentry/utils/profiling/flamegraph/flamegraphThemeProvider'; +import {FlamegraphProvider} from 'sentry/views/explore/profiling/flamegraphProvider'; +import {ProfileGroupProvider} from 'sentry/views/explore/profiling/profileGroupProvider'; + +jest.mock('sentry/utils/analytics'); + +const sampledProfile: Profiling.SampledProfile = { + name: 'profile', + startValue: 0, + endValue: 30, + threadID: 0, + unit: 'nanoseconds', + type: 'sampled', + weights: [10, 10, 10], + samples: [ + [0, 1], + [0, 1], + [0, 2], + ], +}; + +const input: Profiling.Schema = { + activeProfileIndex: 0, + profileID: '', + profiles: [sampledProfile], + projectID: 1, + shared: { + frames: [{name: 'root'}, {name: 'busy'}, {name: 'idle'}], + }, + metadata: {} as Profiling.Schema['metadata'], +}; + +function renderTreeTable() { + const canvasPoolManager = new CanvasPoolManager(); + + render( + + + + + + + + + + ); + + return {canvasPoolManager}; +} + +describe('AggregateFlamegraphTreeTable', () => { + it('renders the sample count and average duration columns when given a profile', async () => { + renderTreeTable(); + + const row = await screen.findByRole('row', {name: /busy/}); + + expect(screen.getByRole('columnheader', {name: /Samples/})).toBeInTheDocument(); + expect( + screen.getByRole('columnheader', {name: /Average Duration/}) + ).toBeInTheDocument(); + expect( + within(within(row).getAllByRole('gridcell')[0]!).getByText('20') + ).toBeInTheDocument(); + expect(row).toHaveAttribute('aria-level', '1'); + }); + + it('highlights the frame on the flamegraph and tracks the click when a row is clicked', async () => { + const {canvasPoolManager} = renderTreeTable(); + const dispatch = jest.spyOn(canvasPoolManager, 'dispatch'); + + await userEvent.click(await screen.findByRole('row', {name: /busy/})); + + expect(dispatch).toHaveBeenCalledWith('highlight frame', [ + [expect.objectContaining({frame: expect.objectContaining({name: 'busy'})})], + 'selected', + ]); + expect(trackAnalytics).toHaveBeenCalledWith( + 'profiling_views.flamegraph.click.highlight_frame', + expect.objectContaining({profile_type: 'landing aggregate calltree'}) + ); + expect(screen.getByRole('row', {name: /busy/})).toHaveAttribute( + 'aria-selected', + 'true' + ); + }); +}); diff --git a/static/app/components/profiling/flamegraph/aggregateFlamegraphTreeTable.tsx b/static/app/components/profiling/flamegraph/aggregateFlamegraphTreeTable.tsx index 299ccc0793e2..4b94a5c0af8b 100644 --- a/static/app/components/profiling/flamegraph/aggregateFlamegraphTreeTable.tsx +++ b/static/app/components/profiling/flamegraph/aggregateFlamegraphTreeTable.tsx @@ -1,12 +1,9 @@ -import {useCallback, useEffect, useMemo, useState, type MouseEvent} from 'react'; -import {css} from '@emotion/react'; -import styled from '@emotion/styled'; -import {IconArrow} from '@sentry/icons/arrow'; +import {Fragment, useCallback, useEffect, useMemo, useState} from 'react'; import {InfoTip} from '@sentry/scraps/info'; -import InteractionStateLayer from '@sentry/scraps/interactionStateLayer'; import {PerformanceDuration} from 'sentry/components/performanceDuration'; +import {SimpleTable} from 'sentry/components/tables/simpleTable'; import {t} from 'sentry/locale'; import {trackAnalytics} from 'sentry/utils/analytics'; import type {AggregateProfileSource} from 'sentry/utils/analytics/profilingAnalyticsEvents'; @@ -22,14 +19,8 @@ import {useFlamegraphTheme} from 'sentry/utils/profiling/flamegraph/useFlamegrap import type {FlamegraphFrame} from 'sentry/utils/profiling/flamegraphFrame'; import {formatColorForFrame} from 'sentry/utils/profiling/gl/utils'; import {useContextMenu} from 'sentry/utils/profiling/hooks/useContextMenu'; -import type {UseVirtualizedTreeProps} from 'sentry/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree'; -import {useVirtualizedTree} from 'sentry/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree'; import {VirtualizedTree} from 'sentry/utils/profiling/hooks/useVirtualizedTree/VirtualizedTree'; import type {VirtualizedTreeNode} from 'sentry/utils/profiling/hooks/useVirtualizedTree/VirtualizedTreeNode'; -import type { - VirtualizedTreeRenderedRow, - VirtualizedTreeRenderedRowHandlers, -} from 'sentry/utils/profiling/hooks/useVirtualizedTree/virtualizedTreeUtils'; import {invertCallTree} from 'sentry/utils/profiling/profile/utils'; import {relativeWeight} from 'sentry/utils/profiling/units/units'; import {useLocalStorageState} from 'sentry/utils/useLocalStorageState'; @@ -39,18 +30,12 @@ import {useProfileGroup} from 'sentry/views/explore/profiling/profileGroupProvid import {AggregateFlamegraphTreeContextMenu} from './aggregateFlamegraphTreeContextMenu'; import { - CALL_TREE_FRAME_WEIGHT_CELL_WIDTH_PX, - CallTreeDynamicColumnsContainer, - CallTreeFixedColumnsContainer, CallTreeTable, CallTreeTableContainer, - CallTreeTableDynamicColumns, - CallTreeTableFixedColumns, - CallTreeTableGhostRow, - CallTreeTableHeader, - CallTreeTableHeaderButton, + CallTreeTableFrameCell, CallTreeTableRow, - syncCallTreeTableScroll, + CallTreeTableWeightCell, + useCallTreeTable, } from './callTreeTable'; function makeSortFunction( @@ -123,7 +108,6 @@ interface AggregateFlamegraphTreeTableProps { profileType: AggregateProfileSource; recursion: 'collapsed' | null; expanded?: boolean; - withoutBorders?: boolean; } export function AggregateFlamegraphTreeTable({ @@ -133,7 +117,6 @@ export function AggregateFlamegraphTreeTable({ profileType, recursion, frameFilter, - withoutBorders, }: AggregateFlamegraphTreeTableProps) { const organization = useOrganization(); const dispatch = useDispatchFlamegraphState(); @@ -207,10 +190,6 @@ export function AggregateFlamegraphTreeTable({ } }, [profileGroup, profiles.threadId, dispatch]); - const [scrollContainerRef, setFixedScrollContainerRef] = - useState(null); - const [dynamicScrollContainerRef, setDynamicScrollContainerRef] = - useState(null); const [sort, setSort] = useState<'sample count' | 'duration' | 'name'>('sample count'); const [direction, setDirection] = useState<'asc' | 'desc'>('desc'); const sortFunction = useMemo(() => { @@ -222,151 +201,24 @@ export function AggregateFlamegraphTreeTable({ ); const contextMenu = useContextMenu({container: tableParentContainer}); - const fixedRenderRow: UseVirtualizedTreeProps['renderRow'] = - useCallback( - ( - r: VirtualizedTreeRenderedRow, - { - handleRowClick, - handleRowMouseEnter, - handleExpandTreeNode, - handleRowKeyDown, - selectedNodeIndex, - }: VirtualizedTreeRenderedRowHandlers - ) => { - return ( - { - r.ref = n; - }} - top={r.styles.top} - tabIndex={selectedNodeIndex === r.key ? 0 : 1} - onKeyDown={handleRowKeyDown} - onClick={handleRowClick} - onMouseEnter={handleRowMouseEnter} - onContextMenu={contextMenu.handleContextMenu} - > - - } - showAvg - avgWeight={ - defined(r.item.node.frame.averageCallDuration) ? ( - - ) : undefined - } - selfWeight={r.item.node.node.totalWeight.toFixed(0)} - relativeSelfWeight={relativeWeight( - referenceNode.node.totalWeight, - r.item.node.node.totalWeight - )} - relativeTotalWeight={relativeWeight( - referenceNode.node.aggregate_duration_ns, - r.item.node.node.aggregate_duration_ns - )} - onExpandClick={handleExpandTreeNode} - /> - - ); - }, - [referenceNode, flamegraph.formatter, getFrameColor, contextMenu] - ); - - const dynamicRenderRow: UseVirtualizedTreeProps['renderRow'] = - useCallback( - ( - r: VirtualizedTreeRenderedRow, - { - handleRowClick, - handleRowMouseEnter, - handleExpandTreeNode, - handleRowKeyDown, - selectedNodeIndex, - }: VirtualizedTreeRenderedRowHandlers - ) => { - return ( - { - r.ref = n; - }} - top={r.styles.top} - tabIndex={selectedNodeIndex === r.key ? 0 : 1} - onKeyDown={handleRowKeyDown} - onClick={handleRowClick} - onMouseEnter={handleRowMouseEnter} - onContextMenu={contextMenu.handleContextMenu} - > - - - ); - }, - [referenceNode, flamegraph.formatter, getFrameColor, contextMenu] - ); - - const onScrollToNode: UseVirtualizedTreeProps['onScrollToNode'] = - useCallback( - ( - node: VirtualizedTreeRenderedRow | undefined, - scrollContainer: HTMLElement | HTMLElement[] | null, - coordinates?: {depth: number; top: number} - ) => { - syncCallTreeTableScroll({node, scrollContainer, coordinates}); - }, - [] - ); - const virtualizedTree = useMemo(() => { return VirtualizedTree.fromRoots(tree ?? []); }, [tree]); - const scrollContainers = useMemo(() => { - return [scrollContainerRef, dynamicScrollContainerRef].filter(c => !!c); - }, [dynamicScrollContainerRef, scrollContainerRef]); - const { items: renderItems, - scrollContainerStyles: scrollContainerStyles, - containerStyles: fixedContainerStyles, + rowCount, + tableRef, handleSortingChange, handleScrollTo, handleExpandTreeNode, handleRowClick: _handleRowClick, - handleRowKeyDown, - handleRowMouseEnter, - selectedNodeIndex, - clickedGhostRowRef, - hoveredGhostRowRef, + getRowProps, getNodeAtIndex, - } = useVirtualizedTree({ + } = useCallTreeTable({ expanded, skipFunction: recursion === 'collapsed' ? skipRecursiveNodes : undefined, sortFunction, - onScrollToNode, - scrollContainer: scrollContainers, - rowHeight: 24, tree, virtualizedTree, }); @@ -375,6 +227,10 @@ export function AggregateFlamegraphTreeTable({ (index: number) => { const handler = _handleRowClick(index); return function (evt: React.MouseEvent) { + trackAnalytics('profiling_views.flamegraph.click.highlight_frame', { + organization, + profile_type: profileType, + }); const frame = getNodeAtIndex(index); if (frame) { canvasPoolManager.dispatch('highlight frame', [[frame], 'selected']); @@ -382,7 +238,7 @@ export function AggregateFlamegraphTreeTable({ handler(evt); }; }, - [canvasPoolManager, _handleRowClick, getNodeAtIndex] + [canvasPoolManager, _handleRowClick, getNodeAtIndex, organization, profileType] ); useEffect(() => { @@ -433,127 +289,85 @@ export function AggregateFlamegraphTreeTable({ }, [setTreeView]); return ( - - - - - - - - {t('Samples')}{' '} - - - {sort === 'sample count' ? ( - - ) : null} - - - - - - - {t('Average Duration')}{' '} - + + + + {t('Samples')}{' '} + + + + {t('Average Duration')}{' '} + + + + {t('Frame')} + + + } + > + {renderItems.map(r => ( + + + {r.item.node.node.totalWeight.toFixed(0)} + + + {defined(r.item.node.frame.averageCallDuration) ? ( + - - {sort === 'duration' ? ( - - ) : null} - - -
- - - {t('Frame')}{' '} - {sort === 'name' ? ( - - ) : null} - -
-
- - - - {/* - The order of these two matters because we want clicked state to - be on top of hover in cases where user is hovering a clicked row. - */} -
-
- {renderItems.map(r => { - const handler = handleRowClick(r.key); - return fixedRenderRow(r, { - handleRowClick: (evt: MouseEvent) => { - trackAnalytics('profiling_views.flamegraph.click.highlight_frame', { - organization, - profile_type: profileType, - }); - handler(evt); - }, - handleRowMouseEnter: handleRowMouseEnter(r.key), - handleExpandTreeNode, - handleRowKeyDown, - selectedNodeIndex, - }); - })} - -
-
-
- - {/* - The order of these two matters because we want clicked state to - be on top of hover in cases where user is hovering a clicked row. - */} -
-
- {renderItems.map(r => { - const handler = handleRowClick(r.key); - return dynamicRenderRow(r, { - handleRowClick: (evt: MouseEvent) => { - handler(evt); - }, - handleRowMouseEnter: handleRowMouseEnter(r.key), - handleExpandTreeNode, - handleRowKeyDown, - selectedNodeIndex, - }); - })} -
-
-
-
-
- + ) : ( + t('Unknown') + )} + + + + ))} - + ); } - -const FrameBar = styled('div')<{withoutBorders?: boolean}>` - overflow: auto; - width: 100%; - position: relative; - background-color: ${p => p.theme.tokens.background.tertiary}; - ${p => - !p.withoutBorders && - css` - border-top: 1px solid ${p.theme.tokens.border.primary}; - `} - flex: 1 1 100%; -`; - -const FrameWeightCell = styled('div')` - width: ${CALL_TREE_FRAME_WEIGHT_CELL_WIDTH_PX}px; -`; diff --git a/static/app/components/profiling/flamegraph/callTreeTable.tsx b/static/app/components/profiling/flamegraph/callTreeTable.tsx index 08b5b419be23..2e7fcf56a7ed 100644 --- a/static/app/components/profiling/flamegraph/callTreeTable.tsx +++ b/static/app/components/profiling/flamegraph/callTreeTable.tsx @@ -1,304 +1,321 @@ -import {Fragment} from 'react'; +import { + useCallback, + useLayoutEffect, + useRef, + useState, + type ReactNode, + type RefObject, +} from 'react'; +import {useTheme} from '@emotion/react'; import styled from '@emotion/styled'; import {IconSettings} from '@sentry/icons/settings'; import {IconUser} from '@sentry/icons/user'; -import type {CSS} from '@sentry/scraps/cssTypes'; +import {Button} from '@sentry/scraps/button'; +import {Container, Flex} from '@sentry/scraps/layout'; +import type {TableColumnConfig} from '@sentry/scraps/table'; +import {Text} from '@sentry/scraps/text'; +import {SimpleTable} from 'sentry/components/tables/simpleTable'; import {t} from 'sentry/locale'; -import {defined} from 'sentry/utils/defined'; import type {FlamegraphFrame} from 'sentry/utils/profiling/flamegraphFrame'; +import { + useVirtualizedTree, + type UseVirtualizedTreeProps, +} from 'sentry/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree'; import type {VirtualizedTreeNode} from 'sentry/utils/profiling/hooks/useVirtualizedTree/VirtualizedTreeNode'; import type {VirtualizedTreeRenderedRow} from 'sentry/utils/profiling/hooks/useVirtualizedTree/virtualizedTreeUtils'; -const enum CallTreeTableClassNames { - ROW = 'CallTreeTableRow', - CELL = 'CallTreeTableTableCell', - FRAME_CELL = 'CallTreeTableTableCellFrame', - WEIGHT = 'CallTreeTableTableCellWeight', - BACKGROUND_WEIGHT = 'CallTreeTableTableCellWeightBar', - FRAME_TYPE = 'CallTreeTableTableCellFrameType', - COLOR_INDICATOR = 'CallTreeTableTableCellColorIndicator', - EXPAND_BUTTON = 'CallTreeTableTableCellExpandButton', - GHOST_ROW_CELL = 'CallTreeTableTableCellGhostRow', - GHOST_ROW_CONTAINER = 'CallTreeTableTableCellGhostRowContainer', +const ROW_HEIGHT = 24; +const WEIGHT_COLUMN_WIDTH = 160; +const INDENT_WIDTH = 14; + +const COLUMNS: TableColumnConfig[] = [ + {key: 'weight', width: WEIGHT_COLUMN_WIDTH}, + {key: 'secondaryWeight', width: WEIGHT_COLUMN_WIDTH}, + {key: 'frame', width: 'minmax(max-content, 1fr)'}, +]; + +function scrollRowIntoView(table: HTMLTableElement, rowIndex: number) { + // The sticky header covers the top of the scroll area, so rows are measured + // against the height below it. + const visibleHeight = table.clientHeight - (table.tHead?.offsetHeight ?? 0); + const rowTop = rowIndex * ROW_HEIGHT; + + if (rowTop < table.scrollTop) { + table.scrollTop = rowTop; + } else if (rowTop + ROW_HEIGHT > table.scrollTop + visibleHeight) { + table.scrollTop = rowTop + ROW_HEIGHT - visibleHeight; + } } -export const CallTreeTable = styled('div')` - font-size: ${p => p.theme.font.size.sm}; - margin: 0; - overflow: auto; - max-height: 100%; - height: 100%; - width: 100%; - display: flex; - flex-direction: column; - background-color: ${p => p.theme.tokens.background.primary}; - - .${CallTreeTableClassNames.ROW} { - display: flex; - line-height: 24px; - font-size: 12px; - position: absolute; - width: 100%; - - &:focus { - outline: none; - } - - &[tabindex='0'] { - background: ${p => p.theme.tokens.background.accent.vibrant}; - color: #fff; - - .${CallTreeTableClassNames.WEIGHT} { - color: ${p => p.theme.colors.white}; - opacity: 0.7; - } - - .${CallTreeTableClassNames.BACKGROUND_WEIGHT} { - background-color: ${props => props.theme.colors.yellow100}; - border-bottom: 1px solid ${props => props.theme.colors.yellow200}; - } - - .${CallTreeTableClassNames.FRAME_TYPE} { - color: ${p => p.theme.colors.white}; - opacity: 0.7; - } - } - - &[data-hovered='true']:not([tabindex='0']) { - background: ${p => p.theme.tokens.background.tertiary}; - } +function scrollCallTreeTableToNode( + table: HTMLTableElement | null, + node: VirtualizedTreeRenderedRow | undefined, + coordinates?: {depth: number; top: number} +) { + if (!table) { + return; } - .${CallTreeTableClassNames.CELL} { - position: relative; - width: 164px; - border-right: 1px solid ${p => p.theme.tokens.border.primary}; - display: flex; - align-items: center; - padding-right: ${p => p.theme.space.md}; - justify-content: flex-end; - - &:focus { - outline: none; - } + if (node) { + scrollRowIntoView(table, node.key); } - .${CallTreeTableClassNames.FRAME_CELL} { - display: flex; - align-items: center; - padding-left: ${p => p.theme.space.md}; - white-space: nowrap; - - &:focus { - outline: none; - } - } - .${CallTreeTableClassNames.WEIGHT} { - display: inline-block; - min-width: 7ch; - padding-right: 0px; - color: ${p => p.theme.tokens.content.secondary}; - opacity: 1; - } - .${CallTreeTableClassNames.BACKGROUND_WEIGHT} { - pointer-events: none; - position: absolute; - right: 0; - top: 0; - background-color: ${props => props.theme.colors.yellow100}; - border-bottom: 1px solid ${props => props.theme.colors.yellow200}; - transform-origin: center right; - height: 100%; - width: 100%; + const depth = coordinates?.depth ?? node?.item.depth; + if (depth === undefined) { + return; } - .${CallTreeTableClassNames.FRAME_TYPE} { - flex-shrink: 0; - width: 26px; - height: 12px; - display: flex; - align-items: center; - justify-content: center; - color: ${p => p.theme.tokens.content.secondary}; - opacity: ${_p => 1}; + // Only scroll sideways when the row's indented content starts outside the left half + // of the frame column, so a user's own horizontal scroll survives keyboard navigation. + const indent = depth * INDENT_WIDTH; + const frameColumnWidth = table.clientWidth - 2 * WEIGHT_COLUMN_WIDTH; + if (indent < table.scrollLeft || indent > table.scrollLeft + frameColumnWidth / 2) { + table.scrollLeft = indent; } +} - .${CallTreeTableClassNames.COLOR_INDICATOR} { - width: 12px; - height: 12px; - border-radius: 2px; - display: inline-block; - flex-shrink: 0; - margin-right: ${p => p.theme.space.xs}; - } +type UseCallTreeTableProps = Omit< + UseVirtualizedTreeProps, + 'onScrollToNode' | 'rowHeight' | 'scrollContainer' +>; + +export function useCallTreeTable(props: UseCallTreeTableProps) { + const tableRef = useRef(null); + const [scrollContainer, setScrollContainer] = useState(null); + + useLayoutEffect(() => { + setScrollContainer(tableRef.current); + }, []); + + const onScrollToNode = useCallback( + ( + node: VirtualizedTreeRenderedRow | undefined, + _scrollContainer: HTMLElement | HTMLElement[] | null, + coordinates?: {depth: number; top: number} + ) => { + scrollCallTreeTableToNode(tableRef.current, node, coordinates); + }, + [] + ); - .${CallTreeTableClassNames.EXPAND_BUTTON} { - width: 10px; - height: 10px; - display: flex; - flex-shrink: 0; - padding: 0; - border: none; - background-color: transparent; - align-items: center; - justify-content: center; - user-select: none; - transform: rotate(0deg); - margin-right: ${p => p.theme.space['2xs']}; - } + const virtualizedTree = useVirtualizedTree({ + ...props, + onScrollToNode, + rowHeight: ROW_HEIGHT, + scrollContainer, + }); + + const {dispatch, handleRowKeyDown, handleRowMouseEnter, items, selectedNodeIndex} = + virtualizedTree; + + // Rows use a roving tabindex. Without a rendered selected row, the first rendered + // row takes the tab stop so keyboard users can still reach the tree. + const tabbableIndex = items.some(item => item.key === selectedNodeIndex) + ? selectedNodeIndex + : items[0]?.key; + + const getRowProps = (row: VirtualizedTreeRenderedRow) => ({ + isSelected: row.key === selectedNodeIndex, + node: row.item, + onFocus: (event: React.FocusEvent) => { + if (event.target === event.currentTarget && row.key !== selectedNodeIndex) { + dispatch({type: 'set selected node index', payload: row.key}); + if (tableRef.current) { + scrollRowIntoView(tableRef.current, row.key); + } + } + }, + onKeyDown: handleRowKeyDown, + onMouseEnter: handleRowMouseEnter(row.key), + ref: (element: HTMLTableRowElement | null) => { + row.ref = element; + }, + tabIndex: row.key === tabbableIndex ? 0 : -1, + }); + + return { + ...virtualizedTree, + getRowProps, + rowCount: virtualizedTree.tree.flattened.length, + tableRef, + }; +} - .${CallTreeTableClassNames.GHOST_ROW_CELL} { - width: 164px; - height: 100%; - border-right: 1px solid ${p => p.theme.tokens.border.primary}; - position: absolute; - left: 0; - top: 0; +interface CallTreeTableProps { + children: ReactNode; + header: ReactNode; + items: Array>; + ref: RefObject; + rowCount: number; +} - &:nth-child(2) { - left: 164px; - } - } +export function CallTreeTable({ + children, + header, + items, + ref, + rowCount, +}: CallTreeTableProps) { + const firstRenderedIndex = items[0]?.key ?? 0; + const lastRenderedIndex = items[items.length - 1]?.key ?? -1; - .${CallTreeTableClassNames.GHOST_ROW_CONTAINER} { - display: flex; - width: 100%; - pointer-events: none; - position: absolute; - height: 100%; - } -`; + return ( + + + {header} + + + {children} + + + ); +} -export const CALL_TREE_FRAME_WEIGHT_CELL_WIDTH_PX = 164; +interface CallTreeTableRowProps { + children: ReactNode; + isSelected: boolean; + node: VirtualizedTreeNode; + onClick: (event: React.MouseEvent) => void; + onContextMenu: (event: React.MouseEvent) => void; + onFocus: (event: React.FocusEvent) => void; + onKeyDown: (event: React.KeyboardEvent) => void; + onMouseEnter: (event: React.MouseEvent) => void; + ref: (element: HTMLTableRowElement | null) => void; + tabIndex: number; +} -export const CallTreeFixedColumnsContainer = styled('div')` - position: absolute; - left: 0; - top: 0; - height: 100%; - width: ${2 * CALL_TREE_FRAME_WEIGHT_CELL_WIDTH_PX}px; - overflow: hidden; - z-index: 1; - - /* Hide scrollbar so we dont end up with double scrollbars */ - > div { - -ms-overflow-style: none; /* IE and Edge */ - scrollbar-width: none; /* Firefox */ - &::-webkit-scrollbar { - display: none; - } - } -`; +export function CallTreeTableRow({ + children, + isSelected, + node, + ...props +}: CallTreeTableRowProps) { + return ( + 0 ? node.expanded : undefined} + aria-level={node.depth + 1} + aria-selected={isSelected} + > + {children} + + ); +} -export const CallTreeDynamicColumnsContainer = styled('div')` - position: absolute; - right: 0; - top: 0; - height: 100%; - width: calc(100% - ${2 * CALL_TREE_FRAME_WEIGHT_CELL_WIDTH_PX}px); - overflow: hidden; - z-index: 1; -`; +interface CallTreeTableWeightCellProps { + children: ReactNode; + isApplicationFrame?: boolean; + relativeWeight?: number; +} -export const CallTreeTableHeader = styled('div')` - top: 0; - z-index: 2; - display: flex; - flex: 1; - flex-grow: 0; - - > div { - position: relative; - border-bottom: 1px solid ${p => p.theme.tokens.border.primary}; - background-color: ${p => p.theme.tokens.background.primary}; - white-space: nowrap; - - &:last-child { - flex: 1; - } +export function CallTreeTableWeightCell({ + children, + isApplicationFrame, + relativeWeight, +}: CallTreeTableWeightCellProps) { + return ( + + {relativeWeight === undefined ? null : ( + + )} + + {children} + + {relativeWeight === undefined ? null : ( + + + {relativeWeight.toFixed(1)}% + + + )} + {isApplicationFrame === undefined ? null : isApplicationFrame ? ( + + ) : ( + + )} + + ); +} - &:not(:last-child) { - border-right: 1px solid ${p => p.theme.tokens.border.primary}; - } - } -`; +interface CallTreeTableFrameCellProps { + frameColor: string; + node: VirtualizedTreeNode; + onExpandClick: ( + node: VirtualizedTreeNode, + expand: boolean, + opts?: {expandChildren: boolean} + ) => void; +} -export const CallTreeTableHeaderButton = styled('button')` - display: flex; - width: 100%; - align-items: center; - justify-content: space-between; - padding: 0 ${p => p.theme.space.md}; - border: none; - background-color: ${p => p.theme.tokens.background.secondary}; - transition: background-color 100ms ease-in-out; - line-height: 29px; - - svg { - width: 10px; - height: 10px; - } -`; +export function CallTreeTableFrameCell({ + frameColor, + node, + onExpandClick, +}: CallTreeTableFrameCellProps) { + const theme = useTheme(); -export const CallTreeTableContainer = styled('div')` - position: relative; - height: 100%; -`; + const handleExpandClick = (event: React.MouseEvent) => { + event.stopPropagation(); + onExpandClick(node, !node.expanded, {expandChildren: event.metaKey}); + }; -type SyncCallTreeScrollParams = { - node: VirtualizedTreeRenderedRow | undefined; - scrollContainer: HTMLElement | HTMLElement[] | null; - coordinates?: {depth: number; top: number}; -}; - -// This is slighlty unfortunate and ugly, but because our two columns are sticky -// we need to scroll the container to the left when we scroll to a node. This -// should be resolved when we split the virtualization between containers and sync scroll, -// but is a larger undertaking and will take a bit longer -export function syncCallTreeTableScroll(args: SyncCallTreeScrollParams) { - if (!args.scrollContainer) { - return; - } - if (args.node) { - const lastCell = args.node.ref?.lastChild?.firstChild as - | HTMLElement - | null - | undefined; - if (lastCell) { - lastCell.scrollIntoView({ - block: 'nearest', - }); - - const left = -328 + (args.node.item.depth * 14 + 8); - if (Array.isArray(args.scrollContainer)) { - args.scrollContainer.forEach(c => { - c.scrollBy({ - left, - }); - }); - } else { - args.scrollContainer.scrollBy({ - left, - }); - } - } - } else if (args.coordinates && args.scrollContainer) { - const left = -328 + (args.coordinates.depth * 14 + 8); - - if (Array.isArray(args.scrollContainer)) { - args.scrollContainer.forEach(c => { - c.scrollBy({ - left, - }); - }); - } else { - args.scrollContainer.scrollBy({ - left, - }); - } - } + return ( + + + + {node.node.children.length > 0 ? ( + + ) : ( + + )} + {node.node.frame.name} + + + ); } export function makeCallTreeTableSortFunction( @@ -373,142 +390,57 @@ export function makeCallTreeTableSortFunction( throw new Error(`Unknown sort property ${property}`); } -const TEXT_ALIGN_RIGHT: React.CSSProperties = {textAlign: 'right'}; +// Sizing the container by its own layout instead of the table's rows keeps the +// table scrolling inside it, which is what keeps the rows virtualized. +export const CallTreeTableContainer = styled('div')` + contain: size; + position: relative; + flex: 1 1 100%; + width: 100%; +`; -interface CallTreeTableRowProps { - children: React.ReactNode; - onClick: (e: React.MouseEvent) => void; - onContextMenu: (e: React.MouseEvent) => void; - onKeyDown: (e: React.KeyboardEvent) => void; - onMouseEnter: (e: React.MouseEvent) => void; - tabIndex: number; - top: CSS['inset']; - ref?: React.Ref; -} -export function CallTreeTableRow({ref, ...props}: CallTreeTableRowProps) { - return ( -
- {props.children} -
- ); -} +// The weight columns stay pinned while deep frames scroll horizontally. +const StickyWeightsTable = styled(SimpleTable)` + tr > :nth-child(-n + 2) { + position: sticky; + z-index: 1; + align-self: stretch; + background: inherit; + border-right: 1px solid ${p => p.theme.tokens.border.primary}; + } -interface BaseCallTreeTableColumns { - formatDuration: (value: number) => string; - frameColor: string; - node: VirtualizedTreeNode; - onExpandClick: ( - node: VirtualizedTreeNode, - expand: boolean, - opts?: {expandChildren: boolean} - ) => void; - referenceNode: FlamegraphFrame; - tabIndex: number; - type: 'count' | 'time'; -} + tr > :first-child { + left: 0; + } -interface CallTreeTableColumns extends BaseCallTreeTableColumns { - relativeSelfWeight: number; - relativeTotalWeight: number; - selfWeight: number | React.ReactNode; - totalWeight: number | React.ReactNode; - avgWeight?: React.ReactNode; - showAvg?: boolean; -} + tr > :nth-child(2) { + left: ${WEIGHT_COLUMN_WIDTH}px; + } +`; -export function CallTreeTableFixedColumns(props: CallTreeTableColumns) { - return ( - -
- {typeof props.selfWeight === 'number' - ? props.formatDuration(props.selfWeight) - : props.selfWeight} -
- {props.relativeSelfWeight.toFixed(1)}% -
-
-
-
- {props.showAvg ? ( - defined(props.avgWeight) ? ( - props.avgWeight - ) : ( - {t('Unknown')} - ) - ) : ( - - {typeof props.totalWeight === 'number' - ? props.formatDuration(props.totalWeight) - : props.totalWeight} -
- {props.relativeTotalWeight.toFixed(1)}% -
-
-
- {props.node.node.node.frame.is_application ? ( - - ) : ( - - )} -
- - )} -
-
- ); -} +const TreeRow = styled(SimpleTable.Row)` + height: ${ROW_HEIGHT}px; + background: ${p => p.theme.tokens.background.primary}; -export function CallTreeTableDynamicColumns(props: BaseCallTreeTableColumns) { - const handleExpanding = (evt: React.MouseEvent) => { - evt.stopPropagation(); - props.onExpandClick(props.node, !props.node.expanded, { - expandChildren: evt.metaKey, - }); - }; + &[data-hovered='true']:not([aria-selected='true']) { + background: ${p => p.theme.tokens.background.tertiary}; + } - return ( -
-
- -
-
{props.node.node.frame.name}
-
-
- ); -} + &[aria-selected='true'] { + background: ${p => p.theme.tokens.background.accent.vibrant}; + color: ${p => p.theme.tokens.content.onVibrant.light}; -export function CallTreeTableGhostRow() { - return ( -
-
-
-
- ); -} + * { + color: inherit; + } + } +`; + +const WeightBar = styled('div')` + position: absolute; + inset: 0; + background-color: ${p => p.theme.colors.yellow100}; + border-bottom: 1px solid ${p => p.theme.colors.yellow200}; + transform-origin: center right; + pointer-events: none; +`; diff --git a/static/app/components/profiling/flamegraph/flamegraphDrawer/flamegraphTreeTable.spec.tsx b/static/app/components/profiling/flamegraph/flamegraphDrawer/flamegraphTreeTable.spec.tsx new file mode 100644 index 000000000000..bb6d359c3e27 --- /dev/null +++ b/static/app/components/profiling/flamegraph/flamegraphDrawer/flamegraphTreeTable.spec.tsx @@ -0,0 +1,190 @@ +import {makeFlamegraph} from 'sentry-test/profiling/utils'; +import {act, render, screen, userEvent, within} from 'sentry-test/reactTestingLibrary'; + +import {FlamegraphTreeTable} from 'sentry/components/profiling/flamegraph/flamegraphDrawer/flamegraphTreeTable'; +import {CanvasPoolManager, CanvasScheduler} from 'sentry/utils/profiling/canvasScheduler'; + +const flamegraph = makeFlamegraph( + { + endValue: 10, + events: [ + {type: 'O', at: 0, frame: 0}, + {type: 'O', at: 1, frame: 1}, + {type: 'O', at: 2, frame: 2}, + {type: 'C', at: 4, frame: 2}, + {type: 'C', at: 6, frame: 1}, + {type: 'O', at: 6, frame: 3}, + {type: 'C', at: 8, frame: 3}, + {type: 'C', at: 10, frame: 0}, + ], + }, + [{name: 'root'}, {name: 'parent'}, {name: 'child'}, {name: 'another'}] +); + +function renderTreeTable() { + const canvasPoolManager = new CanvasPoolManager(); + const canvasScheduler = new CanvasScheduler(); + + render( + 'red'} + onBottomUpClick={jest.fn()} + onTopDownClick={jest.fn()} + recursion={null} + referenceNode={flamegraph.root} + tree={flamegraph.root.children} + /> + ); + + return {canvasPoolManager, canvasScheduler}; +} + +function getRow(frameName: string) { + return screen.getByRole('row', {name: new RegExp(frameName)}); +} + +function getFrameNames() { + return screen + .getAllByRole('row') + .slice(1) + .map(row => within(row).getAllByRole('gridcell')[2]?.textContent?.replace('›', '')); +} + +describe('FlamegraphTreeTable', () => { + beforeEach(() => { + Element.prototype.scrollTo = jest.fn(); + }); + + it('renders root frames as collapsed tree rows when the tree is not expanded', () => { + renderTreeTable(); + + expect(screen.getByRole('treegrid', {name: 'Call tree'})).toBeInTheDocument(); + expect(getFrameNames()).toEqual(['root']); + expect(getRow('root')).toHaveAttribute('aria-level', '1'); + expect(getRow('root')).toHaveAttribute('aria-expanded', 'false'); + }); + + it('shows the children of a frame when its expand button is clicked', async () => { + renderTreeTable(); + + await userEvent.click(within(getRow('root')).getByRole('button', {name: 'Expand'})); + + expect(getFrameNames()).toEqual(['root', 'parent', 'another']); + expect(getRow('root')).toHaveAttribute('aria-expanded', 'true'); + expect(getRow('parent')).toHaveAttribute('aria-level', '2'); + expect(getRow('another')).not.toHaveAttribute('aria-expanded'); + }); + + it('expands every descendant when the expand button is clicked with the meta key', async () => { + renderTreeTable(); + const user = userEvent.setup(); + + await user.keyboard('{Meta>}'); + await user.click(within(getRow('root')).getByRole('button', {name: 'Expand'})); + await user.keyboard('{/Meta}'); + + expect(getFrameNames()).toEqual(['root', 'parent', 'child', 'another']); + }); + + it('expands and moves the selection when arrow keys are pressed on a selected row', async () => { + renderTreeTable(); + + await userEvent.click(within(getRow('root')).getByRole('button', {name: 'Expand'})); + await userEvent.click(getRow('parent')); + await userEvent.keyboard('{ArrowRight}'); + await userEvent.keyboard('{ArrowDown}'); + + expect(getFrameNames()).toEqual(['root', 'parent', 'child', 'another']); + expect(getRow('parent')).toHaveAttribute('aria-selected', 'false'); + expect(getRow('child')).toHaveAttribute('aria-selected', 'true'); + expect(getRow('child')).toHaveFocus(); + }); + + it('selects the first row when it is tabbed to without a selection', async () => { + renderTreeTable(); + + act(() => screen.getByRole('button', {name: 'Frame'}).focus()); + await userEvent.tab(); + await userEvent.keyboard('{Enter}'); + + expect(getRow('root')).toHaveFocus(); + expect(getRow('root')).toHaveAttribute('aria-selected', 'true'); + expect(getFrameNames()).toEqual(['root', 'parent', 'another']); + }); + + it('keeps the horizontal scroll position when a row is clicked', async () => { + renderTreeTable(); + await userEvent.click(within(getRow('root')).getByRole('button', {name: 'Expand'})); + const table = screen.getByRole('treegrid', {name: 'Call tree'}); + table.scrollLeft = 100; + + await userEvent.click(getRow('parent')); + + expect(getRow('parent')).toHaveAttribute('aria-selected', 'true'); + expect(table.scrollLeft).toBe(100); + }); + + it('keeps the horizontal scroll position when an arrow key selects a row whose indent is in view', async () => { + renderTreeTable(); + await userEvent.click(within(getRow('root')).getByRole('button', {name: 'Expand'})); + const table = screen.getByRole('treegrid', {name: 'Call tree'}); + jest.spyOn(table, 'clientWidth', 'get').mockReturnValue(800); + await userEvent.click(getRow('parent')); + table.scrollLeft = 10; + + await userEvent.keyboard('{ArrowDown}'); + + expect(getRow('another')).toHaveAttribute('aria-selected', 'true'); + expect(table.scrollLeft).toBe(10); + }); + + it('scrolls to the indent when an arrow key selects a row whose indent is out of view', async () => { + renderTreeTable(); + await userEvent.click(within(getRow('root')).getByRole('button', {name: 'Expand'})); + const table = screen.getByRole('treegrid', {name: 'Call tree'}); + jest.spyOn(table, 'clientWidth', 'get').mockReturnValue(800); + await userEvent.click(getRow('parent')); + table.scrollLeft = 300; + + await userEvent.keyboard('{ArrowDown}'); + + expect(getRow('another')).toHaveAttribute('aria-selected', 'true'); + expect(table.scrollLeft).toBe(14); + }); + + it('sorts frames by name when the frame header is clicked', async () => { + renderTreeTable(); + + await userEvent.click(within(getRow('root')).getByRole('button', {name: 'Expand'})); + await userEvent.click(screen.getByRole('button', {name: 'Frame'})); + + expect(getFrameNames()).toEqual(['root', 'another', 'parent']); + }); + + it('selects and reveals a frame when the flamegraph shows it in the table', () => { + const {canvasScheduler} = renderTreeTable(); + const child = flamegraph.frames.find(frame => frame.frame.name === 'child')!; + + act(() => canvasScheduler.dispatch('show in table view', child)); + + expect(getFrameNames()).toEqual(['root', 'parent', 'child', 'another']); + expect(getRow('child')).toHaveAttribute('aria-selected', 'true'); + }); + + it('zooms to a frame on the flamegraph when chosen from its context menu', async () => { + const {canvasPoolManager} = renderTreeTable(); + const dispatch = jest.spyOn(canvasPoolManager, 'dispatch'); + + await userEvent.pointer({keys: '[MouseRight]', target: getRow('root')}); + await userEvent.click(screen.getByRole('menuitem', {name: 'Show on flamegraph'})); + + expect(dispatch).toHaveBeenCalledWith('zoom at frame', [ + flamegraph.root.children[0], + 'exact', + ]); + }); +}); diff --git a/static/app/components/profiling/flamegraph/flamegraphDrawer/flamegraphTreeTable.tsx b/static/app/components/profiling/flamegraph/flamegraphDrawer/flamegraphTreeTable.tsx index 59c15ba5e435..7d05177e9035 100644 --- a/static/app/components/profiling/flamegraph/flamegraphDrawer/flamegraphTreeTable.tsx +++ b/static/app/components/profiling/flamegraph/flamegraphDrawer/flamegraphTreeTable.tsx @@ -1,26 +1,19 @@ import type React from 'react'; -import {useCallback, useEffect, useMemo, useState} from 'react'; +import {Fragment, useCallback, useEffect, useMemo, useState} from 'react'; import styled from '@emotion/styled'; -import {IconArrow} from '@sentry/icons/arrow'; import {InfoTip} from '@sentry/scraps/info'; -import InteractionStateLayer from '@sentry/scraps/interactionStateLayer'; import { - CALL_TREE_FRAME_WEIGHT_CELL_WIDTH_PX, - CallTreeDynamicColumnsContainer, - CallTreeFixedColumnsContainer, CallTreeTable, CallTreeTableContainer, - CallTreeTableDynamicColumns, - CallTreeTableFixedColumns, - CallTreeTableGhostRow, - CallTreeTableHeader, - CallTreeTableHeaderButton, + CallTreeTableFrameCell, CallTreeTableRow, + CallTreeTableWeightCell, makeCallTreeTableSortFunction, - syncCallTreeTableScroll, + useCallTreeTable, } from 'sentry/components/profiling/flamegraph/callTreeTable'; +import {SimpleTable} from 'sentry/components/tables/simpleTable'; import {t} from 'sentry/locale'; import type { CanvasPoolManager, @@ -29,10 +22,7 @@ import type { import type {Flamegraph} from 'sentry/utils/profiling/flamegraph'; import type {FlamegraphFrame} from 'sentry/utils/profiling/flamegraphFrame'; import {useContextMenu} from 'sentry/utils/profiling/hooks/useContextMenu'; -import type {UseVirtualizedTreeProps} from 'sentry/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree'; -import {useVirtualizedTree} from 'sentry/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree'; import type {VirtualizedTreeNode} from 'sentry/utils/profiling/hooks/useVirtualizedTree/VirtualizedTreeNode'; -import type {VirtualizedTreeRenderedRow} from 'sentry/utils/profiling/hooks/useVirtualizedTree/virtualizedTreeUtils'; import {relativeWeight} from 'sentry/utils/profiling/units/units'; import {FlamegraphTreeContextMenu} from './flamegraphTreeContextMenu'; @@ -67,11 +57,6 @@ export function FlamegraphTreeTable({ onBottomUpClick, onTopDownClick, }: FlamegraphTreeTableProps) { - const [scrollContainerRef, setFixedScrollContainerRef] = - useState(null); - const [dynamicScrollContainerRef, setDynamicScrollContainerRef] = - useState(null); - const [sort, setSort] = useState<'total weight' | 'self weight' | 'name'>( 'total weight' ); @@ -126,131 +111,19 @@ export function FlamegraphTreeTable({ ]); }, [canvasPoolManager, clickedContextMenuNode, flamegraph]); - const fixedRenderRow: UseVirtualizedTreeProps['renderRow'] = - useCallback( - ( - r: any, - { - handleRowClick, - handleRowMouseEnter, - handleExpandTreeNode, - handleRowKeyDown, - selectedNodeIndex, - }: any - ) => { - return ( - { - r.ref = n; - }} - top={r.styles.top} - tabIndex={selectedNodeIndex === r.key ? 0 : 1} - onKeyDown={handleRowKeyDown} - onClick={handleRowClick} - onMouseEnter={handleRowMouseEnter} - onContextMenu={onRowContextMenu(r.item)} - > - - - ); - }, - [referenceNode, flamegraph.formatter, getFrameColor, onRowContextMenu] - ); - - const dynamicRenderRow: UseVirtualizedTreeProps['renderRow'] = - useCallback( - ( - r: any, - { - handleRowClick, - handleRowMouseEnter, - handleExpandTreeNode, - handleRowKeyDown, - selectedNodeIndex, - }: any - ) => { - return ( - { - r.ref = n; - }} - top={r.styles.top} - tabIndex={selectedNodeIndex === r.key ? 0 : 1} - onKeyDown={handleRowKeyDown} - onClick={handleRowClick} - onMouseEnter={handleRowMouseEnter} - onContextMenu={onRowContextMenu(r.item)} - > - - - ); - }, - [referenceNode, flamegraph.formatter, getFrameColor, onRowContextMenu] - ); - const onScrollToNode: UseVirtualizedTreeProps['onScrollToNode'] = - useCallback( - ( - node: VirtualizedTreeRenderedRow | undefined, - scrollContainer: HTMLElement | HTMLElement[] | null, - coordinates?: {depth: number; top: number} - ) => { - syncCallTreeTableScroll({node, scrollContainer, coordinates}); - }, - [] - ); - - const scrollContainers = useMemo(() => { - return [scrollContainerRef, dynamicScrollContainerRef].filter(c => !!c); - }, [dynamicScrollContainerRef, scrollContainerRef]); - const { items: renderItems, - scrollContainerStyles: scrollContainerStyles, - containerStyles: fixedContainerStyles, + rowCount, + tableRef, handleSortingChange, handleScrollTo, handleExpandTreeNode, handleRowClick, - handleRowKeyDown, - handleRowMouseEnter, - selectedNodeIndex, - clickedGhostRowRef: clickedGhostRowRef, - hoveredGhostRowRef: hoveredGhostRowRef, - } = useVirtualizedTree({ + getRowProps, + } = useCallTreeTable({ expanded, skipFunction: recursion === 'collapsed' ? skipRecursiveNodes : undefined, sortFunction, - onScrollToNode, - scrollContainer: scrollContainers, - rowHeight: 24, tree, }); @@ -279,120 +152,94 @@ export function FlamegraphTreeTable({ }, [canvasScheduler, handleScrollTo]); return ( - - - - - onSortChange('self weight')}> - - - {t('Self Time')}{' '} - - - {sort === 'self weight' ? ( - - ) : null} - - - - onSortChange('total weight')}> - - - {t('Total Time')}{' '} - - - {sort === 'total weight' ? ( - - ) : null} - - -
- onSortChange('name')}> - - {t('Frame')}{' '} - {sort === 'name' ? ( - - ) : null} - -
-
- - - - {/* - The order of these two matters because we want clicked state to - be on top of hover in cases where user is hovering a clicked row. - */} -
-
- {renderItems.map(r => { - return fixedRenderRow(r, { - handleRowClick: handleRowClick(r.key), - handleRowMouseEnter: handleRowMouseEnter(r.key), - handleExpandTreeNode, - handleRowKeyDown, - selectedNodeIndex, - }); - })} - -
-
-
- - {/* - The order of these two matters because we want clicked state to - be on top of hover in cases where user is hovering a clicked row. - */} -
-
- {renderItems.map(r => { - return dynamicRenderRow(r, { - handleRowClick: handleRowClick(r.key), - handleRowMouseEnter: handleRowMouseEnter(r.key), - handleExpandTreeNode, - handleRowKeyDown, - selectedNodeIndex, - }); - })} -
-
-
-
-
- + + + + onSortChange('self weight')} + sort={sort === 'self weight' ? direction : undefined} + > + {t('Self Time')}{' '} + + + onSortChange('total weight')} + sort={sort === 'total weight' ? direction : undefined} + > + {t('Total Time')}{' '} + + + onSortChange('name')} + sort={sort === 'name' ? direction : undefined} + > + {t('Frame')} + + + } + > + {renderItems.map(r => ( + + + {flamegraph.formatter(r.item.node.node.selfWeight)} + + + {flamegraph.formatter(r.item.node.node.totalWeight)} + + + + ))} ); } -const FrameBar = styled('div')` - overflow: auto; - width: 100%; - position: relative; - background-color: ${p => p.theme.tokens.background.tertiary}; - border-top: 1px solid ${p => p.theme.tokens.border.primary}; - flex: 1 1 100%; +const FrameBar = styled(CallTreeTableContainer)` grid-area: table; `; - -const FrameWeightCell = styled('div')` - width: ${CALL_TREE_FRAME_WEIGHT_CELL_WIDTH_PX}px; -`; diff --git a/static/app/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree.spec.tsx b/static/app/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree.spec.tsx index ba93e4340e30..545e76491385 100644 --- a/static/app/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree.spec.tsx +++ b/static/app/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree.spec.tsx @@ -257,4 +257,52 @@ describe('useVirtualizedTree', () => { stableKeys[stableKeys.length - 1]! + 1 ); }); + + it('scrolls to a node after expanding its ancestors', () => { + const scrollContainer = document.createElement('div'); + scrollContainer.scrollTo = jest.fn(); + const onScrollToNode = jest.fn(); + + const {result} = renderHook(useVirtualizedTree, { + initialProps: { + rowHeight: 10, + scrollContainer, + overscroll: 0, + tree: [chain('child', 20)], + onScrollToNode, + }, + }); + + act(() => { + result.current.handleScrollTo(node => node.id === 'child-15'); + }); + + expect(result.current.tree.flattened).toHaveLength(16); + expect(result.current.selectedNodeIndex).toBe(15); + expect(scrollContainer.scrollTo).toHaveBeenCalledWith({top: 160}); + expect(onScrollToNode).toHaveBeenCalledTimes(1); + expect(onScrollToNode.mock.calls[0]?.slice(1)).toEqual([ + scrollContainer, + {top: 160, depth: 15}, + ]); + }); + + it('keeps the first row selected when it is expanded', () => { + const {result} = renderHook(useVirtualizedTree, { + initialProps: { + rowHeight: 10, + scrollContainer: makeScrollContainerMock({height: 100}), + overscroll: 0, + tree: [chain('child', 3)], + initialSelectedNodeIndex: 0, + }, + }); + + act(() => { + result.current.handleExpandTreeNode(result.current.tree.roots[0]!, true); + }); + + expect(result.current.tree.flattened).toHaveLength(2); + expect(result.current.selectedNodeIndex).toBe(0); + }); }); diff --git a/static/app/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree.tsx b/static/app/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree.tsx index efd800c0c20c..7ce403671821 100644 --- a/static/app/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree.tsx +++ b/static/app/utils/profiling/hooks/useVirtualizedTree/useVirtualizedTree.tsx @@ -1,4 +1,12 @@ -import {useCallback, useEffect, useMemo, useReducer, useRef, useState} from 'react'; +import { + useCallback, + useEffect, + useLayoutEffect, + useMemo, + useReducer, + useRef, + useState, +} from 'react'; import {useTheme} from '@emotion/react'; import {useEffectAfterFirstRender} from 'sentry/utils/useEffectAfterFirstRender'; @@ -56,6 +64,22 @@ function scrollToTop(top: number, containers: MaybeContainers) { }); } +// Rows in a table scroll container start below its border and header, not at its top. +function getRowIndexAtClientY( + container: HTMLElement, + clientY: number, + scrollTop: number, + rowHeight: number +) { + const rowsTop = + container instanceof HTMLTableElement + ? container.clientTop + (container.tHead?.offsetHeight ?? 0) + : 0; + return Math.floor( + (scrollTop + clientY - container.getBoundingClientRect().top - rowsTop) / rowHeight + ); +} + function addListenerToContainer( container: MaybeContainers, type: string, @@ -122,6 +146,11 @@ export function useVirtualizedTree( const theme = useTheme(); const clickedGhostRowRef = useRef(null); const hoveredGhostRowRef = useRef(null); + const pendingScrollRef = useRef<{ + depth: number; + index: number; + scrollTop: number; + } | null>(null); const [state, dispatch] = useReducer(VirtualizedTreeReducer, { scrollTop: 0, @@ -372,9 +401,11 @@ export function useVirtualizedTree( return; } - const rect = (evt.target as HTMLDivElement).getBoundingClientRect(); - const index = Math.floor( - (latestStateRef.current.scrollTop + evt.clientY - rect.top) / props.rowHeight + const index = getRowIndexAtClientY( + evt.target as HTMLElement, + evt.clientY, + latestStateRef.current.scrollTop, + props.rowHeight ); // If a node exists at the index, select it @@ -399,9 +430,11 @@ export function useVirtualizedTree( return; } - const rect = (evt.target as HTMLDivElement).getBoundingClientRect(); - const index = Math.floor( - (latestStateRef.current.scrollTop + evt.clientY - rect.top) / props.rowHeight + const index = getRowIndexAtClientY( + evt.target as HTMLElement, + evt.clientY, + latestStateRef.current.scrollTop, + props.rowHeight ); const element = latestItemsRef.current.find(item => item.key === index); @@ -491,10 +524,11 @@ export function useVirtualizedTree( // When we expand nodes, tree.expand will mutate the underlying tree which then // gets copied to the new tree instance. To get the right index, we need to read // it before any mutations are made - const previousNode = latestStateRef.current.selectedNodeIndex - ? (latestTreeRef.current.flattened[latestStateRef.current.selectedNodeIndex] ?? - null) - : null; + const previousNode = + latestStateRef.current.selectedNodeIndex === null + ? null + : (latestTreeRef.current.flattened[latestStateRef.current.selectedNodeIndex] ?? + null); latestTreeRef.current.expandNode(node, expand, opts); const newTree = new VirtualizedTree( @@ -527,10 +561,11 @@ export function useVirtualizedTree( // When we sort nodes, tree.sort will mutate the underlying tree which then // gets copied to the new tree instance. To get the right index, we need to read // it before any mutations are made - const previousNode = latestStateRef.current.selectedNodeIndex - ? (latestTreeRef.current.flattened[latestStateRef.current.selectedNodeIndex] ?? - null) - : null; + const previousNode = + latestStateRef.current.selectedNodeIndex === null + ? null + : (latestTreeRef.current.flattened[latestStateRef.current.selectedNodeIndex] ?? + null); latestTreeRef.current.sort(sortFn); const newTree = new VirtualizedTree( @@ -767,64 +802,48 @@ export function useVirtualizedTree( theme, }); - const newMaxHeight = newTree.flattened.length * props.rowHeight; + // A view larger than the previous one has to render before it can be + // scrolled to its new position, or the scroll is clamped to the previous + // scroll height, so the scroll waits for the next commit. + pendingScrollRef.current = { + depth: node.depth, + index: newlyVisibleIndex, + scrollTop: newScrollTop, + }; + }, - // When a new view is larger than the previous view, we need to update the scroll height - // synchronously so that the view can be scrolled to its new position. If we don't do this, - // then the scrollTo(newScrollTop) will be clamped to the previous scroll height. - if (Array.isArray(props.scrollContainer)) { - props.scrollContainer.forEach(container => { - const firstChild = container?.childNodes?.[0] as HTMLElement | undefined; - if (!firstChild) { - return; - } + [props.rowHeight, props.scrollContainer, theme] + ); - firstChild.style.height = `${newMaxHeight}px`; - firstChild.style.maxHeight = `${newMaxHeight}px`; - }); - } else { - if (props.scrollContainer?.childNodes[0]) { - // Not exactly sure why we need the cast here, maybe we should limit HTMLElement to HTMLDivElement. - // https://stackoverflow.com/questions/58773652/ts2339-property-style-does-not-exist-on-type-element - const firstChild = props.scrollContainer?.childNodes?.[0] as - | HTMLElement - | undefined; - - if (!firstChild) { - return; - } - // oxlint-disable-next-line react/immutability - firstChild.style.height = `${newMaxHeight}px`; - firstChild.style.maxHeight = `${newMaxHeight}px`; - } - } + useLayoutEffect(() => { + const pendingScroll = pendingScrollRef.current; + if (!pendingScroll || !props.scrollContainer) { + return; + } - if (Array.isArray(props.scrollContainer)) { - props.scrollContainer.forEach(container => { - container.scrollTo({ - top: newScrollTop, - }); - }); - } else { - props.scrollContainer.scrollTo({ - top: newScrollTop, + pendingScrollRef.current = null; + + if (Array.isArray(props.scrollContainer)) { + props.scrollContainer.forEach(container => { + container.scrollTo({ + top: pendingScroll.scrollTop, }); - } + }); + } else { + props.scrollContainer.scrollTo({ + top: pendingScroll.scrollTop, + }); + } - if (onScrollToNode) { - onScrollToNode( - latestItemsRef.current.find(item => item.key === newlyVisibleIndex), - props.scrollContainer, - { - top: newScrollTop, - depth: node.depth, - } - ); + onScrollToNode?.( + latestItemsRef.current.find(item => item.key === pendingScroll.index), + props.scrollContainer, + { + top: pendingScroll.scrollTop, + depth: pendingScroll.depth, } - }, - - [props.rowHeight, onScrollToNode, props.scrollContainer, theme] - ); + ); + }); // Basic required styles for the scroll container const scrollContainerStyles: React.CSSProperties = useMemo(() => { diff --git a/static/app/views/explore/profiling/landingAggregateFlamegraph.tsx b/static/app/views/explore/profiling/landingAggregateFlamegraph.tsx index 7b5e0b081694..36c9c2d87c6b 100644 --- a/static/app/views/explore/profiling/landingAggregateFlamegraph.tsx +++ b/static/app/views/explore/profiling/landingAggregateFlamegraph.tsx @@ -334,7 +334,6 @@ export function LandingAggregateFlamegraph({ )}