|
| 1 | +import { useEffect, useState } from 'react'; |
| 2 | +import { useDispatch, useSelector } from 'react-redux'; |
| 3 | +import { useDashboardActions, useDashboardStore } from '@perses-dev/dashboards'; |
| 4 | +import { dashboardsOpened, dashboardsPersesPanelExternallyAdded } from '../../../store/actions'; |
| 5 | + |
| 6 | +interface UseExternalPanelAdditionOptions { |
| 7 | + isEditMode: boolean; |
| 8 | + onEditButtonClick: () => void; |
| 9 | +} |
| 10 | + |
| 11 | +export function useExternalPanelAddition({ |
| 12 | + isEditMode, |
| 13 | + onEditButtonClick, |
| 14 | +}: UseExternalPanelAdditionOptions) { |
| 15 | + const dispatch = useDispatch(); |
| 16 | + const addPersesPanelExternally: any = useSelector( |
| 17 | + (s: any) => s.plugins?.mp?.dashboards?.addPersesPanelExternally, |
| 18 | + ); |
| 19 | + const { openAddPanel } = useDashboardActions(); |
| 20 | + const dashboardStore = useDashboardStore(); |
| 21 | + const [externallyAddedPanel, setExternallyAddedPanel] = useState(null); |
| 22 | + |
| 23 | + const addPanelExternally = (panelDefinition: any): void => { |
| 24 | + // Simulate opening a panel to add the pane so that we can use it to programatically |
| 25 | + // add a panel to the dashboard from an external source (AI assistant). |
| 26 | + if (!isEditMode) { |
| 27 | + onEditButtonClick(); |
| 28 | + } |
| 29 | + openAddPanel(); |
| 30 | + // Wrap the panelDefinition with the groupId structure |
| 31 | + const change = { |
| 32 | + groupId: 0, |
| 33 | + panelDefinition, |
| 34 | + }; |
| 35 | + setExternallyAddedPanel(change); |
| 36 | + }; |
| 37 | + |
| 38 | + useEffect(() => { |
| 39 | + // Listen for external panel addition requests |
| 40 | + if (addPersesPanelExternally) { |
| 41 | + addPanelExternally(addPersesPanelExternally); |
| 42 | + dispatch(dashboardsPersesPanelExternallyAdded()); |
| 43 | + } |
| 44 | + |
| 45 | + // Apply externally added panel |
| 46 | + if (externallyAddedPanel) { |
| 47 | + const groupId = dashboardStore.panelGroupOrder[0]; |
| 48 | + externallyAddedPanel.groupId = groupId; |
| 49 | + |
| 50 | + // Use the temporary panelEditor to add changes to the dashboard. |
| 51 | + const panelEditor = dashboardStore.panelEditor; |
| 52 | + panelEditor.applyChanges(externallyAddedPanel); |
| 53 | + panelEditor.close(); |
| 54 | + |
| 55 | + // Clear the externally added panel after applying changes |
| 56 | + setExternallyAddedPanel(null); |
| 57 | + } |
| 58 | + }, [externallyAddedPanel, addPersesPanelExternally]); |
| 59 | + |
| 60 | + // Advertise when custom dashboard is opened/closed |
| 61 | + useEffect(() => { |
| 62 | + dispatch(dashboardsOpened(true)); |
| 63 | + return () => { |
| 64 | + dispatch(dashboardsOpened(false)); |
| 65 | + }; |
| 66 | + }, [dispatch]); |
| 67 | +} |
0 commit comments