@grafana/data#ArrayVector TypeScript Examples
The following examples show how to use
@grafana/data#ArrayVector.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From grafana-chinese with Apache License 2.0 | 7 votes |
export function feedToDataFrame(feed: RssFeed): DataFrame {
const date = new ArrayVector<number>([]);
const title = new ArrayVector<string>([]);
const link = new ArrayVector<string>([]);
const content = new ArrayVector<string>([]);
for (const item of feed.items) {
const val = dateTime(item.pubDate);
try {
date.buffer.push(val.valueOf());
title.buffer.push(item.title);
link.buffer.push(item.link);
if (item.content) {
const body = item.content.replace(/<\/?[^>]+(>|$)/g, '');
content.buffer.push(body);
}
} catch (err) {
console.warn('Error reading news item:', err, item);
}
}
return {
fields: [
{ name: 'date', type: FieldType.time, config: { title: 'Date' }, values: date },
{ name: 'title', type: FieldType.string, config: {}, values: title },
{ name: 'link', type: FieldType.string, config: {}, values: link },
{ name: 'content', type: FieldType.string, config: {}, values: content },
],
length: date.length,
};
}
Example #2
Source File: DebugSection.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
function makeDebugFields(derivedFields: DerivedFieldConfig[], debugText: string): DebugField[] {
return derivedFields
.filter(field => field.name && field.matcherRegex)
.map(field => {
try {
const testMatch = debugText.match(field.matcherRegex);
const value = testMatch && testMatch[1];
let link;
if (field.url && value) {
link = getLinksFromLogsField(
{
name: '',
type: FieldType.string,
values: new ArrayVector([value]),
config: {
links: [{ title: '', url: field.url }],
},
},
0
)[0];
}
return {
name: field.name,
value: value || '<no match>',
href: link && link.href,
} as DebugField;
} catch (error) {
return {
name: field.name,
error,
} as DebugField;
}
});
}
Example #3
Source File: result_transformer.ts From grafana-chinese with Apache License 2.0 | 6 votes |
/**
* Transforms LokiLogStream structure into a dataFrame. Used when doing standard queries and older version of Loki.
*/
export function legacyLogStreamToDataFrame(
stream: LokiLegacyStreamResult,
reverse?: boolean,
refId?: string
): DataFrame {
let labels: Labels = stream.parsedLabels;
if (!labels && stream.labels) {
labels = parseLabels(stream.labels);
}
const times = new ArrayVector<string>([]);
const timesNs = new ArrayVector<string>([]);
const lines = new ArrayVector<string>([]);
const uids = new ArrayVector<string>([]);
for (const entry of stream.entries) {
const ts = entry.ts || entry.timestamp;
// iso string with nano precision, will be truncated but is parse-able
times.add(ts);
// So this matches new format, we are loosing precision here, which sucks but no easy way to keep it and this
// is for old pre 1.0.0 version Loki so probably does not affect that much.
timesNs.add(dateTime(ts).valueOf() + '000000');
lines.add(entry.line);
uids.add(createUid(ts, stream.labels, entry.line));
}
return constructDataFrame(times, timesNs, lines, uids, labels, reverse, refId);
}
Example #4
Source File: result_transformer.ts From grafana-chinese with Apache License 2.0 | 6 votes |
/**
* Transforms LokiStreamResult structure into a dataFrame. Used when doing standard queries and newer version of Loki.
*/
export function lokiStreamResultToDataFrame(stream: LokiStreamResult, reverse?: boolean, refId?: string): DataFrame {
const labels: Labels = stream.stream;
const labelsString = Object.entries(labels)
.map(([key, val]) => `${key}="${val}"`)
.sort()
.join('');
const times = new ArrayVector<string>([]);
const timesNs = new ArrayVector<string>([]);
const lines = new ArrayVector<string>([]);
const uids = new ArrayVector<string>([]);
for (const [ts, line] of stream.values) {
// num ns epoch in string, we convert it to iso string here so it matches old format
times.add(new Date(parseInt(ts.substr(0, ts.length - 6), 10)).toISOString());
timesNs.add(ts);
lines.add(line);
uids.add(createUid(ts, labelsString, line));
}
return constructDataFrame(times, timesNs, lines, uids, labels, reverse, refId);
}
Example #5
Source File: result_transformer.ts From grafana-chinese with Apache License 2.0 | 6 votes |
/**
* Constructs dataFrame with supplied fields and other data. Also makes sure it is properly reversed if needed.
*/
function constructDataFrame(
times: ArrayVector<string>,
timesNs: ArrayVector<string>,
lines: ArrayVector<string>,
uids: ArrayVector<string>,
labels: Labels,
reverse?: boolean,
refId?: string
) {
const dataFrame = {
refId,
fields: [
{ name: 'ts', type: FieldType.time, config: { title: 'Time' }, values: times }, // Time
{ name: 'line', type: FieldType.string, config: {}, values: lines, labels }, // Line
{ name: 'id', type: FieldType.string, config: {}, values: uids },
{ name: 'tsNs', type: FieldType.time, config: { title: 'Time ns' }, values: timesNs }, // Time
],
length: times.length,
};
if (reverse) {
const mutableDataFrame = new MutableDataFrame(dataFrame);
mutableDataFrame.reverse();
return mutableDataFrame;
}
return dataFrame;
}
Example #6
Source File: Graph.story.tsx From grafana-chinese with Apache License 2.0 | 5 votes |
series: GraphSeriesXY[] = [
{
data: [
[1546372800000, 10],
[1546376400000, 20],
[1546380000000, 10],
],
color: 'red',
isVisible: true,
label: 'A-series',
seriesIndex: 0,
timeField: {
type: FieldType.time,
name: 'time',
values: new ArrayVector([1546372800000, 1546376400000, 1546380000000]),
config: {},
},
valueField: {
type: FieldType.number,
name: 'a-series',
values: new ArrayVector([10, 20, 10]),
config: {
color: {
mode: FieldColorMode.Fixed,
fixedColor: 'red',
},
},
},
timeStep: 3600000,
yAxis: {
index: 0,
},
},
{
data: [
[1546372800000, 20],
[1546376400000, 30],
[1546380000000, 40],
],
color: 'blue',
isVisible: true,
label:
"B-series with an ultra wide label that probably gonna make the tooltip to overflow window. This situation happens, so let's better make sure it behaves nicely :)",
seriesIndex: 1,
timeField: {
type: FieldType.time,
name: 'time',
values: new ArrayVector([1546372800000, 1546376400000, 1546380000000]),
config: {},
},
valueField: {
type: FieldType.number,
name:
"B-series with an ultra wide label that is probably going go make the tooltip overflow window. This situation happens, so let's better make sure it behaves nicely :)",
values: new ArrayVector([20, 30, 40]),
config: {
color: {
mode: FieldColorMode.Fixed,
fixedColor: 'blue',
},
},
},
timeStep: 3600000,
yAxis: {
index: 0,
},
},
]
Example #7
Source File: Graph.test.tsx From grafana-chinese with Apache License 2.0 | 5 votes |
series: GraphSeriesXY[] = [
{
data: [
[1546372800000, 10],
[1546376400000, 20],
[1546380000000, 10],
],
color: 'red',
isVisible: true,
label: 'A-series',
seriesIndex: 0,
timeField: {
type: FieldType.time,
name: 'time',
values: new ArrayVector([1546372800000, 1546376400000, 1546380000000]),
config: {},
},
valueField: {
type: FieldType.number,
name: 'a-series',
values: new ArrayVector([10, 20, 10]),
config: { color: { mode: FieldColorMode.Fixed, fixedColor: 'red' } },
},
timeStep: 3600000,
yAxis: {
index: 0,
},
},
{
data: [
[1546372800000, 20],
[1546376400000, 30],
[1546380000000, 40],
],
color: 'blue',
isVisible: true,
label: 'B-series',
seriesIndex: 0,
timeField: {
type: FieldType.time,
name: 'time',
values: new ArrayVector([1546372800000, 1546376400000, 1546380000000]),
config: {},
},
valueField: {
type: FieldType.number,
name: 'b-series',
values: new ArrayVector([20, 30, 40]),
config: { color: { mode: FieldColorMode.Fixed, fixedColor: 'blue' } },
},
timeStep: 3600000,
yAxis: {
index: 0,
},
},
]
Example #8
Source File: GraphWithLegend.story.tsx From grafana-chinese with Apache License 2.0 | 5 votes |
series: GraphSeriesXY[] = [
{
data: [
[1546372800000, 10],
[1546376400000, 20],
[1546380000000, 10],
],
color: 'red',
isVisible: true,
label: 'A-series',
seriesIndex: 0,
timeField: {
type: FieldType.time,
name: 'time',
values: new ArrayVector([1546372800000, 1546376400000, 1546380000000]),
config: {},
},
valueField: {
type: FieldType.number,
name: 'a-series',
values: new ArrayVector([10, 20, 10]),
config: {
color: {
mode: FieldColorMode.Fixed,
fixedColor: 'red',
},
},
},
timeStep: 3600000,
yAxis: {
index: 1,
},
},
{
data: [
[1546372800000, 20],
[1546376400000, 30],
[1546380000000, 40],
],
color: 'blue',
isVisible: true,
label: 'B-series',
seriesIndex: 1,
timeField: {
type: FieldType.time,
name: 'time',
values: new ArrayVector([1546372800000, 1546376400000, 1546380000000]),
config: {},
},
valueField: {
type: FieldType.number,
name: 'b-series',
values: new ArrayVector([20, 30, 40]),
config: {
color: {
mode: FieldColorMode.Fixed,
fixedColor: 'blue',
},
},
},
timeStep: 3600000,
yAxis: {
index: 1,
},
},
]
Example #9
Source File: result_transformer.ts From grafana-chinese with Apache License 2.0 | 5 votes |
enhanceDataFrame = (dataFrame: DataFrame, config: LokiOptions | null): void => {
if (!config) {
return;
}
const derivedFields = config.derivedFields ?? [];
if (!derivedFields.length) {
return;
}
const fields = derivedFields.reduce((acc, field) => {
const config: FieldConfig = {};
if (field.url) {
config.links = [
{
url: field.url,
title: '',
},
];
}
const dataFrameField = {
name: field.name,
type: FieldType.string,
config,
values: new ArrayVector<string>([]),
};
acc[field.name] = dataFrameField;
return acc;
}, {} as Record<string, any>);
const view = new DataFrameView(dataFrame);
view.forEachRow((row: { line: string }) => {
for (const field of derivedFields) {
const logMatch = row.line.match(field.matcherRegex);
fields[field.name].values.add(logMatch && logMatch[1]);
}
});
dataFrame.fields = [...dataFrame.fields, ...Object.values(fields)];
}
Example #10
Source File: datasource.ts From autohome-compareQueries-datasource with MIT License | 4 votes |
_compareQuery(options, targets, querys, _this) {
var comparePromises: any[] = [];
//console.log('_compareQuery targets', targets)
_.forEach(targets, function(target) {
var query = target.query;
if (query === null || query === '' || querys[query] === null) {
return;
}
var queryObj = _.cloneDeep(querys[query][0]);
queryObj.hide = false;
if (queryObj) {
var compareDsName = queryObj.datasource;
if (target.timeShifts && target.timeShifts.length > 0) {
_.forEach(target.timeShifts, function(timeShift) {
var timeShiftValue;
var timeShiftAlias;
var aliasType = timeShift.aliasType || 'suffix';
var delimiter = timeShift.delimiter || '_';
var comparePromise = _this.datasourceSrv
.get(compareDsName)
.then(function(compareDs) {
if (compareDs.meta.id === _this.meta.id) {
return { data: [] };
}
timeShiftValue = _this.templateSrv.replace(timeShift.value, options.scopedVars);
timeShiftAlias = _this.templateSrv.replace(timeShift.alias, options.scopedVars) || timeShiftValue;
if (timeShiftValue === null || timeShiftValue === '' || typeof timeShiftValue === 'undefined') {
return { data: [] };
}
let compareOptions = _.cloneDeep(options);
compareOptions.range.from = _this.addTimeShift(compareOptions.range.from, timeShiftValue);
compareOptions.range.to = _this.addTimeShift(compareOptions.range.to, timeShiftValue);
compareOptions.range.raw = {
from: compareOptions.range.from,
to: compareOptions.range.to,
};
compareOptions.rangeRaw = compareOptions.range.raw;
queryObj.refId = queryObj.refId + '_' + timeShiftValue;
compareOptions.targets = [queryObj];
compareOptions.requestId = compareOptions.requestId + '_' + timeShiftValue;
var compareResult = compareDs.query(compareOptions);
return typeof compareResult.toPromise === 'function' ? compareResult.toPromise() : compareResult;
})
.then(function(compareResult) {
var data = compareResult.data;
data.forEach(function(line) {
if (line.target) {
// if old time series format
line.target = _this.generalAlias(line.target, timeShiftAlias, aliasType, delimiter);
typeof line.title !== 'undefined' &&
line.title !== null &&
(line.title = _this.generalAlias(line.title, timeShiftAlias, aliasType, delimiter));
} else if (line.fields) {
//else if new data frames format with multiple series
line.fields.forEach(function(field) {
if (field.name) {
field.name = _this.generalAlias(field.name, timeShiftAlias, aliasType, delimiter);
}
if (field.config && field.config.displayName) {
field.config.displayName = _this.generalAlias(
field.config.displayName,
timeShiftAlias,
aliasType,
delimiter
);
}
if (field.config && field.config.displayNameFromDS) {
field.config.displayNameFromDS = _this.generalAlias(
field.config.displayNameFromDS,
timeShiftAlias,
aliasType,
delimiter
);
}
});
}
if (target.process) {
let timeShift_ms = _this.parseShiftToMs(timeShiftValue);
if (line.type === 'table') {
if (line.rows) {
line.rows.forEach(function(row) {
row[0] = row[0] + timeShift_ms;
});
}
} else {
if (line.datapoints) {
// if old time series format
line.datapoints.forEach(function(datapoint) {
datapoint[1] = datapoint[1] + timeShift_ms;
});
} else if (line.fields && line.fields.length > 0) {
//else if new data frames format
const unshiftedTimeField = line.fields.find(field => field.type === 'time');
if (unshiftedTimeField) {
const timeField: MutableField = {
name: unshiftedTimeField.name,
type: unshiftedTimeField.type,
config: unshiftedTimeField.config || {},
labels: unshiftedTimeField.labels,
values: new ArrayVector(),
};
for (let i = 0; i < line.length; i++) {
timeField.values.set(i, unshiftedTimeField.values.get(i) + timeShift_ms);
}
line.fields[0] = timeField;
}
}
}
}
line.hide = target.hide;
});
return {
data: data,
};
});
comparePromises.push(comparePromise);
});
}
}
});
return this.$q.all(comparePromises).then(function(results) {
return {
data: _.flatten(
_.filter(
_.map(results, function(result) {
var data = result.data;
if (data) {
data = _.filter(result.data, function(datum) {
return datum.hide !== true;
});
}
return data;
}),
function(result) {
return result !== undefined && result !== null;
}
)
),
};
});
}
Example #11
Source File: MultiModeGraphTooltip.test.tsx From grafana-chinese with Apache License 2.0 | 4 votes |
describe('MultiModeGraphTooltip', () => {
describe('when shown when hovering over a datapoint', () => {
beforeEach(() => {
dimensions = {
xAxis: createDimension('xAxis', [
{
config: {},
values: new ArrayVector([0, 100, 200]),
name: 'A-series time',
type: FieldType.time,
},
{
config: {},
values: new ArrayVector([0, 100, 200]),
name: 'B-series time',
type: FieldType.time,
},
]),
yAxis: createDimension('yAxis', [
{
config: {},
values: new ArrayVector([10, 20, 10]),
name: 'A-series values',
type: FieldType.number,
},
{
config: {},
values: new ArrayVector([20, 30, 40]),
name: 'B-series values',
type: FieldType.number,
},
]),
};
});
it('highlights series of the datapoint', () => {
// We are simulating hover over A-series, middle point
const activeDimensions: ActiveDimensions<GraphDimensions> = {
xAxis: [0, 1], // column, row
yAxis: [0, 1], // column, row
};
const container = mount(
<MultiModeGraphTooltip
dimensions={dimensions}
activeDimensions={activeDimensions}
// pos is not relevant in this test
pos={{ x: 0, y: 0, pageX: 0, pageY: 0, x1: 0, y1: 0 }}
/>
);
// We rendered two series rows
const rows = container.find('SeriesTableRow');
// We expect A-series(1st row) to be higlighted
expect(rows.get(0).props.isActive).toBeTruthy();
// We expect B-series(2nd row) not to be higlighted
expect(rows.get(1).props.isActive).toBeFalsy();
});
it("doesn't highlight series when not hovering over datapoint", () => {
// We are simulating hover over graph, but not datapoint
const activeDimensions: ActiveDimensions<GraphDimensions> = {
xAxis: [0, undefined], // no active point in time
yAxis: null, // no active series
};
const container = mount(
<MultiModeGraphTooltip
dimensions={dimensions}
activeDimensions={activeDimensions}
// pos is not relevant in this test
pos={{ x: 0, y: 0, pageX: 0, pageY: 0, x1: 0, y1: 0 }}
/>
);
// We rendered two series rows
const rows = container.find('SeriesTableRow');
// We expect A-series(1st row) not to be higlighted
expect(rows.get(0).props.isActive).toBeFalsy();
// We expect B-series(2nd row) not to be higlighted
expect(rows.get(1).props.isActive).toBeFalsy();
});
});
});
Example #12
Source File: linkSuppliers.test.ts From grafana-chinese with Apache License 2.0 | 4 votes |
describe('getLinksFromLogsField', () => {
let originalLinkSrv: LinkService;
beforeAll(() => {
// We do not need more here and TimeSrv is hard to setup fully.
const timeSrvMock: TimeSrv = {
timeRangeForUrl() {
const from = dateTime().subtract(1, 'h');
const to = dateTime();
return { from, to, raw: { from, to } };
},
} as any;
const linkService = new LinkSrv(new TemplateSrv(), timeSrvMock);
originalLinkSrv = getLinkSrv();
setLinkSrv(linkService);
});
afterAll(() => {
setLinkSrv(originalLinkSrv);
});
it('interpolates link from field', () => {
const field: Field = {
name: 'test field',
type: FieldType.number,
config: {
links: [
{
title: 'title1',
url: 'http://domain.com/${__value.raw}',
},
{
title: 'title2',
url: 'http://anotherdomain.sk/${__value.raw}',
},
],
},
values: new ArrayVector([1, 2, 3]),
};
const links = getLinksFromLogsField(field, 2);
expect(links.length).toBe(2);
expect(links[0].href).toBe('http://domain.com/3');
expect(links[1].href).toBe('http://anotherdomain.sk/3');
});
it('handles zero links', () => {
const field: Field = {
name: 'test field',
type: FieldType.number,
config: {},
values: new ArrayVector([1, 2, 3]),
};
const links = getLinksFromLogsField(field, 2);
expect(links.length).toBe(0);
});
it('links to items on the row', () => {
const data = applyFieldOverrides({
data: [
toDataFrame({
name: 'Hello Templates',
refId: 'ZZZ',
fields: [
{ name: 'Time', values: [1, 2, 3] },
{
name: 'Power',
values: [100.2000001, 200, 300],
config: {
unit: 'kW',
decimals: 3,
title: 'TheTitle',
},
},
{
name: 'Last',
values: ['a', 'b', 'c'],
config: {
links: [
{
title: 'By Name',
url: 'http://go/${__data.fields.Power}',
},
{
title: 'By Index',
url: 'http://go/${__data.fields[1]}',
},
{
title: 'By Title',
url: 'http://go/${__data.fields[TheTitle]}',
},
{
title: 'Numeric Value',
url: 'http://go/${__data.fields.Power.numeric}',
},
{
title: 'Text (no suffix)',
url: 'http://go/${__data.fields.Power.text}',
},
{
title: 'Unknown Field',
url: 'http://go/${__data.fields.XYZ}',
},
{
title: 'Data Frame name',
url: 'http://go/${__data.name}',
},
{
title: 'Data Frame refId',
url: 'http://go/${__data.refId}',
},
],
},
},
],
}),
],
fieldOptions: {
defaults: {},
overrides: [],
},
replaceVariables: (val: string) => val,
timeZone: 'utc',
theme: {} as GrafanaTheme,
autoMinMax: true,
})[0];
const rowIndex = 0;
const colIndex = data.fields.length - 1;
const field = data.fields[colIndex];
const fieldDisp: FieldDisplay = {
name: 'hello',
field: field.config,
view: new DataFrameView(data),
rowIndex,
colIndex,
display: field.display!(field.values.get(rowIndex)),
};
const supplier = getFieldLinksSupplier(fieldDisp);
const links = supplier.getLinks({}).map(m => {
return {
title: m.title,
href: m.href,
};
});
expect(links).toMatchInlineSnapshot(`
Array [
Object {
"href": "http://go/100.200 kW",
"title": "By Name",
},
Object {
"href": "http://go/100.200 kW",
"title": "By Index",
},
Object {
"href": "http://go/100.200 kW",
"title": "By Title",
},
Object {
"href": "http://go/100.2000001",
"title": "Numeric Value",
},
Object {
"href": "http://go/100.200",
"title": "Text (no suffix)",
},
Object {
"href": "http://go/\${__data.fields.XYZ}",
"title": "Unknown Field",
},
Object {
"href": "http://go/Hello Templates",
"title": "Data Frame name",
},
Object {
"href": "http://go/ZZZ",
"title": "Data Frame refId",
},
]
`);
});
});