The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
grafana/packages/grafana-ui/src/components/GraphNG/GraphNG.tsx

205 lines
5.9 KiB

import React, { useCallback, useMemo, useRef } from 'react';
import {
compareDataFrameStructures,
DataFrame,
FieldConfig,
FieldMatcher,
FieldType,
formattedValueToString,
getFieldColorModeForField,
getFieldDisplayName,
} from '@grafana/data';
import { alignDataFrames } from './utils';
import { UPlotChart } from '../uPlot/Plot';
import { PlotProps } from '../uPlot/types';
import { AxisPlacement, GraphFieldConfig, GraphMode, PointMode } from '../uPlot/config';
import { useTheme } from '../../themes';
import { VizLayout } from '../VizLayout/VizLayout';
import { LegendDisplayMode, LegendItem, LegendOptions } from '../Legend/Legend';
import { GraphLegend } from '../Graph/GraphLegend';
import { UPlotConfigBuilder } from '../uPlot/config/UPlotConfigBuilder';
import { useRevision } from '../uPlot/hooks';
const defaultFormatter = (v: any) => (v == null ? '-' : v.toFixed(1));
export interface XYFieldMatchers {
x: FieldMatcher;
y: FieldMatcher;
}
Chore: Bump storybook to v6 (#28926) * Wip * feat: get storybook and app building locally * docs: comment webpack react alias * build(grafana-ui): put back ts-loader * build: prefer storybook essentials over actions and docs. bump dark-mode * chore(storybook): migrate to latest config * build: prevent test env throwing Invalid hook call errors * chore: lodash resolves to package dependency rather than project * use decorators as variable instead of function * perf(storybook): reduce bundling time by splitting type check and compilation * refactor(storybook): use sortOrder.order param to sort intro story first * build: use yarn workspace command * refactor(storybook): use previous knobs addon registration * migrate button story to controls * build(storybook): silence warnings in console * build: bump storybook related ts packages * style: remove trailing whitespace * refactor(graphng): export interface for storybook * controls migration guide * fix typo * docs(storybook): default docs to use dark theme as per current implementation * revert(grafana-ui): put back react-is namedExport this was changed for react 17 bump but causes rollup to fail during bundling * chore: bump storybook to 6.1, enable fastRefresh, silence eslint prop-types * docs(grafana-ui): move knobs -> controls migration guide to storybook style-guide * chore(storybook): silence terminal warning about order of docs addon * Update contribute/style-guides/storybook.md Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com> * Apply documentation suggestions Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com> * chore(storybook): bump to 6.1.2 Co-authored-by: Peter Holmberg <peter.hlmbrg@gmail.com> Co-authored-by: achatterjee-grafana <70489351+achatterjee-grafana@users.noreply.github.com>
5 years ago
export interface GraphNGProps extends Omit<PlotProps, 'data' | 'config'> {
data: DataFrame[];
legend?: LegendOptions;
fields?: XYFieldMatchers; // default will assume timeseries data
}
const defaultConfig: GraphFieldConfig = {
mode: GraphMode.Line,
points: PointMode.Auto,
axisPlacement: AxisPlacement.Auto,
};
export const GraphNG: React.FC<GraphNGProps> = ({
data,
fields,
children,
width,
height,
legend,
timeRange,
timeZone,
...plotProps
}) => {
const alignedFrameWithGapTest = useMemo(() => alignDataFrames(data, fields), [data, fields]);
const theme = useTheme();
const legendItemsRef = useRef<LegendItem[]>([]);
const hasLegend = useRef(legend && legend.displayMode !== LegendDisplayMode.Hidden);
const alignedFrame = alignedFrameWithGapTest?.frame;
const compareFrames = useCallback((a?: DataFrame | null, b?: DataFrame | null) => {
if (a && b) {
return compareDataFrameStructures(a, b, ['min', 'max']);
}
return false;
}, []);
const configRev = useRevision(alignedFrame, compareFrames);
const configBuilder = useMemo(() => {
const builder = new UPlotConfigBuilder();
if (!alignedFrame) {
return builder;
}
// X is the first field in the alligned frame
const xField = alignedFrame.fields[0];
if (xField.type === FieldType.time) {
builder.addScale({
scaleKey: 'x',
isTime: true,
});
builder.addAxis({
scaleKey: 'x',
isTime: true,
placement: AxisPlacement.Bottom,
timeZone,
theme,
});
} else {
// Not time!
builder.addScale({
scaleKey: 'x',
});
builder.addAxis({
scaleKey: 'x',
placement: AxisPlacement.Bottom,
theme,
});
}
let seriesIdx = 0;
const legendItems: LegendItem[] = [];
for (let i = 0; i < alignedFrame.fields.length; i++) {
const field = alignedFrame.fields[i];
const config = field.config as FieldConfig<GraphFieldConfig>;
const customConfig: GraphFieldConfig = {
...defaultConfig,
...config.custom,
};
if (field === xField || field.type !== FieldType.number) {
continue;
}
const fmt = field.display ?? defaultFormatter;
const scaleKey = config.unit || '__fixed';
if (customConfig.axisPlacement !== AxisPlacement.Hidden) {
// The builder will manage unique scaleKeys and combine where appropriate
builder.addScale({ scaleKey, min: field.config.min, max: field.config.max });
builder.addAxis({
scaleKey,
label: customConfig.axisLabel,
size: customConfig.axisWidth,
placement: customConfig.axisPlacement ?? AxisPlacement.Auto,
formatValue: v => formattedValueToString(fmt(v)),
theme,
});
}
// need to update field state here because we use a transform to merge framesP
field.state = { ...field.state, seriesIndex: seriesIdx };
const colorMode = getFieldColorModeForField(field);
const seriesColor = colorMode.getCalculator(field, theme)(0, 0);
const pointsMode = customConfig.mode === GraphMode.Points ? PointMode.Always : customConfig.points;
builder.addSeries({
scaleKey,
mode: customConfig.mode!,
lineColor: seriesColor,
lineWidth: customConfig.lineWidth,
lineInterpolation: customConfig.lineInterpolation,
points: pointsMode,
pointSize: customConfig.pointSize,
pointColor: seriesColor,
fillOpacity: customConfig.fillOpacity,
fillColor: seriesColor,
});
if (hasLegend.current) {
const axisPlacement = builder.getAxisPlacement(scaleKey);
legendItems.push({
color: seriesColor,
label: getFieldDisplayName(field, alignedFrame),
yAxis: axisPlacement === AxisPlacement.Left ? 1 : 2,
});
}
seriesIdx++;
}
legendItemsRef.current = legendItems;
return builder;
}, [configRev, timeZone]);
if (alignedFrameWithGapTest == null) {
return (
<div className="panel-empty">
<p>No data found in response</p>
</div>
);
}
let legendElement: React.ReactElement | undefined;
if (hasLegend && legendItemsRef.current.length > 0) {
legendElement = (
<VizLayout.Legend position={legend!.placement} maxHeight="35%" maxWidth="60%">
<GraphLegend placement={legend!.placement} items={legendItemsRef.current} displayMode={legend!.displayMode} />
</VizLayout.Legend>
);
}
return (
<VizLayout width={width} height={height} legend={legendElement}>
{(vizWidth: number, vizHeight: number) => (
<UPlotChart
data={alignedFrameWithGapTest}
config={configBuilder}
width={vizWidth}
height={vizHeight}
timeRange={timeRange}
timeZone={timeZone}
{...plotProps}
>
{children}
</UPlotChart>
)}
</VizLayout>
);
};