forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrendering.ts
451 lines (396 loc) · 13.9 KB
/
rendering.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import { RefObject, useCallback, useEffect, useMemo, useState } from 'react';
import color from 'tinycolor2';
import { GrafanaTheme2 } from '@grafana/data';
import { useTheme2 } from '@grafana/ui';
import {
BAR_BORDER_WIDTH,
BAR_TEXT_PADDING_LEFT,
MUTE_THRESHOLD,
HIDE_THRESHOLD,
LABEL_THRESHOLD,
PIXELS_PER_LEVEL,
GROUP_STRIP_WIDTH,
GROUP_STRIP_PADDING,
GROUP_STRIP_MARGIN_LEFT,
GROUP_TEXT_OFFSET,
} from '../constants';
import { ClickedItemData, ColorScheme, ColorSchemeDiff, TextAlign } from '../types';
import { getBarColorByDiff, getBarColorByPackage, getBarColorByValue } from './colors';
import { CollapseConfig, CollapsedMap, FlameGraphDataContainer, LevelItem } from './dataTransform';
type RenderOptions = {
canvasRef: RefObject<HTMLCanvasElement>;
data: FlameGraphDataContainer;
root: LevelItem;
direction: 'children' | 'parents';
// Depth in number of levels
depth: number;
wrapperWidth: number;
// If we are rendering only zoomed in part of the graph.
rangeMin: number;
rangeMax: number;
matchedLabels: Set<string> | undefined;
textAlign: TextAlign;
// Total ticks that will be used for sizing
totalViewTicks: number;
// Total ticks that will be used for computing colors as some color scheme (like in diff view) should not be affected
// by sandwich or focus view.
totalColorTicks: number;
// Total ticks used to compute the diff colors
totalTicksRight: number | undefined;
colorScheme: ColorScheme | ColorSchemeDiff;
focusedItemData?: ClickedItemData;
collapsedMap: CollapsedMap;
};
export function useFlameRender(options: RenderOptions) {
const {
canvasRef,
data,
root,
depth,
direction,
wrapperWidth,
rangeMin,
rangeMax,
matchedLabels,
textAlign,
totalViewTicks,
totalColorTicks,
totalTicksRight,
colorScheme,
focusedItemData,
collapsedMap,
} = options;
const ctx = useSetupCanvas(canvasRef, wrapperWidth, depth);
const theme = useTheme2();
// There is a bit of dependency injections here that does not add readability, mainly to prevent recomputing some
// common stuff for all the nodes in the graph when only once is enough. perf/readability tradeoff.
const mutedColor = useMemo(() => {
const barMutedColor = color(theme.colors.background.secondary);
return theme.isLight ? barMutedColor.darken(10).toHexString() : barMutedColor.lighten(10).toHexString();
}, [theme]);
const getBarColor = useColorFunction(
totalColorTicks,
totalTicksRight,
colorScheme,
theme,
mutedColor,
rangeMin,
rangeMax,
matchedLabels,
focusedItemData ? focusedItemData.item.level : 0
);
const renderFunc = useRenderFunc(ctx, data, getBarColor, textAlign, collapsedMap);
useEffect(() => {
if (!ctx) {
return;
}
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
const mutedPath2D = new Path2D();
//
// Walk the tree and compute the dimensions for each item in the flamegraph.
//
walkTree(
root,
direction,
data,
totalViewTicks,
rangeMin,
rangeMax,
wrapperWidth,
collapsedMap,
(item, x, y, width, height, label, muted) => {
if (muted) {
// We do a bit of optimization for muted regions, and we render them all in single fill later on as they don't
// have labels and are the same color.
mutedPath2D.rect(x, y, width, height);
} else {
renderFunc(item, x, y, width, height, label);
}
}
);
// Only fill the muted rects
ctx.fillStyle = mutedColor;
ctx.fill(mutedPath2D);
}, [
ctx,
data,
root,
wrapperWidth,
rangeMin,
rangeMax,
totalViewTicks,
direction,
renderFunc,
collapsedMap,
mutedColor,
]);
}
type RenderFunc = (item: LevelItem, x: number, y: number, width: number, height: number, label: string) => void;
type RenderFuncWrap = (
item: LevelItem,
x: number,
y: number,
width: number,
height: number,
label: string,
muted: boolean
) => void;
/**
* Create a render function with some memoization to prevent excesive repainting of the canvas.
* @param ctx
* @param data
* @param getBarColor
* @param textAlign
* @param collapsedMap
*/
function useRenderFunc(
ctx: CanvasRenderingContext2D | undefined,
data: FlameGraphDataContainer,
getBarColor: (item: LevelItem, label: string, muted: boolean) => string,
textAlign: TextAlign,
collapsedMap: CollapsedMap
) {
return useMemo(() => {
if (!ctx) {
return () => {};
}
const renderFunc: RenderFunc = (item, x, y, width, height, label) => {
ctx.beginPath();
ctx.rect(x + BAR_BORDER_WIDTH, y, width, height);
ctx.fillStyle = getBarColor(item, label, false);
ctx.stroke();
ctx.fill();
const collapsedItemConfig = collapsedMap.get(item);
let finalLabel = label;
if (collapsedItemConfig && collapsedItemConfig.collapsed) {
const numberOfCollapsedItems = collapsedItemConfig.items.length;
finalLabel = `(${numberOfCollapsedItems}) ` + label;
}
if (width >= LABEL_THRESHOLD) {
if (collapsedItemConfig) {
renderLabel(
ctx,
data,
finalLabel,
item,
width,
textAlign === 'left' ? x + GROUP_STRIP_MARGIN_LEFT + GROUP_TEXT_OFFSET : x,
y,
textAlign
);
renderGroupingStrip(ctx, x, y, height, item, collapsedItemConfig);
} else {
renderLabel(ctx, data, finalLabel, item, width, x, y, textAlign);
}
}
};
return renderFunc;
}, [ctx, getBarColor, textAlign, data, collapsedMap]);
}
/**
* Render small strip on the left side of the bar to indicate that this item is part of a group that can be collapsed.
* @param ctx
* @param x
* @param y
* @param height
* @param item
* @param collapsedItemConfig
*/
function renderGroupingStrip(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
height: number,
item: LevelItem,
collapsedItemConfig: CollapseConfig
) {
const groupStripX = x + GROUP_STRIP_MARGIN_LEFT;
// This is to mask the label in case we align it right to left.
ctx.beginPath();
ctx.rect(x, y, groupStripX - x + GROUP_STRIP_WIDTH + GROUP_STRIP_PADDING, height);
ctx.fill();
// For item in a group that can be collapsed, we draw a small strip to mark them. On the items that are at the
// start or and end of a group we draw just half the strip so 2 groups next to each other are separated
// visually.
ctx.beginPath();
if (collapsedItemConfig.collapsed) {
ctx.rect(groupStripX, y + height / 4, GROUP_STRIP_WIDTH, height / 2);
} else {
if (collapsedItemConfig.items[0] === item) {
// Top item
ctx.rect(groupStripX, y + height / 2, GROUP_STRIP_WIDTH, height / 2);
} else if (collapsedItemConfig.items[collapsedItemConfig.items.length - 1] === item) {
// Bottom item
ctx.rect(groupStripX, y, GROUP_STRIP_WIDTH, height / 2);
} else {
ctx.rect(groupStripX, y, GROUP_STRIP_WIDTH, height);
}
}
ctx.fillStyle = '#666';
ctx.fill();
}
/**
* Exported for testing don't use directly
* Walks the tree and computes coordinates, dimensions and other data needed for rendering. For each item in the tree
* it defers the rendering to the renderFunc.
*/
export function walkTree(
root: LevelItem,
// In sandwich view we use parents direction to show all callers.
direction: 'children' | 'parents',
data: FlameGraphDataContainer,
totalViewTicks: number,
rangeMin: number,
rangeMax: number,
wrapperWidth: number,
collapsedMap: CollapsedMap,
renderFunc: RenderFuncWrap
) {
// The levelOffset here is to keep track if items that we don't render because they are collapsed into single row.
// That means we have to render next items with an offset of some rows up in the stack.
const stack: Array<{ item: LevelItem; levelOffset: number }> = [];
stack.push({ item: root, levelOffset: 0 });
const pixelsPerTick = (wrapperWidth * window.devicePixelRatio) / totalViewTicks / (rangeMax - rangeMin);
let collapsedItemRendered: LevelItem | undefined = undefined;
while (stack.length > 0) {
const { item, levelOffset } = stack.shift()!;
let curBarTicks = item.value;
const muted = curBarTicks * pixelsPerTick <= MUTE_THRESHOLD;
const width = curBarTicks * pixelsPerTick - (muted ? 0 : BAR_BORDER_WIDTH * 2);
const height = PIXELS_PER_LEVEL;
if (width < HIDE_THRESHOLD) {
// We don't render nor it's children
continue;
}
let offsetModifier = 0;
let skipRender = false;
const collapsedItemConfig = collapsedMap.get(item);
const isCollapsedItem = collapsedItemConfig && collapsedItemConfig.collapsed;
if (isCollapsedItem) {
if (collapsedItemRendered === collapsedItemConfig.items[0]) {
offsetModifier = direction === 'children' ? -1 : +1;
skipRender = true;
} else {
// This is a case where we have another collapsed group right after different collapsed group, so we need to
// reset.
collapsedItemRendered = undefined;
}
} else {
collapsedItemRendered = undefined;
}
if (!skipRender) {
const barX = getBarX(item.start, totalViewTicks, rangeMin, pixelsPerTick);
const barY = (item.level + levelOffset) * PIXELS_PER_LEVEL;
let label = data.getLabel(item.itemIndexes[0]);
if (isCollapsedItem) {
collapsedItemRendered = item;
}
renderFunc(item, barX, barY, width, height, label, muted);
}
const nextList = direction === 'children' ? item.children : item.parents;
if (nextList) {
stack.unshift(...nextList.map((c) => ({ item: c, levelOffset: levelOffset + offsetModifier })));
}
}
}
function useColorFunction(
totalTicks: number,
totalTicksRight: number | undefined,
colorScheme: ColorScheme | ColorSchemeDiff,
theme: GrafanaTheme2,
mutedColor: string,
rangeMin: number,
rangeMax: number,
matchedLabels: Set<string> | undefined,
topLevel: number
) {
return useCallback(
function getColor(item: LevelItem, label: string, muted: boolean) {
// If collapsed and no search we can quickly return the muted color
if (muted && !matchedLabels) {
// Collapsed are always grayed
return mutedColor;
}
const barColor =
item.valueRight !== undefined &&
(colorScheme === ColorSchemeDiff.Default || colorScheme === ColorSchemeDiff.DiffColorBlind)
? getBarColorByDiff(item.value, item.valueRight!, totalTicks, totalTicksRight!, colorScheme)
: colorScheme === ColorScheme.ValueBased
? getBarColorByValue(item.value, totalTicks, rangeMin, rangeMax)
: getBarColorByPackage(label, theme);
if (matchedLabels) {
// Means we are searching, we use color for matches and gray the rest
return matchedLabels.has(label) ? barColor.toHslString() : mutedColor;
}
// Mute if we are above the focused symbol
return item.level > topLevel - 1 ? barColor.toHslString() : barColor.lighten(15).toHslString();
},
[totalTicks, totalTicksRight, colorScheme, theme, rangeMin, rangeMax, matchedLabels, topLevel, mutedColor]
);
}
function useSetupCanvas(canvasRef: RefObject<HTMLCanvasElement>, wrapperWidth: number, numberOfLevels: number) {
const [ctx, setCtx] = useState<CanvasRenderingContext2D>();
useEffect(() => {
if (!(numberOfLevels && canvasRef.current)) {
return;
}
const ctx = canvasRef.current.getContext('2d')!;
const height = PIXELS_PER_LEVEL * numberOfLevels;
canvasRef.current.width = Math.round(wrapperWidth * window.devicePixelRatio);
canvasRef.current.height = Math.round(height);
canvasRef.current.style.width = `${wrapperWidth}px`;
canvasRef.current.style.height = `${height / window.devicePixelRatio}px`;
ctx.textBaseline = 'middle';
ctx.font = 12 * window.devicePixelRatio + 'px monospace';
ctx.strokeStyle = 'white';
setCtx(ctx);
}, [canvasRef, setCtx, wrapperWidth, numberOfLevels]);
return ctx;
}
// Renders a text inside the node rectangle. It allows setting alignment of the text left or right which takes effect
// when text is too long to fit in the rectangle.
function renderLabel(
ctx: CanvasRenderingContext2D,
data: FlameGraphDataContainer,
label: string,
item: LevelItem,
width: number,
x: number,
y: number,
textAlign: TextAlign
) {
ctx.save();
ctx.clip(); // so text does not overflow
ctx.fillStyle = '#222';
const displayValue = data.valueDisplayProcessor(item.value);
const unit = displayValue.suffix ? displayValue.text + displayValue.suffix : displayValue.text;
// We only measure name here instead of full label because of how we deal with the units and aligning later.
const measure = ctx.measureText(label);
const spaceForTextInRect = width - BAR_TEXT_PADDING_LEFT;
let fullLabel = `${label} (${unit})`;
let labelX = Math.max(x, 0) + BAR_TEXT_PADDING_LEFT;
// We use the desired alignment only if there is not enough space for the text, otherwise we keep left alignment as
// that will already show full text.
if (measure.width > spaceForTextInRect) {
ctx.textAlign = textAlign;
// If aligned to the right we don't want to take the space with the unit label as the assumption is user wants to
// mainly see the name. This also reflects how pyro/flamegraph works.
if (textAlign === 'right') {
fullLabel = label;
labelX = x + width - BAR_TEXT_PADDING_LEFT;
}
}
ctx.fillText(fullLabel, labelX, y + PIXELS_PER_LEVEL / 2 + 2);
ctx.restore();
}
/**
* Returns the X position of the bar. totalTicks * rangeMin is to adjust for any current zoom. So if we zoom to a
* section of the graph we align and shift the X coordinates accordingly.
* @param offset
* @param totalTicks
* @param rangeMin
* @param pixelsPerTick
*/
export function getBarX(offset: number, totalTicks: number, rangeMin: number, pixelsPerTick: number) {
return (offset - totalTicks * rangeMin) * pixelsPerTick;
}