UNPKG

@grafana/flamegraph

Version:

Grafana flamegraph visualization component

1 lines • 445 kB
{"version":3,"file":"index.cjs","sources":["../../src/constants.ts","../../src/FlameGraph/FlameGraphContextMenu.tsx","../../src/FlameGraph/FlameGraphTooltip.tsx","../../src/types.ts","../../src/FlameGraph/murmur3.ts","../../src/FlameGraph/colors.ts","../../src/FlameGraph/rendering.ts","../../src/FlameGraph/FlameGraphCanvas.tsx","../../src/FlameGraph/FlameGraphMetadata.tsx","../../src/FlameGraph/FlameGraph.tsx","../../src/FlameGraph/treeTransforms.ts","../../src/FlameGraph/dataTransform.ts","../../src/FlameGraphHeader.tsx","../../src/TopTable/FlameGraphTopTableContainer.tsx","../../src/FlameGraphContainer.tsx","../../src/FlameGraph/testData/dataNestedSet.ts"],"sourcesContent":["export const PIXELS_PER_LEVEL = 22 * window.devicePixelRatio;\nexport const MUTE_THRESHOLD = 10 * window.devicePixelRatio;\nexport const HIDE_THRESHOLD = 0.5 * window.devicePixelRatio;\nexport const LABEL_THRESHOLD = 20 * window.devicePixelRatio;\nexport const BAR_BORDER_WIDTH = 0.5 * window.devicePixelRatio;\nexport const BAR_TEXT_PADDING_LEFT = 4 * window.devicePixelRatio;\nexport const GROUP_STRIP_WIDTH = 3 * window.devicePixelRatio;\nexport const GROUP_STRIP_PADDING = 3 * window.devicePixelRatio;\nexport const GROUP_STRIP_MARGIN_LEFT = 4 * window.devicePixelRatio;\nexport const GROUP_TEXT_OFFSET = 2 * window.devicePixelRatio;\nexport const MIN_WIDTH_TO_SHOW_BOTH_TOPTABLE_AND_FLAMEGRAPH = 800;\nexport const TOP_TABLE_COLUMN_WIDTH = 120;\n","import { DataFrame } from '@grafana/data';\nimport { MenuItem, MenuGroup, ContextMenu, IconName } from '@grafana/ui';\n\nimport { ClickedItemData, SelectedView } from '../types';\n\nimport { CollapseConfig, FlameGraphDataContainer } from './dataTransform';\n\nexport type GetExtraContextMenuButtonsFunction = (\n clickedItemData: ClickedItemData,\n data: DataFrame,\n state: { selectedView: SelectedView; isDiff: boolean; search: string; collapseConfig?: CollapseConfig }\n) => ExtraContextMenuButton[];\n\nexport type ExtraContextMenuButton = {\n label: string;\n icon: IconName;\n onClick: () => void;\n};\n\ntype Props = {\n data: FlameGraphDataContainer;\n itemData: ClickedItemData;\n onMenuItemClick: () => void;\n onItemFocus: () => void;\n onSandwich: () => void;\n onExpandGroup: () => void;\n onCollapseGroup: () => void;\n onExpandAllGroups: () => void;\n onCollapseAllGroups: () => void;\n getExtraContextMenuButtons?: GetExtraContextMenuButtonsFunction;\n collapseConfig?: CollapseConfig;\n collapsing?: boolean;\n allGroupsCollapsed?: boolean;\n allGroupsExpanded?: boolean;\n selectedView: SelectedView;\n search: string;\n};\n\nconst FlameGraphContextMenu = ({\n data,\n itemData,\n onMenuItemClick,\n onItemFocus,\n onSandwich,\n collapseConfig,\n onExpandGroup,\n onCollapseGroup,\n onExpandAllGroups,\n onCollapseAllGroups,\n getExtraContextMenuButtons,\n collapsing,\n allGroupsExpanded,\n allGroupsCollapsed,\n selectedView,\n search,\n}: Props) => {\n function renderItems() {\n const extraButtons =\n getExtraContextMenuButtons?.(itemData, data.data, {\n selectedView,\n isDiff: data.isDiffFlamegraph(),\n search,\n collapseConfig,\n }) || [];\n return (\n <>\n <MenuItem\n label=\"Focus block\"\n icon={'eye'}\n onClick={() => {\n onItemFocus();\n onMenuItemClick();\n }}\n />\n <MenuItem\n label=\"Copy function name\"\n icon={'copy'}\n onClick={() => {\n navigator.clipboard.writeText(itemData.label).then(() => {\n onMenuItemClick();\n });\n }}\n />\n <MenuItem\n label=\"Sandwich view\"\n icon={'gf-show-context'}\n onClick={() => {\n onSandwich();\n onMenuItemClick();\n }}\n />\n {extraButtons.map(({ label, icon, onClick }) => {\n return <MenuItem label={label} icon={icon} onClick={() => onClick()} key={label} />;\n })}\n {collapsing && (\n <MenuGroup label={'Grouping'}>\n {collapseConfig ? (\n collapseConfig.collapsed ? (\n <MenuItem\n label=\"Expand group\"\n icon={'angle-double-down'}\n onClick={() => {\n onExpandGroup();\n onMenuItemClick();\n }}\n />\n ) : (\n <MenuItem\n label=\"Collapse group\"\n icon={'angle-double-up'}\n onClick={() => {\n onCollapseGroup();\n onMenuItemClick();\n }}\n />\n )\n ) : null}\n {!allGroupsExpanded && (\n <MenuItem\n label=\"Expand all groups\"\n icon={'angle-double-down'}\n onClick={() => {\n onExpandAllGroups();\n onMenuItemClick();\n }}\n />\n )}\n {!allGroupsCollapsed && (\n <MenuItem\n label=\"Collapse all groups\"\n icon={'angle-double-up'}\n onClick={() => {\n onCollapseAllGroups();\n onMenuItemClick();\n }}\n />\n )}\n </MenuGroup>\n )}\n </>\n );\n }\n\n return (\n <div data-testid=\"contextMenu\">\n <ContextMenu\n renderMenuItems={renderItems}\n x={itemData.posX + 10}\n y={itemData.posY}\n focusOnOpen={false}\n ></ContextMenu>\n </div>\n );\n};\n\nexport default FlameGraphContextMenu;\n","import { css } from '@emotion/css';\n\nimport { DisplayValue, getValueFormat, GrafanaTheme2 } from '@grafana/data';\nimport { InteractiveTable, Portal, useStyles2, VizTooltipContainer } from '@grafana/ui';\n\nimport { CollapseConfig, FlameGraphDataContainer, LevelItem } from './dataTransform';\n\ntype Props = {\n data: FlameGraphDataContainer;\n totalTicks: number;\n position?: { x: number; y: number };\n item?: LevelItem;\n collapseConfig?: CollapseConfig;\n};\n\nconst FlameGraphTooltip = ({ data, item, totalTicks, position, collapseConfig }: Props) => {\n const styles = useStyles2(getStyles);\n\n if (!(item && position)) {\n return null;\n }\n\n let content;\n\n if (data.isDiffFlamegraph()) {\n const tableData = getDiffTooltipData(data, item, totalTicks);\n content = (\n <InteractiveTable\n className={styles.tooltipTable}\n columns={[\n { id: 'label', header: '' },\n { id: 'baseline', header: 'Baseline' },\n { id: 'comparison', header: 'Comparison' },\n { id: 'diff', header: 'Diff' },\n ]}\n data={tableData}\n getRowId={(originalRow) => originalRow.rowId}\n />\n );\n } else {\n const tooltipData = getTooltipData(data, item, totalTicks);\n content = (\n <p className={styles.lastParagraph}>\n {tooltipData.unitTitle}\n <br />\n Total: <b>{tooltipData.unitValue}</b> ({tooltipData.percentValue}%)\n <br />\n Self: <b>{tooltipData.unitSelf}</b> ({tooltipData.percentSelf}%)\n <br />\n Samples: <b>{tooltipData.samples}</b>\n </p>\n );\n }\n\n return (\n <Portal>\n <VizTooltipContainer className={styles.tooltipContainer} position={position} offset={{ x: 15, y: 0 }}>\n <div className={styles.tooltipContent}>\n <p className={styles.tooltipName}>\n {data.getLabel(item.itemIndexes[0])}\n {collapseConfig && collapseConfig.collapsed ? (\n <span>\n <br />\n and {collapseConfig.items.length} similar items\n </span>\n ) : (\n ''\n )}\n </p>\n {content}\n </div>\n </VizTooltipContainer>\n </Portal>\n );\n};\n\ntype TooltipData = {\n percentValue: number;\n percentSelf: number;\n unitTitle: string;\n unitValue: string;\n unitSelf: string;\n samples: string;\n};\n\nexport const getTooltipData = (data: FlameGraphDataContainer, item: LevelItem, totalTicks: number): TooltipData => {\n const displayValue = data.valueDisplayProcessor(item.value);\n const displaySelf = data.getSelfDisplay(item.itemIndexes);\n\n const percentValue = Math.round(10000 * (displayValue.numeric / totalTicks)) / 100;\n const percentSelf = Math.round(10000 * (displaySelf.numeric / totalTicks)) / 100;\n let unitValue = displayValue.text + displayValue.suffix;\n let unitSelf = displaySelf.text + displaySelf.suffix;\n\n const unitTitle = data.getUnitTitle();\n if (unitTitle === 'Count') {\n if (!displayValue.suffix) {\n // Makes sure we don't show 123undefined or something like that if suffix isn't defined\n unitValue = displayValue.text;\n }\n if (!displaySelf.suffix) {\n // Makes sure we don't show 123undefined or something like that if suffix isn't defined\n unitSelf = displaySelf.text;\n }\n }\n\n return {\n percentValue,\n percentSelf,\n unitTitle,\n unitValue,\n unitSelf,\n samples: displayValue.numeric.toLocaleString(),\n };\n};\n\ntype DiffTableData = {\n rowId: string;\n label: string;\n baseline: string | number;\n comparison: string | number;\n diff: string | number;\n};\n\nexport const getDiffTooltipData = (\n data: FlameGraphDataContainer,\n item: LevelItem,\n totalTicks: number\n): DiffTableData[] => {\n const levels = data.getLevels();\n const totalTicksRight = levels[0][0].valueRight!;\n const totalTicksLeft = totalTicks - totalTicksRight;\n const valueLeft = item.value - item.valueRight!;\n\n const percentageLeft = Math.round((10000 * valueLeft) / totalTicksLeft) / 100;\n const percentageRight = Math.round((10000 * item.valueRight!) / totalTicksRight) / 100;\n\n const diff = ((percentageRight - percentageLeft) / percentageLeft) * 100;\n\n const displayValueLeft = getValueWithUnit(data, data.valueDisplayProcessor(valueLeft));\n const displayValueRight = getValueWithUnit(data, data.valueDisplayProcessor(item.valueRight!));\n\n const shortValFormat = getValueFormat('short');\n\n return [\n {\n rowId: '1',\n label: '% of total',\n baseline: percentageLeft + '%',\n comparison: percentageRight + '%',\n diff: shortValFormat(diff).text + '%',\n },\n {\n rowId: '2',\n label: 'Value',\n baseline: displayValueLeft,\n comparison: displayValueRight,\n diff: getValueWithUnit(data, data.valueDisplayProcessor(item.valueRight! - valueLeft)),\n },\n {\n rowId: '3',\n label: 'Samples',\n baseline: shortValFormat(valueLeft).text,\n comparison: shortValFormat(item.valueRight!).text,\n diff: shortValFormat(item.valueRight! - valueLeft).text,\n },\n ];\n};\n\nfunction getValueWithUnit(data: FlameGraphDataContainer, displayValue: DisplayValue) {\n let unitValue = displayValue.text + displayValue.suffix;\n\n const unitTitle = data.getUnitTitle();\n if (unitTitle === 'Count') {\n if (!displayValue.suffix) {\n // Makes sure we don't show 123undefined or something like that if suffix isn't defined\n unitValue = displayValue.text;\n }\n }\n return unitValue;\n}\n\nconst getStyles = (theme: GrafanaTheme2) => ({\n tooltipContainer: css({\n title: 'tooltipContainer',\n overflow: 'hidden',\n }),\n tooltipContent: css({\n title: 'tooltipContent',\n fontSize: theme.typography.bodySmall.fontSize,\n width: '100%',\n }),\n tooltipName: css({\n title: 'tooltipName',\n marginTop: 0,\n wordBreak: 'break-all',\n }),\n lastParagraph: css({\n title: 'lastParagraph',\n marginBottom: 0,\n }),\n name: css({\n title: 'name',\n marginBottom: '10px',\n }),\n\n tooltipTable: css({\n title: 'tooltipTable',\n maxWidth: '400px',\n }),\n});\n\nexport default FlameGraphTooltip;\n","import { LevelItem } from './FlameGraph/dataTransform';\n\nexport { type FlameGraphDataContainer } from './FlameGraph/dataTransform';\n\nexport { type ExtraContextMenuButton } from './FlameGraph/FlameGraphContextMenu';\n\nexport type ClickedItemData = {\n posX: number;\n posY: number;\n label: string;\n item: LevelItem;\n};\n\nexport enum SampleUnit {\n Bytes = 'bytes',\n Short = 'short',\n Nanoseconds = 'ns',\n}\n\nexport enum SelectedView {\n TopTable = 'topTable',\n FlameGraph = 'flameGraph',\n Both = 'both',\n}\n\nexport interface TableData {\n self: number;\n total: number;\n // For diff view\n totalRight: number;\n}\n\nexport enum ColorScheme {\n ValueBased = 'valueBased',\n PackageBased = 'packageBased',\n}\n\nexport enum ColorSchemeDiff {\n Default = 'default',\n DiffColorBlind = 'diffColorBlind',\n}\n\nexport type TextAlign = 'left' | 'right';\n","// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-nocheck\n/* eslint-disable @typescript-eslint/restrict-plus-operands */\n/*\n\nCopyright (c) 2011 Gary Court\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*/\n\n/* eslint-disable no-plusplus */\n/* eslint-disable prefer-const */\n/* eslint-disable no-bitwise */\n/* eslint-disable camelcase */\n\nexport default function murmurhash3_32_gc(key: string, seed = 0) {\n let remainder;\n let bytes;\n let h1;\n let h1b;\n let c1;\n let c2;\n let k1;\n let i;\n\n remainder = key.length & 3; // key.length % 4\n bytes = key.length - remainder;\n h1 = seed;\n c1 = 0xcc9e2d51;\n c2 = 0x1b873593;\n i = 0;\n\n while (i < bytes) {\n k1 =\n (key.charCodeAt(i) & 0xff) |\n ((key.charCodeAt(++i) & 0xff) << 8) |\n ((key.charCodeAt(++i) & 0xff) << 16) |\n ((key.charCodeAt(++i) & 0xff) << 24);\n ++i;\n\n k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;\n k1 = (k1 << 15) | (k1 >>> 17);\n k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;\n\n h1 ^= k1;\n h1 = (h1 << 13) | (h1 >>> 19);\n h1b = ((h1 & 0xffff) * 5 + ((((h1 >>> 16) * 5) & 0xffff) << 16)) & 0xffffffff;\n h1 = (h1b & 0xffff) + 0x6b64 + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16);\n }\n\n k1 = 0;\n\n switch (remainder) {\n case 3:\n k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;\n // fall through\n case 2:\n k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;\n // fall through\n case 1:\n k1 ^= key.charCodeAt(i) & 0xff;\n // fall through\n default:\n k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;\n k1 = (k1 << 15) | (k1 >>> 17);\n k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;\n h1 ^= k1;\n }\n\n h1 ^= key.length;\n\n h1 ^= h1 >>> 16;\n h1 = ((h1 & 0xffff) * 0x85ebca6b + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;\n h1 ^= h1 >>> 13;\n h1 = ((h1 & 0xffff) * 0xc2b2ae35 + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16)) & 0xffffffff;\n h1 ^= h1 >>> 16;\n\n return h1 >>> 0;\n}\n","import { scaleLinear } from 'd3';\nimport color from 'tinycolor2';\n\nimport { GrafanaTheme2 } from '@grafana/data';\n\nimport { ColorSchemeDiff } from '../types';\n\nimport murmurhash3_32_gc from './murmur3';\n\n// Colors taken from pyroscope, they should be from Grafana originally, but I didn't find from where exactly.\nconst packageColors = [\n color({ h: 24, s: 69, l: 60 }),\n color({ h: 34, s: 65, l: 65 }),\n color({ h: 194, s: 52, l: 61 }),\n color({ h: 163, s: 45, l: 55 }),\n color({ h: 211, s: 48, l: 60 }),\n color({ h: 246, s: 40, l: 65 }),\n color({ h: 305, s: 63, l: 79 }),\n color({ h: 47, s: 100, l: 73 }),\n\n color({ r: 183, g: 219, b: 171 }),\n color({ r: 244, g: 213, b: 152 }),\n color({ r: 78, g: 146, b: 249 }),\n color({ r: 249, g: 186, b: 143 }),\n color({ r: 242, g: 145, b: 145 }),\n color({ r: 130, g: 181, b: 216 }),\n color({ r: 229, g: 168, b: 226 }),\n color({ r: 174, g: 162, b: 224 }),\n color({ r: 154, g: 196, b: 138 }),\n color({ r: 242, g: 201, b: 109 }),\n color({ r: 101, g: 197, b: 219 }),\n color({ r: 249, g: 147, b: 78 }),\n color({ r: 234, g: 100, b: 96 }),\n color({ r: 81, g: 149, b: 206 }),\n color({ r: 214, g: 131, b: 206 }),\n color({ r: 128, g: 110, b: 183 }),\n];\n\nconst byValueMinColor = getBarColorByValue(1, 100, 0, 1);\nconst byValueMaxColor = getBarColorByValue(100, 100, 0, 1);\nexport const byValueGradient = `linear-gradient(90deg, ${byValueMinColor} 0%, ${byValueMaxColor} 100%)`;\n\n// Handpicked some vaguely rainbow-ish colors\nexport const byPackageGradient = `linear-gradient(90deg, ${packageColors[0]} 0%, ${packageColors[2]} 30%, ${packageColors[6]} 50%, ${packageColors[7]} 70%, ${packageColors[8]} 100%)`;\n\nexport function getBarColorByValue(value: number, totalTicks: number, rangeMin: number, rangeMax: number) {\n // / (rangeMax - rangeMin) here so when you click a bar it will adjust the top (clicked)bar to the most 'intense' color\n const intensity = Math.min(1, value / totalTicks / (rangeMax - rangeMin));\n const h = 50 - 50 * intensity;\n const l = 65 + 7 * intensity;\n\n return color({ h, s: 100, l });\n}\n\nexport function getBarColorByPackage(label: string, theme: GrafanaTheme2) {\n const packageName = getPackageName(label);\n // TODO: similar thing happens in trace view with selecting colors of the spans, so maybe this could be unified.\n const hash = murmurhash3_32_gc(packageName || '', 0);\n const colorIndex = hash % packageColors.length;\n let packageColor = packageColors[colorIndex].clone();\n if (theme.isLight) {\n packageColor = packageColor.brighten(15);\n }\n return packageColor;\n}\n\n// green to red\nexport const diffDefaultColors = ['rgb(0, 170, 0)', 'rgb(148, 142, 142)', 'rgb(200, 0, 0)'];\nexport const diffDefaultGradient = `linear-gradient(90deg, ${diffDefaultColors[0]} 0%, ${diffDefaultColors[1]} 50%, ${diffDefaultColors[2]} 100%)`;\nexport const diffColorBlindColors = ['rgb(26, 133, 255)', 'rgb(148, 142, 142)', 'rgb(220, 50, 32)'];\nexport const diffColorBlindGradient = `linear-gradient(90deg, ${diffColorBlindColors[0]} 0%, ${diffColorBlindColors[1]} 50%, ${diffColorBlindColors[2]} 100%)`;\n\nexport function getBarColorByDiff(\n ticks: number,\n ticksRight: number,\n totalTicks: number,\n totalTicksRight: number,\n colorScheme: ColorSchemeDiff\n) {\n const range = colorScheme === ColorSchemeDiff.Default ? diffDefaultColors : diffColorBlindColors;\n const colorScale = scaleLinear()\n .domain([-100, 0, 100])\n // TODO types from DefinitelyTyped seem to mismatch\n // @ts-ignore\n .range(range);\n\n const ticksLeft = ticks - ticksRight;\n const totalTicksLeft = totalTicks - totalTicksRight;\n\n if (totalTicksRight === 0 || totalTicksLeft === 0) {\n // TODO types from DefinitelyTyped seem to mismatch\n // @ts-ignore\n const rgbString: string = colorScale(0);\n // Fallback to neutral color as we probably have no data for one of the sides.\n return color(rgbString);\n }\n\n const percentageLeft = Math.round((10000 * ticksLeft) / totalTicksLeft) / 100;\n const percentageRight = Math.round((10000 * ticksRight) / totalTicksRight) / 100;\n\n const diff = ((percentageRight - percentageLeft) / percentageLeft) * 100;\n\n // TODO types from DefinitelyTyped seem to mismatch\n // @ts-ignore\n const rgbString: string = colorScale(diff);\n return color(rgbString);\n}\n\n// const getColors = memoizeOne((theme) => getFilteredColors(colors, theme));\n\n// Different regexes to get the package name and function name from the label. We may at some point get an info about\n// the language from the backend and use the right regex but right now we just try all of them from most to least\n// specific.\nconst matchers = [\n ['phpspy', /^(?<packageName>([^\\/]*\\/)*)(?<filename>.*\\.php+)(?<line_info>.*)$/],\n ['pyspy', /^(?<packageName>([^\\/]*\\/)*)(?<filename>.*\\.py+)(?<line_info>.*)$/],\n ['rbspy', /^(?<packageName>([^\\/]*\\/)*)(?<filename>.*\\.rb+)(?<line_info>.*)$/],\n [\n 'nodespy',\n /^(\\.\\/node_modules\\/)?(?<packageName>[^/]*)(?<filename>.*\\.?(jsx?|tsx?)?):(?<functionName>.*):(?<line_info>.*)$/,\n ],\n ['gospy', /^(?<packageName>.*?\\/.*?\\.|.*?\\.|.+)(?<functionName>.*)$/], // also 'scrape'\n ['javaspy', /^(?<packageName>.+\\/)(?<filename>.+\\.)(?<functionName>.+)$/],\n ['dotnetspy', /^(?<packageName>.+)\\.(.+)\\.(.+)\\(.*\\)$/],\n ['tracing', /^(?<packageName>.+?):.*$/],\n ['pyroscope-rs', /^(?<packageName>[^::]+)/],\n ['ebpfspy', /^(?<packageName>.+)$/],\n ['unknown', /^(?<packageName>.+)$/],\n];\n\n// Get the package name from the symbol. Try matchers from the list and return first one that matches.\nfunction getPackageName(name: string): string | undefined {\n for (const [_, matcher] of matchers) {\n const match = name.match(matcher);\n if (match) {\n return match.groups?.packageName || '';\n }\n }\n return undefined;\n}\n","import { RefObject, useCallback, useEffect, useMemo, useState } from 'react';\nimport color from 'tinycolor2';\n\nimport { GrafanaTheme2 } from '@grafana/data';\nimport { useTheme2 } from '@grafana/ui';\n\nimport {\n BAR_BORDER_WIDTH,\n BAR_TEXT_PADDING_LEFT,\n MUTE_THRESHOLD,\n HIDE_THRESHOLD,\n LABEL_THRESHOLD,\n PIXELS_PER_LEVEL,\n GROUP_STRIP_WIDTH,\n GROUP_STRIP_PADDING,\n GROUP_STRIP_MARGIN_LEFT,\n GROUP_TEXT_OFFSET,\n} from '../constants';\nimport { ClickedItemData, ColorScheme, ColorSchemeDiff, TextAlign } from '../types';\n\nimport { getBarColorByDiff, getBarColorByPackage, getBarColorByValue } from './colors';\nimport { CollapseConfig, CollapsedMap, FlameGraphDataContainer, LevelItem } from './dataTransform';\n\ntype RenderOptions = {\n canvasRef: RefObject<HTMLCanvasElement>;\n data: FlameGraphDataContainer;\n root: LevelItem;\n direction: 'children' | 'parents';\n\n // Depth in number of levels\n depth: number;\n wrapperWidth: number;\n\n // If we are rendering only zoomed in part of the graph.\n rangeMin: number;\n rangeMax: number;\n\n matchedLabels: Set<string> | undefined;\n textAlign: TextAlign;\n\n // Total ticks that will be used for sizing\n totalViewTicks: number;\n // Total ticks that will be used for computing colors as some color scheme (like in diff view) should not be affected\n // by sandwich or focus view.\n totalColorTicks: number;\n // Total ticks used to compute the diff colors\n totalTicksRight: number | undefined;\n colorScheme: ColorScheme | ColorSchemeDiff;\n focusedItemData?: ClickedItemData;\n collapsedMap: CollapsedMap;\n};\n\nexport function useFlameRender(options: RenderOptions) {\n const {\n canvasRef,\n data,\n root,\n depth,\n direction,\n wrapperWidth,\n rangeMin,\n rangeMax,\n matchedLabels,\n textAlign,\n totalViewTicks,\n totalColorTicks,\n totalTicksRight,\n colorScheme,\n focusedItemData,\n collapsedMap,\n } = options;\n const ctx = useSetupCanvas(canvasRef, wrapperWidth, depth);\n const theme = useTheme2();\n\n // There is a bit of dependency injections here that does not add readability, mainly to prevent recomputing some\n // common stuff for all the nodes in the graph when only once is enough. perf/readability tradeoff.\n\n const mutedColor = useMemo(() => {\n const barMutedColor = color(theme.colors.background.secondary);\n return theme.isLight ? barMutedColor.darken(10).toHexString() : barMutedColor.lighten(10).toHexString();\n }, [theme]);\n\n const getBarColor = useColorFunction(\n totalColorTicks,\n totalTicksRight,\n colorScheme,\n theme,\n mutedColor,\n rangeMin,\n rangeMax,\n matchedLabels,\n focusedItemData ? focusedItemData.item.level : 0\n );\n\n const renderFunc = useRenderFunc(ctx, data, getBarColor, textAlign, collapsedMap);\n\n useEffect(() => {\n if (!ctx) {\n return;\n }\n\n ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n\n const mutedPath2D = new Path2D();\n\n //\n // Walk the tree and compute the dimensions for each item in the flamegraph.\n //\n walkTree(\n root,\n direction,\n data,\n totalViewTicks,\n rangeMin,\n rangeMax,\n wrapperWidth,\n collapsedMap,\n (item, x, y, width, height, label, muted) => {\n if (muted) {\n // We do a bit of optimization for muted regions, and we render them all in single fill later on as they don't\n // have labels and are the same color.\n mutedPath2D.rect(x, y, width, height);\n } else {\n renderFunc(item, x, y, width, height, label);\n }\n }\n );\n\n // Only fill the muted rects\n ctx.fillStyle = mutedColor;\n ctx.fill(mutedPath2D);\n }, [\n ctx,\n data,\n root,\n wrapperWidth,\n rangeMin,\n rangeMax,\n totalViewTicks,\n direction,\n renderFunc,\n collapsedMap,\n mutedColor,\n ]);\n}\n\ntype RenderFunc = (item: LevelItem, x: number, y: number, width: number, height: number, label: string) => void;\n\ntype RenderFuncWrap = (\n item: LevelItem,\n x: number,\n y: number,\n width: number,\n height: number,\n label: string,\n muted: boolean\n) => void;\n\n/**\n * Create a render function with some memoization to prevent excesive repainting of the canvas.\n * @param ctx\n * @param data\n * @param getBarColor\n * @param textAlign\n * @param collapsedMap\n */\nfunction useRenderFunc(\n ctx: CanvasRenderingContext2D | undefined,\n data: FlameGraphDataContainer,\n getBarColor: (item: LevelItem, label: string, muted: boolean) => string,\n textAlign: TextAlign,\n collapsedMap: CollapsedMap\n) {\n return useMemo(() => {\n if (!ctx) {\n return () => {};\n }\n\n const renderFunc: RenderFunc = (item, x, y, width, height, label) => {\n ctx.beginPath();\n ctx.rect(x + BAR_BORDER_WIDTH, y, width, height);\n ctx.fillStyle = getBarColor(item, label, false);\n ctx.stroke();\n ctx.fill();\n\n const collapsedItemConfig = collapsedMap.get(item);\n let finalLabel = label;\n if (collapsedItemConfig && collapsedItemConfig.collapsed) {\n const numberOfCollapsedItems = collapsedItemConfig.items.length;\n finalLabel = `(${numberOfCollapsedItems}) ` + label;\n }\n\n if (width >= LABEL_THRESHOLD) {\n if (collapsedItemConfig) {\n renderLabel(\n ctx,\n data,\n finalLabel,\n item,\n width,\n textAlign === 'left' ? x + GROUP_STRIP_MARGIN_LEFT + GROUP_TEXT_OFFSET : x,\n y,\n textAlign\n );\n\n renderGroupingStrip(ctx, x, y, height, item, collapsedItemConfig);\n } else {\n renderLabel(ctx, data, finalLabel, item, width, x, y, textAlign);\n }\n }\n };\n\n return renderFunc;\n }, [ctx, getBarColor, textAlign, data, collapsedMap]);\n}\n\n/**\n * Render small strip on the left side of the bar to indicate that this item is part of a group that can be collapsed.\n * @param ctx\n * @param x\n * @param y\n * @param height\n * @param item\n * @param collapsedItemConfig\n */\nfunction renderGroupingStrip(\n ctx: CanvasRenderingContext2D,\n x: number,\n y: number,\n height: number,\n item: LevelItem,\n collapsedItemConfig: CollapseConfig\n) {\n const groupStripX = x + GROUP_STRIP_MARGIN_LEFT;\n\n // This is to mask the label in case we align it right to left.\n ctx.beginPath();\n ctx.rect(x, y, groupStripX - x + GROUP_STRIP_WIDTH + GROUP_STRIP_PADDING, height);\n ctx.fill();\n\n // For item in a group that can be collapsed, we draw a small strip to mark them. On the items that are at the\n // start or and end of a group we draw just half the strip so 2 groups next to each other are separated\n // visually.\n ctx.beginPath();\n if (collapsedItemConfig.collapsed) {\n ctx.rect(groupStripX, y + height / 4, GROUP_STRIP_WIDTH, height / 2);\n } else {\n if (collapsedItemConfig.items[0] === item) {\n // Top item\n ctx.rect(groupStripX, y + height / 2, GROUP_STRIP_WIDTH, height / 2);\n } else if (collapsedItemConfig.items[collapsedItemConfig.items.length - 1] === item) {\n // Bottom item\n ctx.rect(groupStripX, y, GROUP_STRIP_WIDTH, height / 2);\n } else {\n ctx.rect(groupStripX, y, GROUP_STRIP_WIDTH, height);\n }\n }\n\n ctx.fillStyle = '#666';\n ctx.fill();\n}\n\n/**\n * Exported for testing don't use directly\n * Walks the tree and computes coordinates, dimensions and other data needed for rendering. For each item in the tree\n * it defers the rendering to the renderFunc.\n */\nexport function walkTree(\n root: LevelItem,\n // In sandwich view we use parents direction to show all callers.\n direction: 'children' | 'parents',\n data: FlameGraphDataContainer,\n totalViewTicks: number,\n rangeMin: number,\n rangeMax: number,\n wrapperWidth: number,\n collapsedMap: CollapsedMap,\n renderFunc: RenderFuncWrap\n) {\n // The levelOffset here is to keep track if items that we don't render because they are collapsed into single row.\n // That means we have to render next items with an offset of some rows up in the stack.\n const stack: Array<{ item: LevelItem; levelOffset: number }> = [];\n stack.push({ item: root, levelOffset: 0 });\n\n const pixelsPerTick = (wrapperWidth * window.devicePixelRatio) / totalViewTicks / (rangeMax - rangeMin);\n let collapsedItemRendered: LevelItem | undefined = undefined;\n\n while (stack.length > 0) {\n const { item, levelOffset } = stack.shift()!;\n let curBarTicks = item.value;\n const muted = curBarTicks * pixelsPerTick <= MUTE_THRESHOLD;\n const width = curBarTicks * pixelsPerTick - (muted ? 0 : BAR_BORDER_WIDTH * 2);\n const height = PIXELS_PER_LEVEL;\n\n if (width < HIDE_THRESHOLD) {\n // We don't render nor it's children\n continue;\n }\n\n let offsetModifier = 0;\n let skipRender = false;\n const collapsedItemConfig = collapsedMap.get(item);\n const isCollapsedItem = collapsedItemConfig && collapsedItemConfig.collapsed;\n\n if (isCollapsedItem) {\n if (collapsedItemRendered === collapsedItemConfig.items[0]) {\n offsetModifier = direction === 'children' ? -1 : +1;\n skipRender = true;\n } else {\n // This is a case where we have another collapsed group right after different collapsed group, so we need to\n // reset.\n collapsedItemRendered = undefined;\n }\n } else {\n collapsedItemRendered = undefined;\n }\n\n if (!skipRender) {\n const barX = getBarX(item.start, totalViewTicks, rangeMin, pixelsPerTick);\n const barY = (item.level + levelOffset) * PIXELS_PER_LEVEL;\n\n let label = data.getLabel(item.itemIndexes[0]);\n if (isCollapsedItem) {\n collapsedItemRendered = item;\n }\n\n renderFunc(item, barX, barY, width, height, label, muted);\n }\n\n const nextList = direction === 'children' ? item.children : item.parents;\n if (nextList) {\n stack.unshift(...nextList.map((c) => ({ item: c, levelOffset: levelOffset + offsetModifier })));\n }\n }\n}\n\nfunction useColorFunction(\n totalTicks: number,\n totalTicksRight: number | undefined,\n colorScheme: ColorScheme | ColorSchemeDiff,\n theme: GrafanaTheme2,\n mutedColor: string,\n rangeMin: number,\n rangeMax: number,\n matchedLabels: Set<string> | undefined,\n topLevel: number\n) {\n return useCallback(\n function getColor(item: LevelItem, label: string, muted: boolean) {\n // If collapsed and no search we can quickly return the muted color\n if (muted && !matchedLabels) {\n // Collapsed are always grayed\n return mutedColor;\n }\n\n const barColor =\n item.valueRight !== undefined &&\n (colorScheme === ColorSchemeDiff.Default || colorScheme === ColorSchemeDiff.DiffColorBlind)\n ? getBarColorByDiff(item.value, item.valueRight!, totalTicks, totalTicksRight!, colorScheme)\n : colorScheme === ColorScheme.ValueBased\n ? getBarColorByValue(item.value, totalTicks, rangeMin, rangeMax)\n : getBarColorByPackage(label, theme);\n\n if (matchedLabels) {\n // Means we are searching, we use color for matches and gray the rest\n return matchedLabels.has(label) ? barColor.toHslString() : mutedColor;\n }\n\n // Mute if we are above the focused symbol\n return item.level > topLevel - 1 ? barColor.toHslString() : barColor.lighten(15).toHslString();\n },\n [totalTicks, totalTicksRight, colorScheme, theme, rangeMin, rangeMax, matchedLabels, topLevel, mutedColor]\n );\n}\n\nfunction useSetupCanvas(canvasRef: RefObject<HTMLCanvasElement>, wrapperWidth: number, numberOfLevels: number) {\n const [ctx, setCtx] = useState<CanvasRenderingContext2D>();\n\n useEffect(() => {\n if (!(numberOfLevels && canvasRef.current)) {\n return;\n }\n const ctx = canvasRef.current.getContext('2d')!;\n\n const height = PIXELS_PER_LEVEL * numberOfLevels;\n canvasRef.current.width = Math.round(wrapperWidth * window.devicePixelRatio);\n canvasRef.current.height = Math.round(height);\n canvasRef.current.style.width = `${wrapperWidth}px`;\n canvasRef.current.style.height = `${height / window.devicePixelRatio}px`;\n\n ctx.textBaseline = 'middle';\n ctx.font = 12 * window.devicePixelRatio + 'px monospace';\n ctx.strokeStyle = 'white';\n setCtx(ctx);\n }, [canvasRef, setCtx, wrapperWidth, numberOfLevels]);\n return ctx;\n}\n\n// Renders a text inside the node rectangle. It allows setting alignment of the text left or right which takes effect\n// when text is too long to fit in the rectangle.\nfunction renderLabel(\n ctx: CanvasRenderingContext2D,\n data: FlameGraphDataContainer,\n label: string,\n item: LevelItem,\n width: number,\n x: number,\n y: number,\n textAlign: TextAlign\n) {\n ctx.save();\n ctx.clip(); // so text does not overflow\n ctx.fillStyle = '#222';\n\n const displayValue = data.valueDisplayProcessor(item.value);\n const unit = displayValue.suffix ? displayValue.text + displayValue.suffix : displayValue.text;\n\n // We only measure name here instead of full label because of how we deal with the units and aligning later.\n const measure = ctx.measureText(label);\n const spaceForTextInRect = width - BAR_TEXT_PADDING_LEFT;\n\n let fullLabel = `${label} (${unit})`;\n let labelX = Math.max(x, 0) + BAR_TEXT_PADDING_LEFT;\n\n // We use the desired alignment only if there is not enough space for the text, otherwise we keep left alignment as\n // that will already show full text.\n if (measure.width > spaceForTextInRect) {\n ctx.textAlign = textAlign;\n // If aligned to the right we don't want to take the space with the unit label as the assumption is user wants to\n // mainly see the name. This also reflects how pyro/flamegraph works.\n if (textAlign === 'right') {\n fullLabel = label;\n labelX = x + width - BAR_TEXT_PADDING_LEFT;\n }\n }\n\n ctx.fillText(fullLabel, labelX, y + PIXELS_PER_LEVEL / 2 + 2);\n ctx.restore();\n}\n\n/**\n * Returns the X position of the bar. totalTicks * rangeMin is to adjust for any current zoom. So if we zoom to a\n * section of the graph we align and shift the X coordinates accordingly.\n * @param offset\n * @param totalTicks\n * @param rangeMin\n * @param pixelsPerTick\n */\nexport function getBarX(offset: number, totalTicks: number, rangeMin: number, pixelsPerTick: number) {\n return (offset - totalTicks * rangeMin) * pixelsPerTick;\n}\n","import { css } from '@emotion/css';\nimport { MouseEvent as ReactMouseEvent, useCallback, useEffect, useRef, useState } from 'react';\nimport * as React from 'react';\nimport { useMeasure } from 'react-use';\n\nimport { PIXELS_PER_LEVEL } from '../constants';\nimport { ClickedItemData, ColorScheme, ColorSchemeDiff, SelectedView, TextAlign } from '../types';\n\nimport FlameGraphContextMenu, { GetExtraContextMenuButtonsFunction } from './FlameGraphContextMenu';\nimport FlameGraphTooltip from './FlameGraphTooltip';\nimport { CollapsedMap, FlameGraphDataContainer, LevelItem } from './dataTransform';\nimport { getBarX, useFlameRender } from './rendering';\n\ntype Props = {\n data: FlameGraphDataContainer;\n rangeMin: number;\n rangeMax: number;\n matchedLabels: Set<string> | undefined;\n setRangeMin: (range: number) => void;\n setRangeMax: (range: number) => void;\n style?: React.CSSProperties;\n onItemFocused: (data: ClickedItemData) => void;\n focusedItemData?: ClickedItemData;\n textAlign: TextAlign;\n onSandwich: (label: string) => void;\n colorScheme: ColorScheme | ColorSchemeDiff;\n\n root: LevelItem;\n direction: 'children' | 'parents';\n // Depth in number of levels\n depth: number;\n\n totalProfileTicks: number;\n totalProfileTicksRight?: number;\n totalViewTicks: number;\n showFlameGraphOnly?: boolean;\n\n collapsedMap: CollapsedMap;\n setCollapsedMap: (collapsedMap: CollapsedMap) => void;\n collapsing?: boolean;\n getExtraContextMenuButtons?: GetExtraContextMenuButtonsFunction;\n\n selectedView: SelectedView;\n search: string;\n};\n\nconst FlameGraphCanvas = ({\n data,\n rangeMin,\n rangeMax,\n matchedLabels,\n setRangeMin,\n setRangeMax,\n onItemFocused,\n focusedItemData,\n textAlign,\n onSandwich,\n colorScheme,\n totalProfileTicks,\n totalProfileTicksRight,\n totalViewTicks,\n root,\n direction,\n depth,\n showFlameGraphOnly,\n collapsedMap,\n setCollapsedMap,\n collapsing,\n getExtraContextMenuButtons,\n selectedView,\n search,\n}: Props) => {\n const styles = getStyles();\n\n const [sizeRef, { width: wrapperWidth }] = useMeasure<HTMLDivElement>();\n const graphRef = useRef<HTMLCanvasElement>(null);\n const [tooltipItem, setTooltipItem] = useState<LevelItem>();\n\n const [clickedItemData, setClickedItemData] = useState<ClickedItemData>();\n\n useFlameRender({\n canvasRef: graphRef,\n colorScheme,\n data,\n focusedItemData,\n root,\n direction,\n depth,\n rangeMax,\n rangeMin,\n matchedLabels,\n textAlign,\n totalViewTicks,\n // We need this so that if we have a diff profile and are in sandwich view we still show the same diff colors.\n totalColorTicks: data.isDiffFlamegraph() ? totalProfileTicks : totalViewTicks,\n totalTicksRight: totalProfileTicksRight,\n wrapperWidth,\n collapsedMap,\n });\n\n const onGraphClick = useCallback(\n (e: ReactMouseEvent<HTMLCanvasElement>) => {\n setTooltipItem(undefined);\n const pixelsPerTick = graphRef.current!.clientWidth / totalViewTicks / (rangeMax - rangeMin);\n const item = convertPixelCoordinatesToBarCoordinates(\n { x: e.nativeEvent.offsetX, y: e.nativeEvent.offsetY },\n root,\n direction,\n depth,\n pixelsPerTick,\n totalViewTicks,\n rangeMin,\n collapsedMap\n );\n\n // if clicking on a block in the canvas\n if (item) {\n setClickedItemData({\n posY: e.clientY,\n posX: e.clientX,\n item,\n label: data.getLabel(item.itemIndexes[0]),\n });\n } else {\n // if clicking on the canvas but there is no block beneath the cursor\n setClickedItemData(undefined);\n }\n },\n [data, rangeMin, rangeMax, totalViewTicks, root, direction, depth, collapsedMap]\n );\n\n const [mousePosition, setMousePosition] = useState<{ x: number; y: number }>();\n const onGraphMouseMove = useCallback(\n (e: ReactMouseEvent<HTMLCanvasElement>) => {\n if (clickedItemData === undefined) {\n setTooltipItem(undefined);\n setMousePosition(undefined);\n const pixelsPerTick = graphRef.current!.clientWidth / totalViewTicks / (rangeMax - rangeMin);\n const item = convertPixelCoordinatesToBarCoordinates(\n { x: e.nativeEvent.offsetX, y: e.nativeEvent.offsetY },\n root,\n direction,\n depth,\n pixelsPerTick,\n totalViewTicks,\n rangeMin,\n collapsedMap\n );\n\n if (item) {\n setMousePosition({ x: e.clientX, y: e.clientY });\n setTooltipItem(item);\n }\n }\n },\n [rangeMin, rangeMax, totalViewTicks, clickedItemData, setMousePosition, root, direction, depth, collapsedMap]\n );\n\n const onGraphMouseLeave = useCallback(() => {\n setTooltipItem(undefined);\n }, []);\n\n // hide context menu if outside the flame graph canvas is clicked\n useEffect(() => {\n const handleOnClick = (e: MouseEvent) => {\n if (\n e.target instanceof HTMLElement &&\n e.target.parentElement?.id !== 'flameGraphCanvasContainer_clickOutsideCheck'\n ) {\n setClickedItemData(undefined);\n }\n };\n window.addEventListener('click', handleOnClick);\n return () => window.removeEventListener('click', handleOnClick);\n }, [setClickedItemData]);\n\n return (\n <div className={styles.graph}>\n <div className={styles.canvasWrapper} id=\"flameGraphCanvasContainer_clickOutsideCheck\" ref={sizeRef}>\n <canvas\n ref={graphRef}\n data-testid=\"flameGraph\"\n onClick={onGraphClick}\n onMouseMove={onGraphMouseMove}\n onMouseLeave={onGraphMouseLeave}\n />\n </div>\n <FlameGraphTooltip\n position={mousePosition}\n item={tooltipItem}\n data={data}\n totalTicks={totalViewTicks}\n collapseConfig={tooltipItem ? collapsedMap.get(tooltipItem) : undefined}\n />\n {!showFlameGraphOnly && clickedItemData && (\n <FlameGraphContextMenu\n data={data}\n itemData={clickedItemData}\n collapsing={collapsing}\n collapseConfig={collapsedMap.get(clickedItemData.item)}\n onMenuItemClick={() => {\n setClickedItemData(undefined);\n }}\n onItemFocus={() => {\n setRangeMin(clickedItemData.item.start / totalViewTicks);\n setRangeMax((clickedItemData.item.start + clickedItemData.item.value) / totalViewTicks);\n onItemFocused(clickedItemData);\n }}\n onSandwich={() => {\n onSandwich(data.getLabel(clickedItemData.item.itemIndexes[0]));\n }}\n onExpandGroup={() => {\n setCollapsedMap(collapsedMap.setCollapsedStatus(clickedItemData.item, false));\n }}\n onCollapseGroup={() => {\n setCollapsedMap(collapsedMap.setCollapsedStatus(clickedItemData.item, true));\n }}\n onExpandAllGroups={() => {\n setCollapsedMap(collapsedMap.setAllCollapsedStatus(false));\n }}\n onCollapseAllGroups={() => {\n setCollapsedMap(collapsedMap.setAllCollapsedStatus(true));\n }}\n allGroupsCollapsed={Array.from(collapsedMap.values()).every((i) => i.collapsed)}\n allGroupsExpanded={Array.from(collapsedMap.values()).every((i) => !i.collapsed)}\n getExtraContextMenuButtons={getExtraContextMenuButtons}\n selectedView={selectedView}\n search={search}\n />\n )}\n </div>\n );\n};\n\nconst getStyles = () => ({\n graph: css({\n label: 'graph',\n overflow: 'auto',\n flexGrow: 1,\n flexBasis: '50%',\n }),\n canvasContainer: css({\n label: 'canvasContainer',\n display: 'flex',\n }),\n canvasWrapper: css({\n label: 'canvasWrapper',\n cursor: 'pointer',\n flex: 1,\n overflow: 'hidden',\n }),\n sandwichMarker: css({\n label: 'sandwichMarker',\n writingMode: 'vertical-lr',\n transform: 'rotate(180deg)',\n overflow: 'hidden',\n whiteSpace: 'nowrap',\n }),\n sandwichMarkerIcon: css({\n label: 'sandwichMarkerIcon',\n verticalAlign: 'baseline',\n }),\n});\n\nexport const convertPixelCoordinatesToBarCoordinates = (\n // position relative to the start of the graph\n pos: { x: number; y: number },\n root: LevelItem,\n direction: 'children' | 'parents',\n depth: number,\n pixelsPerTick: number,\n totalTicks: number,\n rangeMin: number,\n collapsedMap: CollapsedMap\n): LevelItem | undefined => {\n let next: LevelItem | undefined = root;\n let currentLevel = direction === 'children' ? 0 : depth - 1;\n const levelIndex = Math.floor(pos.y / (PIXELS_PER_LEVEL / window.devicePixelRatio));\n let found = undefined;\n\n while (next) {\n const node: LevelItem = next;\n next = undefined;\n if (currentLevel === levelIndex) {\n found = node;\n break;\n }\n\n const nextList = direction === 'children' ? node.children : node.parents || [];\n\n for (const child of nextList) {\n const xStart = getBarX(child.start, totalTicks, rangeMin, pixelsPerTick);\n const xEnd = getBarX(child.start + child.value, totalTicks, rangeMin, pixelsPerTick);\n if (xStart <= pos.x && pos.x < xEnd) {\n next = child;\n // Check if item is a collapsed item. if so also check if the item is the first collapsed item in the chain,\n // which we render, or a child which we don't render. If it's a child in the chain then don't increase the\n // level end effectively skip it.\n const collapsedConfig = collapsedMap.get(child);\n if (!collapsedConfig || !collapsedConfig.collapsed || collapsedConfig.items[0] === child) {\n currentLevel = currentLevel + (direction === 'children' ? 1 : -1);\n }\n break;\n }\n }\n }\n\n return found;\n};\n\nexport default FlameGraphCanvas;\n","import { css } from '@emotion/css';\nimport { memo, ReactNode } from 'react';\n\nimport { getValueFormat, GrafanaTheme2 } from '@grafana/data';\nimport { Icon, IconButton, Tooltip, useStyles2 } from '@grafana/ui';\n\nimport { ClickedItemData } from '../types';\n\nimport { FlameGraphDataContainer } from './dataTransform';\n\ntype Props = {\n data: FlameGraphDataContainer;\n totalTicks: number;\n onFocusPillClick: () => void;\n onSandwichPillClick: () => void;\n focusedItem?: ClickedItemData;\n sandwichedLabel?: string;\n};\n\nconst FlameGraphMetadata = memo(\n ({ data, focusedItem, totalTicks, sandwichedLabel, onFocusPillClick, onSandwichPillClick }: Props) => {\n const styles = useStyles2(getStyles);\n const parts: ReactNode[] = [];\n const ticksVal = getValueFormat('short')(totalTicks);\n\n const displayValue = data.valueDisplayProcessor(totalTicks);\n let unitValue = displayValue.text + displayValue.suffix;\n const unitTitle = data.getUnitTitle();\n if (unitTitle === 'Count') {\n if (!displayValue.suffix) {\n // Makes sure we don't show 123undefined or something like that if suffix isn't defined\n unitValue = displayValue.text;\n }\n }\n\n parts.push(\n <div className={styles.metadataPill} key={'default'}>\n {unitValue} | {ticksVal.text}\n {ticksVal.suffix} samples ({unitTitle})\n </div>\n );\n\n if (sandwichedLabel) {\n parts.push(\n <Tooltip key={'sandwich'} content={sandwichedLabel} placement=\"top\">\n <div>\n <Icon size={'sm'} name={'angle-right'} />\n <div className={styles.metadataPill}>\n <Icon size={'sm'} name={'gf-show-context'} />{' '}\n <span className={styles.metadataPillName}>\n {sandwichedLabel.substring(sandwichedLabel.lastIndexOf('/') + 1)}\n </span>\n <IconButton\n className={styles.pillCloseButton}\n name={'times'}\n size={'sm'}\n onClick={onSandwichPillClick}\n tooltip={'Remove sandwich view'}\n aria-label={'Remove sandwich view'}\n />\n </div>\n </div>\n </Tooltip>\n );\n }\n\n if (focusedItem) {\n const percentValue = totalTicks > 0 ? Math.round(10000 * (focusedItem.item.value / totalTicks)) / 100 : 0;\n const iconName = percentValue > 0 ? 'eye' : 'exclamation-circle';\n\n parts.push(\n <Tooltip key={'focus'} content={focusedItem.label} placement=\"top\">\n <div>\n <Icon size={'sm'} name={'angle-right'} />\n <div className={styles.metadataPill}>\n <Icon size={'sm'} name={iconName} />\n &nbsp;{percentValue}% of total\n <IconButton\n className={styles.pillCloseButton}\n name={'times'}\n size={'sm'}\n onClick={onFocusPillClick}\n tooltip={'Remove focus'}\n aria-label={'Remove focus'}\n />\n </div>\n </div>\n </Tooltip>\n );\n }\n\n return <div className={styles.metadata}>{parts}</div>;\n }\n);\n\nFlameGraphMetadata.displayName = 'FlameGraphMetadata';\