bars.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. import uPlot, { Axis, AlignedData, Scale } from 'uplot';
  2. import { DataFrame, GrafanaTheme2 } from '@grafana/data';
  3. import { alpha } from '@grafana/data/src/themes/colorManipulator';
  4. import {
  5. StackingMode,
  6. VisibilityMode,
  7. ScaleDirection,
  8. ScaleOrientation,
  9. VizTextDisplayOptions,
  10. VizLegendOptions,
  11. } from '@grafana/schema';
  12. import { measureText, PlotTooltipInterpolator } from '@grafana/ui';
  13. import { formatTime } from '@grafana/ui/src/components/uPlot/config/UPlotAxisBuilder';
  14. import { preparePlotData2, StackingGroup } from '../../../../../packages/grafana-ui/src/components/uPlot/utils';
  15. import { distribute, SPACE_BETWEEN } from './distribute';
  16. import { intersects, pointWithin, Quadtree, Rect } from './quadtree';
  17. const groupDistr = SPACE_BETWEEN;
  18. const barDistr = SPACE_BETWEEN;
  19. // min.max font size for value label
  20. const VALUE_MIN_FONT_SIZE = 8;
  21. const VALUE_MAX_FONT_SIZE = 30;
  22. // % of width/height of the bar that value should fit in when measuring size
  23. const BAR_FONT_SIZE_RATIO = 0.65;
  24. // distance between label and a bar in % of bar width
  25. const LABEL_OFFSET_FACTOR_VT = 0.1;
  26. const LABEL_OFFSET_FACTOR_HZ = 0.15;
  27. // max distance
  28. const LABEL_OFFSET_MAX_VT = 5;
  29. const LABEL_OFFSET_MAX_HZ = 10;
  30. // text baseline middle runs through the middle of lowercase letters
  31. // since bar values are numbers and uppercase-like, we want the middle of uppercase
  32. // this is a cheap fudge factor that skips expensive and inconsistent cross-browser measuring
  33. const MIDDLE_BASELINE_SHIFT = 0.1;
  34. /**
  35. * @internal
  36. */
  37. export interface BarsOptions {
  38. xOri: ScaleOrientation;
  39. xDir: ScaleDirection;
  40. groupWidth: number;
  41. barWidth: number;
  42. barRadius: number;
  43. showValue: VisibilityMode;
  44. stacking: StackingMode;
  45. rawValue: (seriesIdx: number, valueIdx: number) => number | null;
  46. getColor?: (seriesIdx: number, valueIdx: number, value: any) => string | null;
  47. fillOpacity?: number;
  48. formatValue: (seriesIdx: number, value: any) => string;
  49. text?: VizTextDisplayOptions;
  50. onHover?: (seriesIdx: number, valueIdx: number) => void;
  51. onLeave?: (seriesIdx: number, valueIdx: number) => void;
  52. legend?: VizLegendOptions;
  53. xSpacing?: number;
  54. xTimeAuto?: boolean;
  55. }
  56. /**
  57. * @internal
  58. */
  59. interface ValueLabelTable {
  60. [index: number]: ValueLabelArray;
  61. }
  62. /**
  63. * @internal
  64. */
  65. interface ValueLabelArray {
  66. [index: number]: ValueLabel;
  67. }
  68. /**
  69. * @internal
  70. */
  71. interface ValueLabel {
  72. text: string;
  73. value: number | null;
  74. hidden: boolean;
  75. bbox?: Rect;
  76. textMetrics?: TextMetrics;
  77. x?: number;
  78. y?: number;
  79. }
  80. /**
  81. * @internal
  82. */
  83. function calculateFontSizeWithMetrics(
  84. text: string,
  85. width: number,
  86. height: number,
  87. lineHeight: number,
  88. maxSize?: number
  89. ) {
  90. // calculate width in 14px
  91. const textSize = measureText(text, 14);
  92. // how much bigger than 14px can we make it while staying within our width constraints
  93. const fontSizeBasedOnWidth = (width / (textSize.width + 2)) * 14;
  94. const fontSizeBasedOnHeight = height / lineHeight;
  95. // final fontSize
  96. const optimalSize = Math.min(fontSizeBasedOnHeight, fontSizeBasedOnWidth);
  97. return {
  98. fontSize: Math.min(optimalSize, maxSize ?? optimalSize),
  99. textMetrics: textSize,
  100. };
  101. }
  102. /**
  103. * @internal
  104. */
  105. export function getConfig(opts: BarsOptions, theme: GrafanaTheme2) {
  106. const { xOri, xDir: dir, rawValue, getColor, formatValue, fillOpacity = 1, showValue, xSpacing = 0 } = opts;
  107. const isXHorizontal = xOri === ScaleOrientation.Horizontal;
  108. const hasAutoValueSize = !Boolean(opts.text?.valueSize);
  109. const isStacked = opts.stacking !== StackingMode.None;
  110. const pctStacked = opts.stacking === StackingMode.Percent;
  111. let { groupWidth, barWidth, barRadius = 0 } = opts;
  112. if (isStacked) {
  113. [groupWidth, barWidth] = [barWidth, groupWidth];
  114. }
  115. let qt: Quadtree;
  116. let hRect: Rect | null;
  117. const xSplits: Axis.Splits = (u: uPlot) => {
  118. const dim = isXHorizontal ? u.bbox.width : u.bbox.height;
  119. const _dir = dir * (isXHorizontal ? 1 : -1);
  120. let dataLen = u.data[0].length;
  121. let lastIdx = dataLen - 1;
  122. let skipMod = 0;
  123. if (xSpacing !== 0) {
  124. let cssDim = dim / devicePixelRatio;
  125. let maxTicks = Math.abs(Math.floor(cssDim / xSpacing));
  126. skipMod = dataLen < maxTicks ? 0 : Math.ceil(dataLen / maxTicks);
  127. }
  128. let splits: number[] = [];
  129. // for distr: 2 scales, the splits array should contain indices into data[0] rather than values
  130. u.data[0].forEach((v, i) => {
  131. let shouldSkip = skipMod !== 0 && (xSpacing > 0 ? i : lastIdx - i) % skipMod > 0;
  132. if (!shouldSkip) {
  133. splits.push(i);
  134. }
  135. });
  136. return _dir === 1 ? splits : splits.reverse();
  137. };
  138. // the splits passed into here are data[0] values looked up by the indices returned from splits()
  139. const xValues: Axis.Values = (u, splits, axisIdx, foundSpace, foundIncr) => {
  140. if (opts.xTimeAuto) {
  141. // bit of a hack:
  142. // temporarily set x scale range to temporal (as expected by formatTime()) rather than ordinal
  143. let xScale = u.scales.x;
  144. let oMin = xScale.min;
  145. let oMax = xScale.max;
  146. xScale.min = u.data[0][0];
  147. xScale.max = u.data[0][u.data[0].length - 1];
  148. let vals = formatTime(u, splits, axisIdx, foundSpace, foundIncr);
  149. // revert
  150. xScale.min = oMin;
  151. xScale.max = oMax;
  152. return vals;
  153. }
  154. return splits.map((v) => formatValue(0, v));
  155. };
  156. // this expands the distr: 2 scale so that the indicies of each data[0] land at the proper justified positions
  157. const xRange: Scale.Range = (u, min, max) => {
  158. min = 0;
  159. max = Math.max(1, u.data[0].length - 1);
  160. let pctOffset = 0;
  161. // how far in is the first tick in % of full dimension
  162. distribute(u.data[0].length, groupWidth, groupDistr, 0, (di, lftPct, widPct) => {
  163. pctOffset = lftPct + widPct / 2;
  164. });
  165. // expand scale range by equal amounts on both ends
  166. let rn = max - min;
  167. if (pctOffset === 0.5) {
  168. min -= rn;
  169. } else {
  170. let upScale = 1 / (1 - pctOffset * 2);
  171. let offset = (upScale * rn - rn) / 2;
  172. min -= offset;
  173. max += offset;
  174. }
  175. return [min, max];
  176. };
  177. let distrTwo = (groupCount: number, barCount: number) => {
  178. let out = Array.from({ length: barCount }, () => ({
  179. offs: Array(groupCount).fill(0),
  180. size: Array(groupCount).fill(0),
  181. }));
  182. distribute(groupCount, groupWidth, groupDistr, null, (groupIdx, groupOffPct, groupDimPct) => {
  183. distribute(barCount, barWidth, barDistr, null, (barIdx, barOffPct, barDimPct) => {
  184. out[barIdx].offs[groupIdx] = groupOffPct + groupDimPct * barOffPct;
  185. out[barIdx].size[groupIdx] = groupDimPct * barDimPct;
  186. });
  187. });
  188. return out;
  189. };
  190. let distrOne = (groupCount: number, barCount: number) => {
  191. let out = Array.from({ length: barCount }, () => ({
  192. offs: Array(groupCount).fill(0),
  193. size: Array(groupCount).fill(0),
  194. }));
  195. distribute(groupCount, groupWidth, groupDistr, null, (groupIdx, groupOffPct, groupDimPct) => {
  196. distribute(barCount, barWidth, barDistr, null, (barIdx, barOffPct, barDimPct) => {
  197. out[barIdx].offs[groupIdx] = groupOffPct;
  198. out[barIdx].size[groupIdx] = groupDimPct;
  199. });
  200. });
  201. return out;
  202. };
  203. const LABEL_OFFSET_FACTOR = isXHorizontal ? LABEL_OFFSET_FACTOR_VT : LABEL_OFFSET_FACTOR_HZ;
  204. const LABEL_OFFSET_MAX = isXHorizontal ? LABEL_OFFSET_MAX_VT : LABEL_OFFSET_MAX_HZ;
  205. let barsPctLayout: Array<null | { offs: number[]; size: number[] }> = [];
  206. let barsColors: Array<null | { fill: Array<string | null>; stroke: Array<string | null> }> = [];
  207. let scaleFactor = 1;
  208. let labels: ValueLabelTable;
  209. let fontSize = opts.text?.valueSize ?? VALUE_MAX_FONT_SIZE;
  210. let labelOffset = LABEL_OFFSET_MAX;
  211. // minimum available space for labels between bar end and plotting area bound (in canvas pixels)
  212. let vSpace = Infinity;
  213. let hSpace = Infinity;
  214. let useMappedColors = getColor != null;
  215. let mappedColorDisp = useMappedColors
  216. ? {
  217. fill: {
  218. unit: 3,
  219. values: (u: uPlot, seriesIdx: number) => barsColors[seriesIdx]!.fill,
  220. },
  221. stroke: {
  222. unit: 3,
  223. values: (u: uPlot, seriesIdx: number) => barsColors[seriesIdx]!.stroke,
  224. },
  225. }
  226. : {};
  227. let barsBuilder = uPlot.paths.bars!({
  228. radius: barRadius,
  229. disp: {
  230. x0: {
  231. unit: 2,
  232. values: (u, seriesIdx) => barsPctLayout[seriesIdx]!.offs,
  233. },
  234. size: {
  235. unit: 2,
  236. values: (u, seriesIdx) => barsPctLayout[seriesIdx]!.size,
  237. },
  238. ...mappedColorDisp,
  239. },
  240. // collect rendered bar geometry
  241. each: (u, seriesIdx, dataIdx, lft, top, wid, hgt) => {
  242. // we get back raw canvas coords (included axes & padding)
  243. // translate to the plotting area origin
  244. lft -= u.bbox.left;
  245. top -= u.bbox.top;
  246. let val = u.data[seriesIdx][dataIdx]!;
  247. // accum min space abvailable for labels
  248. if (isXHorizontal) {
  249. vSpace = Math.min(vSpace, val < 0 ? u.bbox.height - (top + hgt) : top);
  250. hSpace = wid;
  251. } else {
  252. vSpace = hgt;
  253. hSpace = Math.min(hSpace, val < 0 ? lft : u.bbox.width - (lft + wid));
  254. }
  255. let barRect = { x: lft, y: top, w: wid, h: hgt, sidx: seriesIdx, didx: dataIdx };
  256. qt.add(barRect);
  257. if (showValue !== VisibilityMode.Never) {
  258. const raw = rawValue(seriesIdx, dataIdx)!;
  259. let divider = 1;
  260. if (pctStacked && alignedTotals![seriesIdx][dataIdx]!) {
  261. divider = alignedTotals![seriesIdx][dataIdx]!;
  262. }
  263. const v = divider === 0 ? 0 : raw / divider;
  264. // Format Values and calculate label offsets
  265. const text = formatValue(seriesIdx, v);
  266. labelOffset = Math.min(labelOffset, Math.round(LABEL_OFFSET_FACTOR * (isXHorizontal ? wid : hgt)));
  267. if (labels[dataIdx] === undefined) {
  268. labels[dataIdx] = {};
  269. }
  270. labels[dataIdx][seriesIdx] = { text: text, value: rawValue(seriesIdx, dataIdx), hidden: false };
  271. // Calculate font size when it's set to be automatic
  272. if (hasAutoValueSize) {
  273. const { fontSize: calculatedSize, textMetrics } = calculateFontSizeWithMetrics(
  274. labels[dataIdx][seriesIdx].text,
  275. hSpace * (isXHorizontal ? BAR_FONT_SIZE_RATIO : 1) - (isXHorizontal ? 0 : labelOffset),
  276. vSpace * (isXHorizontal ? 1 : BAR_FONT_SIZE_RATIO) - (isXHorizontal ? labelOffset : 0),
  277. 1
  278. );
  279. // Save text metrics
  280. labels[dataIdx][seriesIdx].textMetrics = textMetrics;
  281. // Retrieve the new font size and use it
  282. let autoFontSize = Math.round(Math.min(fontSize, VALUE_MAX_FONT_SIZE, calculatedSize));
  283. // Calculate the scaling factor for bouding boxes
  284. // Take into account the fact that calculateFontSize
  285. // uses 14px measurement so we need to adjust the scale factor
  286. scaleFactor = (autoFontSize / fontSize) * (autoFontSize / 14);
  287. // Update the end font-size
  288. fontSize = autoFontSize;
  289. } else {
  290. labels[dataIdx][seriesIdx].textMetrics = measureText(labels[dataIdx][seriesIdx].text, fontSize);
  291. }
  292. let middleShift = isXHorizontal ? 0 : -Math.round(MIDDLE_BASELINE_SHIFT * fontSize);
  293. let value = rawValue(seriesIdx, dataIdx);
  294. if (value != null) {
  295. // Calculate final co-ordinates for text position
  296. const x =
  297. u.bbox.left + (isXHorizontal ? lft + wid / 2 : value < 0 ? lft - labelOffset : lft + wid + labelOffset);
  298. const y =
  299. u.bbox.top +
  300. (isXHorizontal ? (value < 0 ? top + hgt + labelOffset : top - labelOffset) : top + hgt / 2 - middleShift);
  301. // Retrieve textMetrics with necessary default values
  302. // These _shouldn't_ be undefined at this point
  303. // but they _could_ be.
  304. const {
  305. textMetrics = {
  306. width: 1,
  307. actualBoundingBoxAscent: 1,
  308. actualBoundingBoxDescent: 1,
  309. },
  310. } = labels[dataIdx][seriesIdx];
  311. // Adjust bounding boxes based on text scale
  312. // factor and orientation (which changes the baseline)
  313. let xAdjust = 0,
  314. yAdjust = 0;
  315. if (isXHorizontal) {
  316. // Adjust for baseline which is "top" in this case
  317. xAdjust = (textMetrics.width * scaleFactor) / 2;
  318. // yAdjust only matters when when the value isn't negative
  319. yAdjust =
  320. value > 0
  321. ? (textMetrics.actualBoundingBoxAscent + textMetrics.actualBoundingBoxDescent) * scaleFactor
  322. : 0;
  323. } else {
  324. // Adjust from the baseline which is "middle" in this case
  325. yAdjust = ((textMetrics.actualBoundingBoxAscent + textMetrics.actualBoundingBoxDescent) * scaleFactor) / 2;
  326. // Adjust for baseline being "right" in the x direction
  327. xAdjust = value < 0 ? textMetrics.width * scaleFactor : 0;
  328. }
  329. // Construct final bounding box for the label text
  330. labels[dataIdx][seriesIdx].x = x;
  331. labels[dataIdx][seriesIdx].y = y;
  332. labels[dataIdx][seriesIdx].bbox = {
  333. x: x - xAdjust,
  334. y: y - yAdjust,
  335. w: textMetrics.width * scaleFactor,
  336. h: (textMetrics.actualBoundingBoxAscent + textMetrics.actualBoundingBoxDescent) * scaleFactor,
  337. };
  338. }
  339. }
  340. },
  341. });
  342. const init = (u: uPlot) => {
  343. let over = u.over;
  344. over.style.overflow = 'hidden';
  345. u.root.querySelectorAll('.u-cursor-pt').forEach((el) => {
  346. (el as HTMLElement).style.borderRadius = '0';
  347. });
  348. };
  349. const cursor: uPlot.Cursor = {
  350. x: false,
  351. y: false,
  352. drag: {
  353. x: false,
  354. y: false,
  355. },
  356. dataIdx: (u, seriesIdx) => {
  357. if (seriesIdx === 1) {
  358. hRect = null;
  359. let cx = u.cursor.left! * devicePixelRatio;
  360. let cy = u.cursor.top! * devicePixelRatio;
  361. qt.get(cx, cy, 1, 1, (o) => {
  362. if (pointWithin(cx, cy, o.x, o.y, o.x + o.w, o.y + o.h)) {
  363. hRect = o;
  364. }
  365. });
  366. }
  367. return hRect && seriesIdx === hRect.sidx ? hRect.didx : null;
  368. },
  369. points: {
  370. fill: 'rgba(255,255,255,0.4)',
  371. bbox: (u, seriesIdx) => {
  372. let isHovered = hRect && seriesIdx === hRect.sidx;
  373. return {
  374. left: isHovered ? hRect!.x / devicePixelRatio : -10,
  375. top: isHovered ? hRect!.y / devicePixelRatio : -10,
  376. width: isHovered ? hRect!.w / devicePixelRatio : 0,
  377. height: isHovered ? hRect!.h / devicePixelRatio : 0,
  378. };
  379. },
  380. },
  381. };
  382. // Build bars
  383. const drawClear = (u: uPlot) => {
  384. qt = qt || new Quadtree(0, 0, u.bbox.width, u.bbox.height);
  385. qt.clear();
  386. // clear the path cache to force drawBars() to rebuild new quadtree
  387. u.series.forEach((s) => {
  388. // @ts-ignore
  389. s._paths = null;
  390. });
  391. if (isStacked) {
  392. //barsPctLayout = [null as any].concat(distrOne(u.data.length - 1, u.data[0].length));
  393. barsPctLayout = [null as any].concat(distrOne(u.data[0].length, u.data.length - 1));
  394. } else {
  395. barsPctLayout = [null as any].concat(distrTwo(u.data[0].length, u.data.length - 1));
  396. }
  397. if (useMappedColors) {
  398. barsColors = [null];
  399. // map per-bar colors
  400. for (let i = 1; i < u.data.length; i++) {
  401. let colors = (u.data[i] as Array<number | null>).map((value, valueIdx) => {
  402. if (value != null) {
  403. return getColor!(i, valueIdx, value);
  404. }
  405. return null;
  406. });
  407. barsColors.push({
  408. fill: fillOpacity < 1 ? colors.map((c) => (c != null ? alpha(c, fillOpacity) : null)) : colors,
  409. stroke: colors,
  410. });
  411. }
  412. }
  413. labels = {};
  414. fontSize = opts.text?.valueSize ?? VALUE_MAX_FONT_SIZE;
  415. labelOffset = LABEL_OFFSET_MAX;
  416. vSpace = hSpace = Infinity;
  417. };
  418. // uPlot hook to draw the labels on the bar chart.
  419. const draw = (u: uPlot) => {
  420. if (showValue === VisibilityMode.Never || fontSize < VALUE_MIN_FONT_SIZE) {
  421. return;
  422. }
  423. u.ctx.save();
  424. u.ctx.fillStyle = theme.colors.text.primary;
  425. u.ctx.font = `${fontSize}px ${theme.typography.fontFamily}`;
  426. let curAlign: CanvasTextAlign | undefined = undefined,
  427. curBaseline: CanvasTextBaseline | undefined = undefined;
  428. for (const didx in labels) {
  429. // exclude first label from overlap testing
  430. let first = true;
  431. for (const sidx in labels[didx]) {
  432. const label = labels[didx][sidx];
  433. const { text, value, x = 0, y = 0 } = label;
  434. let align: CanvasTextAlign = isXHorizontal ? 'center' : value !== null && value < 0 ? 'right' : 'left';
  435. let baseline: CanvasTextBaseline = isXHorizontal
  436. ? value !== null && value < 0
  437. ? 'top'
  438. : 'alphabetic'
  439. : 'middle';
  440. if (align !== curAlign) {
  441. u.ctx.textAlign = curAlign = align;
  442. }
  443. if (baseline !== curBaseline) {
  444. u.ctx.textBaseline = curBaseline = baseline;
  445. }
  446. if (showValue === VisibilityMode.Always) {
  447. u.ctx.fillText(text, x, y);
  448. } else if (showValue === VisibilityMode.Auto) {
  449. let { bbox } = label;
  450. let intersectsLabel = false;
  451. if (bbox == null) {
  452. intersectsLabel = true;
  453. label.hidden = true;
  454. } else if (!first) {
  455. // Test for any collisions
  456. for (const subsidx in labels[didx]) {
  457. if (subsidx === sidx) {
  458. continue;
  459. }
  460. const label2 = labels[didx][subsidx];
  461. const { bbox: bbox2, hidden } = label2;
  462. if (!hidden && bbox2 && intersects(bbox, bbox2)) {
  463. intersectsLabel = true;
  464. label.hidden = true;
  465. break;
  466. }
  467. }
  468. }
  469. first = false;
  470. !intersectsLabel && u.ctx.fillText(text, x, y);
  471. }
  472. }
  473. }
  474. u.ctx.restore();
  475. };
  476. // handle hover interaction with quadtree probing
  477. const interpolateTooltip: PlotTooltipInterpolator = (
  478. updateActiveSeriesIdx,
  479. updateActiveDatapointIdx,
  480. updateTooltipPosition,
  481. u
  482. ) => {
  483. if (hRect) {
  484. updateActiveSeriesIdx(hRect.sidx);
  485. updateActiveDatapointIdx(hRect.didx);
  486. updateTooltipPosition();
  487. } else {
  488. updateTooltipPosition(true);
  489. }
  490. };
  491. let alignedTotals: AlignedData | null = null;
  492. function prepData(frames: DataFrame[], stackingGroups: StackingGroup[]) {
  493. alignedTotals = null;
  494. return preparePlotData2(frames[0], stackingGroups, ({ totals }) => {
  495. alignedTotals = totals;
  496. });
  497. }
  498. return {
  499. cursor,
  500. // scale & axis opts
  501. xRange,
  502. xValues,
  503. xSplits,
  504. barsBuilder,
  505. // hooks
  506. init,
  507. drawClear,
  508. draw,
  509. interpolateTooltip,
  510. prepData,
  511. };
  512. }