-
Notifications
You must be signed in to change notification settings - Fork 36
[FEATURE] Bar Chart CSV Export Plugin #226
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
ericahinkleRH
wants to merge
1
commit into
perses:main
Choose a base branch
from
ericahinkleRH:Bar-Chart-Fixed-Plugin
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| ); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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' }); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?There was a problem hiding this comment.
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.0so we use this to be able to use a specific version for this plugin. When we upgrade all the plugins to use0.52.0-beta.1we can move this back topeerDependencies.There was a problem hiding this comment.
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 ...
There was a problem hiding this comment.
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.3and is resolving the issue raised hereThere was a problem hiding this comment.
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.