1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- import {useCallback, useRef} from 'react';
- import {CHART_PALETTE} from 'sentry/constants/chartPalette';
- import theme from 'sentry/utils/theme';
- const CACHE_SIZE = 20;
- export function createChartPalette(seriesNames: string[]): Record<string, string> {
- const uniqueSeriesNames = Array.from(new Set(seriesNames));
-
-
- const chartColors =
- theme.charts.getColorPalette(Math.max(uniqueSeriesNames.length - 2, -1)) ??
- CHART_PALETTE[CHART_PALETTE.length - 1];
- return uniqueSeriesNames.reduce(
- (palette, seriesName, i) => {
- palette[seriesName] = chartColors[i % chartColors.length];
- return palette;
- },
- {} as Record<string, string>
- );
- }
- export function getCachedChartPalette(
- cache: Readonly<Record<string, string>>[],
- seriesNames: string[]
- ): Readonly<Record<string, string>> {
-
-
- let cacheIndex = -1;
- for (let i = cache.length - 1; i >= 0; i--) {
- const palette = cache[i];
- if (seriesNames.every(seriesName => seriesName in palette)) {
- cacheIndex = i;
- break;
- }
- }
- if (cacheIndex > -1) {
- const cachedPalette = cache[cacheIndex];
- if (cacheIndex !== cache.length - 1) {
-
- cache.splice(cacheIndex, 1);
- cache.push(cachedPalette);
- }
- return cachedPalette;
- }
-
- const newPalette = createChartPalette(seriesNames);
-
- if (seriesNames.length > 1) {
- cache.push(newPalette);
- }
-
- if (cache.length > CACHE_SIZE) {
- const overflow = cache.length - CACHE_SIZE;
- cache.splice(0, overflow);
- }
- return newPalette;
- }
- export const useGetCachedChartPalette = () => {
- const cacheRef = useRef<Readonly<Record<string, string>>[]>([]);
- return useCallback((seriesNames: string[]) => {
-
- return {...getCachedChartPalette(cacheRef.current, seriesNames)};
- }, []);
- };
|