@perses-dev/dashboards 0.46.0-rc0 → 0.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/components/DeletePanelGroupDialog/DeletePanelGroupDialog.js +1 -1
- package/dist/cjs/components/GridLayout/GridLayout.js +8 -2
- package/dist/cjs/components/Variables/TemplateVariable.js +1 -1
- package/dist/cjs/context/DashboardProvider/DashboardProvider.js +2 -1
- package/dist/cjs/context/TemplateVariableProvider/TemplateVariableProvider.js +2 -1
- package/dist/cjs/views/ViewDashboard/DashboardApp.js +2 -1
- package/dist/components/DeletePanelGroupDialog/DeletePanelGroupDialog.js +1 -1
- package/dist/components/DeletePanelGroupDialog/DeletePanelGroupDialog.js.map +1 -1
- package/dist/components/GridLayout/GridLayout.d.ts.map +1 -1
- package/dist/components/GridLayout/GridLayout.js +8 -2
- package/dist/components/GridLayout/GridLayout.js.map +1 -1
- package/dist/components/Variables/TemplateVariable.js +1 -1
- package/dist/components/Variables/TemplateVariable.js.map +1 -1
- package/dist/context/DashboardProvider/DashboardProvider.d.ts.map +1 -1
- package/dist/context/DashboardProvider/DashboardProvider.js +3 -2
- package/dist/context/DashboardProvider/DashboardProvider.js.map +1 -1
- package/dist/context/TemplateVariableProvider/TemplateVariableProvider.d.ts.map +1 -1
- package/dist/context/TemplateVariableProvider/TemplateVariableProvider.js +2 -1
- package/dist/context/TemplateVariableProvider/TemplateVariableProvider.js.map +1 -1
- package/dist/views/ViewDashboard/DashboardApp.js +2 -1
- package/dist/views/ViewDashboard/DashboardApp.js.map +1 -1
- package/package.json +6 -6
|
@@ -34,7 +34,7 @@ const DeletePanelGroupDialog = ()=>{
|
|
|
34
34
|
const panelGroupId = deletePanelGroupDialog === null || deletePanelGroupDialog === void 0 ? void 0 : deletePanelGroupDialog.panelGroupId;
|
|
35
35
|
const handleDelete = (e)=>{
|
|
36
36
|
e.preventDefault();
|
|
37
|
-
if (panelGroupId
|
|
37
|
+
if (panelGroupId === undefined) {
|
|
38
38
|
throw new Error('group index is undefined');
|
|
39
39
|
}
|
|
40
40
|
deletePanelGroup(panelGroupId);
|
|
@@ -32,7 +32,6 @@ const _GridItemContent = require("./GridItemContent");
|
|
|
32
32
|
const _GridContainer = require("./GridContainer");
|
|
33
33
|
const DEFAULT_MARGIN = 10;
|
|
34
34
|
const ROW_HEIGHT = 30;
|
|
35
|
-
const ResponsiveGridLayout = (0, _reactgridlayout.WidthProvider)(_reactgridlayout.Responsive);
|
|
36
35
|
function GridLayout(props) {
|
|
37
36
|
const { panelGroupId, panelOptions, panelFullHeight } = props;
|
|
38
37
|
const theme = (0, _material.useTheme)();
|
|
@@ -50,6 +49,9 @@ function GridLayout(props) {
|
|
|
50
49
|
if (viewPanelItemId === undefined) {
|
|
51
50
|
return true;
|
|
52
51
|
}
|
|
52
|
+
if (hasViewPanel) {
|
|
53
|
+
setIsOpen(true);
|
|
54
|
+
}
|
|
53
55
|
return hasViewPanel;
|
|
54
56
|
}, [
|
|
55
57
|
hasViewPanel,
|
|
@@ -98,9 +100,13 @@ function GridLayout(props) {
|
|
|
98
100
|
// exclude margin and padding from total width
|
|
99
101
|
setGridColWidth((containerWidth - marginWidth - containerPaddingWidth) / cols);
|
|
100
102
|
};
|
|
103
|
+
// https://github.com/react-grid-layout/react-grid-layout?tab=readme-ov-file#react-hooks-performance
|
|
104
|
+
const ResponsiveGridLayout = (0, _react.useMemo)(()=>(0, _reactgridlayout.WidthProvider)(_reactgridlayout.Responsive), []);
|
|
101
105
|
return /*#__PURE__*/ (0, _jsxruntime.jsxs)(_GridContainer.GridContainer, {
|
|
102
106
|
sx: {
|
|
103
|
-
display: isGridDisplayed ? 'block' : 'none'
|
|
107
|
+
display: isGridDisplayed ? 'block' : 'none',
|
|
108
|
+
height: itemLayoutViewed ? `${panelFullHeight}px` : 'unset',
|
|
109
|
+
overflow: itemLayoutViewed ? 'hidden' : 'unset'
|
|
104
110
|
},
|
|
105
111
|
children: [
|
|
106
112
|
groupDefinition.title !== undefined && /*#__PURE__*/ (0, _jsxruntime.jsx)(_GridTitle.GridTitle, {
|
|
@@ -203,7 +203,7 @@ const StyledPopper = (props)=>/*#__PURE__*/ (0, _jsxruntime.jsx)(_material.Poppe
|
|
|
203
203
|
const LETTER_HSIZE = 8; // approximation
|
|
204
204
|
const ARROW_OFFSET = 40; // right offset for list variables (= take into account the dropdown toggle size)
|
|
205
205
|
const getWidthPx = (inputValue, kind)=>{
|
|
206
|
-
const width = (inputValue.length + 1) * LETTER_HSIZE + (kind
|
|
206
|
+
const width = (inputValue.length + 1) * LETTER_HSIZE + (kind === 'list' ? ARROW_OFFSET : 0);
|
|
207
207
|
if (width < _constants.MIN_TEMPLATE_VARIABLE_WIDTH) {
|
|
208
208
|
return _constants.MIN_TEMPLATE_VARIABLE_WIDTH;
|
|
209
209
|
} else if (width > _constants.MAX_TEMPLATE_VARIABLE_WIDTH) {
|
|
@@ -33,6 +33,7 @@ _export(exports, {
|
|
|
33
33
|
});
|
|
34
34
|
const _jsxruntime = require("react/jsx-runtime");
|
|
35
35
|
const _zustand = require("zustand");
|
|
36
|
+
const _traditional = require("zustand/traditional");
|
|
36
37
|
const _middleware = require("zustand/middleware");
|
|
37
38
|
const _immer = require("zustand/middleware/immer");
|
|
38
39
|
const _shallow = require("zustand/shallow");
|
|
@@ -57,7 +58,7 @@ function useDashboardStore(selector) {
|
|
|
57
58
|
if (store === undefined) {
|
|
58
59
|
throw new Error('No DashboardContext found. Did you forget a Provider?');
|
|
59
60
|
}
|
|
60
|
-
return (0,
|
|
61
|
+
return (0, _traditional.useStoreWithEqualityFn)(store, selector, _shallow.shallow);
|
|
61
62
|
}
|
|
62
63
|
function DashboardProvider(props) {
|
|
63
64
|
const createDashboardStore = (0, _react.useCallback)(initStore, [
|
|
@@ -52,6 +52,7 @@ _export(exports, {
|
|
|
52
52
|
const _jsxruntime = require("react/jsx-runtime");
|
|
53
53
|
const _react = require("react");
|
|
54
54
|
const _zustand = require("zustand");
|
|
55
|
+
const _traditional = require("zustand/traditional");
|
|
55
56
|
const _immer = require("zustand/middleware/immer");
|
|
56
57
|
const _middleware = require("zustand/middleware");
|
|
57
58
|
const _immer1 = /*#__PURE__*/ _interop_require_default(require("immer"));
|
|
@@ -75,7 +76,7 @@ function useTemplateVariableStoreCtx() {
|
|
|
75
76
|
}
|
|
76
77
|
function useTemplateVariableValues(variableNames) {
|
|
77
78
|
const store = useTemplateVariableStoreCtx();
|
|
78
|
-
return (0,
|
|
79
|
+
return (0, _traditional.useStoreWithEqualityFn)(store, (s)=>{
|
|
79
80
|
const vars = {};
|
|
80
81
|
// Collect values of local variables, from the variable state
|
|
81
82
|
const names = variableNames !== null && variableNames !== void 0 ? variableNames : s.variableDefinitions.map((value)=>value.spec.name);
|
|
@@ -19,7 +19,7 @@ export const DeletePanelGroupDialog = ()=>{
|
|
|
19
19
|
const panelGroupId = deletePanelGroupDialog === null || deletePanelGroupDialog === void 0 ? void 0 : deletePanelGroupDialog.panelGroupId;
|
|
20
20
|
const handleDelete = (e)=>{
|
|
21
21
|
e.preventDefault();
|
|
22
|
-
if (panelGroupId
|
|
22
|
+
if (panelGroupId === undefined) {
|
|
23
23
|
throw new Error('group index is undefined');
|
|
24
24
|
}
|
|
25
25
|
deletePanelGroup(panelGroupId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/DeletePanelGroupDialog/DeletePanelGroupDialog.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { FormEvent } from 'react';\nimport { IconButton, Dialog, DialogTitle, DialogContent, DialogActions, Button } from '@mui/material';\nimport CloseIcon from 'mdi-material-ui/Close';\nimport { useDeletePanelGroupDialog } from '../../context';\n\nexport const DeletePanelGroupDialog = () => {\n const { deletePanelGroupDialog, closeDeletePanelGroupDialog, deletePanelGroup } = useDeletePanelGroupDialog();\n\n const panelGroupId = deletePanelGroupDialog?.panelGroupId;\n\n const handleDelete = (e: FormEvent) => {\n e.preventDefault();\n if (panelGroupId
|
|
1
|
+
{"version":3,"sources":["../../../src/components/DeletePanelGroupDialog/DeletePanelGroupDialog.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { FormEvent } from 'react';\nimport { IconButton, Dialog, DialogTitle, DialogContent, DialogActions, Button } from '@mui/material';\nimport CloseIcon from 'mdi-material-ui/Close';\nimport { useDeletePanelGroupDialog } from '../../context';\n\nexport const DeletePanelGroupDialog = () => {\n const { deletePanelGroupDialog, closeDeletePanelGroupDialog, deletePanelGroup } = useDeletePanelGroupDialog();\n\n const panelGroupId = deletePanelGroupDialog?.panelGroupId;\n\n const handleDelete = (e: FormEvent) => {\n e.preventDefault();\n if (panelGroupId === undefined) {\n throw new Error('group index is undefined');\n }\n deletePanelGroup(panelGroupId);\n closeDeletePanelGroupDialog();\n };\n\n return (\n <Dialog open={deletePanelGroupDialog !== undefined}>\n <DialogTitle>Delete Panel Group</DialogTitle>\n <IconButton\n aria-label=\"Close\"\n onClick={() => closeDeletePanelGroupDialog()}\n sx={(theme) => ({\n position: 'absolute',\n top: theme.spacing(0.5),\n right: theme.spacing(0.5),\n })}\n >\n <CloseIcon />\n </IconButton>\n <form onSubmit={handleDelete}>\n <DialogContent dividers sx={{ width: '500px' }}>\n Are you sure you want to delete {deletePanelGroupDialog?.panelGroupName ?? 'panel group'}? This will delete\n all the panels within the group.\n </DialogContent>\n <DialogActions>\n <Button variant=\"contained\" type=\"submit\">\n Delete\n </Button>\n <Button variant=\"outlined\" color=\"secondary\" onClick={() => closeDeletePanelGroupDialog()}>\n Cancel\n </Button>\n </DialogActions>\n </form>\n </Dialog>\n );\n};\n"],"names":["IconButton","Dialog","DialogTitle","DialogContent","DialogActions","Button","CloseIcon","useDeletePanelGroupDialog","DeletePanelGroupDialog","deletePanelGroupDialog","closeDeletePanelGroupDialog","deletePanelGroup","panelGroupId","handleDelete","e","preventDefault","undefined","Error","open","aria-label","onClick","sx","theme","position","top","spacing","right","form","onSubmit","dividers","width","panelGroupName","variant","type","color"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAGjC,SAASA,UAAU,EAAEC,MAAM,EAAEC,WAAW,EAAEC,aAAa,EAAEC,aAAa,EAAEC,MAAM,QAAQ,gBAAgB;AACtG,OAAOC,eAAe,wBAAwB;AAC9C,SAASC,yBAAyB,QAAQ,gBAAgB;AAE1D,OAAO,MAAMC,yBAAyB;IACpC,MAAM,EAAEC,sBAAsB,EAAEC,2BAA2B,EAAEC,gBAAgB,EAAE,GAAGJ;IAElF,MAAMK,eAAeH,mCAAAA,6CAAAA,uBAAwBG,YAAY;IAEzD,MAAMC,eAAe,CAACC;QACpBA,EAAEC,cAAc;QAChB,IAAIH,iBAAiBI,WAAW;YAC9B,MAAM,IAAIC,MAAM;QAClB;QACAN,iBAAiBC;QACjBF;IACF;QAkByCD;IAhBzC,qBACE,MAACR;QAAOiB,MAAMT,2BAA2BO;;0BACvC,KAACd;0BAAY;;0BACb,KAACF;gBACCmB,cAAW;gBACXC,SAAS,IAAMV;gBACfW,IAAI,CAACC,QAAW,CAAA;wBACdC,UAAU;wBACVC,KAAKF,MAAMG,OAAO,CAAC;wBACnBC,OAAOJ,MAAMG,OAAO,CAAC;oBACvB,CAAA;0BAEA,cAAA,KAACnB;;0BAEH,MAACqB;gBAAKC,UAAUf;;kCACd,MAACV;wBAAc0B,QAAQ;wBAACR,IAAI;4BAAES,OAAO;wBAAQ;;4BAAG;4BACbrB,CAAAA,yCAAAA,mCAAAA,6CAAAA,uBAAwBsB,cAAc,cAAtCtB,oDAAAA,yCAA0C;4BAAc;;;kCAG3F,MAACL;;0CACC,KAACC;gCAAO2B,SAAQ;gCAAYC,MAAK;0CAAS;;0CAG1C,KAAC5B;gCAAO2B,SAAQ;gCAAWE,OAAM;gCAAYd,SAAS,IAAMV;0CAA+B;;;;;;;;AAOrG,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GridLayout.d.ts","sourceRoot":"","sources":["../../../src/components/GridLayout/GridLayout.tsx"],"names":[],"mappings":"AAgBA,OAAO,EAIL,YAAY,EAIb,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"GridLayout.d.ts","sourceRoot":"","sources":["../../../src/components/GridLayout/GridLayout.tsx"],"names":[],"mappings":"AAgBA,OAAO,EAIL,YAAY,EAIb,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAOxC,MAAM,WAAW,eAAe;IAC9B,YAAY,EAAE,YAAY,CAAC;IAC3B,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,eAAe,2CAqIhD"}
|
|
@@ -22,7 +22,6 @@ import { GridItemContent } from './GridItemContent';
|
|
|
22
22
|
import { GridContainer } from './GridContainer';
|
|
23
23
|
const DEFAULT_MARGIN = 10;
|
|
24
24
|
const ROW_HEIGHT = 30;
|
|
25
|
-
const ResponsiveGridLayout = WidthProvider(Responsive);
|
|
26
25
|
/**
|
|
27
26
|
* Layout component that arranges children in a Grid based on the definition.
|
|
28
27
|
*/ export function GridLayout(props) {
|
|
@@ -42,6 +41,9 @@ const ResponsiveGridLayout = WidthProvider(Responsive);
|
|
|
42
41
|
if (viewPanelItemId === undefined) {
|
|
43
42
|
return true;
|
|
44
43
|
}
|
|
44
|
+
if (hasViewPanel) {
|
|
45
|
+
setIsOpen(true);
|
|
46
|
+
}
|
|
45
47
|
return hasViewPanel;
|
|
46
48
|
}, [
|
|
47
49
|
hasViewPanel,
|
|
@@ -90,9 +92,13 @@ const ResponsiveGridLayout = WidthProvider(Responsive);
|
|
|
90
92
|
// exclude margin and padding from total width
|
|
91
93
|
setGridColWidth((containerWidth - marginWidth - containerPaddingWidth) / cols);
|
|
92
94
|
};
|
|
95
|
+
// https://github.com/react-grid-layout/react-grid-layout?tab=readme-ov-file#react-hooks-performance
|
|
96
|
+
const ResponsiveGridLayout = useMemo(()=>WidthProvider(Responsive), []);
|
|
93
97
|
return /*#__PURE__*/ _jsxs(GridContainer, {
|
|
94
98
|
sx: {
|
|
95
|
-
display: isGridDisplayed ? 'block' : 'none'
|
|
99
|
+
display: isGridDisplayed ? 'block' : 'none',
|
|
100
|
+
height: itemLayoutViewed ? `${panelFullHeight}px` : 'unset',
|
|
101
|
+
overflow: itemLayoutViewed ? 'hidden' : 'unset'
|
|
96
102
|
},
|
|
97
103
|
children: [
|
|
98
104
|
groupDefinition.title !== undefined && /*#__PURE__*/ _jsx(GridTitle, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/GridLayout/GridLayout.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { useMemo, useState } from 'react';\nimport { Responsive, WidthProvider, Layouts, Layout } from 'react-grid-layout';\nimport { Collapse, useTheme } from '@mui/material';\nimport { ErrorAlert, ErrorBoundary } from '@perses-dev/components';\nimport {\n useEditMode,\n usePanelGroup,\n usePanelGroupActions,\n PanelGroupId,\n PanelGroupItemLayout,\n useViewPanel,\n PanelGroupDefinition,\n} from '../../context';\nimport { GRID_LAYOUT_COLS, GRID_LAYOUT_SMALL_BREAKPOINT } from '../../constants';\nimport { PanelOptions } from '../Panel';\nimport { GridTitle } from './GridTitle';\nimport { GridItemContent } from './GridItemContent';\nimport { GridContainer } from './GridContainer';\nconst DEFAULT_MARGIN = 10;\nconst ROW_HEIGHT = 30;\nconst ResponsiveGridLayout = WidthProvider(Responsive);\n\nexport interface GridLayoutProps {\n panelGroupId: PanelGroupId;\n panelOptions?: PanelOptions;\n panelFullHeight?: number;\n}\n\n/**\n * Layout component that arranges children in a Grid based on the definition.\n */\nexport function GridLayout(props: GridLayoutProps) {\n const { panelGroupId, panelOptions, panelFullHeight } = props;\n const theme = useTheme();\n const groupDefinition: PanelGroupDefinition = usePanelGroup(panelGroupId);\n const { updatePanelGroupLayouts } = usePanelGroupActions(panelGroupId);\n\n const [isOpen, setIsOpen] = useState(!groupDefinition.isCollapsed ?? true);\n const { isEditMode } = useEditMode();\n\n const [gridColWidth, setGridColWidth] = useState(0);\n\n const viewPanelItemId = useViewPanel();\n const hasViewPanel = viewPanelItemId?.panelGroupId === panelGroupId; // current panelGroup contains the panel extended?\n const itemLayoutViewed = viewPanelItemId?.panelGroupItemLayoutId;\n\n // If there is a panel in view mode, we should hide the grid if the panel is not in the current group.\n const isGridDisplayed = useMemo(() => {\n if (viewPanelItemId === undefined) {\n return true;\n }\n return hasViewPanel;\n }, [hasViewPanel, viewPanelItemId]);\n\n // Item layout is override if there is a panel in view mode\n const itemLayouts: PanelGroupItemLayout[] = useMemo(() => {\n if (itemLayoutViewed) {\n return groupDefinition.itemLayouts.map((itemLayout) => {\n if (itemLayout.i === itemLayoutViewed) {\n const rowTitleHeight = 40 + 8; // 40 is the height of the row title and 8 is the margin height\n return {\n h: Math.round(((panelFullHeight ?? window.innerHeight) - rowTitleHeight) / (ROW_HEIGHT + DEFAULT_MARGIN)), // Viewed panel should take the full height remaining\n i: itemLayoutViewed,\n w: 48,\n x: 0,\n y: 0,\n } as PanelGroupItemLayout;\n }\n return itemLayout;\n });\n }\n return groupDefinition.itemLayouts;\n }, [groupDefinition.itemLayouts, itemLayoutViewed, panelFullHeight]);\n\n const handleLayoutChange = (currentLayout: Layout[], allLayouts: Layouts) => {\n // Using the value from `allLayouts` instead of `currentLayout` because of\n // a bug in react-layout-grid where `currentLayout` does not adjust properly\n // when going to a smaller breakpoint and then back to a larger breakpoint.\n // https://github.com/react-grid-layout/react-grid-layout/issues/1663\n const smallLayout = allLayouts[GRID_LAYOUT_SMALL_BREAKPOINT];\n if (smallLayout && !hasViewPanel) {\n updatePanelGroupLayouts(smallLayout);\n }\n };\n\n /**\n * Calculate the column width so we can determine the width of each panel for suggested step ms\n * https://github.com/react-grid-layout/react-grid-layout/blob/master/lib/calculateUtils.js#L14-L35\n */\n const handleWidthChange = (\n containerWidth: number,\n margin: [number, number],\n cols: number,\n containerPadding: [number, number]\n ) => {\n const marginX = margin[0];\n const marginWidth = marginX * (cols - 1);\n const containerPaddingWidth = containerPadding[0] * 2;\n // exclude margin and padding from total width\n setGridColWidth((containerWidth - marginWidth - containerPaddingWidth) / cols);\n };\n\n return (\n <GridContainer sx={{ display: isGridDisplayed ? 'block' : 'none' }}>\n {groupDefinition.title !== undefined && (\n <GridTitle\n panelGroupId={panelGroupId}\n title={groupDefinition.title}\n collapse={\n groupDefinition.isCollapsed === undefined\n ? undefined\n : { isOpen, onToggleOpen: () => setIsOpen((current) => !current) }\n }\n />\n )}\n <Collapse in={isOpen} unmountOnExit appear={false} data-testid=\"panel-group-content\">\n <ResponsiveGridLayout\n className=\"layout\"\n breakpoints={{ sm: theme.breakpoints.values.sm, xxs: 0 }}\n cols={GRID_LAYOUT_COLS}\n rowHeight={ROW_HEIGHT}\n draggableHandle=\".drag-handle\"\n resizeHandles={['se']}\n isDraggable={isEditMode && !hasViewPanel}\n isResizable={isEditMode && !hasViewPanel}\n margin={[DEFAULT_MARGIN, DEFAULT_MARGIN]}\n containerPadding={[0, 10]}\n layouts={{ [GRID_LAYOUT_SMALL_BREAKPOINT]: itemLayouts }}\n onLayoutChange={handleLayoutChange}\n onWidthChange={handleWidthChange}\n allowOverlap={hasViewPanel} // Enabling overlap when viewing a specific panel because panel in front of the viewed panel will add empty spaces (empty row height)\n >\n {itemLayouts.map(({ i, w }) => (\n <div\n key={i}\n style={{\n display: itemLayoutViewed !== undefined ? (itemLayoutViewed === i ? 'unset' : 'none') : 'unset',\n }}\n >\n <ErrorBoundary FallbackComponent={ErrorAlert}>\n <GridItemContent\n panelOptions={panelOptions}\n panelGroupItemId={{ panelGroupId, panelGroupItemLayoutId: i }}\n width={calculateGridItemWidth(w, gridColWidth)}\n />\n </ErrorBoundary>\n </div>\n ))}\n </ResponsiveGridLayout>\n </Collapse>\n </GridContainer>\n );\n}\n\n/**\n * Calculates grid item width\n * @param w number of columns the grid item spans\n * @param colWidth the width of each column in px\n * @returns grid item's width in px\n * https://github.com/react-grid-layout/react-grid-layout/blob/master/lib/calculateUtils.js#L14-L35\n */\nconst calculateGridItemWidth = (w: number, colWidth: number) => {\n // 0 * Infinity === NaN, which causes problems with resize contraints\n if (!Number.isFinite(w)) return w;\n return Math.round(colWidth * w + Math.max(0, w - 1) * DEFAULT_MARGIN);\n};\n"],"names":["useMemo","useState","Responsive","WidthProvider","Collapse","useTheme","ErrorAlert","ErrorBoundary","useEditMode","usePanelGroup","usePanelGroupActions","useViewPanel","GRID_LAYOUT_COLS","GRID_LAYOUT_SMALL_BREAKPOINT","GridTitle","GridItemContent","GridContainer","DEFAULT_MARGIN","ROW_HEIGHT","ResponsiveGridLayout","GridLayout","props","panelGroupId","panelOptions","panelFullHeight","theme","groupDefinition","updatePanelGroupLayouts","isOpen","setIsOpen","isCollapsed","isEditMode","gridColWidth","setGridColWidth","viewPanelItemId","hasViewPanel","itemLayoutViewed","panelGroupItemLayoutId","isGridDisplayed","undefined","itemLayouts","map","itemLayout","i","rowTitleHeight","h","Math","round","window","innerHeight","w","x","y","handleLayoutChange","currentLayout","allLayouts","smallLayout","handleWidthChange","containerWidth","margin","cols","containerPadding","marginX","marginWidth","containerPaddingWidth","sx","display","title","collapse","onToggleOpen","current","in","unmountOnExit","appear","data-testid","className","breakpoints","sm","values","xxs","rowHeight","draggableHandle","resizeHandles","isDraggable","isResizable","layouts","onLayoutChange","onWidthChange","allowOverlap","div","style","FallbackComponent","panelGroupItemId","width","calculateGridItemWidth","colWidth","Number","isFinite","max"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AACjC,SAASA,OAAO,EAAEC,QAAQ,QAAQ,QAAQ;AAC1C,SAASC,UAAU,EAAEC,aAAa,QAAyB,oBAAoB;AAC/E,SAASC,QAAQ,EAAEC,QAAQ,QAAQ,gBAAgB;AACnD,SAASC,UAAU,EAAEC,aAAa,QAAQ,yBAAyB;AACnE,SACEC,WAAW,EACXC,aAAa,EACbC,oBAAoB,EAGpBC,YAAY,QAEP,gBAAgB;AACvB,SAASC,gBAAgB,EAAEC,4BAA4B,QAAQ,kBAAkB;AAEjF,SAASC,SAAS,QAAQ,cAAc;AACxC,SAASC,eAAe,QAAQ,oBAA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apD,cAAc,CAACI;oBAC5BiD,aAAarD,cAAc,CAACI;oBAC5BwB,QAAQ;wBAAC1C;wBAAgBA;qBAAe;oBACxC4C,kBAAkB;wBAAC;wBAAG;qBAAG;oBACzBwB,SAAS;wBAAE,CAACxE,6BAA6B,EAAE2B;oBAAY;oBACvD8C,gBAAgBjC;oBAChBkC,eAAe9B;oBACf+B,cAAcrD;8BAEbK,YAAYC,GAAG,CAAC,CAAC,EAAEE,CAAC,EAAEO,CAAC,EAAE,iBACxB,KAACuC;4BAECC,OAAO;gCACLxB,SAAS9B,qBAAqBG,YAAaH,qBAAqBO,IAAI,UAAU,SAAU;4BAC1F;sCAEA,cAAA,KAACpC;gCAAcoF,mBAAmBrF;0CAChC,cAAA,KAACS;oCACCQ,cAAcA;oCACdqE,kBAAkB;wCAAEtE;wCAAce,wBAAwBM;oCAAE;oCAC5DkD,OAAOC,uBAAuB5C,GAAGlB;;;2BAThCW;;;;;AAkBnB;AAEA;;;;;;CAMC,GACD,MAAMmD,yBAAyB,CAAC5C,GAAW6C;IACzC,qEAAqE;IACrE,IAAI,CAACC,OAAOC,QAAQ,CAAC/C,IAAI,OAAOA;IAChC,OAAOJ,KAAKC,KAAK,CAACgD,WAAW7C,IAAIJ,KAAKoD,GAAG,CAAC,GAAGhD,IAAI,KAAKjC;AACxD"}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/GridLayout/GridLayout.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { useMemo, useState } from 'react';\nimport { Responsive, WidthProvider, Layouts, Layout } from 'react-grid-layout';\nimport { Collapse, useTheme } from '@mui/material';\nimport { ErrorAlert, ErrorBoundary } from '@perses-dev/components';\nimport {\n useEditMode,\n usePanelGroup,\n usePanelGroupActions,\n PanelGroupId,\n PanelGroupItemLayout,\n useViewPanel,\n PanelGroupDefinition,\n} from '../../context';\nimport { GRID_LAYOUT_COLS, GRID_LAYOUT_SMALL_BREAKPOINT } from '../../constants';\nimport { PanelOptions } from '../Panel';\nimport { GridTitle } from './GridTitle';\nimport { GridItemContent } from './GridItemContent';\nimport { GridContainer } from './GridContainer';\nconst DEFAULT_MARGIN = 10;\nconst ROW_HEIGHT = 30;\n\nexport interface GridLayoutProps {\n panelGroupId: PanelGroupId;\n panelOptions?: PanelOptions;\n panelFullHeight?: number;\n}\n\n/**\n * Layout component that arranges children in a Grid based on the definition.\n */\nexport function GridLayout(props: GridLayoutProps) {\n const { panelGroupId, panelOptions, panelFullHeight } = props;\n const theme = useTheme();\n const groupDefinition: PanelGroupDefinition = usePanelGroup(panelGroupId);\n const { updatePanelGroupLayouts } = usePanelGroupActions(panelGroupId);\n\n const [isOpen, setIsOpen] = useState(!groupDefinition.isCollapsed ?? true);\n const { isEditMode } = useEditMode();\n\n const [gridColWidth, setGridColWidth] = useState(0);\n\n const viewPanelItemId = useViewPanel();\n const hasViewPanel = viewPanelItemId?.panelGroupId === panelGroupId; // current panelGroup contains the panel extended?\n const itemLayoutViewed = viewPanelItemId?.panelGroupItemLayoutId;\n\n // If there is a panel in view mode, we should hide the grid if the panel is not in the current group.\n const isGridDisplayed = useMemo(() => {\n if (viewPanelItemId === undefined) {\n return true;\n }\n if (hasViewPanel) {\n setIsOpen(true);\n }\n return hasViewPanel;\n }, [hasViewPanel, viewPanelItemId]);\n\n // Item layout is override if there is a panel in view mode\n const itemLayouts: PanelGroupItemLayout[] = useMemo(() => {\n if (itemLayoutViewed) {\n return groupDefinition.itemLayouts.map((itemLayout) => {\n if (itemLayout.i === itemLayoutViewed) {\n const rowTitleHeight = 40 + 8; // 40 is the height of the row title and 8 is the margin height\n return {\n h: Math.round(((panelFullHeight ?? window.innerHeight) - rowTitleHeight) / (ROW_HEIGHT + DEFAULT_MARGIN)), // Viewed panel should take the full height remaining\n i: itemLayoutViewed,\n w: 48,\n x: 0,\n y: 0,\n } as PanelGroupItemLayout;\n }\n return itemLayout;\n });\n }\n return groupDefinition.itemLayouts;\n }, [groupDefinition.itemLayouts, itemLayoutViewed, panelFullHeight]);\n\n const handleLayoutChange = (currentLayout: Layout[], allLayouts: Layouts) => {\n // Using the value from `allLayouts` instead of `currentLayout` because of\n // a bug in react-layout-grid where `currentLayout` does not adjust properly\n // when going to a smaller breakpoint and then back to a larger breakpoint.\n // https://github.com/react-grid-layout/react-grid-layout/issues/1663\n const smallLayout = allLayouts[GRID_LAYOUT_SMALL_BREAKPOINT];\n if (smallLayout && !hasViewPanel) {\n updatePanelGroupLayouts(smallLayout);\n }\n };\n\n /**\n * Calculate the column width so we can determine the width of each panel for suggested step ms\n * https://github.com/react-grid-layout/react-grid-layout/blob/master/lib/calculateUtils.js#L14-L35\n */\n const handleWidthChange = (\n containerWidth: number,\n margin: [number, number],\n cols: number,\n containerPadding: [number, number]\n ) => {\n const marginX = margin[0];\n const marginWidth = marginX * (cols - 1);\n const containerPaddingWidth = containerPadding[0] * 2;\n // exclude margin and padding from total width\n setGridColWidth((containerWidth - marginWidth - containerPaddingWidth) / cols);\n };\n\n // https://github.com/react-grid-layout/react-grid-layout?tab=readme-ov-file#react-hooks-performance\n const ResponsiveGridLayout = useMemo(() => WidthProvider(Responsive), []);\n\n return (\n <GridContainer\n sx={{\n display: isGridDisplayed ? 'block' : 'none',\n height: itemLayoutViewed ? `${panelFullHeight}px` : 'unset',\n overflow: itemLayoutViewed ? 'hidden' : 'unset',\n }}\n >\n {groupDefinition.title !== undefined && (\n <GridTitle\n panelGroupId={panelGroupId}\n title={groupDefinition.title}\n collapse={\n groupDefinition.isCollapsed === undefined\n ? undefined\n : { isOpen, onToggleOpen: () => setIsOpen((current) => !current) }\n }\n />\n )}\n <Collapse in={isOpen} unmountOnExit appear={false} data-testid=\"panel-group-content\">\n <ResponsiveGridLayout\n className=\"layout\"\n breakpoints={{ sm: theme.breakpoints.values.sm, xxs: 0 }}\n cols={GRID_LAYOUT_COLS}\n rowHeight={ROW_HEIGHT}\n draggableHandle=\".drag-handle\"\n resizeHandles={['se']}\n isDraggable={isEditMode && !hasViewPanel}\n isResizable={isEditMode && !hasViewPanel}\n margin={[DEFAULT_MARGIN, DEFAULT_MARGIN]}\n containerPadding={[0, 10]}\n layouts={{ [GRID_LAYOUT_SMALL_BREAKPOINT]: itemLayouts }}\n onLayoutChange={handleLayoutChange}\n onWidthChange={handleWidthChange}\n allowOverlap={hasViewPanel} // Enabling overlap when viewing a specific panel because panel in front of the viewed panel will add empty spaces (empty row height)\n >\n {itemLayouts.map(({ i, w }) => (\n <div\n key={i}\n style={{\n display: itemLayoutViewed !== undefined ? (itemLayoutViewed === i ? 'unset' : 'none') : 'unset',\n }}\n >\n <ErrorBoundary FallbackComponent={ErrorAlert}>\n <GridItemContent\n panelOptions={panelOptions}\n panelGroupItemId={{ panelGroupId, panelGroupItemLayoutId: i }}\n width={calculateGridItemWidth(w, gridColWidth)}\n />\n </ErrorBoundary>\n </div>\n ))}\n </ResponsiveGridLayout>\n </Collapse>\n </GridContainer>\n );\n}\n\n/**\n * Calculates grid item width\n * @param w number of columns the grid item spans\n * @param colWidth the width of each column in px\n * @returns grid item's width in px\n * https://github.com/react-grid-layout/react-grid-layout/blob/master/lib/calculateUtils.js#L14-L35\n */\nconst calculateGridItemWidth = (w: number, colWidth: number) => {\n // 0 * Infinity === NaN, which causes problems with resize contraints\n if (!Number.isFinite(w)) return w;\n return Math.round(colWidth * w + Math.max(0, w - 1) * DEFAULT_MARGIN);\n};\n"],"names":["useMemo","useState","Responsive","WidthProvider","Collapse","useTheme","ErrorAlert","ErrorBoundary","useEditMode","usePanelGroup","usePanelGroupActions","useViewPanel","GRID_LAYOUT_COLS","GRID_LAYOUT_SMALL_BREAKPOINT","GridTitle","GridItemContent","GridContainer","DEFAULT_MARGIN","ROW_HEIGHT","GridLayout","props","panelGroupId","panelOptions","panelFullHeight","theme","groupDefinition","updatePanelGroupLayouts","isOpen","setIsOpen","isCollapsed","isEditMode","gridColWidth","setGridColWidth","viewPanelItemId","hasViewPanel","itemLayoutViewed","panelGroupItemLayoutId","isGridDisplayed","undefined","itemLayouts","map","itemLayout","i","rowTitleHeight","h","Math","round","window","innerHeight","w","x","y","handleLayoutChange","currentLayout","allLayouts","smallLayout","handleWidthChange","containerWidth","margin","cols","containerPadding","marginX","marginWidth","containerPaddingWidth","ResponsiveGridLayout","sx","display","height","overflow","title","collapse","onToggleOpen","current","in","unmountOnExit","appear","data-testid","className","breakpoints","sm","values","xxs","rowHeight","draggableHandle","resizeHandles","isDraggable","isResizable","layouts","onLayoutChange","onWidthChange","allowOverlap","div","style","FallbackComponent","panelGroupItemId","width","calculateGridItemWidth","colWidth","Number","isFinite","max"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AACjC,SAASA,OAAO,EAAEC,QAAQ,QAAQ,QAAQ;AAC1C,SAASC,UAAU,EAAEC,aAAa,QAAyB,oBAAoB;AAC/E,SAASC,QAAQ,EAAEC,QAAQ,QAAQ,gBAAgB;AACnD,SAASC,UAAU,EAAEC,aAAa,QAAQ,yBAAyB;AACnE,SACEC,WAAW,EACXC,aAAa,EACbC,oBAAoB,EAGpBC,YAAY,QAEP,gBAAgB;AACvB,SAASC,gBAAgB,EAAEC,4BAA4B,QAAQ,kBAAkB;AAEjF,SAASC,SAAS,QAAQ,cAAc;AACxC,SAASC,eAAe,QAAQ,oBAAoB;AACpD,SAASC,aAAa,QAAQ,kBAAkB;AAChD,MAAMC,iBAAiB;AACvB,MAAMC,aAA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BACvDtB,MAAM/C;oBACNsE,WAAWhE;oBACXiE,iBAAgB;oBAChBC,eAAe;wBAAC;qBAAK;oBACrBC,aAAavD,cAAc,CAACI;oBAC5BoD,aAAaxD,cAAc,CAACI;oBAC5BwB,QAAQ;wBAACzC;wBAAgBA;qBAAe;oBACxC2C,kBAAkB;wBAAC;wBAAG;qBAAG;oBACzB2B,SAAS;wBAAE,CAAC1E,6BAA6B,EAAE0B;oBAAY;oBACvDiD,gBAAgBpC;oBAChBqC,eAAejC;oBACfkC,cAAcxD;8BAEbK,YAAYC,GAAG,CAAC,CAAC,EAAEE,CAAC,EAAEO,CAAC,EAAE,iBACxB,KAAC0C;4BAECC,OAAO;gCACL1B,SAAS/B,qBAAqBG,YAAaH,qBAAqBO,IAAI,UAAU,SAAU;4BAC1F;sCAEA,cAAA,KAACnC;gCAAcsF,mBAAmBvF;0CAChC,cAAA,KAACS;oCACCO,cAAcA;oCACdwE,kBAAkB;wCAAEzE;wCAAce,wBAAwBM;oCAAE;oCAC5DqD,OAAOC,uBAAuB/C,GAAGlB;;;2BAThCW;;;;;AAkBnB;AAEA;;;;;;CAMC,GACD,MAAMsD,yBAAyB,CAAC/C,GAAWgD;IACzC,qEAAqE;IACrE,IAAI,CAACC,OAAOC,QAAQ,CAAClD,IAAI,OAAOA;IAChC,OAAOJ,KAAKC,KAAK,CAACmD,WAAWhD,IAAIJ,KAAKuD,GAAG,CAAC,GAAGnD,IAAI,KAAKhC;AACxD"}
|
|
@@ -185,7 +185,7 @@ const StyledPopper = (props)=>/*#__PURE__*/ _jsx(Popper, {
|
|
|
185
185
|
const LETTER_HSIZE = 8; // approximation
|
|
186
186
|
const ARROW_OFFSET = 40; // right offset for list variables (= take into account the dropdown toggle size)
|
|
187
187
|
const getWidthPx = (inputValue, kind)=>{
|
|
188
|
-
const width = (inputValue.length + 1) * LETTER_HSIZE + (kind
|
|
188
|
+
const width = (inputValue.length + 1) * LETTER_HSIZE + (kind === 'list' ? ARROW_OFFSET : 0);
|
|
189
189
|
if (width < MIN_TEMPLATE_VARIABLE_WIDTH) {
|
|
190
190
|
return MIN_TEMPLATE_VARIABLE_WIDTH;
|
|
191
191
|
} else if (width > MAX_TEMPLATE_VARIABLE_WIDTH) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/Variables/TemplateVariable.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { useEffect, useMemo, useState } from 'react';\nimport { LinearProgress, TextField, Autocomplete, Popper, PopperProps } from '@mui/material';\nimport {\n DEFAULT_ALL_VALUE,\n ListVariableDefinition,\n ListVariableSpec,\n TextVariableDefinition,\n UnknownSpec,\n VariableName,\n VariableValue,\n} from '@perses-dev/core';\nimport { useListVariablePluginValues, VariableOption, VariableState } from '@perses-dev/plugin-system';\nimport { UseQueryResult } from '@tanstack/react-query';\nimport { useTemplateVariable, useTemplateVariableActions } from '../../context';\nimport { MAX_TEMPLATE_VARIABLE_WIDTH, MIN_TEMPLATE_VARIABLE_WIDTH } from '../../constants';\n\ntype TemplateVariableProps = {\n name: VariableName;\n source?: string;\n};\n\nfunction variableOptionToVariableValue(options: VariableOption | VariableOption[] | null): VariableValue {\n if (options === null) {\n return null;\n }\n if (Array.isArray(options)) {\n return options.map((v) => {\n return v.value;\n });\n }\n return options.value;\n}\n\nexport function TemplateVariable({ name, source }: TemplateVariableProps) {\n const ctx = useTemplateVariable(name, source);\n const kind = ctx.definition?.kind;\n switch (kind) {\n case 'TextVariable':\n return <TextVariable name={name} source={source} />;\n case 'ListVariable':\n return <ListVariable name={name} source={source} />;\n }\n\n return <div>Unsupported Variable Kind: ${kind}</div>;\n}\n\nexport function useListVariableState(\n spec: ListVariableSpec<UnknownSpec> | undefined,\n state: VariableState | undefined,\n variablesOptionsQuery: Partial<UseQueryResult<VariableOption[]>>\n): {\n // Value, Loading, Options are modified only when we want to save the changes made\n value: VariableValue | undefined;\n loading: boolean;\n options: VariableOption[] | undefined;\n // selectedOptions is/are the option(s) selected in the view\n selectedOptions: VariableOption | VariableOption[];\n // viewOptions are the options used in the view only (= options + All if allowed)\n viewOptions: VariableOption[];\n} {\n const allowMultiple = spec?.allowMultiple === true;\n const allowAllValue = spec?.allowAllValue === true;\n const sort = spec?.sort;\n const loading = useMemo(() => variablesOptionsQuery.isFetching ?? false, [variablesOptionsQuery.isFetching]);\n const options = useMemo(() => variablesOptionsQuery.data ?? [], [variablesOptionsQuery.data]);\n\n let value = state?.value;\n\n // Make sure value is an array if allowMultiple is true\n if (allowMultiple && !Array.isArray(value)) {\n value = typeof value === 'string' ? [value] : [];\n }\n\n // Sort the provided list of options according to the method defined\n const sortedOptions = useMemo((): VariableOption[] => {\n const opts = options ? [...options] : [];\n\n if (!sort || sort === 'none') return opts;\n\n switch (sort) {\n case 'alphabetical-asc':\n return opts.sort((a, b) => (a.label > b.label ? 1 : -1));\n case 'alphabetical-desc':\n return opts.sort((a, b) => (a.label > b.label ? -1 : 1));\n case 'numerical-asc':\n return opts.sort((a, b) => (parseInt(a.label) > parseInt(b.label) ? 1 : -1));\n case 'numerical-desc':\n return opts.sort((a, b) => (parseInt(a.label) < parseInt(b.label) ? 1 : -1));\n case 'alphabetical-ci-asc':\n return opts.sort((a, b) => (a.label.toLowerCase() > b.label.toLowerCase() ? 1 : -1));\n case 'alphabetical-ci-desc':\n return opts.sort((a, b) => (a.label.toLowerCase() > b.label.toLowerCase() ? -1 : 1));\n default:\n return opts;\n }\n }, [options, sort]);\n\n const viewOptions = useMemo(() => {\n let computedOptions = sortedOptions;\n\n // Add the all value if it's allowed\n if (allowAllValue) {\n computedOptions = [{ value: DEFAULT_ALL_VALUE, label: 'All' }, ...computedOptions];\n }\n return computedOptions;\n }, [allowAllValue, sortedOptions]);\n\n const valueIsInOptions = useMemo(\n () =>\n Boolean(\n viewOptions.find((v) => {\n if (allowMultiple) {\n return (value as string[]).includes(v.value);\n }\n return value === v.value;\n })\n ),\n [viewOptions, value, allowMultiple]\n );\n\n value = useMemo(() => {\n const firstOptionValue = viewOptions?.[allowAllValue ? 1 : 0]?.value;\n\n // If there is no value but there are options, or the value is not in options, we set the value to the first option.\n if (firstOptionValue) {\n if (!valueIsInOptions || !value || value.length === 0) {\n return allowMultiple ? [firstOptionValue] : firstOptionValue;\n }\n }\n\n return value;\n }, [viewOptions, value, valueIsInOptions, allowMultiple, allowAllValue]);\n\n const selectedOptions = useMemo(() => {\n // In the case Autocomplete.multiple equals false, Autocomplete.value expects a single object, not\n // an array, hence this conditional\n if (Array.isArray(value)) {\n return viewOptions.filter((o) => {\n return value?.includes(o.value);\n });\n } else {\n return (\n viewOptions.find((o) => {\n return value === o.value;\n }) ?? { value: '', label: '' }\n );\n }\n }, [value, viewOptions]);\n\n return { value, loading, options, selectedOptions, viewOptions };\n}\n\nconst StyledPopper = (props: PopperProps) => (\n <Popper placeholder={undefined} {...props} sx={{ minWidth: 'fit-content' }} placement=\"bottom-start\" />\n);\n\nconst LETTER_HSIZE = 8; // approximation\nconst ARROW_OFFSET = 40; // right offset for list variables (= take into account the dropdown toggle size)\nconst getWidthPx = (inputValue: string, kind: 'list' | 'text'): number => {\n const width = (inputValue.length + 1) * LETTER_HSIZE + (kind == 'list' ? ARROW_OFFSET : 0);\n if (width < MIN_TEMPLATE_VARIABLE_WIDTH) {\n return MIN_TEMPLATE_VARIABLE_WIDTH;\n } else if (width > MAX_TEMPLATE_VARIABLE_WIDTH) {\n return MAX_TEMPLATE_VARIABLE_WIDTH;\n } else {\n return width;\n }\n};\n\nfunction ListVariable({ name, source }: TemplateVariableProps) {\n const ctx = useTemplateVariable(name, source);\n const definition = ctx.definition as ListVariableDefinition;\n const variablesOptionsQuery = useListVariablePluginValues(definition);\n const { setVariableValue, setVariableLoading, setVariableOptions } = useTemplateVariableActions();\n const { selectedOptions, value, loading, options, viewOptions } = useListVariableState(\n definition?.spec,\n ctx.state,\n variablesOptionsQuery\n );\n const [inputValue, setInputValue] = useState<string>('');\n const [inputWidth, setInputWidth] = useState(MIN_TEMPLATE_VARIABLE_WIDTH);\n\n const title = definition?.spec.display?.name ?? name;\n const allowMultiple = definition?.spec.allowMultiple === true;\n const allowAllValue = definition?.spec.allowAllValue === true;\n\n // Update value when changed\n useEffect(() => {\n if (value) {\n setVariableValue(name, value, source);\n }\n }, [setVariableValue, name, value, source]);\n\n // Update loading when changed\n useEffect(() => {\n setVariableLoading(name, loading, source);\n }, [setVariableLoading, name, loading, source]);\n\n // Update options when changed\n useEffect(() => {\n if (options) {\n setVariableOptions(name, options, source);\n }\n }, [setVariableOptions, name, options, source]);\n\n return (\n <>\n <Autocomplete\n disablePortal\n disableCloseOnSelect={allowMultiple}\n multiple={allowMultiple}\n fullWidth\n limitTags={3}\n size=\"small\"\n disableClearable\n PopperComponent={StyledPopper}\n renderInput={(params) => {\n return allowMultiple ? (\n <TextField {...params} label={title} />\n ) : (\n <TextField {...params} label={title} style={{ width: `${inputWidth}px` }} />\n );\n }}\n sx={{\n '& .MuiInputBase-root': {\n minHeight: '38px',\n },\n '& .MuiInputBase-root.MuiOutlinedInput-root.MuiInputBase-sizeSmall': {\n paddingY: '5px',\n paddingLeft: '5px',\n },\n }}\n value={selectedOptions}\n onChange={(_, value) => {\n if ((value === null || (Array.isArray(value) && value.length === 0)) && allowAllValue) {\n setVariableValue(name, DEFAULT_ALL_VALUE, source);\n } else {\n setVariableValue(name, variableOptionToVariableValue(value), source);\n }\n }}\n inputValue={inputValue}\n onInputChange={(_, newInputValue) => {\n setInputValue(newInputValue);\n if (!allowMultiple) {\n setInputWidth(getWidthPx(newInputValue, 'list'));\n }\n }}\n options={viewOptions}\n />\n {loading && <LinearProgress />}\n </>\n );\n}\n\nfunction TextVariable({ name, source }: TemplateVariableProps) {\n const ctx = useTemplateVariable(name, source);\n const state = ctx.state;\n const definition = ctx.definition as TextVariableDefinition;\n const [tempValue, setTempValue] = useState(state?.value ?? '');\n const [inputWidth, setInputWidth] = useState(getWidthPx(tempValue as string, 'text'));\n const { setVariableValue } = useTemplateVariableActions();\n\n useEffect(() => {\n setTempValue(state?.value ?? '');\n }, [state?.value]);\n\n return (\n <TextField\n title={tempValue as string}\n value={tempValue}\n //onChange={(e) => setTempValue(e.target.value)}\n onChange={(e) => {\n setTempValue(e.target.value);\n setInputWidth(getWidthPx(e.target.value, 'text'));\n }}\n onBlur={() => setVariableValue(name, tempValue, source)}\n placeholder={name}\n label={definition?.spec.display?.name ?? name}\n InputProps={{\n readOnly: definition?.spec.constant ?? false,\n }}\n sx={{\n width: `${inputWidth}px`,\n '& .MuiInputBase-root': {\n minHeight: '38px',\n },\n '& .MuiInputBase-input': {\n textOverflow: 'ellipsis',\n },\n }}\n />\n );\n}\n"],"names":["useEffect","useMemo","useState","LinearProgress","TextField","Autocomplete","Popper","DEFAULT_ALL_VALUE","useListVariablePluginValues","useTemplateVariable","useTemplateVariableActions","MAX_TEMPLATE_VARIABLE_WIDTH","MIN_TEMPLATE_VARIABLE_WIDTH","variableOptionToVariableValue","options","Array","isArray","map","v","value","TemplateVariable","name","source","ctx","kind","definition","TextVariable","ListVariable","div","useListVariableState","spec","state","variablesOptionsQuery","allowMultiple","allowAllValue","sort","loading","isFetching","data","sortedOptions","opts","a","b","label","parseInt","toLowerCase","viewOptions","computedOptions","valueIsInOptions","Boolean","find","includes","firstOptionValue","length","selectedOptions","filter","o","StyledPopper","props","placeholder","undefined","sx","minWidth","placement","LETTER_HSIZE","ARROW_OFFSET","getWidthPx","inputValue","width","setVariableValue","setVariableLoading","setVariableOptions","setInputValue","inputWidth","setInputWidth","title","display","disablePortal","disableCloseOnSelect","multiple","fullWidth","limitTags","size","disableClearable","PopperComponent","renderInput","params","style","minHeight","paddingY","paddingLeft","onChange","_","onInputChange","newInputValue","tempValue","setTempValue","e","target","onBlur","InputProps","readOnly","constant","textOverflow"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAQ;AACrD,SAASC,cAAc,EAAEC,SAAS,EAAEC,YAAY,EAAEC,MAAM,QAAqB,gBAAgB;AAC7F,SACEC,iBAAiB,QAOZ,mBAAmB;AAC1B,SAASC,2BAA2B,QAAuC,4BAA4B;AAEvG,SAASC,mBAAmB,EAAEC,0BAA0B,QAAQ,gBAAgB;AAChF,SAASC,2BAA2B,EAAEC,2BAA2B,QAAQ,kBAAkB;AAO3F,SAASC,8BAA8BC,OAAiD;IACtF,IAAIA,YAAY,MAAM;QACpB,OAAO;IACT;IACA,IAAIC,MAAMC,OAAO,CAACF,UAAU;QAC1B,OAAOA,QAAQG,GAAG,CAAC,CAACC;YAClB,OAAOA,EAAEC,KAAK;QAChB;IACF;IACA,OAAOL,QAAQK,KAAK;AACtB;AAEA,OAAO,SAASC,iBAAiB,EAAEC,IAAI,EAAEC,MAAM,EAAyB;QAEzDC;IADb,MAAMA,MAAMd,oBAAoBY,MAAMC;IACtC,MAAME,QAAOD,kBAAAA,IAAIE,UAAU,cAAdF,sCAAAA,gBAAgBC,IAAI;IACjC,OAAQA;QACN,KAAK;YACH,qBAAO,KAACE;gBAAaL,MAAMA;gBAAMC,QAAQA;;QAC3C,KAAK;YACH,qBAAO,KAACK;gBAAaN,MAAMA;gBAAMC,QAAQA;;IAC7C;IAEA,qBAAO,MAACM;;YAAI;YAA6BJ;;;AAC3C;AAEA,OAAO,SAASK,qBACdC,IAA+C,EAC/CC,KAA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AAOZ,KAAK;KAAC;QAaNM,+BAEKA;IAbhB,qBACE,KAACrB;QACCuE,OAAOoB;QACP5E,OAAO4E;QACP,gDAAgD;QAChDJ,UAAU,CAACM;YACTD,aAAaC,EAAEC,MAAM,CAAC/E,KAAK;YAC3BuD,cAAcR,WAAW+B,EAAEC,MAAM,CAAC/E,KAAK,EAAE;QAC3C;QACAgF,QAAQ,IAAM9B,iBAAiBhD,MAAM0E,WAAWzE;QAChDqC,aAAatC;QACbsB,OAAOlB,CAAAA,gCAAAA,uBAAAA,kCAAAA,2BAAAA,WAAYK,IAAI,CAAC8C,OAAO,cAAxBnD,+CAAAA,yBAA0BJ,IAAI,cAA9BI,2CAAAA,gCAAkCJ;QACzC+E,YAAY;YACVC,UAAU5E,CAAAA,4BAAAA,uBAAAA,iCAAAA,WAAYK,IAAI,CAACwE,QAAQ,cAAzB7E,uCAAAA,4BAA6B;QACzC;QACAoC,IAAI;YACFO,OAAO,CAAC,EAAEK,WAAW,EAAE,CAAC;YACxB,wBAAwB;gBACtBe,WAAW;YACb;YACA,yBAAyB;gBACvBe,cAAc;YAChB;QACF;;AAGN"}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/Variables/TemplateVariable.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { useEffect, useMemo, useState } from 'react';\nimport { LinearProgress, TextField, Autocomplete, Popper, PopperProps } from '@mui/material';\nimport {\n DEFAULT_ALL_VALUE,\n ListVariableDefinition,\n ListVariableSpec,\n TextVariableDefinition,\n UnknownSpec,\n VariableName,\n VariableValue,\n} from '@perses-dev/core';\nimport { useListVariablePluginValues, VariableOption, VariableState } from '@perses-dev/plugin-system';\nimport { UseQueryResult } from '@tanstack/react-query';\nimport { useTemplateVariable, useTemplateVariableActions } from '../../context';\nimport { MAX_TEMPLATE_VARIABLE_WIDTH, MIN_TEMPLATE_VARIABLE_WIDTH } from '../../constants';\n\ntype TemplateVariableProps = {\n name: VariableName;\n source?: string;\n};\n\nfunction variableOptionToVariableValue(options: VariableOption | VariableOption[] | null): VariableValue {\n if (options === null) {\n return null;\n }\n if (Array.isArray(options)) {\n return options.map((v) => {\n return v.value;\n });\n }\n return options.value;\n}\n\nexport function TemplateVariable({ name, source }: TemplateVariableProps) {\n const ctx = useTemplateVariable(name, source);\n const kind = ctx.definition?.kind;\n switch (kind) {\n case 'TextVariable':\n return <TextVariable name={name} source={source} />;\n case 'ListVariable':\n return <ListVariable name={name} source={source} />;\n }\n\n return <div>Unsupported Variable Kind: ${kind}</div>;\n}\n\nexport function useListVariableState(\n spec: ListVariableSpec<UnknownSpec> | undefined,\n state: VariableState | undefined,\n variablesOptionsQuery: Partial<UseQueryResult<VariableOption[]>>\n): {\n // Value, Loading, Options are modified only when we want to save the changes made\n value: VariableValue | undefined;\n loading: boolean;\n options: VariableOption[] | undefined;\n // selectedOptions is/are the option(s) selected in the view\n selectedOptions: VariableOption | VariableOption[];\n // viewOptions are the options used in the view only (= options + All if allowed)\n viewOptions: VariableOption[];\n} {\n const allowMultiple = spec?.allowMultiple === true;\n const allowAllValue = spec?.allowAllValue === true;\n const sort = spec?.sort;\n const loading = useMemo(() => variablesOptionsQuery.isFetching ?? false, [variablesOptionsQuery.isFetching]);\n const options = useMemo(() => variablesOptionsQuery.data ?? [], [variablesOptionsQuery.data]);\n\n let value = state?.value;\n\n // Make sure value is an array if allowMultiple is true\n if (allowMultiple && !Array.isArray(value)) {\n value = typeof value === 'string' ? [value] : [];\n }\n\n // Sort the provided list of options according to the method defined\n const sortedOptions = useMemo((): VariableOption[] => {\n const opts = options ? [...options] : [];\n\n if (!sort || sort === 'none') return opts;\n\n switch (sort) {\n case 'alphabetical-asc':\n return opts.sort((a, b) => (a.label > b.label ? 1 : -1));\n case 'alphabetical-desc':\n return opts.sort((a, b) => (a.label > b.label ? -1 : 1));\n case 'numerical-asc':\n return opts.sort((a, b) => (parseInt(a.label) > parseInt(b.label) ? 1 : -1));\n case 'numerical-desc':\n return opts.sort((a, b) => (parseInt(a.label) < parseInt(b.label) ? 1 : -1));\n case 'alphabetical-ci-asc':\n return opts.sort((a, b) => (a.label.toLowerCase() > b.label.toLowerCase() ? 1 : -1));\n case 'alphabetical-ci-desc':\n return opts.sort((a, b) => (a.label.toLowerCase() > b.label.toLowerCase() ? -1 : 1));\n default:\n return opts;\n }\n }, [options, sort]);\n\n const viewOptions = useMemo(() => {\n let computedOptions = sortedOptions;\n\n // Add the all value if it's allowed\n if (allowAllValue) {\n computedOptions = [{ value: DEFAULT_ALL_VALUE, label: 'All' }, ...computedOptions];\n }\n return computedOptions;\n }, [allowAllValue, sortedOptions]);\n\n const valueIsInOptions = useMemo(\n () =>\n Boolean(\n viewOptions.find((v) => {\n if (allowMultiple) {\n return (value as string[]).includes(v.value);\n }\n return value === v.value;\n })\n ),\n [viewOptions, value, allowMultiple]\n );\n\n value = useMemo(() => {\n const firstOptionValue = viewOptions?.[allowAllValue ? 1 : 0]?.value;\n\n // If there is no value but there are options, or the value is not in options, we set the value to the first option.\n if (firstOptionValue) {\n if (!valueIsInOptions || !value || value.length === 0) {\n return allowMultiple ? [firstOptionValue] : firstOptionValue;\n }\n }\n\n return value;\n }, [viewOptions, value, valueIsInOptions, allowMultiple, allowAllValue]);\n\n const selectedOptions = useMemo(() => {\n // In the case Autocomplete.multiple equals false, Autocomplete.value expects a single object, not\n // an array, hence this conditional\n if (Array.isArray(value)) {\n return viewOptions.filter((o) => {\n return value?.includes(o.value);\n });\n } else {\n return (\n viewOptions.find((o) => {\n return value === o.value;\n }) ?? { value: '', label: '' }\n );\n }\n }, [value, viewOptions]);\n\n return { value, loading, options, selectedOptions, viewOptions };\n}\n\nconst StyledPopper = (props: PopperProps) => (\n <Popper placeholder={undefined} {...props} sx={{ minWidth: 'fit-content' }} placement=\"bottom-start\" />\n);\n\nconst LETTER_HSIZE = 8; // approximation\nconst ARROW_OFFSET = 40; // right offset for list variables (= take into account the dropdown toggle size)\nconst getWidthPx = (inputValue: string, kind: 'list' | 'text'): number => {\n const width = (inputValue.length + 1) * LETTER_HSIZE + (kind === 'list' ? ARROW_OFFSET : 0);\n if (width < MIN_TEMPLATE_VARIABLE_WIDTH) {\n return MIN_TEMPLATE_VARIABLE_WIDTH;\n } else if (width > MAX_TEMPLATE_VARIABLE_WIDTH) {\n return MAX_TEMPLATE_VARIABLE_WIDTH;\n } else {\n return width;\n }\n};\n\nfunction ListVariable({ name, source }: TemplateVariableProps) {\n const ctx = useTemplateVariable(name, source);\n const definition = ctx.definition as ListVariableDefinition;\n const variablesOptionsQuery = useListVariablePluginValues(definition);\n const { setVariableValue, setVariableLoading, setVariableOptions } = useTemplateVariableActions();\n const { selectedOptions, value, loading, options, viewOptions } = useListVariableState(\n definition?.spec,\n ctx.state,\n variablesOptionsQuery\n );\n const [inputValue, setInputValue] = useState<string>('');\n const [inputWidth, setInputWidth] = useState(MIN_TEMPLATE_VARIABLE_WIDTH);\n\n const title = definition?.spec.display?.name ?? name;\n const allowMultiple = definition?.spec.allowMultiple === true;\n const allowAllValue = definition?.spec.allowAllValue === true;\n\n // Update value when changed\n useEffect(() => {\n if (value) {\n setVariableValue(name, value, source);\n }\n }, [setVariableValue, name, value, source]);\n\n // Update loading when changed\n useEffect(() => {\n setVariableLoading(name, loading, source);\n }, [setVariableLoading, name, loading, source]);\n\n // Update options when changed\n useEffect(() => {\n if (options) {\n setVariableOptions(name, options, source);\n }\n }, [setVariableOptions, name, options, source]);\n\n return (\n <>\n <Autocomplete\n disablePortal\n disableCloseOnSelect={allowMultiple}\n multiple={allowMultiple}\n fullWidth\n limitTags={3}\n size=\"small\"\n disableClearable\n PopperComponent={StyledPopper}\n renderInput={(params) => {\n return allowMultiple ? (\n <TextField {...params} label={title} />\n ) : (\n <TextField {...params} label={title} style={{ width: `${inputWidth}px` }} />\n );\n }}\n sx={{\n '& .MuiInputBase-root': {\n minHeight: '38px',\n },\n '& .MuiInputBase-root.MuiOutlinedInput-root.MuiInputBase-sizeSmall': {\n paddingY: '5px',\n paddingLeft: '5px',\n },\n }}\n value={selectedOptions}\n onChange={(_, value) => {\n if ((value === null || (Array.isArray(value) && value.length === 0)) && allowAllValue) {\n setVariableValue(name, DEFAULT_ALL_VALUE, source);\n } else {\n setVariableValue(name, variableOptionToVariableValue(value), source);\n }\n }}\n inputValue={inputValue}\n onInputChange={(_, newInputValue) => {\n setInputValue(newInputValue);\n if (!allowMultiple) {\n setInputWidth(getWidthPx(newInputValue, 'list'));\n }\n }}\n options={viewOptions}\n />\n {loading && <LinearProgress />}\n </>\n );\n}\n\nfunction TextVariable({ name, source }: TemplateVariableProps) {\n const ctx = useTemplateVariable(name, source);\n const state = ctx.state;\n const definition = ctx.definition as TextVariableDefinition;\n const [tempValue, setTempValue] = useState(state?.value ?? '');\n const [inputWidth, setInputWidth] = useState(getWidthPx(tempValue as string, 'text'));\n const { setVariableValue } = useTemplateVariableActions();\n\n useEffect(() => {\n setTempValue(state?.value ?? '');\n }, [state?.value]);\n\n return (\n <TextField\n title={tempValue as string}\n value={tempValue}\n //onChange={(e) => setTempValue(e.target.value)}\n onChange={(e) => {\n setTempValue(e.target.value);\n setInputWidth(getWidthPx(e.target.value, 'text'));\n }}\n onBlur={() => setVariableValue(name, tempValue, source)}\n placeholder={name}\n label={definition?.spec.display?.name ?? name}\n InputProps={{\n readOnly: definition?.spec.constant ?? false,\n }}\n sx={{\n width: `${inputWidth}px`,\n '& .MuiInputBase-root': {\n minHeight: '38px',\n },\n '& .MuiInputBase-input': {\n textOverflow: 'ellipsis',\n },\n }}\n />\n );\n}\n"],"names":["useEffect","useMemo","useState","LinearProgress","TextField","Autocomplete","Popper","DEFAULT_ALL_VALUE","useListVariablePluginValues","useTemplateVariable","useTemplateVariableActions","MAX_TEMPLATE_VARIABLE_WIDTH","MIN_TEMPLATE_VARIABLE_WIDTH","variableOptionToVariableValue","options","Array","isArray","map","v","value","TemplateVariable","name","source","ctx","kind","definition","TextVariable","ListVariable","div","useListVariableState","spec","state","variablesOptionsQuery","allowMultiple","allowAllValue","sort","loading","isFetching","data","sortedOptions","opts","a","b","label","parseInt","toLowerCase","viewOptions","computedOptions","valueIsInOptions","Boolean","find","includes","firstOptionValue","length","selectedOptions","filter","o","StyledPopper","props","placeholder","undefined","sx","minWidth","placement","LETTER_HSIZE","ARROW_OFFSET","getWidthPx","inputValue","width","setVariableValue","setVariableLoading","setVariableOptions","setInputValue","inputWidth","setInputWidth","title","display","disablePortal","disableCloseOnSelect","multiple","fullWidth","limitTags","size","disableClearable","PopperComponent","renderInput","params","style","minHeight","paddingY","paddingLeft","onChange","_","onInputChange","newInputValue","tempValue","setTempValue","e","target","onBlur","InputProps","readOnly","constant","textOverflow"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAQ;AACrD,SAASC,cAAc,EAAEC,SAAS,EAAEC,YAAY,EAAEC,MAAM,QAAqB,gBAAgB;AAC7F,SACEC,iBAAiB,QAOZ,mBAAmB;AAC1B,SAASC,2BAA2B,QAAuC,4BAA4B;AAEvG,SAASC,mBAAmB,EAAEC,0BAA0B,QAAQ,gBAAgB;AAChF,SAASC,2BAA2B,EAAEC,2BAA2B,QAAQ,kBAAkB;AAO3F,SAASC,8BAA8BC,OAAiD;IACtF,IAAIA,YAAY,MAAM;QACpB,OAAO;IACT;IACA,IAAIC,MAAMC,OAAO,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|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DashboardProvider.d.ts","sourceRoot":"","sources":["../../../src/context/DashboardProvider/DashboardProvider.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"DashboardProvider.d.ts","sourceRoot":"","sources":["../../../src/context/DashboardProvider/DashboardProvider.tsx"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAIxC,OAAO,EAAiB,SAAS,EAAgD,MAAM,OAAO,CAAC;AAC/F,OAAO,EACL,iBAAiB,EACjB,OAAO,EACP,eAAe,EACf,cAAc,EAEd,cAAc,EACd,0BAA0B,EAC3B,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAA+B,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAChG,OAAO,EAAsD,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAC1G,OAAO,EAA0B,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAChF,OAAO,EAAoB,UAAU,EAAE,MAAM,eAAe,CAAC;AAC7D,OAAO,EAA+B,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAChG,OAAO,EAA0B,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAChF,OAAO,EAAmC,qCAAqC,EAAE,MAAM,gCAAgC,CAAC;AACxH,OAAO,EAAgC,kCAAkC,EAAE,MAAM,6BAA6B,CAAC;AAC/G,OAAO,EAA6B,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EAA6B,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAE1F,OAAO,EAAwB,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAE1E,MAAM,WAAW,mBACf,SAAQ,eAAe,EACrB,UAAU,EACV,qBAAqB,EACrB,qBAAqB,EACrB,gBAAgB,EAChB,gBAAgB,EAChB,qCAAqC,EACrC,mBAAmB,EACnB,mBAAmB,EACnB,kCAAkC,EAClC,cAAc;IAChB,UAAU,EAAE,OAAO,CAAC;IACpB,WAAW,EAAE,CAAC,UAAU,EAAE,OAAO,KAAK,IAAI,CAAC;IAC3C,YAAY,EAAE,CAAC,SAAS,EAAE,iBAAiB,GAAG,0BAA0B,KAAK,IAAI,CAAC;IAClF,IAAI,EAAE,iBAAiB,CAAC,MAAM,CAAC,GAAG,0BAA0B,CAAC,MAAM,CAAC,CAAC;IACrE,QAAQ,EAAE,eAAe,CAAC;IAC1B,QAAQ,EAAE,cAAc,CAAC;IACzB,eAAe,EAAE,cAAc,CAAC;IAChC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAC7C,GAAG,CAAC,EAAE,cAAc,CAAC;CACtB;AAED,MAAM,WAAW,mBAAmB;IAClC,iBAAiB,EAAE,iBAAiB,GAAG,0BAA0B,CAAC;IAClE,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,CAAC;CAC9D;AAED,MAAM,WAAW,sBAAsB;IACrC,YAAY,EAAE,mBAAmB,CAAC;IAClC,QAAQ,CAAC,EAAE,SAAS,CAAC;CACtB;AAED,eAAO,MAAM,gBAAgB,oEAAsE,CAAC;AAEpG,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,CAAC,KAM/E;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,sBAAsB,2CA0B9D"}
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
// See the License for the specific language governing permissions and
|
|
12
12
|
// limitations under the License.
|
|
13
13
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
14
|
-
import { createStore
|
|
14
|
+
import { createStore } from 'zustand';
|
|
15
|
+
import { useStoreWithEqualityFn } from 'zustand/traditional';
|
|
15
16
|
import { devtools } from 'zustand/middleware';
|
|
16
17
|
import { immer } from 'zustand/middleware/immer';
|
|
17
18
|
import { shallow } from 'zustand/shallow';
|
|
@@ -36,7 +37,7 @@ export function useDashboardStore(selector) {
|
|
|
36
37
|
if (store === undefined) {
|
|
37
38
|
throw new Error('No DashboardContext found. Did you forget a Provider?');
|
|
38
39
|
}
|
|
39
|
-
return
|
|
40
|
+
return useStoreWithEqualityFn(store, selector, shallow);
|
|
40
41
|
}
|
|
41
42
|
export function DashboardProvider(props) {
|
|
42
43
|
const createDashboardStore = useCallback(initStore, [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/context/DashboardProvider/DashboardProvider.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { createStore, useStore } from 'zustand';\nimport type { StoreApi } from 'zustand';\nimport { devtools } from 'zustand/middleware';\nimport { immer } from 'zustand/middleware/immer';\nimport { shallow } from 'zustand/shallow';\nimport { createContext, ReactNode, useCallback, useContext, useEffect, useState } from 'react';\nimport {\n DashboardResource,\n Display,\n ProjectMetadata,\n DurationString,\n DEFAULT_REFRESH_INTERVAL,\n DatasourceSpec,\n EphemeralDashboardResource,\n} from '@perses-dev/core';\nimport { usePlugin, usePluginRegistry } from '@perses-dev/plugin-system';\nimport { createPanelGroupEditorSlice, PanelGroupEditorSlice } from './panel-group-editor-slice';\nimport { convertLayoutsToPanelGroups, createPanelGroupSlice, PanelGroupSlice } from './panel-group-slice';\nimport { createPanelEditorSlice, PanelEditorSlice } from './panel-editor-slice';\nimport { createPanelSlice, PanelSlice } from './panel-slice';\nimport { createDeletePanelGroupSlice, DeletePanelGroupSlice } from './delete-panel-group-slice';\nimport { createDeletePanelSlice, DeletePanelSlice } from './delete-panel-slice';\nimport { createDiscardChangesDialogSlice, DiscardChangesConfirmationDialogSlice } from './discard-changes-dialog-slice';\nimport { createSaveChangesDialogSlice, SaveChangesConfirmationDialogSlice } from './save-changes-dialog-slice';\nimport { createDuplicatePanelSlice, DuplicatePanelSlice } from './duplicate-panel-slice';\nimport { createEditJsonDialogSlice, EditJsonDialogSlice } from './edit-json-dialog-slice';\nimport { createPanelDefinition } from './common';\nimport { createViewPanelSlice, ViewPanelSlice } from './view-panel-slice';\n\nexport interface DashboardStoreState\n extends PanelGroupSlice,\n PanelSlice,\n PanelGroupEditorSlice,\n DeletePanelGroupSlice,\n PanelEditorSlice,\n DeletePanelSlice,\n DiscardChangesConfirmationDialogSlice,\n DuplicatePanelSlice,\n EditJsonDialogSlice,\n SaveChangesConfirmationDialogSlice,\n ViewPanelSlice {\n isEditMode: boolean;\n setEditMode: (isEditMode: boolean) => void;\n setDashboard: (dashboard: DashboardResource | EphemeralDashboardResource) => void;\n kind: DashboardResource['kind'] | EphemeralDashboardResource['kind'];\n metadata: ProjectMetadata;\n duration: DurationString;\n refreshInterval: DurationString;\n display?: Display;\n datasources?: Record<string, DatasourceSpec>;\n ttl?: DurationString;\n}\n\nexport interface DashboardStoreProps {\n dashboardResource: DashboardResource | EphemeralDashboardResource;\n isEditMode?: boolean;\n viewPanelRef?: string;\n setViewPanelRef?: (viewPanelRef: string | undefined) => void;\n}\n\nexport interface DashboardProviderProps {\n initialState: DashboardStoreProps;\n children?: ReactNode;\n}\n\nexport const DashboardContext = createContext<StoreApi<DashboardStoreState> | undefined>(undefined);\n\nexport function useDashboardStore<T>(selector: (state: DashboardStoreState) => T) {\n const store = useContext(DashboardContext);\n if (store === undefined) {\n throw new Error('No DashboardContext found. Did you forget a Provider?');\n }\n return useStore(store, selector, shallow);\n}\n\nexport function DashboardProvider(props: DashboardProviderProps) {\n const createDashboardStore = useCallback(initStore, [props]);\n\n // load plugin to retrieve initial spec if default panel kind is defined\n const { defaultPluginKinds } = usePluginRegistry();\n const defaultPanelKind = defaultPluginKinds?.['Panel'] ?? '';\n const { data: plugin } = usePlugin('Panel', defaultPanelKind);\n\n const [store] = useState(createDashboardStore(props)); // prevent calling createDashboardStore every time it rerenders\n\n useEffect(() => {\n if (plugin === undefined) return;\n const defaultPanelSpec = plugin.createInitialOptions();\n // set default panel kind, spec, and queries for add panel editor\n store.setState({\n initialValues: {\n panelDefinition: createPanelDefinition(defaultPanelKind, defaultPanelSpec),\n },\n });\n }, [plugin, store, defaultPanelKind]);\n\n return (\n <DashboardContext.Provider value={store as StoreApi<DashboardStoreState>}>\n {props.children}\n </DashboardContext.Provider>\n );\n}\n\nfunction initStore(props: DashboardProviderProps) {\n const {\n initialState: { dashboardResource, isEditMode, viewPanelRef, setViewPanelRef },\n } = props;\n\n const {\n kind,\n metadata,\n spec: { display, duration, refreshInterval = DEFAULT_REFRESH_INTERVAL, datasources },\n } = dashboardResource;\n\n const ttl = 'ttl' in dashboardResource.spec ? dashboardResource.spec.ttl : undefined;\n\n let {\n spec: { layouts, panels },\n } = dashboardResource;\n\n // Set fallbacks in case the frontend is used with a non-Perses backend\n layouts = layouts ?? [];\n panels = panels ?? {};\n\n const store = createStore<DashboardStoreState>()(\n immer(\n devtools((...args) => {\n const [set] = args;\n return {\n /* Groups */\n ...createPanelGroupSlice(layouts)(...args),\n ...createPanelGroupEditorSlice(...args),\n ...createDeletePanelGroupSlice(...args),\n /* Panels */\n ...createPanelSlice(panels)(...args),\n ...createPanelEditorSlice()(...args),\n ...createDeletePanelSlice()(...args),\n ...createDuplicatePanelSlice()(...args),\n ...createViewPanelSlice(viewPanelRef, setViewPanelRef)(...args),\n /* General */\n ...createDiscardChangesDialogSlice(...args),\n ...createEditJsonDialogSlice(...args),\n ...createSaveChangesDialogSlice(...args),\n kind,\n metadata,\n display,\n duration,\n refreshInterval,\n datasources,\n ttl,\n isEditMode: !!isEditMode,\n setEditMode: (isEditMode: boolean) => set({ isEditMode }),\n setDashboard: ({\n kind,\n metadata,\n spec: { display, panels = {}, layouts = [], duration, refreshInterval, datasources = {} },\n }) => {\n set((state) => {\n state.kind = kind;\n state.metadata = metadata;\n state.display = display;\n state.panels = panels;\n const { panelGroups, panelGroupOrder } = convertLayoutsToPanelGroups(layouts);\n state.panelGroups = panelGroups;\n state.panelGroupOrder = panelGroupOrder;\n state.duration = duration;\n state.refreshInterval = refreshInterval ?? DEFAULT_REFRESH_INTERVAL;\n state.datasources = datasources;\n // TODO: add ttl here to e.g allow edition from JSON view, but probably requires quite some refactoring\n });\n },\n };\n })\n )\n );\n\n return store;\n}\n"],"names":["createStore","useStore","devtools","immer","shallow","createContext","useCallback","useContext","useEffect","useState","DEFAULT_REFRESH_INTERVAL","usePlugin","usePluginRegistry","createPanelGroupEditorSlice","convertLayoutsToPanelGroups","createPanelGroupSlice","createPanelEditorSlice","createPanelSlice","createDeletePanelGroupSlice","createDeletePanelSlice","createDiscardChangesDialogSlice","createSaveChangesDialogSlice","createDuplicatePanelSlice","createEditJsonDialogSlice","createPanelDefinition","createViewPanelSlice","DashboardContext","undefined","useDashboardStore","selector","store","Error","DashboardProvider","props","createDashboardStore","initStore","defaultPluginKinds","defaultPanelKind","data","plugin","defaultPanelSpec","createInitialOptions","setState","initialValues","panelDefinition","Provider","value","children","initialState","dashboardResource","isEditMode","viewPanelRef","setViewPanelRef","kind","metadata","spec","display","duration","refreshInterval","datasources","ttl","layouts","panels","args","set","setEditMode","setDashboard","state","panelGroups","panelGroupOrder"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,WAAW,EAAEC,QAAQ,QAAQ,UAAU;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C,GAAG5C,4BAA4B4C,KAAK;YACpC,GAAGzC,+BAA+ByC,KAAK;YACvC,GAAGtC,qBAAqB0B,cAAcC,oBAAoBW,KAAK;YAC/D,WAAW,GACX,GAAG3C,mCAAmC2C,KAAK;YAC3C,GAAGxC,6BAA6BwC,KAAK;YACrC,GAAG1C,gCAAgC0C,KAAK;YACxCV;YACAC;YACAE;YACAC;YACAC;YACAC;YACAC;YACAV,YAAY,CAAC,CAACA;YACde,aAAa,CAACf,aAAwBc,IAAI;oBAAEd;gBAAW;YACvDgB,cAAc,CAAC,EACbb,IAAI,EACJC,QAAQ,EACRC,MAAM,EAAEC,OAAO,EAAEM,SAAS,CAAC,CAAC,EAAED,UAAU,EAAE,EAAEJ,QAAQ,EAAEC,eAAe,EAAEC,cAAc,CAAC,CAAC,EAAE,EAC1F;gBACCK,IAAI,CAACG;oBACHA,MAAMd,IAAI,GAAGA;oBACbc,MAAMb,QAAQ,GAAGA;oBACjBa,MAAMX,OAAO,GAAGA;oBAChBW,MAAML,MAAM,GAAGA;oBACf,MAAM,EAAEM,WAAW,EAAEC,eAAe,EAAE,GAAGvD,4BAA4B+C;oBACrEM,MAAMC,WAAW,GAAGA;oBACpBD,MAAME,eAAe,GAAGA;oBACxBF,MAAMV,QAAQ,GAAGA;oBACjBU,MAAMT,eAAe,GAAGA,4BAAAA,6BAAAA,kBAAmBhD;oBAC3CyD,MAAMR,WAAW,GAAGA;gBACpB,uGAAuG;gBACzG;YACF;QACF;IACF;IAIJ,OAAO7B;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../src/context/DashboardProvider/DashboardProvider.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { createStore } from 'zustand';\nimport { useStoreWithEqualityFn } from 'zustand/traditional';\nimport type { StoreApi } from 'zustand';\nimport { devtools } from 'zustand/middleware';\nimport { immer } from 'zustand/middleware/immer';\nimport { shallow } from 'zustand/shallow';\nimport { createContext, ReactNode, useCallback, useContext, useEffect, useState } from 'react';\nimport {\n DashboardResource,\n Display,\n ProjectMetadata,\n DurationString,\n DEFAULT_REFRESH_INTERVAL,\n DatasourceSpec,\n EphemeralDashboardResource,\n} from '@perses-dev/core';\nimport { usePlugin, usePluginRegistry } from '@perses-dev/plugin-system';\nimport { createPanelGroupEditorSlice, PanelGroupEditorSlice } from './panel-group-editor-slice';\nimport { convertLayoutsToPanelGroups, createPanelGroupSlice, PanelGroupSlice } from './panel-group-slice';\nimport { createPanelEditorSlice, PanelEditorSlice } from './panel-editor-slice';\nimport { createPanelSlice, PanelSlice } from './panel-slice';\nimport { createDeletePanelGroupSlice, DeletePanelGroupSlice } from './delete-panel-group-slice';\nimport { createDeletePanelSlice, DeletePanelSlice } from './delete-panel-slice';\nimport { createDiscardChangesDialogSlice, DiscardChangesConfirmationDialogSlice } from './discard-changes-dialog-slice';\nimport { createSaveChangesDialogSlice, SaveChangesConfirmationDialogSlice } from './save-changes-dialog-slice';\nimport { createDuplicatePanelSlice, DuplicatePanelSlice } from './duplicate-panel-slice';\nimport { createEditJsonDialogSlice, EditJsonDialogSlice } from './edit-json-dialog-slice';\nimport { createPanelDefinition } from './common';\nimport { createViewPanelSlice, ViewPanelSlice } from './view-panel-slice';\n\nexport interface DashboardStoreState\n extends PanelGroupSlice,\n PanelSlice,\n PanelGroupEditorSlice,\n DeletePanelGroupSlice,\n PanelEditorSlice,\n DeletePanelSlice,\n DiscardChangesConfirmationDialogSlice,\n DuplicatePanelSlice,\n EditJsonDialogSlice,\n SaveChangesConfirmationDialogSlice,\n ViewPanelSlice {\n isEditMode: boolean;\n setEditMode: (isEditMode: boolean) => void;\n setDashboard: (dashboard: DashboardResource | EphemeralDashboardResource) => void;\n kind: DashboardResource['kind'] | EphemeralDashboardResource['kind'];\n metadata: ProjectMetadata;\n duration: DurationString;\n refreshInterval: DurationString;\n display?: Display;\n datasources?: Record<string, DatasourceSpec>;\n ttl?: DurationString;\n}\n\nexport interface DashboardStoreProps {\n dashboardResource: DashboardResource | EphemeralDashboardResource;\n isEditMode?: boolean;\n viewPanelRef?: string;\n setViewPanelRef?: (viewPanelRef: string | undefined) => void;\n}\n\nexport interface DashboardProviderProps {\n initialState: DashboardStoreProps;\n children?: ReactNode;\n}\n\nexport const DashboardContext = createContext<StoreApi<DashboardStoreState> | undefined>(undefined);\n\nexport function useDashboardStore<T>(selector: (state: DashboardStoreState) => T) {\n const store = useContext(DashboardContext);\n if (store === undefined) {\n throw new Error('No DashboardContext found. Did you forget a Provider?');\n }\n return useStoreWithEqualityFn(store, selector, shallow);\n}\n\nexport function DashboardProvider(props: DashboardProviderProps) {\n const createDashboardStore = useCallback(initStore, [props]);\n\n // load plugin to retrieve initial spec if default panel kind is defined\n const { defaultPluginKinds } = usePluginRegistry();\n const defaultPanelKind = defaultPluginKinds?.['Panel'] ?? '';\n const { data: plugin } = usePlugin('Panel', defaultPanelKind);\n\n const [store] = useState(createDashboardStore(props)); // prevent calling createDashboardStore every time it rerenders\n\n useEffect(() => {\n if (plugin === undefined) return;\n const defaultPanelSpec = plugin.createInitialOptions();\n // set default panel kind, spec, and queries for add panel editor\n store.setState({\n initialValues: {\n panelDefinition: createPanelDefinition(defaultPanelKind, defaultPanelSpec),\n },\n });\n }, [plugin, store, defaultPanelKind]);\n\n return (\n <DashboardContext.Provider value={store as StoreApi<DashboardStoreState>}>\n {props.children}\n </DashboardContext.Provider>\n );\n}\n\nfunction initStore(props: DashboardProviderProps) {\n const {\n initialState: { dashboardResource, isEditMode, viewPanelRef, setViewPanelRef },\n } = props;\n\n const {\n kind,\n metadata,\n spec: { display, duration, refreshInterval = DEFAULT_REFRESH_INTERVAL, datasources },\n } = dashboardResource;\n\n const ttl = 'ttl' in dashboardResource.spec ? dashboardResource.spec.ttl : undefined;\n\n let {\n spec: { layouts, panels },\n } = dashboardResource;\n\n // Set fallbacks in case the frontend is used with a non-Perses backend\n layouts = layouts ?? [];\n panels = panels ?? {};\n\n const store = createStore<DashboardStoreState>()(\n immer(\n devtools((...args) => {\n const [set] = args;\n return {\n /* Groups */\n ...createPanelGroupSlice(layouts)(...args),\n ...createPanelGroupEditorSlice(...args),\n ...createDeletePanelGroupSlice(...args),\n /* Panels */\n ...createPanelSlice(panels)(...args),\n ...createPanelEditorSlice()(...args),\n ...createDeletePanelSlice()(...args),\n ...createDuplicatePanelSlice()(...args),\n ...createViewPanelSlice(viewPanelRef, setViewPanelRef)(...args),\n /* General */\n ...createDiscardChangesDialogSlice(...args),\n ...createEditJsonDialogSlice(...args),\n ...createSaveChangesDialogSlice(...args),\n kind,\n metadata,\n display,\n duration,\n refreshInterval,\n datasources,\n ttl,\n isEditMode: !!isEditMode,\n setEditMode: (isEditMode: boolean) => set({ isEditMode }),\n setDashboard: ({\n kind,\n metadata,\n spec: { display, panels = {}, layouts = [], duration, refreshInterval, datasources = {} },\n }) => {\n set((state) => {\n state.kind = kind;\n state.metadata = metadata;\n state.display = display;\n state.panels = panels;\n const { panelGroups, panelGroupOrder } = convertLayoutsToPanelGroups(layouts);\n state.panelGroups = panelGroups;\n state.panelGroupOrder = panelGroupOrder;\n state.duration = duration;\n state.refreshInterval = refreshInterval ?? DEFAULT_REFRESH_INTERVAL;\n state.datasources = datasources;\n // TODO: add ttl here to e.g allow edition from JSON view, but probably requires quite some refactoring\n });\n },\n };\n })\n )\n );\n\n return store;\n}\n"],"names":["createStore","useStoreWithEqualityFn","devtools","immer","shallow","createContext","useCallback","useContext","useEffect","useState","DEFAULT_REFRESH_INTERVAL","usePlugin","usePluginRegistry","createPanelGroupEditorSlice","convertLayoutsToPanelGroups","createPanelGroupSlice","createPanelEditorSlice","createPanelSlice","createDeletePanelGroupSlice","createDeletePanelSlice","createDiscardChangesDialogSlice","createSaveChangesDialogSlice","createDuplicatePanelSlice","createEditJsonDialogSlice","createPanelDefinition","createViewPanelSlice","DashboardContext","undefined","useDashboardStore","selector","store","Error","DashboardProvider","props","createDashboardStore","initStore","defaultPluginKinds","defaultPanelKind","data","plugin","defaultPanelSpec","createInitialOptions","setState","initialValues","panelDefinition","Provider","value","children","initialState","dashboardResource","isEditMode","viewPanelRef","setViewPanelRef","kind","metadata","spec","display","duration","refreshInterval","datasources","ttl","layouts","panels","args","set","setEditMode","setDashboard","state","panelGroups","panelGroupOrder"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,WAAW,QAAQ,UAAU;AACtC,SAASC,sBAAsB,QAAQ,sBAAsB;AAE7D,SAASC,QAAQ,QAAQ,qBAAqB;AAC9C,SAASC,KAAK,QAAQ,2BAA2B;AACjD,SAASC,OAAO,QAAQ,kBAAkB;AAC1C,SAASC,aAAa,EAAaC,WAAW,EAAEC,UAAU,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAQ;AAC/F,SAKEC,wBAAwB,QAGnB,mBAAmB;AAC1B,SAASC,SAAS,EAAEC,iBAAiB,QAAQ,4BAA4B;AACzE,SAASC,2BAA2B,QAA+B,6BAA6B;AAChG,SAASC,2BAA2B,EAAEC,qBAAqB,QAAyB,sBAAsB;AAC1G,SAASC,sBAAsB,QAA0B,uBAAuB;AAChF,SAASC,gBAAgB,QAAoB,gBAAgB;AAC7D,SAASC,2BAA2B,QAA+B,6BAA6B;AAChG,SAASC,sBAAsB,QAA0B,uBAAuB;AAChF,SAASC,+BAA+B,QAA+C,iCAAiC;AACxH,SAASC,4BAA4B,QAA4C,8BAA8B;AAC/G,S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MAAMX,OAAO,GAAGA;oBAChBW,MAAML,MAAM,GAAGA;oBACf,MAAM,EAAEM,WAAW,EAAEC,eAAe,EAAE,GAAGvD,4BAA4B+C;oBACrEM,MAAMC,WAAW,GAAGA;oBACpBD,MAAME,eAAe,GAAGA;oBACxBF,MAAMV,QAAQ,GAAGA;oBACjBU,MAAMT,eAAe,GAAGA,4BAAAA,6BAAAA,kBAAmBhD;oBAC3CyD,MAAMR,WAAW,GAAGA;gBACpB,uGAAuG;gBACzG;YACF;QACF;IACF;IAIJ,OAAO7B;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TemplateVariableProvider.d.ts","sourceRoot":"","sources":["../../../src/context/TemplateVariableProvider/TemplateVariableProvider.tsx"],"names":[],"mappings":"AAaA,OAAO,EAAiB,SAAS,EAAiC,MAAM,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"TemplateVariableProvider.d.ts","sourceRoot":"","sources":["../../../src/context/TemplateVariableProvider/TemplateVariableProvider.tsx"],"names":[],"mappings":"AAaA,OAAO,EAAiB,SAAS,EAAiC,MAAM,OAAO,CAAC;AAMhF,OAAO,EAEL,gBAAgB,EAChB,aAAa,EACb,qBAAqB,EACrB,cAAc,EAGf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAEL,YAAY,EACZ,aAAa,EACb,kBAAkB,EAGlB,yBAAyB,EAC1B,MAAM,kBAAkB,CAAC;AAK1B,KAAK,qBAAqB,GAAG;IAC3B,mBAAmB,EAAE,kBAAkB,EAAE,CAAC;IAC1C,2BAA2B,EAAE,0BAA0B,EAAE,CAAC;IAC1D,aAAa,EAAE,qBAAqB,CAAC;IACrC,gBAAgB,EAAE,CAAC,YAAY,EAAE,YAAY,EAAE,KAAK,EAAE,aAAa,EAAE,MAAM,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9F,kBAAkB,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,cAAc,EAAE,EAAE,MAAM,C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AC,EACvC,QAAQ,EACR,0BAA+B,EAC/B,2BAAgC,EAChC,gBAAqB,GACtB,EAAE,6BAA6B,2CAQ/B;AAED,wBAAgB,uCAAuC,CAAC,EACtD,QAAQ,EACR,0BAA+B,EAC/B,2BAAgC,EAChC,gBAAqB,GACtB,EAAE,6BAA6B,2CAY/B"}
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
14
14
|
import { createContext, useContext, useMemo, useState } from 'react';
|
|
15
15
|
import { createStore, useStore } from 'zustand';
|
|
16
|
+
import { useStoreWithEqualityFn } from 'zustand/traditional';
|
|
16
17
|
import { immer } from 'zustand/middleware/immer';
|
|
17
18
|
import { devtools } from 'zustand/middleware';
|
|
18
19
|
import produce from 'immer';
|
|
@@ -31,7 +32,7 @@ export function useTemplateVariableStoreCtx() {
|
|
|
31
32
|
}
|
|
32
33
|
export function useTemplateVariableValues(variableNames) {
|
|
33
34
|
const store = useTemplateVariableStoreCtx();
|
|
34
|
-
return
|
|
35
|
+
return useStoreWithEqualityFn(store, (s)=>{
|
|
35
36
|
const vars = {};
|
|
36
37
|
// Collect values of local variables, from the variable state
|
|
37
38
|
const names = variableNames !== null && variableNames !== void 0 ? variableNames : s.variableDefinitions.map((value)=>value.spec.name);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/context/TemplateVariableProvider/TemplateVariableProvider.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { createContext, ReactNode, useContext, useMemo, useState } from 'react';\nimport { createStore, useStore } from 'zustand';\nimport { immer } from 'zustand/middleware/immer';\nimport { devtools } from 'zustand/middleware';\nimport produce from 'immer';\nimport {\n TemplateVariableContext,\n VariableStateMap,\n VariableState,\n VariableStoreStateMap,\n VariableOption,\n BuiltinVariableContext,\n useTimeRange,\n} from '@perses-dev/plugin-system';\nimport {\n DEFAULT_ALL_VALUE as ALL_VALUE,\n VariableName,\n VariableValue,\n VariableDefinition,\n formatDuration,\n intervalToPrometheusDuration,\n BuiltinVariableDefinition,\n} from '@perses-dev/core';\nimport { checkSavedDefaultVariableStatus, findVariableDefinitionByName, mergeVariableDefinitions } from './utils';\nimport { hydrateTemplateVariableStates } from './hydrationUtils';\nimport { getInitalValuesFromQueryParameters, getURLQueryParamName, useVariableQueryParams } from './query-params';\n\ntype TemplateVariableStore = {\n variableDefinitions: VariableDefinition[];\n externalVariableDefinitions: ExternalVariableDefinition[];\n variableState: VariableStoreStateMap;\n setVariableValue: (variableName: VariableName, value: VariableValue, source?: string) => void;\n setVariableOptions: (name: VariableName, options: VariableOption[], source?: string) => void;\n setVariableLoading: (name: VariableName, loading: boolean, source?: string) => void;\n setVariableDefinitions: (definitions: VariableDefinition[]) => void;\n setVariableDefaultValues: () => VariableDefinition[];\n getSavedVariablesStatus: () => { isSavedVariableModified: boolean; modifiedVariableNames: string[] };\n};\n\nconst TemplateVariableStoreContext = createContext<ReturnType<typeof createTemplateVariableSrvStore> | undefined>(\n undefined\n);\nexport function useTemplateVariableStoreCtx() {\n const context = useContext(TemplateVariableStoreContext);\n if (!context) {\n throw new Error('TemplateVariableStoreContext not initialized');\n }\n return context;\n}\n\nexport function useTemplateVariableValues(variableNames?: string[]) {\n const store = useTemplateVariableStoreCtx();\n return useStore(\n store,\n (s) => {\n const vars: VariableStateMap = {};\n\n // Collect values of local variables, from the variable state\n const names = variableNames ?? s.variableDefinitions.map((value) => value.spec.name);\n names.forEach((name) => {\n const varState = s.variableState.get({ name });\n if (!varState || varState.overridden) {\n return;\n }\n vars[name] = varState;\n });\n\n // Collect values of external variables, from the variable state\n s.externalVariableDefinitions.forEach((d) => {\n const source = d.source;\n d.definitions.forEach((value) => {\n const name = value.spec.name;\n const varState = s.variableState.get({ name, source });\n if (!varState || varState.overridden) {\n return;\n }\n vars[name] = varState;\n });\n });\n\n return vars;\n },\n (left, right) => {\n return JSON.stringify(left) === JSON.stringify(right);\n }\n );\n}\n\n/**\n * Get the state and definition of a variable from the Template variables context.\n * @param name name of the variable\n * @param source if given, it searches in the external variables\n */\nexport function useTemplateVariable(name: string, source?: string) {\n const store = useTemplateVariableStoreCtx();\n return useStore(store, (s) => {\n const state = s.variableState.get({ name, source });\n const definitions = source\n ? s.externalVariableDefinitions.find((v) => v.source === source)?.definitions\n : s.variableDefinitions;\n const definition = (definitions || []).find((v) => v.spec.name === name);\n\n return { state, definition };\n });\n}\n\nexport function useTemplateVariableActions() {\n const store = useTemplateVariableStoreCtx();\n return useStore(store, (s) => {\n return {\n setVariableValue: s.setVariableValue,\n setVariableLoading: s.setVariableLoading,\n setVariableOptions: s.setVariableOptions,\n setVariableDefinitions: s.setVariableDefinitions,\n setVariableDefaultValues: s.setVariableDefaultValues,\n getSavedVariablesStatus: s.getSavedVariablesStatus,\n };\n });\n}\n\nexport function useTemplateVariableDefinitions() {\n const store = useTemplateVariableStoreCtx();\n return useStore(store, (s) => s.variableDefinitions);\n}\n\nexport function useTemplateExternalVariableDefinitions() {\n const store = useTemplateVariableStoreCtx();\n return useStore(store, (s) => s.externalVariableDefinitions);\n}\n\nexport function useTemplateVariableStore() {\n const store = useTemplateVariableStoreCtx();\n return useStore(store);\n}\n\ninterface PluginProviderProps {\n children: ReactNode;\n builtinVariables?: BuiltinVariableDefinition[];\n}\n\nfunction PluginProvider({ children, builtinVariables }: PluginProviderProps) {\n const originalValues = useTemplateVariableValues();\n const definitions = useTemplateVariableDefinitions();\n const externalDefinitions = useTemplateExternalVariableDefinitions();\n const { absoluteTimeRange } = useTimeRange();\n\n const values = useMemo(() => {\n const contextValues: VariableStateMap = {};\n\n // This will loop through all the current variables values\n // and update any variables that have ALL_VALUE as their current value\n // to include all options.\n Object.keys(originalValues).forEach((name) => {\n const v = { ...originalValues[name] } as VariableState;\n\n if (v.value === ALL_VALUE) {\n const definition = findVariableDefinitionByName(name, definitions, externalDefinitions);\n // If the variable is a list variable and has a custom all value, then use that value instead\n if (definition?.kind === 'ListVariable' && definition.spec.customAllValue) {\n v.value = definition.spec.customAllValue;\n } else {\n v.value = v.options?.map((o: { value: string }) => o.value) ?? null;\n }\n }\n contextValues[name] = v;\n });\n return contextValues;\n }, [originalValues, definitions, externalDefinitions]);\n\n const allBuiltinVariables: BuiltinVariableDefinition[] = useMemo(() => {\n const result: BuiltinVariableDefinition[] = [\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__from',\n value: () => absoluteTimeRange.start.valueOf().toString(),\n source: 'Dashboard',\n display: {\n name: '__from',\n description: 'Start time of the current time range in unix millisecond epoch',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__to',\n value: () => absoluteTimeRange.end.valueOf().toString(),\n source: 'Dashboard',\n display: {\n name: '__to',\n description: 'End time of the current time range in unix millisecond epoch',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__range',\n value: () => formatDuration(intervalToPrometheusDuration(absoluteTimeRange)),\n source: 'Dashboard',\n display: {\n name: '__range',\n description: 'The range for the current dashboard in human readable format',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__range_s',\n value: () => ((absoluteTimeRange.end.valueOf() - absoluteTimeRange.start.valueOf()) / 1000).toString(),\n source: 'Dashboard',\n display: {\n name: '__range_s',\n description: 'The range for the current dashboard in second',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__range_ms',\n value: () => (absoluteTimeRange.end.valueOf() - absoluteTimeRange.start.valueOf()).toString(),\n source: 'Dashboard',\n display: {\n name: '__range_ms',\n description: 'The range for the current dashboard in millisecond',\n hidden: true,\n },\n },\n },\n ];\n builtinVariables?.forEach((def) => result.push(def));\n return result;\n }, [absoluteTimeRange, builtinVariables]);\n\n return (\n <BuiltinVariableContext.Provider value={{ variables: allBuiltinVariables }}>\n <TemplateVariableContext.Provider value={{ state: values }}>{children}</TemplateVariableContext.Provider>\n </BuiltinVariableContext.Provider>\n );\n}\n\ninterface TemplateVariableSrvArgs {\n initialVariableDefinitions?: VariableDefinition[];\n externalVariableDefinitions?: ExternalVariableDefinition[];\n queryParams?: ReturnType<typeof useVariableQueryParams>;\n}\n\nfunction createTemplateVariableSrvStore({\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n queryParams,\n}: TemplateVariableSrvArgs) {\n const initialParams = getInitalValuesFromQueryParameters(queryParams ? queryParams[0] : {});\n const store = createStore<TemplateVariableStore>()(\n devtools(\n immer((set, get) => ({\n variableState: hydrateTemplateVariableStates(\n initialVariableDefinitions,\n initialParams,\n externalVariableDefinitions\n ),\n variableDefinitions: initialVariableDefinitions,\n externalVariableDefinitions: externalVariableDefinitions,\n setVariableDefinitions(definitions: VariableDefinition[]) {\n set(\n (state) => {\n state.variableDefinitions = definitions;\n state.variableState = hydrateTemplateVariableStates(\n definitions,\n initialParams,\n externalVariableDefinitions\n );\n },\n false,\n '[Variables] setVariableDefinitions' // Used for action name in Redux devtools\n );\n },\n setVariableOptions(name, options, source?: string) {\n set(\n (state) => {\n const varState = state.variableState.get({ name, source });\n if (!varState) {\n return;\n }\n varState.options = options;\n },\n false,\n '[Variables] setVariableOptions'\n );\n },\n setVariableLoading(name, loading, source?: string) {\n set(\n (state) => {\n const varState = state.variableState.get({ name, source });\n if (!varState) {\n return;\n }\n varState.loading = loading;\n },\n false,\n '[Variables] setVariableLoading'\n );\n },\n setVariableValue: (name, value, source?: string) =>\n set(\n (state) => {\n let val = value;\n const varState = state.variableState.get({ name, source });\n if (!varState) {\n return;\n }\n\n // Make sure there is only one all value\n if (Array.isArray(val) && val.includes(ALL_VALUE)) {\n if (val.at(-1) === ALL_VALUE) {\n val = ALL_VALUE;\n } else {\n val = val.filter((v) => v !== ALL_VALUE);\n }\n }\n if (queryParams) {\n const setQueryParams = queryParams[1];\n setQueryParams({ [getURLQueryParamName(name)]: val });\n }\n varState.value = val;\n },\n false,\n '[Variables] setVariableValue'\n ),\n setVariableDefaultValues: () => {\n const variableDefinitions = get().variableDefinitions;\n const variableState = get().variableState;\n const updatedVariables = produce(variableDefinitions, (draft) => {\n draft.forEach((variable, index) => {\n const name = variable.spec.name;\n if (variable.kind === 'ListVariable') {\n const currentVariable = variableState.get({ name });\n if (currentVariable?.value !== undefined) {\n draft[index] = {\n kind: 'ListVariable',\n spec: produce(variable.spec, (specDraft) => {\n specDraft.defaultValue = currentVariable.value;\n }),\n };\n }\n } else if (variable.kind === 'TextVariable') {\n const currentVariable = variableState.get({ name });\n const currentVariableValue = typeof currentVariable?.value === 'string' ? currentVariable.value : '';\n if (currentVariable?.value !== undefined) {\n draft[index] = {\n kind: 'TextVariable',\n spec: produce(variable.spec, (specDraft) => {\n specDraft.value = currentVariableValue;\n }),\n };\n }\n }\n });\n });\n set(\n (state) => {\n state.variableDefinitions = updatedVariables;\n },\n false,\n '[Variables] setVariableDefaultValues'\n );\n return updatedVariables;\n },\n getSavedVariablesStatus: () => {\n return checkSavedDefaultVariableStatus(get().variableDefinitions, get().variableState);\n },\n }))\n )\n );\n\n return store;\n}\n\nexport type ExternalVariableDefinition = {\n source: string;\n tooltip?: {\n title?: string;\n description?: string;\n };\n editLink?: string;\n definitions: VariableDefinition[];\n};\n\nexport interface TemplateVariableProviderProps {\n children: ReactNode;\n initialVariableDefinitions?: VariableDefinition[];\n /**\n * The external variables allow you to give to the provider some additional variables, not defined in the dashboard and static.\n * It means that you won´t be able to update them from the dashboard itself, but you will see them appear and will be able\n * to modify their runtime value as any other variable.\n * If one of the external variable has the same name as a local one, it will be marked as overridden.\n * You can define one list of variable definition by source and as many source as you want.\n * The order of the sources is important as first one will take precedence on the following ones, in case they have same names.\n */\n externalVariableDefinitions?: ExternalVariableDefinition[];\n builtinVariables?: BuiltinVariableDefinition[];\n}\n\nexport function TemplateVariableProvider({\n children,\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n builtinVariables = [],\n}: TemplateVariableProviderProps) {\n const [store] = useState(createTemplateVariableSrvStore({ initialVariableDefinitions, externalVariableDefinitions }));\n\n return (\n <TemplateVariableStoreContext.Provider value={store}>\n <PluginProvider builtinVariables={builtinVariables}>{children}</PluginProvider>\n </TemplateVariableStoreContext.Provider>\n );\n}\n\nexport function TemplateVariableProviderWithQueryParams({\n children,\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n builtinVariables = [],\n}: TemplateVariableProviderProps) {\n const allVariableDefs = mergeVariableDefinitions(initialVariableDefinitions, externalVariableDefinitions);\n const queryParams = useVariableQueryParams(allVariableDefs);\n const [store] = useState(\n createTemplateVariableSrvStore({ initialVariableDefinitions, externalVariableDefinitions, queryParams })\n );\n\n return (\n <TemplateVariableStoreContext.Provider value={store}>\n <PluginProvider builtinVariables={builtinVariables}>{children}</PluginProvider>\n </TemplateVariableStoreContext.Provider>\n );\n}\n"],"names":["createContext","useContext","useMemo","useState","createStore","useStore","immer","devtools","produce","TemplateVariableContext","BuiltinVariableContext","useTimeRange","DEFAULT_ALL_VALUE","ALL_VALUE","formatDuration","intervalToPrometheusDuration","checkSavedDefaultVariableStatus","findVariableDefinitionByName","mergeVariableDefinitions","hydrateTemplateVariableStates","getInitalValuesFromQueryParameters","getURLQueryParamName","useVariableQueryParams","TemplateVariableStoreContext","undefined","useTemplateVariableStoreCtx","context","Error","useTemplateVariableValues","variableNames","store","s","vars","names","variableDefinitions","map","value","spec","name","forEach","varState","variableState","get","overridden","externalVariableDefinitions","d","source","definitions","left","right","JSON","stringify","useTemplateVariable","state","find","v","definition","useTemplateVariableActions","setVariableValue","setVariableLoading","setVariableOptions","setVariableDefinitions","setVariableDefaultValues","getSavedVariablesStatus","useTemplateVariableDefinitions","useTemplateExternalVariableDefinitions","useTemplateVariableStore","PluginProvider","children","builtinVariables","originalValues","externalDefinitions","absoluteTimeRange","values","contextValues","Object","keys","kind","customAllValue","options","o","allBuiltinVariables","result","start","valueOf","toString","display","description","hidden","end","def","push","Provider","variables","createTemplateVariableSrvStore","initialVariableDefinitions","queryParams","initialParams","set","loading","val","Array","isArray","includes","at","filter","setQueryParams","updatedVariables","draft","variable","index","currentVariable","specDraft","defaultValue","currentVariableValue","TemplateVariableProvider","TemplateVariableProviderWithQueryParams","allVariableDefs"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,aAAa,EAAaC,UAAU,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAQ;AAChF,SAASC,WAAW,EAAEC,QAAQ,QAAQ,UAAU;AAChD,SAASC,KAAK,QAAQ,2BAA2B;AACjD,SAASC,QAAQ,QAAQ,qBAAqB;AAC9C,OAAOC,aAAa,QAAQ;AAC5B,SACEC,uBAAuB,EAKvBC,sBAAsB,EACtBC,YAAY,QACP,4BAA4B;AACnC,SACEC,qBAAqBC,SAAS,EAI9BC,cAAc,EACdC,4BAA4B,QAEvB,mBAAmB;AAC1B,SAASC,+BAA+B,EAAEC,4BAA4B,EAAEC,wBAAwB,QAAQ,UAAU;AAClH,SAASC,6BAA6B,QAAQ,mBAAmB;AACjE,SAASC,kCAAkC,EAAEC,oBAAoB,EAAEC,sBAAsB,QAAQ,iBAAiB;AAclH,MAAMC,6CAA+BvB,cACnCwB;AAEF,OAAO,SAASC;IACd,MAAMC,UAAUzB,WAAWsB;IAC3B,IAAI,CAACG,SAAS;QACZ,MAAM,IAAIC,MAAM;IAClB;IACA,OAAOD;AACT;AAEA,OAAO,SAASE,0BAA0BC,aAAwB;IAChE,M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MAAM,GAAG3B,SAAS2F,+BAA+B;QAAEC;QAA4BnD;IAA4B;IAElH,qBACE,KAACrB,6BAA6BqE,QAAQ;QAACxD,OAAON;kBAC5C,cAAA,KAACqC;YAAeE,kBAAkBA;sBAAmBD;;;AAG3D;AAEA,OAAO,SAASgD,wCAAwC,EACtDhD,QAAQ,EACR2B,6BAA6B,EAAE,EAC/BnD,8BAA8B,EAAE,EAChCyB,mBAAmB,EAAE,EACS;IAC9B,MAAMgD,kBAAkBnG,yBAAyB6E,4BAA4BnD;IAC7E,MAAMoD,cAAc1E,uBAAuB+F;IAC3C,MAAM,CAACvF,MAAM,GAAG3B,SACd2F,+BAA+B;QAAEC;QAA4BnD;QAA6BoD;IAAY;IAGxG,qBACE,KAACzE,6BAA6BqE,QAAQ;QAACxD,OAAON;kBAC5C,cAAA,KAACqC;YAAeE,kBAAkBA;sBAAmBD;;;AAG3D"}
|
|
1
|
+
{"version":3,"sources":["../../../src/context/TemplateVariableProvider/TemplateVariableProvider.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { createContext, ReactNode, useContext, useMemo, useState } from 'react';\nimport { createStore, useStore } from 'zustand';\nimport { useStoreWithEqualityFn } from 'zustand/traditional';\nimport { immer } from 'zustand/middleware/immer';\nimport { devtools } from 'zustand/middleware';\nimport produce from 'immer';\nimport {\n TemplateVariableContext,\n VariableStateMap,\n VariableState,\n VariableStoreStateMap,\n VariableOption,\n BuiltinVariableContext,\n useTimeRange,\n} from '@perses-dev/plugin-system';\nimport {\n DEFAULT_ALL_VALUE as ALL_VALUE,\n VariableName,\n VariableValue,\n VariableDefinition,\n formatDuration,\n intervalToPrometheusDuration,\n BuiltinVariableDefinition,\n} from '@perses-dev/core';\nimport { checkSavedDefaultVariableStatus, findVariableDefinitionByName, mergeVariableDefinitions } from './utils';\nimport { hydrateTemplateVariableStates } from './hydrationUtils';\nimport { getInitalValuesFromQueryParameters, getURLQueryParamName, useVariableQueryParams } from './query-params';\n\ntype TemplateVariableStore = {\n variableDefinitions: VariableDefinition[];\n externalVariableDefinitions: ExternalVariableDefinition[];\n variableState: VariableStoreStateMap;\n setVariableValue: (variableName: VariableName, value: VariableValue, source?: string) => void;\n setVariableOptions: (name: VariableName, options: VariableOption[], source?: string) => void;\n setVariableLoading: (name: VariableName, loading: boolean, source?: string) => void;\n setVariableDefinitions: (definitions: VariableDefinition[]) => void;\n setVariableDefaultValues: () => VariableDefinition[];\n getSavedVariablesStatus: () => { isSavedVariableModified: boolean; modifiedVariableNames: string[] };\n};\n\nconst TemplateVariableStoreContext = createContext<ReturnType<typeof createTemplateVariableSrvStore> | undefined>(\n undefined\n);\nexport function useTemplateVariableStoreCtx() {\n const context = useContext(TemplateVariableStoreContext);\n if (!context) {\n throw new Error('TemplateVariableStoreContext not initialized');\n }\n return context;\n}\n\nexport function useTemplateVariableValues(variableNames?: string[]) {\n const store = useTemplateVariableStoreCtx();\n return useStoreWithEqualityFn(\n store,\n (s) => {\n const vars: VariableStateMap = {};\n\n // Collect values of local variables, from the variable state\n const names = variableNames ?? s.variableDefinitions.map((value) => value.spec.name);\n names.forEach((name) => {\n const varState = s.variableState.get({ name });\n if (!varState || varState.overridden) {\n return;\n }\n vars[name] = varState;\n });\n\n // Collect values of external variables, from the variable state\n s.externalVariableDefinitions.forEach((d) => {\n const source = d.source;\n d.definitions.forEach((value) => {\n const name = value.spec.name;\n const varState = s.variableState.get({ name, source });\n if (!varState || varState.overridden) {\n return;\n }\n vars[name] = varState;\n });\n });\n\n return vars;\n },\n (left, right) => {\n return JSON.stringify(left) === JSON.stringify(right);\n }\n );\n}\n\n/**\n * Get the state and definition of a variable from the Template variables context.\n * @param name name of the variable\n * @param source if given, it searches in the external variables\n */\nexport function useTemplateVariable(name: string, source?: string) {\n const store = useTemplateVariableStoreCtx();\n return useStore(store, (s) => {\n const state = s.variableState.get({ name, source });\n const definitions = source\n ? s.externalVariableDefinitions.find((v) => v.source === source)?.definitions\n : s.variableDefinitions;\n const definition = (definitions || []).find((v) => v.spec.name === name);\n\n return { state, definition };\n });\n}\n\nexport function useTemplateVariableActions() {\n const store = useTemplateVariableStoreCtx();\n return useStore(store, (s) => {\n return {\n setVariableValue: s.setVariableValue,\n setVariableLoading: s.setVariableLoading,\n setVariableOptions: s.setVariableOptions,\n setVariableDefinitions: s.setVariableDefinitions,\n setVariableDefaultValues: s.setVariableDefaultValues,\n getSavedVariablesStatus: s.getSavedVariablesStatus,\n };\n });\n}\n\nexport function useTemplateVariableDefinitions() {\n const store = useTemplateVariableStoreCtx();\n return useStore(store, (s) => s.variableDefinitions);\n}\n\nexport function useTemplateExternalVariableDefinitions() {\n const store = useTemplateVariableStoreCtx();\n return useStore(store, (s) => s.externalVariableDefinitions);\n}\n\nexport function useTemplateVariableStore() {\n const store = useTemplateVariableStoreCtx();\n return useStore(store);\n}\n\ninterface PluginProviderProps {\n children: ReactNode;\n builtinVariables?: BuiltinVariableDefinition[];\n}\n\nfunction PluginProvider({ children, builtinVariables }: PluginProviderProps) {\n const originalValues = useTemplateVariableValues();\n const definitions = useTemplateVariableDefinitions();\n const externalDefinitions = useTemplateExternalVariableDefinitions();\n const { absoluteTimeRange } = useTimeRange();\n\n const values = useMemo(() => {\n const contextValues: VariableStateMap = {};\n\n // This will loop through all the current variables values\n // and update any variables that have ALL_VALUE as their current value\n // to include all options.\n Object.keys(originalValues).forEach((name) => {\n const v = { ...originalValues[name] } as VariableState;\n\n if (v.value === ALL_VALUE) {\n const definition = findVariableDefinitionByName(name, definitions, externalDefinitions);\n // If the variable is a list variable and has a custom all value, then use that value instead\n if (definition?.kind === 'ListVariable' && definition.spec.customAllValue) {\n v.value = definition.spec.customAllValue;\n } else {\n v.value = v.options?.map((o: { value: string }) => o.value) ?? null;\n }\n }\n contextValues[name] = v;\n });\n return contextValues;\n }, [originalValues, definitions, externalDefinitions]);\n\n const allBuiltinVariables: BuiltinVariableDefinition[] = useMemo(() => {\n const result: BuiltinVariableDefinition[] = [\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__from',\n value: () => absoluteTimeRange.start.valueOf().toString(),\n source: 'Dashboard',\n display: {\n name: '__from',\n description: 'Start time of the current time range in unix millisecond epoch',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__to',\n value: () => absoluteTimeRange.end.valueOf().toString(),\n source: 'Dashboard',\n display: {\n name: '__to',\n description: 'End time of the current time range in unix millisecond epoch',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__range',\n value: () => formatDuration(intervalToPrometheusDuration(absoluteTimeRange)),\n source: 'Dashboard',\n display: {\n name: '__range',\n description: 'The range for the current dashboard in human readable format',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__range_s',\n value: () => ((absoluteTimeRange.end.valueOf() - absoluteTimeRange.start.valueOf()) / 1000).toString(),\n source: 'Dashboard',\n display: {\n name: '__range_s',\n description: 'The range for the current dashboard in second',\n hidden: true,\n },\n },\n },\n {\n kind: 'BuiltinVariable',\n spec: {\n name: '__range_ms',\n value: () => (absoluteTimeRange.end.valueOf() - absoluteTimeRange.start.valueOf()).toString(),\n source: 'Dashboard',\n display: {\n name: '__range_ms',\n description: 'The range for the current dashboard in millisecond',\n hidden: true,\n },\n },\n },\n ];\n builtinVariables?.forEach((def) => result.push(def));\n return result;\n }, [absoluteTimeRange, builtinVariables]);\n\n return (\n <BuiltinVariableContext.Provider value={{ variables: allBuiltinVariables }}>\n <TemplateVariableContext.Provider value={{ state: values }}>{children}</TemplateVariableContext.Provider>\n </BuiltinVariableContext.Provider>\n );\n}\n\ninterface TemplateVariableSrvArgs {\n initialVariableDefinitions?: VariableDefinition[];\n externalVariableDefinitions?: ExternalVariableDefinition[];\n queryParams?: ReturnType<typeof useVariableQueryParams>;\n}\n\nfunction createTemplateVariableSrvStore({\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n queryParams,\n}: TemplateVariableSrvArgs) {\n const initialParams = getInitalValuesFromQueryParameters(queryParams ? queryParams[0] : {});\n const store = createStore<TemplateVariableStore>()(\n devtools(\n immer((set, get) => ({\n variableState: hydrateTemplateVariableStates(\n initialVariableDefinitions,\n initialParams,\n externalVariableDefinitions\n ),\n variableDefinitions: initialVariableDefinitions,\n externalVariableDefinitions: externalVariableDefinitions,\n setVariableDefinitions(definitions: VariableDefinition[]) {\n set(\n (state) => {\n state.variableDefinitions = definitions;\n state.variableState = hydrateTemplateVariableStates(\n definitions,\n initialParams,\n externalVariableDefinitions\n );\n },\n false,\n '[Variables] setVariableDefinitions' // Used for action name in Redux devtools\n );\n },\n setVariableOptions(name, options, source?: string) {\n set(\n (state) => {\n const varState = state.variableState.get({ name, source });\n if (!varState) {\n return;\n }\n varState.options = options;\n },\n false,\n '[Variables] setVariableOptions'\n );\n },\n setVariableLoading(name, loading, source?: string) {\n set(\n (state) => {\n const varState = state.variableState.get({ name, source });\n if (!varState) {\n return;\n }\n varState.loading = loading;\n },\n false,\n '[Variables] setVariableLoading'\n );\n },\n setVariableValue: (name, value, source?: string) =>\n set(\n (state) => {\n let val = value;\n const varState = state.variableState.get({ name, source });\n if (!varState) {\n return;\n }\n\n // Make sure there is only one all value\n if (Array.isArray(val) && val.includes(ALL_VALUE)) {\n if (val.at(-1) === ALL_VALUE) {\n val = ALL_VALUE;\n } else {\n val = val.filter((v) => v !== ALL_VALUE);\n }\n }\n if (queryParams) {\n const setQueryParams = queryParams[1];\n setQueryParams({ [getURLQueryParamName(name)]: val });\n }\n varState.value = val;\n },\n false,\n '[Variables] setVariableValue'\n ),\n setVariableDefaultValues: () => {\n const variableDefinitions = get().variableDefinitions;\n const variableState = get().variableState;\n const updatedVariables = produce(variableDefinitions, (draft) => {\n draft.forEach((variable, index) => {\n const name = variable.spec.name;\n if (variable.kind === 'ListVariable') {\n const currentVariable = variableState.get({ name });\n if (currentVariable?.value !== undefined) {\n draft[index] = {\n kind: 'ListVariable',\n spec: produce(variable.spec, (specDraft) => {\n specDraft.defaultValue = currentVariable.value;\n }),\n };\n }\n } else if (variable.kind === 'TextVariable') {\n const currentVariable = variableState.get({ name });\n const currentVariableValue = typeof currentVariable?.value === 'string' ? currentVariable.value : '';\n if (currentVariable?.value !== undefined) {\n draft[index] = {\n kind: 'TextVariable',\n spec: produce(variable.spec, (specDraft) => {\n specDraft.value = currentVariableValue;\n }),\n };\n }\n }\n });\n });\n set(\n (state) => {\n state.variableDefinitions = updatedVariables;\n },\n false,\n '[Variables] setVariableDefaultValues'\n );\n return updatedVariables;\n },\n getSavedVariablesStatus: () => {\n return checkSavedDefaultVariableStatus(get().variableDefinitions, get().variableState);\n },\n }))\n )\n );\n\n return store;\n}\n\nexport type ExternalVariableDefinition = {\n source: string;\n tooltip?: {\n title?: string;\n description?: string;\n };\n editLink?: string;\n definitions: VariableDefinition[];\n};\n\nexport interface TemplateVariableProviderProps {\n children: ReactNode;\n initialVariableDefinitions?: VariableDefinition[];\n /**\n * The external variables allow you to give to the provider some additional variables, not defined in the dashboard and static.\n * It means that you won´t be able to update them from the dashboard itself, but you will see them appear and will be able\n * to modify their runtime value as any other variable.\n * If one of the external variable has the same name as a local one, it will be marked as overridden.\n * You can define one list of variable definition by source and as many source as you want.\n * The order of the sources is important as first one will take precedence on the following ones, in case they have same names.\n */\n externalVariableDefinitions?: ExternalVariableDefinition[];\n builtinVariables?: BuiltinVariableDefinition[];\n}\n\nexport function TemplateVariableProvider({\n children,\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n builtinVariables = [],\n}: TemplateVariableProviderProps) {\n const [store] = useState(createTemplateVariableSrvStore({ initialVariableDefinitions, externalVariableDefinitions }));\n\n return (\n <TemplateVariableStoreContext.Provider value={store}>\n <PluginProvider builtinVariables={builtinVariables}>{children}</PluginProvider>\n </TemplateVariableStoreContext.Provider>\n );\n}\n\nexport function TemplateVariableProviderWithQueryParams({\n children,\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n builtinVariables = [],\n}: TemplateVariableProviderProps) {\n const allVariableDefs = mergeVariableDefinitions(initialVariableDefinitions, externalVariableDefinitions);\n const queryParams = useVariableQueryParams(allVariableDefs);\n const [store] = useState(\n createTemplateVariableSrvStore({ initialVariableDefinitions, externalVariableDefinitions, queryParams })\n );\n\n return (\n <TemplateVariableStoreContext.Provider value={store}>\n <PluginProvider builtinVariables={builtinVariables}>{children}</PluginProvider>\n </TemplateVariableStoreContext.Provider>\n );\n}\n"],"names":["createContext","useContext","useMemo","useState","createStore","useStore","useStoreWithEqualityFn","immer","devtools","produce","TemplateVariableContext","BuiltinVariableContext","useTimeRange","DEFAULT_ALL_VALUE","ALL_VALUE","formatDuration","intervalToPrometheusDuration","checkSavedDefaultVariableStatus","findVariableDefinitionByName","mergeVariableDefinitions","hydrateTemplateVariableStates","getInitalValuesFromQueryParameters","getURLQueryParamName","useVariableQueryParams","TemplateVariableStoreContext","undefined","useTemplateVariableStoreCtx","context","Error","useTemplateVariableValues","variableNames","store","s","vars","names","variableDefinitions","map","value","spec","name","forEach","varState","variableState","get","overridden","externalVariableDefinitions","d","source","definitions","left","right","JSON","stringify","useTemplateVariable","state","find","v","definition","useTemplateVariableActions","setVariableValue","setVariableLoading","setVariableOptions","setVariableDefinitions","setVariableDefaultValues","getSavedVariablesStatus","useTemplateVariableDefinitions","useTemplateExternalVariableDefinitions","useTemplateVariableStore","PluginProvider","children","builtinVariables","originalValues","externalDefinitions","absoluteTimeRange","values","contextValues","Object","keys","kind","customAllValue","options","o","allBuiltinVariables","result","start","valueOf","toString","display","description","hidden","end","def","push","Provider","variables","createTemplateVariableSrvStore","initialVariableDefinitions","queryParams","initialParams","set","loading","val","Array","isArray","includes","at","filter","setQueryParams","updatedVariables","draft","variable","index","currentVariable","specDraft","defaultValue","currentVariableValue","TemplateVariableProvider","TemplateVariableProviderWithQueryParams","allVariableDefs"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,aAAa,EAAaC,UAAU,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAQ;AAChF,SAASC,WAAW,EAAEC,QAAQ,QAAQ,UAAU;AAChD,SAASC,sBAAsB,QAAQ,sBAAsB;AAC7D,SAASC,KAAK,QAAQ,2BAA2B;AACjD,SAASC,QAAQ,QAAQ,qBAAqB;AAC9C,OAAOC,aAAa,QAAQ;AAC5B,SACEC,uBAAuB,EAKvBC,sBAAsB,EACtBC,YAAY,QACP,4BAA4B;AACnC,SACEC,qBAAqBC,SAAS,EAI9BC,cAAc,EACdC,4BAA4B,QAEvB,mBAAmB;AAC1B,SAASC,+BAA+B,EAAEC,4BAA4B,EAAEC,wBAAwB,QAAQ,UAAU;AAClH,SAASC,6BAA6B,QAAQ,mBAAmB;AACjE,SAASC,kCAAkC,EAAEC,oBAAoB,EAAEC,sBAAsB,QAAQ,iBAAiB;AAclH,MAAMC,6CAA+BxB,cACnCyB;AAEF,OAAO,SAASC;IACd,MAAMC,UAAU1B,WAAWuB;IAC3B,IAAI,CAACG,SAAS;QACZ,MAAM,IAAIC,MAAM;IAClB;IACA,OAAOD;AACT;AAEA,OAAO,SAASE,0BAA0BC,aAAwB;IAChE,MAAMC,QAAQL;IACd,OAAOpB,uBACLyB,OACA,CAACC;QACC,MAAMC,OAAyB,CAAC;QAEhC,6DAA6D;QAC7D,MAAMC,QAAQJ,0BAAAA,2BAAAA,gBAAiBE,EAAEG,mBAAmB,CAACC,GAAG,CA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G3D;AAEA,OAAO,SAASgD,wCAAwC,EACtDhD,QAAQ,EACR2B,6BAA6B,EAAE,EAC/BnD,8BAA8B,EAAE,EAChCyB,mBAAmB,EAAE,EACS;IAC9B,MAAMgD,kBAAkBnG,yBAAyB6E,4BAA4BnD;IAC7E,MAAMoD,cAAc1E,uBAAuB+F;IAC3C,MAAM,CAACvF,MAAM,GAAG5B,SACd4F,+BAA+B;QAAEC;QAA4BnD;QAA6BoD;IAAY;IAGxG,qBACE,KAACzE,6BAA6BqE,QAAQ;QAACxD,OAAON;kBAC5C,cAAA,KAACqC;YAAeE,kBAAkBA;sBAAmBD;;;AAG3D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/views/ViewDashboard/DashboardApp.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { useState } from 'react';\nimport { Box } from '@mui/material';\nimport { ChartsProvider, ErrorAlert, ErrorBoundary, useChartsTheme } from '@perses-dev/components';\nimport { DashboardResource, EphemeralDashboardResource } from '@perses-dev/core';\nimport { useDatasourceStore } from '@perses-dev/plugin-system';\nimport {\n PanelDrawer,\n Dashboard,\n PanelGroupDialog,\n DeletePanelGroupDialog,\n DashboardDiscardChangesConfirmationDialog,\n DashboardToolbar,\n DeletePanelDialog,\n EmptyDashboardProps,\n EditJsonDialog,\n SaveChangesConfirmationDialog,\n} from '../../components';\nimport { OnSaveDashboard, useDashboard, useDiscardChangesConfirmationDialog, useEditMode } from '../../context';\n\nexport interface DashboardAppProps {\n emptyDashboardProps?: Partial<EmptyDashboardProps>;\n dashboardResource: DashboardResource | EphemeralDashboardResource;\n dashboardTitleComponent?: JSX.Element;\n onSave?: OnSaveDashboard;\n onDiscard?: (entity: DashboardResource) => void;\n initialVariableIsSticky?: boolean;\n isReadonly: boolean;\n isCreating?: boolean;\n}\n\nexport const DashboardApp = (props: DashboardAppProps) => {\n const {\n dashboardResource,\n dashboardTitleComponent,\n emptyDashboardProps,\n onSave,\n onDiscard,\n initialVariableIsSticky,\n isReadonly,\n isCreating,\n } = props;\n\n const chartsTheme = useChartsTheme();\n\n const { isEditMode, setEditMode } = useEditMode();\n const { dashboard, setDashboard } = useDashboard();\n const [originalDashboard, setOriginalDashboard] = useState<\n DashboardResource | EphemeralDashboardResource | undefined\n >(undefined);\n const { setSavedDatasources } = useDatasourceStore();\n\n const { openDiscardChangesConfirmationDialog, closeDiscardChangesConfirmationDialog } =\n useDiscardChangesConfirmationDialog();\n\n const handleDiscardChanges = () => {\n // Reset to the original spec and exit edit mode\n if (originalDashboard) {\n setDashboard(originalDashboard);\n }\n setEditMode(false);\n closeDiscardChangesConfirmationDialog();\n if (onDiscard) {\n onDiscard(dashboard as unknown as DashboardResource);\n }\n };\n\n const onEditButtonClick = () => {\n setEditMode(true);\n setOriginalDashboard(dashboard);\n setSavedDatasources(dashboard.spec.datasources ?? {});\n };\n\n const onCancelButtonClick = () => {\n // check if dashboard has been modified\n if (JSON.stringify(dashboard) === JSON.stringify(originalDashboard)) {\n setEditMode(false);\n } else {\n openDiscardChangesConfirmationDialog({\n onDiscardChanges: () => {\n handleDiscardChanges();\n },\n onCancel: () => {\n closeDiscardChangesConfirmationDialog();\n },\n });\n }\n };\n\n return (\n <Box\n sx={{\n flexGrow: 1,\n overflowX: 'hidden',\n overflowY: 'auto',\n display: 'flex',\n flexDirection: 'column',\n }}\n >\n <DashboardToolbar\n dashboardName={dashboardResource.metadata.name}\n dashboardTitleComponent={dashboardTitleComponent}\n initialVariableIsSticky={initialVariableIsSticky}\n onSave={onSave}\n isReadonly={isReadonly}\n onEditButtonClick={onEditButtonClick}\n onCancelButtonClick={onCancelButtonClick}\n />\n <Box sx={{
|
|
1
|
+
{"version":3,"sources":["../../../src/views/ViewDashboard/DashboardApp.tsx"],"sourcesContent":["// Copyright 2023 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { useState } from 'react';\nimport { Box } from '@mui/material';\nimport { ChartsProvider, ErrorAlert, ErrorBoundary, useChartsTheme } from '@perses-dev/components';\nimport { DashboardResource, EphemeralDashboardResource } from '@perses-dev/core';\nimport { useDatasourceStore } from '@perses-dev/plugin-system';\nimport {\n PanelDrawer,\n Dashboard,\n PanelGroupDialog,\n DeletePanelGroupDialog,\n DashboardDiscardChangesConfirmationDialog,\n DashboardToolbar,\n DeletePanelDialog,\n EmptyDashboardProps,\n EditJsonDialog,\n SaveChangesConfirmationDialog,\n} from '../../components';\nimport { OnSaveDashboard, useDashboard, useDiscardChangesConfirmationDialog, useEditMode } from '../../context';\n\nexport interface DashboardAppProps {\n emptyDashboardProps?: Partial<EmptyDashboardProps>;\n dashboardResource: DashboardResource | EphemeralDashboardResource;\n dashboardTitleComponent?: JSX.Element;\n onSave?: OnSaveDashboard;\n onDiscard?: (entity: DashboardResource) => void;\n initialVariableIsSticky?: boolean;\n isReadonly: boolean;\n isCreating?: boolean;\n}\n\nexport const DashboardApp = (props: DashboardAppProps) => {\n const {\n dashboardResource,\n dashboardTitleComponent,\n emptyDashboardProps,\n onSave,\n onDiscard,\n initialVariableIsSticky,\n isReadonly,\n isCreating,\n } = props;\n\n const chartsTheme = useChartsTheme();\n\n const { isEditMode, setEditMode } = useEditMode();\n const { dashboard, setDashboard } = useDashboard();\n const [originalDashboard, setOriginalDashboard] = useState<\n DashboardResource | EphemeralDashboardResource | undefined\n >(undefined);\n const { setSavedDatasources } = useDatasourceStore();\n\n const { openDiscardChangesConfirmationDialog, closeDiscardChangesConfirmationDialog } =\n useDiscardChangesConfirmationDialog();\n\n const handleDiscardChanges = () => {\n // Reset to the original spec and exit edit mode\n if (originalDashboard) {\n setDashboard(originalDashboard);\n }\n setEditMode(false);\n closeDiscardChangesConfirmationDialog();\n if (onDiscard) {\n onDiscard(dashboard as unknown as DashboardResource);\n }\n };\n\n const onEditButtonClick = () => {\n setEditMode(true);\n setOriginalDashboard(dashboard);\n setSavedDatasources(dashboard.spec.datasources ?? {});\n };\n\n const onCancelButtonClick = () => {\n // check if dashboard has been modified\n if (JSON.stringify(dashboard) === JSON.stringify(originalDashboard)) {\n setEditMode(false);\n } else {\n openDiscardChangesConfirmationDialog({\n onDiscardChanges: () => {\n handleDiscardChanges();\n },\n onCancel: () => {\n closeDiscardChangesConfirmationDialog();\n },\n });\n }\n };\n\n return (\n <Box\n sx={{\n flexGrow: 1,\n overflowX: 'hidden',\n overflowY: 'auto',\n display: 'flex',\n flexDirection: 'column',\n }}\n >\n <DashboardToolbar\n dashboardName={dashboardResource.metadata.name}\n dashboardTitleComponent={dashboardTitleComponent}\n initialVariableIsSticky={initialVariableIsSticky}\n onSave={onSave}\n isReadonly={isReadonly}\n onEditButtonClick={onEditButtonClick}\n onCancelButtonClick={onCancelButtonClick}\n />\n <Box sx={{ paddingTop: 2, paddingX: 2, height: '100%' }}>\n <ErrorBoundary FallbackComponent={ErrorAlert}>\n <Dashboard\n emptyDashboardProps={{\n onEditButtonClick,\n ...emptyDashboardProps,\n }}\n />\n </ErrorBoundary>\n <ChartsProvider chartsTheme={chartsTheme} enablePinning={false}>\n <PanelDrawer />\n </ChartsProvider>\n <PanelGroupDialog />\n <DeletePanelGroupDialog />\n <DeletePanelDialog />\n <DashboardDiscardChangesConfirmationDialog />\n <EditJsonDialog isReadonly={!isEditMode} disableMetadataEdition={!isCreating} />\n <SaveChangesConfirmationDialog />\n </Box>\n </Box>\n );\n};\n"],"names":["useState","Box","ChartsProvider","ErrorAlert","ErrorBoundary","useChartsTheme","useDatasourceStore","PanelDrawer","Dashboard","PanelGroupDialog","DeletePanelGroupDialog","DashboardDiscardChangesConfirmationDialog","DashboardToolbar","DeletePanelDialog","EditJsonDialog","SaveChangesConfirmationDialog","useDashboard","useDiscardChangesConfirmationDialog","useEditMode","DashboardApp","props","dashboardResource","dashboardTitleComponent","emptyDashboardProps","onSave","onDiscard","initialVariableIsSticky","isReadonly","isCreating","chartsTheme","isEditMode","setEditMode","dashboard","setDashboard","originalDashboard","setOriginalDashboard","undefined","setSavedDatasources","openDiscardChangesConfirmationDialog","closeDiscardChangesConfirmationDialog","handleDiscardChanges","onEditButtonClick","spec","datasources","onCancelButtonClick","JSON","stringify","onDiscardChanges","onCancel","sx","flexGrow","overflowX","overflowY","display","flexDirection","dashboardName","metadata","name","paddingTop","paddingX","height","FallbackComponent","enablePinning","disableMetadataEdition"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,QAAQ,QAAQ,QAAQ;AACjC,SAASC,GAAG,QAAQ,gBAAgB;AACpC,SAASC,cAAc,EAAEC,UAAU,EAAEC,aAAa,EAAEC,cAAc,QAAQ,yBAAyB;AAEnG,SAASC,kBAAkB,QAAQ,4BAA4B;AAC/D,SACEC,WAAW,EACXC,SAAS,EACTC,gBAAgB,EAChBC,sBAAsB,EACtBC,yCAAyC,EACzCC,gBAAgB,EAChBC,iBAAiB,EAEjBC,cAAc,EACdC,6BAA6B,QACxB,mBAAmB;AAC1B,SAA0BC,YAAY,EAAEC,mCAAmC,EAAEC,WAAW,QAAQ,gBAAgB;AA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,MAAC3C;gBAAIgD,IAAI;oBAAES,YAAY;oBAAGC,UAAU;oBAAGC,QAAQ;gBAAO;;kCACpD,KAACxD;wBAAcyD,mBAAmB1D;kCAChC,cAAA,KAACK;4BACCe,qBAAqB;gCACnBkB;gCACA,GAAGlB,mBAAmB;4BACxB;;;kCAGJ,KAACrB;wBAAe2B,aAAaA;wBAAaiC,eAAe;kCACvD,cAAA,KAACvD;;kCAEH,KAACE;kCACD,KAACC;kCACD,KAACG;kCACD,KAACF;kCACD,KAACG;wBAAea,YAAY,CAACG;wBAAYiC,wBAAwB,CAACnC;;kCAClE,KAACb;;;;;AAIT,EAAE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@perses-dev/dashboards",
|
|
3
|
-
"version": "0.46.0
|
|
3
|
+
"version": "0.46.0",
|
|
4
4
|
"description": "The dashboards feature in Perses",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"homepage": "https://github.com/perses/perses/blob/main/README.md",
|
|
@@ -29,9 +29,9 @@
|
|
|
29
29
|
"lint:fix": "eslint --fix src --ext .ts,.tsx"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@perses-dev/components": "0.46.0
|
|
33
|
-
"@perses-dev/core": "0.46.0
|
|
34
|
-
"@perses-dev/plugin-system": "0.46.0
|
|
32
|
+
"@perses-dev/components": "0.46.0",
|
|
33
|
+
"@perses-dev/core": "0.46.0",
|
|
34
|
+
"@perses-dev/plugin-system": "0.46.0",
|
|
35
35
|
"@types/react-grid-layout": "^1.3.2",
|
|
36
36
|
"date-fns": "^2.28.0",
|
|
37
37
|
"immer": "^9.0.15",
|
|
@@ -45,8 +45,8 @@
|
|
|
45
45
|
"zustand": "^4.3.3"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
|
-
"@perses-dev/internal-utils": "0.46.0
|
|
49
|
-
"@perses-dev/storybook": "0.46.0
|
|
48
|
+
"@perses-dev/internal-utils": "0.46.0",
|
|
49
|
+
"@perses-dev/storybook": "0.46.0",
|
|
50
50
|
"history": "^5.3.0",
|
|
51
51
|
"intersection-observer": "^0.12.2"
|
|
52
52
|
},
|