mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Traces: Consistent span colors for service names (#50782)
* Show consistent span colors * Update tests * Test for ensuring red is not used
This commit is contained in:
parent
bd6c027a01
commit
7b14cd5fdb
@ -30,20 +30,10 @@ it('gives different colors for each for each key', () => {
|
||||
expect(colorOne).not.toBe(colorTwo);
|
||||
});
|
||||
|
||||
it('should clear cache', () => {
|
||||
clear();
|
||||
const colorOne = getColorByKey('serviceA', createTheme());
|
||||
clear();
|
||||
const colorTwo = getColorByKey('serviceB', createTheme());
|
||||
expect(colorOne).toBe(colorTwo);
|
||||
});
|
||||
|
||||
it('should not allow red', () => {
|
||||
clear();
|
||||
getColorByKey('serviceA', createTheme());
|
||||
getColorByKey('serviceB', createTheme());
|
||||
getColorByKey('serviceC', createTheme());
|
||||
getColorByKey('serviceD', createTheme());
|
||||
const colorFive = getColorByKey('serviceE', createTheme());
|
||||
expect(colorFive).not.toBe('#E24D42');
|
||||
// when aPAKNMeFcF is hashed it's index is 4
|
||||
// which is red, which we disallow because it looks like an error
|
||||
const colorOne = getColorByKey('aPAKNMeFcF', createTheme());
|
||||
expect(colorOne).not.toBe('#E24D42');
|
||||
});
|
||||
|
@ -32,26 +32,36 @@ class ColorGenerator {
|
||||
colorsHex: string[];
|
||||
colorsRgb: Array<[number, number, number]>;
|
||||
cache: Map<string, number>;
|
||||
currentIdx: number;
|
||||
|
||||
constructor(colorsHex: string[]) {
|
||||
this.colorsHex = colorsHex;
|
||||
this.colorsRgb = colorsHex.map(strToRgb);
|
||||
this.cache = new Map();
|
||||
this.currentIdx = 0;
|
||||
}
|
||||
|
||||
_getColorIndex(key: string): number {
|
||||
let i = this.cache.get(key);
|
||||
if (i == null) {
|
||||
const hash = this.hashCode(key.toLowerCase());
|
||||
const hashIndex = Math.abs(hash % this.colorsHex.length);
|
||||
// colors[4] is red (which we want to disallow as a span color because it looks like an error)
|
||||
i = this.currentIdx !== 4 ? this.currentIdx : this.currentIdx + 1;
|
||||
i = hashIndex === 4 ? hashIndex + 1 : hashIndex;
|
||||
this.cache.set(key, i);
|
||||
this.currentIdx = (i + 1) % this.colorsHex.length;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
hashCode(key: string) {
|
||||
var hash = 0,
|
||||
i,
|
||||
chr;
|
||||
for (i = 0; i < key.length; i++) {
|
||||
chr = key.charCodeAt(i);
|
||||
hash = (hash << 5) - hash + chr;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/**
|
||||
* Will assign a color to an arbitrary key.
|
||||
* If the key has been used already, it will
|
||||
@ -74,7 +84,6 @@ class ColorGenerator {
|
||||
|
||||
clear() {
|
||||
this.cache.clear();
|
||||
this.currentIdx = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user