Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions barchart/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@
"main": "lib/cjs/index.js",
"module": "lib/index.js",
"types": "lib/index.d.ts",
"dependencies": {
"@perses-dev/components": "0.52.0-beta.1",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do you need to move out the perses dependencies from the peerDependencies ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

because the current dependencies of the monorepo are still pointing to 0.51.0 so we use this to be able to use a specific version for this plugin. When we upgrade all the plugins to use 0.52.0-beta.1 we can move this back to peerDependencies.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah yeah ok got it. We will need another release of perses/perses to unlock the upgrade here unfortunately ...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this change is not needed anymore as the PR #236 upgraded the @perses-dev dependencies to the v0.52.0-beta.3 and is resolving the issue raised here

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes exactly, let us know @ericahinkleRH if you have time to work on this feature. If not we can take over.

"@perses-dev/core": "0.52.0-beta.1",
"@perses-dev/plugin-system": "0.52.0-beta.1"
},
"peerDependencies": {
"@emotion/react": "^11.7.1",
"@emotion/styled": "^11.6.0",
"@hookform/resolvers": "^3.2.0",
"@perses-dev/components": "^0.51.0-rc.1",
"@perses-dev/core": "^0.51.0-rc.1",
"@perses-dev/plugin-system": "^0.51.0-rc.1",
"date-fns": "^4.1.0",
"date-fns-tz": "^3.2.0",
"echarts": "5.5.0",
Expand Down
15 changes: 7 additions & 8 deletions barchart/src/BarChart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,17 @@ import { PanelPlugin } from '@perses-dev/plugin-system';
import { createInitialBarChartOptions, BarChartOptions } from './bar-chart-model';
import { BarChartOptionsEditorSettings } from './BarChartOptionsEditorSettings';
import { BarChartPanel, BarChartPanelProps } from './BarChartPanel';
import { BarChartExportAction } from './BarChartExportAction';

/**
* The core BarChart panel plugin for Perses.
*/
export const BarChart: PanelPlugin<BarChartOptions, BarChartPanelProps> = {
PanelComponent: BarChartPanel,
panelOptionsEditorComponents: [
supportedQueryTypes: ['TimeSeriesQuery'],
panelOptionsEditorComponents: [{ label: 'Settings', content: BarChartOptionsEditorSettings }],
createInitialOptions: createInitialBarChartOptions,
actions: [
{
label: 'Settings',
content: BarChartOptionsEditorSettings,
component: BarChartExportAction,
location: 'header',
},
],
supportedQueryTypes: ['TimeSeriesQuery'],
createInitialOptions: createInitialBarChartOptions,
};
63 changes: 63 additions & 0 deletions barchart/src/BarChartExportAction.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Copyright 2023 The Perses Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import React, { useCallback, useMemo } from 'react';
import { IconButton, Tooltip } from '@mui/material';
import DownloadIcon from 'mdi-material-ui/Download';
import { BarChartPanelProps } from './BarChartPanel';
import { extractExportableData, isExportableData, sanitizeFilename, exportDataAsCSV } from './CSVExportUtils';

export const BarChartExportAction: React.FC<BarChartPanelProps> = ({ queryResults, definition }) => {
const exportableData = useMemo(() => {
return extractExportableData(queryResults);
}, [queryResults]);

const canExport = isExportableData(exportableData);

const handleExport = useCallback(() => {
if (!exportableData || !canExport) return;

try {
const title = definition?.spec?.display?.name || 'Bar Chart Data';

const csvBlob = exportDataAsCSV({
data: exportableData,
});

const baseFilename = sanitizeFilename(title);
const filename = `${baseFilename}_data.csv`;

const link = document.createElement('a');
link.href = URL.createObjectURL(csvBlob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
} catch (error) {
console.error('Bar chart export failed:', error);
}
}, [exportableData, canExport, definition]);

if (!canExport) {
return null;
}

return (
<Tooltip title="Export as CSV">
<IconButton size="small" onClick={handleExport} aria-label="Export bar chart data as CSV">
<DownloadIcon fontSize="inherit" />
</IconButton>
</Tooltip>
);
};
173 changes: 173 additions & 0 deletions barchart/src/CSVExportUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
// Copyright 2023 The Perses Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

export interface BarDataPoint {
value: unknown;
}

export interface DataSeries {
name?: string;
formattedName?: string;
legendName?: string;
displayName?: string;
legend?: string;
labels?: Record<string, string>;
values: Array<[number | string, unknown]> | BarDataPoint[];
}

export interface ExportableData {
series: DataSeries[];
metadata?: Record<string, unknown>;
}

export const isExportableData = (data: unknown): data is ExportableData => {
if (!data || typeof data !== 'object') return false;
const candidate = data as Record<string, unknown>;
return Array.isArray(candidate.series) && candidate.series.length > 0;
};

export interface QueryDataInput {
data?: unknown;
error?: unknown;
}

export const extractExportableData = (queryResults: QueryDataInput[]): ExportableData | undefined => {
if (!queryResults || queryResults.length === 0) return undefined;

const allSeries: DataSeries[] = [];
let metadata: ExportableData['metadata'] = undefined;

queryResults.forEach((query) => {
if (query?.data && typeof query.data === 'object' && 'series' in query.data) {
const data = query.data as ExportableData;
if (data.series && Array.isArray(data.series) && data.series.length > 0) {
allSeries.push(...data.series);
if (!metadata && data.metadata) {
metadata = data.metadata;
}
}
}
});

if (allSeries.length > 0) {
return {
series: allSeries,
metadata,
};
}

return undefined;
};

export const sanitizeFilename = (filename: string): string => {
return filename
.replace(/[<>:"/\\|?*]/g, ' ')
.trim()
.split(/\s+/)
.filter((word) => word.length > 0)
.map((word, index) => {
if (index === 0) {
return word.toLowerCase();
}
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
})
.join('');
};

export const escapeCsvValue = (value: unknown): string => {
if (value === null || value === undefined) {
return '';
}

const stringValue = String(value);

if (
stringValue.includes(',') ||
stringValue.includes('"') ||
stringValue.includes('\n') ||
stringValue.includes('\r')
) {
return `"${stringValue.replace(/"/g, '""')}"`;
}

return stringValue;
};

export interface ExportDataOptions {
data: ExportableData;
}

export const exportDataAsCSV = ({ data }: ExportDataOptions): Blob => {
if (!isExportableData(data)) {
console.warn('No valid data found to export to CSV.');
return new Blob([''], { type: 'text/csv;charset=utf-8' });
}

const seriesData: Array<{ label: string; value: number | null }> = [];

for (let i = 0; i < data.series.length; i++) {
const series = data.series[i];

if (!series) {
continue;
}

if (!Array.isArray(series.values) || series.values.length === 0) {
continue;
}

let aggregatedValue: number | null = null;

for (let j = 0; j < series.values.length; j++) {
const entry = series.values[j];
let value: unknown;

if (Array.isArray(entry) && entry.length >= 2) {
value = entry[1];
} else if (typeof entry === 'object' && entry !== null && 'value' in entry) {
const dataPoint = entry as BarDataPoint;
value = dataPoint.value;
} else {
continue;
}

if (value !== null && value !== undefined && !isNaN(Number(value))) {
aggregatedValue = Number(value);
break;
}
}

seriesData.push({
label: series.name || `Series ${i + 1}`,
value: aggregatedValue,
});
}

if (seriesData.length === 0) {
console.warn('No valid series data found to export to CSV.');
return new Blob([''], { type: 'text/csv;charset=utf-8' });
}

let csvString = 'Label,Value\n';

for (let index = 0; index < seriesData.length; index++) {
const item = seriesData[index];
if (!item) continue;
csvString += `${escapeCsvValue(item.label)},${escapeCsvValue(item.value)}`;
if (index < seriesData.length - 1) {
csvString += '\n';
}
}

return new Blob([csvString], { type: 'text/csv;charset=utf-8' });
};
1 change: 1 addition & 0 deletions barchart/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ export * from './BarChart';
export * from './BarChartOptionsEditorSettings';
export { getPluginModule } from './getPluginModule';
export * from './utils';
export * from './CSVExportUtils';
82 changes: 79 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading