@perses-dev/dashboards 0.51.0-beta.0 → 0.51.0-rc.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/GridLayout/GridLayout.js +4 -8
- package/dist/cjs/components/PanelDrawer/PanelEditorForm.js +21 -9
- package/dist/cjs/context/VariableProvider/VariableProvider.js +16 -20
- package/dist/cjs/test/datasource-provider.js +1 -1
- package/dist/components/Datasources/DatasourceEditor.js.map +1 -1
- package/dist/components/DownloadButton/DownloadButton.js.map +1 -1
- package/dist/components/GridLayout/GridContainer.js.map +1 -1
- package/dist/components/GridLayout/GridLayout.d.ts.map +1 -1
- package/dist/components/GridLayout/GridLayout.js +5 -9
- package/dist/components/GridLayout/GridLayout.js.map +1 -1
- package/dist/components/GridLayout/GridTitle.js.map +1 -1
- package/dist/components/Panel/HeaderIconButton.d.ts +1 -1
- package/dist/components/Panel/HeaderIconButton.d.ts.map +1 -1
- package/dist/components/Panel/Panel.js.map +1 -1
- package/dist/components/Panel/PanelHeader.js.map +1 -1
- package/dist/components/Panel/PanelLinks.js.map +1 -1
- package/dist/components/PanelDrawer/PanelEditorForm.d.ts.map +1 -1
- package/dist/components/PanelDrawer/PanelEditorForm.js +21 -9
- package/dist/components/PanelDrawer/PanelEditorForm.js.map +1 -1
- package/dist/components/SaveChangesConfirmationDialog/SaveChangesConfirmationDialog.js.map +1 -1
- package/dist/components/SaveDashboardButton/SaveDashboardButton.js.map +1 -1
- package/dist/components/Variables/BuiltinVariableAccordions.js.map +1 -1
- package/dist/components/Variables/Variable.js.map +1 -1
- package/dist/components/Variables/VariableEditor.js.map +1 -1
- package/dist/components/Variables/VariableList.js.map +1 -1
- package/dist/constants/user-interface-text.js.map +1 -1
- package/dist/context/DashboardProvider/dashboard-provider-api.js.map +1 -1
- package/dist/context/DashboardProvider/delete-panel-slice.js.map +1 -1
- package/dist/context/DashboardProvider/duplicate-panel-slice.js.map +1 -1
- package/dist/context/DashboardProvider/panel-editor-slice.js.map +1 -1
- package/dist/context/DashboardProvider/panel-group-slice.d.ts +1 -1
- package/dist/context/DashboardProvider/panel-group-slice.d.ts.map +1 -1
- package/dist/context/DashboardProvider/panel-group-slice.js.map +1 -1
- package/dist/context/DatasourceStoreProvider.js.map +1 -1
- package/dist/context/VariableProvider/VariableProvider.d.ts.map +1 -1
- package/dist/context/VariableProvider/VariableProvider.js +13 -12
- package/dist/context/VariableProvider/VariableProvider.js.map +1 -1
- package/dist/context/VariableProvider/query-params.js.map +1 -1
- package/dist/context/useDashboard.js.map +1 -1
- package/dist/test/datasource-provider.d.ts +1 -1
- package/dist/test/datasource-provider.d.ts.map +1 -1
- package/dist/test/datasource-provider.js +1 -1
- package/dist/test/datasource-provider.js.map +1 -1
- package/dist/utils/panelUtils.js.map +1 -1
- package/package.json +8 -9
- package/dist/cjs/stories/decorators/WithDashboard.js +0 -41
- package/dist/cjs/stories/decorators/WithDatasourceStore.js +0 -39
- package/dist/cjs/stories/decorators/WithVariables.js +0 -37
- package/dist/cjs/stories/decorators/constants.js +0 -39
- package/dist/cjs/stories/decorators/index.js +0 -33
- package/dist/stories/decorators/WithDashboard.js +0 -33
- package/dist/stories/decorators/WithDashboard.js.map +0 -1
- package/dist/stories/decorators/WithDatasourceStore.js +0 -31
- package/dist/stories/decorators/WithDatasourceStore.js.map +0 -1
- package/dist/stories/decorators/WithVariables.js +0 -29
- package/dist/stories/decorators/WithVariables.js.map +0 -1
- package/dist/stories/decorators/constants.js +0 -31
- package/dist/stories/decorators/constants.js.map +0 -1
- package/dist/stories/decorators/index.js +0 -18
- package/dist/stories/decorators/index.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/context/DatasourceStoreProvider.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 { ReactElement, ReactNode, useCallback, useMemo, useState } from 'react';\nimport {\n DashboardResource,\n DashboardSpec,\n DatasourceResource,\n DatasourceSelector,\n DatasourceSpec,\n GlobalDatasourceResource,\n useEvent,\n EphemeralDashboardResource,\n DatasourceDefinition,\n} from '@perses-dev/core';\nimport {\n DatasourceStoreContext,\n DatasourceStore,\n DatasourceSelectItemGroup,\n usePluginRegistry,\n DatasourceClient,\n DatasourceSelectItem,\n} from '@perses-dev/plugin-system';\n\nexport interface DatasourceStoreProviderProps {\n dashboardResource?: DashboardResource | EphemeralDashboardResource;\n projectName?: string;\n datasourceApi: DatasourceApi;\n children?: ReactNode;\n savedDatasources?: Record<string, DatasourceSpec>;\n onCreate?: (client: DatasourceClient) => DatasourceClient;\n}\n\nexport type BuildDatasourceProxyUrlParams = {\n project?: string;\n dashboard?: string;\n name: string;\n};\n\nexport type BuildDatasourceProxyUrlFunc = (p: BuildDatasourceProxyUrlParams) => string;\n\n/**\n * The external API for fetching datasource resources\n */\nexport interface DatasourceApi {\n buildProxyUrl?: BuildDatasourceProxyUrlFunc;\n getDatasource: (project: string, selector: DatasourceSelector) => Promise<DatasourceResource | undefined>;\n getGlobalDatasource: (selector: DatasourceSelector) => Promise<GlobalDatasourceResource | undefined>;\n listDatasources: (project: string, pluginKind?: string) => Promise<DatasourceResource[]>;\n listGlobalDatasources: (pluginKind?: string) => Promise<GlobalDatasourceResource[]>;\n}\n\n/**\n * A `DatasourceContext` provider that uses an external API to resolve datasource selectors.\n */\nexport function DatasourceStoreProvider(props: DatasourceStoreProviderProps): ReactElement {\n const { projectName, datasourceApi, onCreate, children } = props;\n const [dashboardResource, setDashboardResource] = useState(props.dashboardResource);\n const [savedDatasources, setSavedDatasources] = useState<Record<string, DatasourceSpec>>(\n props.savedDatasources ?? {}\n );\n const project = projectName ?? dashboardResource?.metadata.project;\n\n const { getPlugin, listPluginMetadata } = usePluginRegistry();\n\n const findDatasource = useEvent(async (selector: DatasourceSelector) => {\n // Try to find it in dashboard spec\n if (dashboardResource) {\n const { datasources } = dashboardResource.spec;\n const dashboardDatasource = findDashboardDatasource(datasources, selector);\n if (dashboardDatasource !== undefined) {\n return {\n spec: dashboardDatasource.spec,\n proxyUrl: buildDatasourceProxyUrl(datasourceApi, {\n project: dashboardResource.metadata.project,\n dashboard: dashboardResource.metadata.name,\n name: dashboardDatasource.name,\n }),\n };\n }\n }\n\n if (project) {\n // Try to find it at the project level as a Datasource resource\n const datasource = await datasourceApi.getDatasource(project, selector);\n if (datasource !== undefined) {\n return {\n spec: datasource.spec,\n proxyUrl: buildDatasourceProxyUrl(datasourceApi, {\n project: datasource.metadata.project,\n name: datasource.metadata.name,\n }),\n };\n }\n }\n\n // Try to find it at the global level as a GlobalDatasource resource\n const globalDatasource = await datasourceApi.getGlobalDatasource(selector);\n if (globalDatasource !== undefined) {\n return {\n spec: globalDatasource.spec,\n proxyUrl: buildDatasourceProxyUrl(datasourceApi, {\n name: globalDatasource.metadata.name,\n }),\n };\n }\n\n throw new Error(`No datasource found for kind '${selector.kind}' and name '${selector.name}'`);\n });\n\n // Gets a datasource spec for a given selector\n const getDatasource = useCallback(\n async (selector: DatasourceSelector): Promise<DatasourceSpec> => {\n const { spec } = await findDatasource(selector);\n return spec;\n },\n [findDatasource]\n );\n\n // Given a Datasource selector, finds the spec for it and then uses its corresponding plugin the create a client\n const getDatasourceClient = useCallback(\n async function getClient<Client extends DatasourceClient>(selector: DatasourceSelector): Promise<Client> {\n const { kind } = selector;\n const [{ spec, proxyUrl }, plugin] = await Promise.all([findDatasource(selector), getPlugin('Datasource', kind)]);\n\n // allows extending client\n const client = plugin.createClient(spec.plugin.spec, { proxyUrl }) as Client;\n if (onCreate !== undefined) {\n return onCreate(client) as Client;\n }\n return client;\n },\n [findDatasource, getPlugin, onCreate]\n );\n\n const listDatasourceSelectItems = useEvent(\n async (datasourcePluginName: string): Promise<DatasourceSelectItemGroup[]> => {\n const [pluginMetadata, datasources, globalDatasources] = await Promise.all([\n listPluginMetadata(['Datasource']),\n project ? datasourceApi.listDatasources(project, datasourcePluginName) : [],\n datasourceApi.listGlobalDatasources(datasourcePluginName),\n ]);\n\n // Find the metadata for the plugin type they asked for, so we can use it for the name of the default datasource\n const datasourcePluginMetadata = pluginMetadata.find((metadata) => metadata.spec.name === datasourcePluginName);\n if (datasourcePluginMetadata === undefined) {\n throw new Error(`Could not find a Datasource plugin with kind '${datasourcePluginName}'`);\n }\n\n // Get helper for computing results properly\n const { results, addItem } = buildDatasourceSelectItemGroups(datasourcePluginMetadata.spec.display.name);\n\n // Start with dashboard datasources with the highest precedence\n if (dashboardResource?.spec.datasources) {\n for (const selectorName in dashboardResource.spec.datasources) {\n const spec = dashboardResource.spec.datasources[selectorName];\n if (spec === undefined || spec.plugin.kind !== datasourcePluginName) continue;\n\n const saved = selectorName in savedDatasources;\n addItem({ spec, selectorName, selectorGroup: 'dashboard', saved });\n }\n }\n\n // Now look at project-level datasources\n for (const datasource of datasources) {\n const selectorName = datasource.metadata.name;\n addItem({\n spec: datasource.spec,\n selectorName,\n selectorGroup: 'project',\n editLink: `/projects/${project}/datasources`,\n });\n }\n\n // And finally global datasources\n for (const globalDatasource of globalDatasources) {\n const selectorName = globalDatasource.metadata.name;\n addItem({ spec: globalDatasource.spec, selectorName, selectorGroup: 'global', editLink: '/admin/datasources' });\n }\n\n return results;\n }\n );\n\n const getLocalDatasources = useCallback((): Record<string, DatasourceSpec> => {\n return dashboardResource?.spec.datasources ?? {};\n }, [dashboardResource]);\n\n const getSavedDatasources = useCallback((): Record<string, DatasourceSpec> => {\n return savedDatasources;\n }, [savedDatasources]);\n\n const setLocalDatasources = useCallback(\n (datasources: Record<string, DatasourceSpec>) => {\n if (dashboardResource) {\n setDashboardResource(\n dashboardResource.kind === 'Dashboard'\n ? ({\n ...dashboardResource,\n spec: {\n ...dashboardResource.spec,\n datasources: datasources,\n },\n } as DashboardResource)\n : ({\n ...dashboardResource,\n spec: {\n ...dashboardResource.spec,\n datasources: datasources,\n },\n } as EphemeralDashboardResource)\n );\n }\n },\n [dashboardResource]\n );\n\n const ctxValue: DatasourceStore = useMemo(\n () =>\n ({\n getDatasource,\n getDatasourceClient,\n getLocalDatasources,\n setLocalDatasources,\n setSavedDatasources,\n getSavedDatasources,\n listDatasourceSelectItems,\n }) as DatasourceStore,\n [\n getDatasource,\n getDatasourceClient,\n getLocalDatasources,\n setLocalDatasources,\n listDatasourceSelectItems,\n setSavedDatasources,\n getSavedDatasources,\n ]\n );\n\n return <DatasourceStoreContext.Provider value={ctxValue}>{children}</DatasourceStoreContext.Provider>;\n}\n\nfunction buildDatasourceProxyUrl(api: DatasourceApi, params: BuildDatasourceProxyUrlParams): string {\n return api.buildProxyUrl ? api.buildProxyUrl(params) : '';\n}\n\n// Helper to find a datasource in the list embedded in a dashboard spec\nfunction findDashboardDatasource(\n dashboardDatasources: DashboardSpec['datasources'],\n selector: DatasourceSelector\n): DatasourceDefinition | undefined {\n if (dashboardDatasources === undefined) return undefined;\n\n // If using a name in the selector...\n if (selector.name !== undefined) {\n const named = dashboardDatasources[selector.name];\n if (named === undefined) return undefined;\n return named.plugin.kind === selector.kind ? { name: selector.name, spec: named } : undefined;\n }\n\n // If only using a kind, try to find one with that kind that is the default\n const result = Object.entries(dashboardDatasources).find(\n (entry) => entry[1].plugin.kind === selector.kind && entry[1].default\n );\n if (!result) {\n return undefined;\n }\n return { name: result[0], spec: result[1] };\n}\n\ninterface AddDatasouceSelectItemParams {\n spec: DatasourceSpec;\n selectorName: string;\n selectorGroup?: string;\n editLink?: string;\n saved?: boolean;\n}\n\ntype AddDatasourceSelectItemFunc = (params: AddDatasouceSelectItemParams) => void;\n\n/**\n * Helper for building a list of DatasourceSelectItemGroup results.\n * @param pluginDisplayName\n */\nfunction buildDatasourceSelectItemGroups(pluginDisplayName: string): {\n results: DatasourceSelectItemGroup[];\n addItem: AddDatasourceSelectItemFunc;\n} {\n const results: DatasourceSelectItemGroup[] = [];\n const usedNames = new Set<string>();\n let isFirst = true;\n let explicitDefaultAdded = false;\n const groupIndices: Record<string, number> = {};\n let currentGroupIndex = 1; // 0 is the default group, always there as it contains at least the first item.\n\n const addItem = ({\n spec,\n selectorName,\n selectorGroup: group,\n editLink,\n saved,\n }: AddDatasouceSelectItemParams): void => {\n group = group ?? '';\n\n // Ensure the default group is always present as soon as an item is added.\n if (isFirst) {\n results.push({\n group: `Default ${pluginDisplayName}`,\n items: [],\n });\n }\n\n // Create the group if necessary\n let selectItemGroup = results[groupIndices[group] ?? -1];\n if (!selectItemGroup) {\n groupIndices[group] = currentGroupIndex;\n selectItemGroup = { items: [], group, editLink };\n results[currentGroupIndex] = selectItemGroup;\n currentGroupIndex++;\n }\n\n // Add item to the group\n const isOverridden = usedNames.has(selectorName);\n selectItemGroup.items.push({\n name: spec.display?.name ?? selectorName,\n overridden: isOverridden,\n saved,\n selector: {\n kind: spec.plugin.kind,\n name: selectorName,\n group,\n },\n });\n usedNames.add(selectorName);\n\n const isExplicitDefault = !isOverridden && spec.default && !explicitDefaultAdded;\n if (results[0] && (isFirst || isExplicitDefault)) {\n // If we haven't added a default yet and this is a default, add default option to the beginning of the results\n results[0].items = [\n {\n name: `Default (${selectorName} from ${group})`,\n selector: {\n kind: spec.plugin.kind,\n },\n },\n ];\n // We consider that we added the default datasource only if it has been explicitly set as default.\n // If we add this datasource as default just because it's the first, it still needs to be overridable by\n // another datasource explicitly set as default.\n explicitDefaultAdded = isExplicitDefault;\n }\n\n // At the end, we make sure the overriding item(s) is well flagged so\n if (isOverridden) {\n for (let i = explicitDefaultAdded ? 1 : 0; i < currentGroupIndex; i++) {\n (results[i]?.items ?? [])\n .filter((item: DatasourceSelectItem) => item.selector.name === selectorName)\n .forEach((item: DatasourceSelectItem) => {\n item.overriding = true;\n });\n }\n }\n\n isFirst = false;\n };\n\n return { results, addItem };\n}\n"],"names":["useCallback","useMemo","useState","useEvent","DatasourceStoreContext","usePluginRegistry","DatasourceStoreProvider","props","projectName","datasourceApi","onCreate","children","dashboardResource","setDashboardResource","savedDatasources","setSavedDatasources","project","metadata","getPlugin","listPluginMetadata","findDatasource","selector","datasources","spec","dashboardDatasource","findDashboardDatasource","undefined","proxyUrl","buildDatasourceProxyUrl","dashboard","name","datasource","getDatasource","globalDatasource","getGlobalDatasource","Error","kind","getDatasourceClient","getClient","plugin","Promise","all","client","createClient","listDatasourceSelectItems","datasourcePluginName","pluginMetadata","globalDatasources","listDatasources","listGlobalDatasources","datasourcePluginMetadata","find","results","addItem","buildDatasourceSelectItemGroups","display","selectorName","saved","selectorGroup","editLink","getLocalDatasources","getSavedDatasources","setLocalDatasources","ctxValue","Provider","value","api","params","buildProxyUrl","dashboardDatasources","named","result","Object","entries","entry","default","pluginDisplayName","usedNames","Set","isFirst","explicitDefaultAdded","groupIndices","currentGroupIndex","group","push","items","selectItemGroup","isOverridden","has","overridden","add","isExplicitDefault","i","filter","item","forEach","overriding"],"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,SAAkCA,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAQ;AAChF,SAOEC,QAAQ,QAGH,mBAAmB;AAC1B,SACEC,sBAAsB,EAGtBC,iBAAiB,QAGZ,4BAA4B;AA8BnC;;CAEC,GACD,OAAO,SAASC,wBAAwBC,KAAmC;IACzE,MAAM,EAAEC,WAAW,EAAEC,aAAa,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,GAAGJ;IAC3D,MAAM,CAACK,mBAAmBC,qBAAqB,GAAGX,SAASK,MAAMK,iBAAiB;IAClF,MAAM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;YACD,kGAAkG;YAClG,wGAAwG;YACxG,gDAAgD;YAChD4C,uBAAuBW;QACzB;QAEA,qEAAqE;QACrE,IAAIJ,cAAc;YAChB,IAAK,IAAIK,IAAIZ,uBAAuB,IAAI,GAAGY,IAAIV,mBAAmBU,IAAK;gBACpExC,CAAAA,OAAO,CAACwC,EAAE,EAAEP,SAAS,EAAE,AAAD,EACpBQ,MAAM,CAAC,CAACC,OAA+BA,KAAKzE,QAAQ,CAACS,IAAI,KAAK0B,cAC9DuC,OAAO,CAAC,CAACD;oBACRA,KAAKE,UAAU,GAAG;gBACpB;YACJ;QACF;QAEAjB,UAAU;IACZ;IAEA,OAAO;QAAE3B;QAASC;IAAQ;AAC5B"}
|
|
1
|
+
{"version":3,"sources":["../../src/context/DatasourceStoreProvider.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 { ReactElement, ReactNode, useCallback, useMemo, useState } from 'react';\nimport {\n DashboardResource,\n DashboardSpec,\n DatasourceResource,\n DatasourceSelector,\n DatasourceSpec,\n GlobalDatasourceResource,\n useEvent,\n EphemeralDashboardResource,\n DatasourceDefinition,\n} from '@perses-dev/core';\nimport {\n DatasourceStoreContext,\n DatasourceStore,\n DatasourceSelectItemGroup,\n usePluginRegistry,\n DatasourceClient,\n DatasourceSelectItem,\n} from '@perses-dev/plugin-system';\n\nexport interface DatasourceStoreProviderProps {\n dashboardResource?: DashboardResource | EphemeralDashboardResource;\n projectName?: string;\n datasourceApi: DatasourceApi;\n children?: ReactNode;\n savedDatasources?: Record<string, DatasourceSpec>;\n onCreate?: (client: DatasourceClient) => DatasourceClient;\n}\n\nexport type BuildDatasourceProxyUrlParams = {\n project?: string;\n dashboard?: string;\n name: string;\n};\n\nexport type BuildDatasourceProxyUrlFunc = (p: BuildDatasourceProxyUrlParams) => string;\n\n/**\n * The external API for fetching datasource resources\n */\nexport interface DatasourceApi {\n buildProxyUrl?: BuildDatasourceProxyUrlFunc;\n getDatasource: (project: string, selector: DatasourceSelector) => Promise<DatasourceResource | undefined>;\n getGlobalDatasource: (selector: DatasourceSelector) => Promise<GlobalDatasourceResource | undefined>;\n listDatasources: (project: string, pluginKind?: string) => Promise<DatasourceResource[]>;\n listGlobalDatasources: (pluginKind?: string) => Promise<GlobalDatasourceResource[]>;\n}\n\n/**\n * A `DatasourceContext` provider that uses an external API to resolve datasource selectors.\n */\nexport function DatasourceStoreProvider(props: DatasourceStoreProviderProps): ReactElement {\n const { projectName, datasourceApi, onCreate, children } = props;\n const [dashboardResource, setDashboardResource] = useState(props.dashboardResource);\n const [savedDatasources, setSavedDatasources] = useState<Record<string, DatasourceSpec>>(\n props.savedDatasources ?? {}\n );\n const project = projectName ?? dashboardResource?.metadata.project;\n\n const { getPlugin, listPluginMetadata } = usePluginRegistry();\n\n const findDatasource = useEvent(async (selector: DatasourceSelector) => {\n // Try to find it in dashboard spec\n if (dashboardResource) {\n const { datasources } = dashboardResource.spec;\n const dashboardDatasource = findDashboardDatasource(datasources, selector);\n if (dashboardDatasource !== undefined) {\n return {\n spec: dashboardDatasource.spec,\n proxyUrl: buildDatasourceProxyUrl(datasourceApi, {\n project: dashboardResource.metadata.project,\n dashboard: dashboardResource.metadata.name,\n name: dashboardDatasource.name,\n }),\n };\n }\n }\n\n if (project) {\n // Try to find it at the project level as a Datasource resource\n const datasource = await datasourceApi.getDatasource(project, selector);\n if (datasource !== undefined) {\n return {\n spec: datasource.spec,\n proxyUrl: buildDatasourceProxyUrl(datasourceApi, {\n project: datasource.metadata.project,\n name: datasource.metadata.name,\n }),\n };\n }\n }\n\n // Try to find it at the global level as a GlobalDatasource resource\n const globalDatasource = await datasourceApi.getGlobalDatasource(selector);\n if (globalDatasource !== undefined) {\n return {\n spec: globalDatasource.spec,\n proxyUrl: buildDatasourceProxyUrl(datasourceApi, {\n name: globalDatasource.metadata.name,\n }),\n };\n }\n\n throw new Error(`No datasource found for kind '${selector.kind}' and name '${selector.name}'`);\n });\n\n // Gets a datasource spec for a given selector\n const getDatasource = useCallback(\n async (selector: DatasourceSelector): Promise<DatasourceSpec> => {\n const { spec } = await findDatasource(selector);\n return spec;\n },\n [findDatasource]\n );\n\n // Given a Datasource selector, finds the spec for it and then uses its corresponding plugin the create a client\n const getDatasourceClient = useCallback(\n async function getClient<Client extends DatasourceClient>(selector: DatasourceSelector): Promise<Client> {\n const { kind } = selector;\n const [{ spec, proxyUrl }, plugin] = await Promise.all([findDatasource(selector), getPlugin('Datasource', kind)]);\n\n // allows extending client\n const client = plugin.createClient(spec.plugin.spec, { proxyUrl }) as Client;\n if (onCreate !== undefined) {\n return onCreate(client) as Client;\n }\n return client;\n },\n [findDatasource, getPlugin, onCreate]\n );\n\n const listDatasourceSelectItems = useEvent(\n async (datasourcePluginName: string): Promise<DatasourceSelectItemGroup[]> => {\n const [pluginMetadata, datasources, globalDatasources] = await Promise.all([\n listPluginMetadata(['Datasource']),\n project ? datasourceApi.listDatasources(project, datasourcePluginName) : [],\n datasourceApi.listGlobalDatasources(datasourcePluginName),\n ]);\n\n // Find the metadata for the plugin type they asked for, so we can use it for the name of the default datasource\n const datasourcePluginMetadata = pluginMetadata.find((metadata) => metadata.spec.name === datasourcePluginName);\n if (datasourcePluginMetadata === undefined) {\n throw new Error(`Could not find a Datasource plugin with kind '${datasourcePluginName}'`);\n }\n\n // Get helper for computing results properly\n const { results, addItem } = buildDatasourceSelectItemGroups(datasourcePluginMetadata.spec.display.name);\n\n // Start with dashboard datasources with the highest precedence\n if (dashboardResource?.spec.datasources) {\n for (const selectorName in dashboardResource.spec.datasources) {\n const spec = dashboardResource.spec.datasources[selectorName];\n if (spec === undefined || spec.plugin.kind !== datasourcePluginName) continue;\n\n const saved = selectorName in savedDatasources;\n addItem({ spec, selectorName, selectorGroup: 'dashboard', saved });\n }\n }\n\n // Now look at project-level datasources\n for (const datasource of datasources) {\n const selectorName = datasource.metadata.name;\n addItem({\n spec: datasource.spec,\n selectorName,\n selectorGroup: 'project',\n editLink: `/projects/${project}/datasources`,\n });\n }\n\n // And finally global datasources\n for (const globalDatasource of globalDatasources) {\n const selectorName = globalDatasource.metadata.name;\n addItem({ spec: globalDatasource.spec, selectorName, selectorGroup: 'global', editLink: '/admin/datasources' });\n }\n\n return results;\n }\n );\n\n const getLocalDatasources = useCallback((): Record<string, DatasourceSpec> => {\n return dashboardResource?.spec.datasources ?? {};\n }, [dashboardResource]);\n\n const getSavedDatasources = useCallback((): Record<string, DatasourceSpec> => {\n return savedDatasources;\n }, [savedDatasources]);\n\n const setLocalDatasources = useCallback(\n (datasources: Record<string, DatasourceSpec>) => {\n if (dashboardResource) {\n setDashboardResource(\n dashboardResource.kind === 'Dashboard'\n ? ({\n ...dashboardResource,\n spec: {\n ...dashboardResource.spec,\n datasources: datasources,\n },\n } as DashboardResource)\n : ({\n ...dashboardResource,\n spec: {\n ...dashboardResource.spec,\n datasources: datasources,\n },\n } as EphemeralDashboardResource)\n );\n }\n },\n [dashboardResource]\n );\n\n const ctxValue: DatasourceStore = useMemo(\n () =>\n ({\n getDatasource,\n getDatasourceClient,\n getLocalDatasources,\n setLocalDatasources,\n setSavedDatasources,\n getSavedDatasources,\n listDatasourceSelectItems,\n }) as DatasourceStore,\n [\n getDatasource,\n getDatasourceClient,\n getLocalDatasources,\n setLocalDatasources,\n listDatasourceSelectItems,\n setSavedDatasources,\n getSavedDatasources,\n ]\n );\n\n return <DatasourceStoreContext.Provider value={ctxValue}>{children}</DatasourceStoreContext.Provider>;\n}\n\nfunction buildDatasourceProxyUrl(api: DatasourceApi, params: BuildDatasourceProxyUrlParams): string {\n return api.buildProxyUrl ? api.buildProxyUrl(params) : '';\n}\n\n// Helper to find a datasource in the list embedded in a dashboard spec\nfunction findDashboardDatasource(\n dashboardDatasources: DashboardSpec['datasources'],\n selector: DatasourceSelector\n): DatasourceDefinition | undefined {\n if (dashboardDatasources === undefined) return undefined;\n\n // If using a name in the selector...\n if (selector.name !== undefined) {\n const named = dashboardDatasources[selector.name];\n if (named === undefined) return undefined;\n return named.plugin.kind === selector.kind ? { name: selector.name, spec: named } : undefined;\n }\n\n // If only using a kind, try to find one with that kind that is the default\n const result = Object.entries(dashboardDatasources).find(\n (entry) => entry[1].plugin.kind === selector.kind && entry[1].default\n );\n if (!result) {\n return undefined;\n }\n return { name: result[0], spec: result[1] };\n}\n\ninterface AddDatasouceSelectItemParams {\n spec: DatasourceSpec;\n selectorName: string;\n selectorGroup?: string;\n editLink?: string;\n saved?: boolean;\n}\n\ntype AddDatasourceSelectItemFunc = (params: AddDatasouceSelectItemParams) => void;\n\n/**\n * Helper for building a list of DatasourceSelectItemGroup results.\n * @param pluginDisplayName\n */\nfunction buildDatasourceSelectItemGroups(pluginDisplayName: string): {\n results: DatasourceSelectItemGroup[];\n addItem: AddDatasourceSelectItemFunc;\n} {\n const results: DatasourceSelectItemGroup[] = [];\n const usedNames = new Set<string>();\n let isFirst = true;\n let explicitDefaultAdded = false;\n const groupIndices: Record<string, number> = {};\n let currentGroupIndex = 1; // 0 is the default group, always there as it contains at least the first item.\n\n const addItem = ({\n spec,\n selectorName,\n selectorGroup: group,\n editLink,\n saved,\n }: AddDatasouceSelectItemParams): void => {\n group = group ?? '';\n\n // Ensure the default group is always present as soon as an item is added.\n if (isFirst) {\n results.push({\n group: `Default ${pluginDisplayName}`,\n items: [],\n });\n }\n\n // Create the group if necessary\n let selectItemGroup = results[groupIndices[group] ?? -1];\n if (!selectItemGroup) {\n groupIndices[group] = currentGroupIndex;\n selectItemGroup = { items: [], group, editLink };\n results[currentGroupIndex] = selectItemGroup;\n currentGroupIndex++;\n }\n\n // Add item to the group\n const isOverridden = usedNames.has(selectorName);\n selectItemGroup.items.push({\n name: spec.display?.name ?? selectorName,\n overridden: isOverridden,\n saved,\n selector: {\n kind: spec.plugin.kind,\n name: selectorName,\n group,\n },\n });\n usedNames.add(selectorName);\n\n const isExplicitDefault = !isOverridden && spec.default && !explicitDefaultAdded;\n if (results[0] && (isFirst || isExplicitDefault)) {\n // If we haven't added a default yet and this is a default, add default option to the beginning of the results\n results[0].items = [\n {\n name: `Default (${selectorName} from ${group})`,\n selector: {\n kind: spec.plugin.kind,\n },\n },\n ];\n // We consider that we added the default datasource only if it has been explicitly set as default.\n // If we add this datasource as default just because it's the first, it still needs to be overridable by\n // another datasource explicitly set as default.\n explicitDefaultAdded = isExplicitDefault;\n }\n\n // At the end, we make sure the overriding item(s) is well flagged so\n if (isOverridden) {\n for (let i = explicitDefaultAdded ? 1 : 0; i < currentGroupIndex; i++) {\n (results[i]?.items ?? [])\n .filter((item: DatasourceSelectItem) => item.selector.name === selectorName)\n .forEach((item: DatasourceSelectItem) => {\n item.overriding = true;\n });\n }\n }\n\n isFirst = false;\n };\n\n return { results, addItem };\n}\n"],"names":["useCallback","useMemo","useState","useEvent","DatasourceStoreContext","usePluginRegistry","DatasourceStoreProvider","props","projectName","datasourceApi","onCreate","children","dashboardResource","setDashboardResource","savedDatasources","setSavedDatasources","project","metadata","getPlugin","listPluginMetadata","findDatasource","selector","datasources","spec","dashboardDatasource","findDashboardDatasource","undefined","proxyUrl","buildDatasourceProxyUrl","dashboard","name","datasource","getDatasource","globalDatasource","getGlobalDatasource","Error","kind","getDatasourceClient","getClient","plugin","Promise","all","client","createClient","listDatasourceSelectItems","datasourcePluginName","pluginMetadata","globalDatasources","listDatasources","listGlobalDatasources","datasourcePluginMetadata","find","results","addItem","buildDatasourceSelectItemGroups","display","selectorName","saved","selectorGroup","editLink","getLocalDatasources","getSavedDatasources","setLocalDatasources","ctxValue","Provider","value","api","params","buildProxyUrl","dashboardDatasources","named","result","Object","entries","entry","default","pluginDisplayName","usedNames","Set","isFirst","explicitDefaultAdded","groupIndices","currentGroupIndex","group","push","items","selectItemGroup","isOverridden","has","overridden","add","isExplicitDefault","i","filter","item","forEach","overriding"],"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,SAAkCA,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAQ;AAChF,SAOEC,QAAQ,QAGH,mBAAmB;AAC1B,SACEC,sBAAsB,EAGtBC,iBAAiB,QAGZ,4BAA4B;AA8BnC;;CAEC,GACD,OAAO,SAASC,wBAAwBC,KAAmC;IACzE,MAAM,EAAEC,WAAW,EAAEC,aAAa,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,GAAGJ;IAC3D,MAAM,CAACK,mBAAmBC,qBAAqB,GAAGX,SAASK,MAAMK,iBAAiB;IAClF,MAAM,CAACE,kBAAkBC,oBAAoB,GAAGb,SAC9CK,MAAMO,gBAAgB,IAAI,CAAC;IAE7B,MAAME,UAAUR,eAAeI,mBAAmBK,SAASD;IAE3D,MAAM,EAAEE,SAAS,EAAEC,kBAAkB,EAAE,GAAGd;IAE1C,MAAMe,iBAAiBjB,SAAS,OAAOkB;QACrC,mCAAmC;QACnC,IAAIT,mBAAmB;YACrB,MAAM,EAAEU,WAAW,EAAE,GAAGV,kBAAkBW,IAAI;YAC9C,MAAMC,sBAAsBC,wBAAwBH,aAAaD;YACjE,IAAIG,wBAAwBE,WAAW;gBACrC,OAAO;oBACLH,MAAMC,oBAAoBD,IAAI;oBAC9BI,UAAUC,wBAAwBnB,eAAe;wBAC/CO,SAASJ,kBAAkBK,QAAQ,CAACD,OAAO;wBAC3Ca,WAAWjB,kBAAkBK,QAAQ,CAACa,IAAI;wBAC1CA,MAAMN,oBAAoBM,IAAI;oBAChC;gBACF;YACF;QACF;QAEA,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;QACxB,MAAMK,eAAeV,UAAUW,GAAG,CAAChC;QACnC8B,gBAAgBD,KAAK,CAACD,IAAI,CAAC;YACzBtD,MAAMP,KAAKgC,OAAO,EAAEzB,QAAQ0B;YAC5BiC,YAAYF;YACZ9B;YACApC,UAAU;gBACRe,MAAMb,KAAKgB,MAAM,CAACH,IAAI;gBACtBN,MAAM0B;gBACN2B;YACF;QACF;QACAN,UAAUa,GAAG,CAAClC;QAEd,MAAMmC,oBAAoB,CAACJ,gBAAgBhE,KAAKoD,OAAO,IAAI,CAACK;QAC5D,IAAI5B,OAAO,CAAC,EAAE,IAAK2B,CAAAA,WAAWY,iBAAgB,GAAI;YAChD,8GAA8G;YAC9GvC,OAAO,CAAC,EAAE,CAACiC,KAAK,GAAG;gBACjB;oBACEvD,MAAM,CAAC,SAAS,EAAE0B,aAAa,MAAM,EAAE2B,MAAM,CAAC,CAAC;oBAC/C9D,UAAU;wBACRe,MAAMb,KAAKgB,MAAM,CAACH,IAAI;oBACxB;gBACF;aACD;YACD,kGAAkG;YAClG,wGAAwG;YACxG,gDAAgD;YAChD4C,uBAAuBW;QACzB;QAEA,qEAAqE;QACrE,IAAIJ,cAAc;YAChB,IAAK,IAAIK,IAAIZ,uBAAuB,IAAI,GAAGY,IAAIV,mBAAmBU,IAAK;gBACpExC,CAAAA,OAAO,CAACwC,EAAE,EAAEP,SAAS,EAAE,AAAD,EACpBQ,MAAM,CAAC,CAACC,OAA+BA,KAAKzE,QAAQ,CAACS,IAAI,KAAK0B,cAC9DuC,OAAO,CAAC,CAACD;oBACRA,KAAKE,UAAU,GAAG;gBACpB;YACJ;QACF;QAEAjB,UAAU;IACZ;IAEA,OAAO;QAAE3B;QAASC;IAAQ;AAC5B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VariableProvider.d.ts","sourceRoot":"","sources":["../../../src/context/VariableProvider/VariableProvider.tsx"],"names":[],"mappings":"AAaA,OAAO,EAAiB,YAAY,EAAE,SAAS,EAAiC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AM,MAAM,0BAA0B,GAAG;IACvC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE;QACR,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,MAAM,CAAC;KACtB,CAAC;IACF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,kBAAkB,EAAE,CAAC;CACnC,CAAC;AAEF,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,SAAS,CAAC;IACpB,0BAA0B,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAClD,2BAA2B,CAAC,EAAE,0BAA0B,EAAE,CAAC;IAC3D,0BAA0B,CAAC,EAAE,yBAAyB,EAAE,CAAC;CAC1D;AAGD,wBAAgB,gBAAgB,CAAC,EAC/B,QAAQ,EACR,0BAA+B,EAC/B,2BAAgC,EAChC,0BAA+B,GAChC,EAAE,qBAAqB,GAAG,YAAY,CAUtC;AAED,wBAAgB,+BAA+B,CAAC,EAC9C,QAAQ,EACR,0BAA+B,EAC/B,2BAAgC,EAChC,0BAA0B,EAAE,gBAAqB,GAClD,EAAE,qBAAqB,GAAG,YAAY,CAYtC"}
|
|
@@ -16,7 +16,8 @@ import { createStore, useStore } from 'zustand';
|
|
|
16
16
|
import { useStoreWithEqualityFn } from 'zustand/traditional';
|
|
17
17
|
import { immer } from 'zustand/middleware/immer';
|
|
18
18
|
import { devtools } from 'zustand/middleware';
|
|
19
|
-
import
|
|
19
|
+
import { shallow } from 'zustand/shallow';
|
|
20
|
+
import { produce } from 'immer';
|
|
20
21
|
import { VariableContext, BuiltinVariableContext, useTimeRange } from '@perses-dev/plugin-system';
|
|
21
22
|
import { DEFAULT_ALL_VALUE as ALL_VALUE, formatDuration, intervalToPrometheusDuration } from '@perses-dev/core';
|
|
22
23
|
import { checkSavedDefaultVariableStatus, findVariableDefinitionByName, mergeVariableDefinitions } from './utils';
|
|
@@ -88,7 +89,7 @@ export function useVariableDefinitionStates(variableNames) {
|
|
|
88
89
|
}
|
|
89
90
|
export function useVariableDefinitionActions() {
|
|
90
91
|
const store = useVariableDefinitionStoreCtx();
|
|
91
|
-
return
|
|
92
|
+
return useStoreWithEqualityFn(store, (s)=>{
|
|
92
93
|
return {
|
|
93
94
|
setVariableValue: s.setVariableValue,
|
|
94
95
|
setVariableLoading: s.setVariableLoading,
|
|
@@ -97,7 +98,7 @@ export function useVariableDefinitionActions() {
|
|
|
97
98
|
setVariableDefaultValues: s.setVariableDefaultValues,
|
|
98
99
|
getSavedVariablesStatus: s.getSavedVariablesStatus
|
|
99
100
|
};
|
|
100
|
-
});
|
|
101
|
+
}, shallow);
|
|
101
102
|
}
|
|
102
103
|
export function useVariableDefinitions() {
|
|
103
104
|
const store = useVariableDefinitionStoreCtx();
|
|
@@ -333,10 +334,10 @@ function createVariableDefinitionStore({ initialVariableDefinitions = [], extern
|
|
|
333
334
|
}
|
|
334
335
|
// TODO: merge the different providers related to Variables under a single one (and keep "VariableProvider" as a name)
|
|
335
336
|
export function VariableProvider({ children, initialVariableDefinitions = [], externalVariableDefinitions = [], builtinVariableDefinitions = [] }) {
|
|
336
|
-
const [store] = useState(createVariableDefinitionStore({
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
337
|
+
const [store] = useState(()=>createVariableDefinitionStore({
|
|
338
|
+
initialVariableDefinitions,
|
|
339
|
+
externalVariableDefinitions
|
|
340
|
+
}));
|
|
340
341
|
return /*#__PURE__*/ _jsx(VariableDefinitionStoreContext.Provider, {
|
|
341
342
|
value: store,
|
|
342
343
|
children: /*#__PURE__*/ _jsx(PluginProvider, {
|
|
@@ -348,11 +349,11 @@ export function VariableProvider({ children, initialVariableDefinitions = [], ex
|
|
|
348
349
|
export function VariableProviderWithQueryParams({ children, initialVariableDefinitions = [], externalVariableDefinitions = [], builtinVariableDefinitions: builtinVariables = [] }) {
|
|
349
350
|
const allVariableDefs = mergeVariableDefinitions(initialVariableDefinitions, externalVariableDefinitions);
|
|
350
351
|
const queryParams = useVariableQueryParams(allVariableDefs);
|
|
351
|
-
const [store] = useState(createVariableDefinitionStore({
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
352
|
+
const [store] = useState(()=>createVariableDefinitionStore({
|
|
353
|
+
initialVariableDefinitions,
|
|
354
|
+
externalVariableDefinitions,
|
|
355
|
+
queryParams
|
|
356
|
+
}));
|
|
356
357
|
return /*#__PURE__*/ _jsx(VariableDefinitionStoreContext.Provider, {
|
|
357
358
|
value: store,
|
|
358
359
|
children: /*#__PURE__*/ _jsx(PluginProvider, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/context/VariableProvider/VariableProvider.tsx"],"sourcesContent":["// Copyright 2024 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, ReactElement, ReactNode, useContext, useMemo, useState } from 'react';\nimport { createStore, StoreApi, 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 VariableContext,\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 TextVariableDefinition,\n ListVariableDefinition,\n} from '@perses-dev/core';\nimport { checkSavedDefaultVariableStatus, findVariableDefinitionByName, mergeVariableDefinitions } from './utils';\nimport { hydrateVariableDefinitionStates as hydrateVariableDefinitionStates } from './hydrationUtils';\nimport { getInitalValuesFromQueryParameters, getURLQueryParamName, useVariableQueryParams } from './query-params';\n\n/**\n * This store is used to manipulate and read the definition of the variables and their state.\n * - being local or external variables.\n * - being text or list variables.\n * - being of any state (value, options, loading, error, ...) check {@VariableState}\n * Go and read each property documentation for more details.\n */\ntype VariableDefinitionStore = {\n /**\n * List of local variables definitions.\n * This is typically the variable definition that can be modified through the setVariableDefinition setter.\n *\n * In Perses App ecosystem, this is typically the dashboard scope variables, that's why we call them local.\n * Note that depending on the form, we can reuse this store to modify higher scope variables. For example,\n * when we modify the variable of a project, we'll set this field with project scope variables. To be able to modify\n * them.\n */\n variableDefinitions: VariableDefinition[];\n /**\n * List of external variable definitions.\n * This is static variable definitions that won´t be modified under this context.\n * You'll have to set one list of external variable definition by scope. See {@link ExternalVariableDefinition} for\n * more details.\n *\n * In Perses App ecosystem, this is typically the project or global scope variables.\n * Note that depending on the form, we can reuse this store to modify higher scope variables. For example,\n * when we modify the variable of a project, we'll set this field with global scope variables. Which means we\n * won't be able to modify them from this form.\n */\n externalVariableDefinitions: ExternalVariableDefinition[];\n /**\n * Additionally to definitions, we need to associate to each variable a state. That's what this map is meant for.\n * This can be heavily modified under this context, using the different setters available.\n * Note that the state of local AND external variables can be modified.\n */\n variableState: VariableStoreStateMap;\n /**\n * Allow to modify the `value` property of a variable in the state map.\n * @param variableName identify the variable\n * @param value new value\n * @param source identify the variable source if this is an external variable. See {@link ExternalVariableDefinition}\n */\n setVariableValue: (variableName: VariableName, value: VariableValue, source?: string) => void;\n /**\n * Allow to modify the `options` property of a variable in the state map.\n * @param variableName identify the variable\n * @param options new value\n * @param source identify the variable source if this is an external variable. See {@link ExternalVariableDefinition}\n */\n setVariableOptions: (name: VariableName, options: VariableOption[], source?: string) => void;\n /**\n * Allow to modify the `loading` property of a variable in the state map.\n * @param variableName identify the variable\n * @param laoding new value\n * @param source identify the variable source if this is an external variable. See {@link ExternalVariableDefinition}\n */\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\n/**\n * Context object for {@link VariableDefinitionStore}.\n */\nconst VariableDefinitionStoreContext = createContext<StoreApi<VariableDefinitionStore> | undefined>(undefined);\nexport function useVariableDefinitionStoreCtx(): StoreApi<VariableDefinitionStore> {\n const context = useContext(VariableDefinitionStoreContext);\n if (!context) {\n throw new Error('VariableStoreContext not initialized');\n }\n return context;\n}\n\nexport function useVariableDefinitionStates(variableNames?: string[]): VariableStateMap {\n const store = useVariableDefinitionStoreCtx();\n return useStoreWithEqualityFn(\n store,\n (s) => {\n const varStates: 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 varStates[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 varStates[name] = varState;\n });\n });\n\n return varStates;\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 variables context.\n * @param name name of the variable\n * @param source if given, it searches in the external variables\n */\nexport function useVariableDefinitionAndState(\n name: string,\n source?: string\n): {\n definition: TextVariableDefinition | ListVariableDefinition | undefined;\n state: VariableState | undefined;\n} {\n const store = useVariableDefinitionStoreCtx();\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 useVariableDefinitionActions(): {\n setVariableLoading: (name: VariableName, loading: boolean, source?: string) => void;\n getSavedVariablesStatus: () => { isSavedVariableModified: boolean; modifiedVariableNames: string[] };\n setVariableDefaultValues: () => VariableDefinition[];\n setVariableValue: (variableName: VariableName, value: VariableValue, source?: string) => void;\n setVariableOptions: (name: VariableName, options: VariableOption[], source?: string) => void;\n setVariableDefinitions: (definitions: VariableDefinition[]) => void;\n} {\n const store = useVariableDefinitionStoreCtx();\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 useVariableDefinitions(): VariableDefinition[] {\n const store = useVariableDefinitionStoreCtx();\n return useStore(store, (s) => s.variableDefinitions);\n}\n\nexport function useExternalVariableDefinitions(): ExternalVariableDefinition[] {\n const store = useVariableDefinitionStoreCtx();\n return useStore(store, (s) => s.externalVariableDefinitions);\n}\n\ninterface PluginProviderProps {\n children: ReactNode;\n builtinVariables?: BuiltinVariableDefinition[];\n}\n\nfunction PluginProvider({ children, builtinVariables }: PluginProviderProps): ReactElement {\n const originalValues = useVariableDefinitionStates();\n const definitions = useVariableDefinitions();\n const externalDefinitions = useExternalVariableDefinitions();\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 <VariableContext.Provider value={{ state: values }}>{children}</VariableContext.Provider>\n </BuiltinVariableContext.Provider>\n );\n}\n\ninterface VariableDefinitionStoreArgs {\n initialVariableDefinitions?: VariableDefinition[];\n externalVariableDefinitions?: ExternalVariableDefinition[];\n queryParams?: ReturnType<typeof useVariableQueryParams>;\n}\n\nfunction createVariableDefinitionStore({\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n queryParams,\n}: VariableDefinitionStoreArgs): StoreApi<VariableDefinitionStore> {\n const initialParams = getInitalValuesFromQueryParameters(queryParams ? queryParams[0] : {});\n const store = createStore<VariableDefinitionStore>()(\n devtools(\n immer((set, get) => ({\n variableState: hydrateVariableDefinitionStates(\n initialVariableDefinitions,\n initialParams,\n externalVariableDefinitions\n ),\n variableDefinitions: initialVariableDefinitions,\n externalVariableDefinitions: externalVariableDefinitions,\n setVariableDefinitions(definitions: VariableDefinition[]): void {\n set(\n (state) => {\n state.variableDefinitions = definitions;\n state.variableState = hydrateVariableDefinitionStates(\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): void {\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): void {\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): void =>\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: (): VariableDefinition[] => {\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 modifiedVariableNames: string[];\n isSavedVariableModified: boolean;\n } => {\n return checkSavedDefaultVariableStatus(get().variableDefinitions, get().variableState);\n },\n }))\n )\n );\n\n return store as unknown as StoreApi<VariableDefinitionStore>; // TODO: @Gladorme check if we can avoid this cast\n}\n\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 */\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 VariableProviderProps {\n children: ReactNode;\n initialVariableDefinitions?: VariableDefinition[];\n externalVariableDefinitions?: ExternalVariableDefinition[];\n builtinVariableDefinitions?: BuiltinVariableDefinition[];\n}\n\n// TODO: merge the different providers related to Variables under a single one (and keep \"VariableProvider\" as a name)\nexport function VariableProvider({\n children,\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n builtinVariableDefinitions = [],\n}: VariableProviderProps): ReactElement {\n const [store] = useState(createVariableDefinitionStore({ initialVariableDefinitions, externalVariableDefinitions }));\n\n return (\n <VariableDefinitionStoreContext.Provider value={store}>\n <PluginProvider builtinVariables={builtinVariableDefinitions}>{children}</PluginProvider>\n </VariableDefinitionStoreContext.Provider>\n );\n}\n\nexport function VariableProviderWithQueryParams({\n children,\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n builtinVariableDefinitions: builtinVariables = [],\n}: VariableProviderProps): ReactElement {\n const allVariableDefs = mergeVariableDefinitions(initialVariableDefinitions, externalVariableDefinitions);\n const queryParams = useVariableQueryParams(allVariableDefs);\n const [store] = useState(\n createVariableDefinitionStore({ initialVariableDefinitions, externalVariableDefinitions, queryParams })\n );\n\n return (\n <VariableDefinitionStoreContext.Provider value={store}>\n <PluginProvider builtinVariables={builtinVariables}>{children}</PluginProvider>\n </VariableDefinitionStoreContext.Provider>\n );\n}\n"],"names":["createContext","useContext","useMemo","useState","createStore","useStore","useStoreWithEqualityFn","immer","devtools","produce","VariableContext","BuiltinVariableContext","useTimeRange","DEFAULT_ALL_VALUE","ALL_VALUE","formatDuration","intervalToPrometheusDuration","checkSavedDefaultVariableStatus","findVariableDefinitionByName","mergeVariableDefinitions","hydrateVariableDefinitionStates","getInitalValuesFromQueryParameters","getURLQueryParamName","useVariableQueryParams","VariableDefinitionStoreContext","undefined","useVariableDefinitionStoreCtx","context","Error","useVariableDefinitionStates","variableNames","store","s","varStates","names","variableDefinitions","map","value","spec","name","forEach","varState","variableState","get","overridden","externalVariableDefinitions","d","source","definitions","left","right","JSON","stringify","useVariableDefinitionAndState","state","find","v","definition","useVariableDefinitionActions","setVariableValue","setVariableLoading","setVariableOptions","setVariableDefinitions","setVariableDefaultValues","getSavedVariablesStatus","useVariableDefinitions","useExternalVariableDefinitions","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","createVariableDefinitionStore","initialVariableDefinitions","queryParams","initialParams","set","loading","val","Array","isArray","includes","at","filter","setQueryParams","updatedVariables","draft","variable","index","currentVariable","specDraft","defaultValue","currentVariableValue","VariableProvider","builtinVariableDefinitions","VariableProviderWithQueryParams","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,EAA2BC,UAAU,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAQ;AAC9F,SAASC,WAAW,EAAYC,QAAQ,QAAQ,UAAU;AAC1D,SAASC,sBAAsB,QAAQ,sBAAsB;AAC7D,SAASC,KAAK,QAAQ,2BAA2B;AACjD,SAASC,QAAQ,QAAQ,qBAAqB;AAC9C,OAAOC,aAAa,QAAQ;AAC5B,SACEC,eAAe,EAKfC,sBAAsB,EACtBC,YAAY,QACP,4BAA4B;AACnC,SACEC,qBAAqBC,SAAS,EAI9BC,cAAc,EACdC,4BAA4B,QAIvB,mBAAmB;AAC1B,SAASC,+BAA+B,EAAEC,4BAA4B,EAAEC,wBAAwB,QAAQ,UAAU;AAClH,SAASC,mCAAmCA,+BAA+B,QAAQ,mBAAmB;AACtG,SAASC,kCAAkC,EAAEC,oBAAoB,EAAEC,sBAAsB,QAAQ,iBAAiB;AAgElH;;CAEC,GACD,MAAMC,+CAAiCxB,cAA6DyB;AACpG,OAAO,SAASC;IACd,MAAMC,UAAU1B,WAAWuB;IAC3B,IAAI,CAACG,SAAS;QACZ,MAAM,IAAIC,MAAM;IAClB;IACA,OAAOD;AACT;AAEA,OAAO,SAASE,4BAA4BC,aAAwB;IAClE,MAAMC,QAAQL;IACd,OAAOpB,uBACLyB,OACA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AC7E,MAAMmD,cAAczE,uBAAuB+F;IAC3C,MAAM,CAACvF,MAAM,GAAG5B,SACd2F,8BAA8B;QAAEC;QAA4BlD;QAA6BmD;IAAY;IAGvG,qBACE,KAACxE,+BAA+BoE,QAAQ;QAACvD,OAAON;kBAC9C,cAAA,KAACoC;YAAeE,kBAAkBA;sBAAmBD;;;AAG3D"}
|
|
1
|
+
{"version":3,"sources":["../../../src/context/VariableProvider/VariableProvider.tsx"],"sourcesContent":["// Copyright 2024 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, ReactElement, ReactNode, useContext, useMemo, useState } from 'react';\nimport { createStore, StoreApi, useStore } from 'zustand';\nimport { useStoreWithEqualityFn } from 'zustand/traditional';\nimport { immer } from 'zustand/middleware/immer';\nimport { devtools } from 'zustand/middleware';\nimport { shallow } from 'zustand/shallow';\nimport { produce } from 'immer';\nimport {\n VariableContext,\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 TextVariableDefinition,\n ListVariableDefinition,\n} from '@perses-dev/core';\nimport { checkSavedDefaultVariableStatus, findVariableDefinitionByName, mergeVariableDefinitions } from './utils';\nimport { hydrateVariableDefinitionStates as hydrateVariableDefinitionStates } from './hydrationUtils';\nimport { getInitalValuesFromQueryParameters, getURLQueryParamName, useVariableQueryParams } from './query-params';\n\n/**\n * This store is used to manipulate and read the definition of the variables and their state.\n * - being local or external variables.\n * - being text or list variables.\n * - being of any state (value, options, loading, error, ...) check {@VariableState}\n * Go and read each property documentation for more details.\n */\ntype VariableDefinitionStore = {\n /**\n * List of local variables definitions.\n * This is typically the variable definition that can be modified through the setVariableDefinition setter.\n *\n * In Perses App ecosystem, this is typically the dashboard scope variables, that's why we call them local.\n * Note that depending on the form, we can reuse this store to modify higher scope variables. For example,\n * when we modify the variable of a project, we'll set this field with project scope variables. To be able to modify\n * them.\n */\n variableDefinitions: VariableDefinition[];\n /**\n * List of external variable definitions.\n * This is static variable definitions that won´t be modified under this context.\n * You'll have to set one list of external variable definition by scope. See {@link ExternalVariableDefinition} for\n * more details.\n *\n * In Perses App ecosystem, this is typically the project or global scope variables.\n * Note that depending on the form, we can reuse this store to modify higher scope variables. For example,\n * when we modify the variable of a project, we'll set this field with global scope variables. Which means we\n * won't be able to modify them from this form.\n */\n externalVariableDefinitions: ExternalVariableDefinition[];\n /**\n * Additionally to definitions, we need to associate to each variable a state. That's what this map is meant for.\n * This can be heavily modified under this context, using the different setters available.\n * Note that the state of local AND external variables can be modified.\n */\n variableState: VariableStoreStateMap;\n /**\n * Allow to modify the `value` property of a variable in the state map.\n * @param variableName identify the variable\n * @param value new value\n * @param source identify the variable source if this is an external variable. See {@link ExternalVariableDefinition}\n */\n setVariableValue: (variableName: VariableName, value: VariableValue, source?: string) => void;\n /**\n * Allow to modify the `options` property of a variable in the state map.\n * @param variableName identify the variable\n * @param options new value\n * @param source identify the variable source if this is an external variable. See {@link ExternalVariableDefinition}\n */\n setVariableOptions: (name: VariableName, options: VariableOption[], source?: string) => void;\n /**\n * Allow to modify the `loading` property of a variable in the state map.\n * @param variableName identify the variable\n * @param laoding new value\n * @param source identify the variable source if this is an external variable. See {@link ExternalVariableDefinition}\n */\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\n/**\n * Context object for {@link VariableDefinitionStore}.\n */\nconst VariableDefinitionStoreContext = createContext<StoreApi<VariableDefinitionStore> | undefined>(undefined);\nexport function useVariableDefinitionStoreCtx(): StoreApi<VariableDefinitionStore> {\n const context = useContext(VariableDefinitionStoreContext);\n if (!context) {\n throw new Error('VariableStoreContext not initialized');\n }\n return context;\n}\n\nexport function useVariableDefinitionStates(variableNames?: string[]): VariableStateMap {\n const store = useVariableDefinitionStoreCtx();\n return useStoreWithEqualityFn(\n store,\n (s) => {\n const varStates: 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 varStates[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 varStates[name] = varState;\n });\n });\n\n return varStates;\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 variables context.\n * @param name name of the variable\n * @param source if given, it searches in the external variables\n */\nexport function useVariableDefinitionAndState(\n name: string,\n source?: string\n): {\n definition: TextVariableDefinition | ListVariableDefinition | undefined;\n state: VariableState | undefined;\n} {\n const store = useVariableDefinitionStoreCtx();\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 useVariableDefinitionActions(): {\n setVariableLoading: (name: VariableName, loading: boolean, source?: string) => void;\n getSavedVariablesStatus: () => { isSavedVariableModified: boolean; modifiedVariableNames: string[] };\n setVariableDefaultValues: () => VariableDefinition[];\n setVariableValue: (variableName: VariableName, value: VariableValue, source?: string) => void;\n setVariableOptions: (name: VariableName, options: VariableOption[], source?: string) => void;\n setVariableDefinitions: (definitions: VariableDefinition[]) => void;\n} {\n const store = useVariableDefinitionStoreCtx();\n return useStoreWithEqualityFn(\n store,\n (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 shallow\n );\n}\n\nexport function useVariableDefinitions(): VariableDefinition[] {\n const store = useVariableDefinitionStoreCtx();\n return useStore(store, (s) => s.variableDefinitions);\n}\n\nexport function useExternalVariableDefinitions(): ExternalVariableDefinition[] {\n const store = useVariableDefinitionStoreCtx();\n return useStore(store, (s) => s.externalVariableDefinitions);\n}\n\ninterface PluginProviderProps {\n children: ReactNode;\n builtinVariables?: BuiltinVariableDefinition[];\n}\n\nfunction PluginProvider({ children, builtinVariables }: PluginProviderProps): ReactElement {\n const originalValues = useVariableDefinitionStates();\n const definitions = useVariableDefinitions();\n const externalDefinitions = useExternalVariableDefinitions();\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 <VariableContext.Provider value={{ state: values }}>{children}</VariableContext.Provider>\n </BuiltinVariableContext.Provider>\n );\n}\n\ninterface VariableDefinitionStoreArgs {\n initialVariableDefinitions?: VariableDefinition[];\n externalVariableDefinitions?: ExternalVariableDefinition[];\n queryParams?: ReturnType<typeof useVariableQueryParams>;\n}\n\nfunction createVariableDefinitionStore({\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n queryParams,\n}: VariableDefinitionStoreArgs): StoreApi<VariableDefinitionStore> {\n const initialParams = getInitalValuesFromQueryParameters(queryParams ? queryParams[0] : {});\n const store = createStore<VariableDefinitionStore>()(\n devtools(\n immer((set, get) => ({\n variableState: hydrateVariableDefinitionStates(\n initialVariableDefinitions,\n initialParams,\n externalVariableDefinitions\n ),\n variableDefinitions: initialVariableDefinitions,\n externalVariableDefinitions: externalVariableDefinitions,\n setVariableDefinitions(definitions: VariableDefinition[]): void {\n set(\n (state) => {\n state.variableDefinitions = definitions;\n state.variableState = hydrateVariableDefinitionStates(\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): void {\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): void {\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): void =>\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: (): VariableDefinition[] => {\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 modifiedVariableNames: string[];\n isSavedVariableModified: boolean;\n } => {\n return checkSavedDefaultVariableStatus(get().variableDefinitions, get().variableState);\n },\n }))\n )\n );\n\n return store as unknown as StoreApi<VariableDefinitionStore>; // TODO: @Gladorme check if we can avoid this cast\n}\n\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 */\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 VariableProviderProps {\n children: ReactNode;\n initialVariableDefinitions?: VariableDefinition[];\n externalVariableDefinitions?: ExternalVariableDefinition[];\n builtinVariableDefinitions?: BuiltinVariableDefinition[];\n}\n\n// TODO: merge the different providers related to Variables under a single one (and keep \"VariableProvider\" as a name)\nexport function VariableProvider({\n children,\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n builtinVariableDefinitions = [],\n}: VariableProviderProps): ReactElement {\n const [store] = useState(() =>\n createVariableDefinitionStore({ initialVariableDefinitions, externalVariableDefinitions })\n );\n\n return (\n <VariableDefinitionStoreContext.Provider value={store}>\n <PluginProvider builtinVariables={builtinVariableDefinitions}>{children}</PluginProvider>\n </VariableDefinitionStoreContext.Provider>\n );\n}\n\nexport function VariableProviderWithQueryParams({\n children,\n initialVariableDefinitions = [],\n externalVariableDefinitions = [],\n builtinVariableDefinitions: builtinVariables = [],\n}: VariableProviderProps): ReactElement {\n const allVariableDefs = mergeVariableDefinitions(initialVariableDefinitions, externalVariableDefinitions);\n const queryParams = useVariableQueryParams(allVariableDefs);\n const [store] = useState(() =>\n createVariableDefinitionStore({ initialVariableDefinitions, externalVariableDefinitions, queryParams })\n );\n\n return (\n <VariableDefinitionStoreContext.Provider value={store}>\n <PluginProvider builtinVariables={builtinVariables}>{children}</PluginProvider>\n </VariableDefinitionStoreContext.Provider>\n );\n}\n"],"names":["createContext","useContext","useMemo","useState","createStore","useStore","useStoreWithEqualityFn","immer","devtools","shallow","produce","VariableContext","BuiltinVariableContext","useTimeRange","DEFAULT_ALL_VALUE","ALL_VALUE","formatDuration","intervalToPrometheusDuration","checkSavedDefaultVariableStatus","findVariableDefinitionByName","mergeVariableDefinitions","hydrateVariableDefinitionStates","getInitalValuesFromQueryParameters","getURLQueryParamName","useVariableQueryParams","VariableDefinitionStoreContext","undefined","useVariableDefinitionStoreCtx","context","Error","useVariableDefinitionStates","variableNames","store","s","varStates","names","variableDefinitions","map","value","spec","name","forEach","varState","variableState","get","overridden","externalVariableDefinitions","d","source","definitions","left","right","JSON","stringify","useVariableDefinitionAndState","state","find","v","definition","useVariableDefinitionActions","setVariableValue","setVariableLoading","setVariableOptions","setVariableDefinitions","setVariableDefaultValues","getSavedVariablesStatus","useVariableDefinitions","useExternalVariableDefinitions","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","createVariableDefinitionStore","initialVariableDefinitions","queryParams","initialParams","set","loading","val","Array","isArray","includes","at","filter","setQueryParams","updatedVariables","draft","variable","index","currentVariable","specDraft","defaultValue","currentVariableValue","VariableProvider","builtinVariableDefinitions","VariableProviderWithQueryParams","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,EAA2BC,UAAU,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAQ;AAC9F,SAASC,WAAW,EAAYC,QAAQ,QAAQ,UAAU;AAC1D,SAASC,sBAAsB,QAAQ,sBAAsB;AAC7D,SAASC,KAAK,QAAQ,2BAA2B;AACjD,SAASC,QAAQ,QAAQ,qBAAqB;AAC9C,SAASC,OAAO,QAAQ,kBAAkB;AAC1C,SAASC,OAAO,QAAQ,QAAQ;AAChC,SACEC,eAAe,EAKfC,sBAAsB,EACtBC,YAAY,QACP,4BAA4B;AACnC,SACEC,qBAAqBC,SAAS,EAI9BC,cAAc,EACdC,4BAA4B,QAIvB,mBAAmB;AAC1B,SAASC,+BAA+B,EAAEC,4BAA4B,EAAEC,wBAAwB,QAAQ,UAAU;AAClH,SAASC,mCAAmCA,+BAA+B,QAAQ,mBAAmB;AACtG,SAASC,kCAAkC,EAAEC,oBAAoB,EAAEC,sBAAsB,QAAQ,iBAAiB;AAgElH;;CAEC,GACD,MAAMC,+CAAiCzB,cAA6D0B;AACpG,OAAO,SAASC;IACd,MAAMC,UAAU3B,WAAWwB;IAC3B,IAAI,CAACG,SAAS;QACZ,MAAM,IAAIC,MAAM;IAClB;IACA,OAAOD;AACT;AAEA,OAAO,SAASE,4BAA4BC,aAAwB;IAClE,MAAMC,QAAQL;IACd,OAAOrB,uBACL0B,OACA,CAACC;QACC,MAAMC,YAA8B,CAAC;Q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E,uBAAuB+F;IAC3C,MAAM,CAACvF,MAAM,GAAG7B,SAAS,IACvB4F,8BAA8B;YAAEC;YAA4BlD;YAA6BmD;QAAY;IAGvG,qBACE,KAACxE,+BAA+BoE,QAAQ;QAACvD,OAAON;kBAC9C,cAAA,KAACoC;YAAeE,kBAAkBA;sBAAmBD;;;AAG3D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/context/VariableProvider/query-params.ts"],"sourcesContent":["// Copyright 2024 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 { VariableValue, VariableDefinition } from '@perses-dev/core';\nimport { QueryParamConfig, useQueryParams } from 'use-query-params';\n\nconst variableQueryParameterPrefix = 'var-';\n\nexport function getURLQueryParamName(name: string): string {\n return `${variableQueryParameterPrefix}${name}`;\n}\n\nexport function encodeVariableValue(value: VariableValue): string | null {\n if (Array.isArray(value)) {\n return value.join(',');\n }\n return value;\n}\n\nexport function decodeVariableValue(value: string): VariableValue {\n if (!value) {\n return null;\n }\n const values = value.split(',');\n if (values.length === 1) {\n return values[0] as string;\n }\n return values;\n}\n\nconst VariableValueParam: QueryParamConfig<VariableValue> = {\n encode: encodeVariableValue,\n decode: (v) => {\n if (typeof v === 'string') {\n return decodeVariableValue(v);\n }\n return '';\n },\n};\n\nexport function useVariableQueryParams(defs: VariableDefinition[]): ReturnType<typeof useQueryParams> {\n const config: Record<string, typeof VariableValueParam> = {};\n defs.forEach((def) => {\n const name = getURLQueryParamName(def.spec.name);\n config[name] = VariableValueParam;\n });\n return useQueryParams(config, { updateType: 'replaceIn' });\n}\n\nexport function getInitalValuesFromQueryParameters(\n queryParamValues: Record<string, VariableValue>\n): Record<string, VariableValue> {\n const values: Record<string, VariableValue> = {};\n Object.keys(queryParamValues).forEach((key) => {\n const value = queryParamValues[key];\n if (!value) {\n return;\n }\n const name = key.replace(variableQueryParameterPrefix, '');\n values[name] = value;\n });\n return values;\n}\n"],"names":["useQueryParams","variableQueryParameterPrefix","getURLQueryParamName","name","encodeVariableValue","value","Array","isArray","join","decodeVariableValue","values","split","length","VariableValueParam","encode","decode","v","useVariableQueryParams","defs","config","forEach","def","spec","updateType","getInitalValuesFromQueryParameters","queryParamValues","Object","keys","key","replace"],"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,SAA2BA,cAAc,QAAQ,mBAAmB;AAEpE,MAAMC,+BAA+B;AAErC,OAAO,SAASC,qBAAqBC,IAAY;IAC/C,OAAO,
|
|
1
|
+
{"version":3,"sources":["../../../src/context/VariableProvider/query-params.ts"],"sourcesContent":["// Copyright 2024 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 { VariableValue, VariableDefinition } from '@perses-dev/core';\nimport { QueryParamConfig, useQueryParams } from 'use-query-params';\n\nconst variableQueryParameterPrefix = 'var-';\n\nexport function getURLQueryParamName(name: string): string {\n return `${variableQueryParameterPrefix}${name}`;\n}\n\nexport function encodeVariableValue(value: VariableValue): string | null {\n if (Array.isArray(value)) {\n return value.join(',');\n }\n return value;\n}\n\nexport function decodeVariableValue(value: string): VariableValue {\n if (!value) {\n return null;\n }\n const values = value.split(',');\n if (values.length === 1) {\n return values[0] as string;\n }\n return values;\n}\n\nconst VariableValueParam: QueryParamConfig<VariableValue> = {\n encode: encodeVariableValue,\n decode: (v) => {\n if (typeof v === 'string') {\n return decodeVariableValue(v);\n }\n return '';\n },\n};\n\nexport function useVariableQueryParams(defs: VariableDefinition[]): ReturnType<typeof useQueryParams> {\n const config: Record<string, typeof VariableValueParam> = {};\n defs.forEach((def) => {\n const name = getURLQueryParamName(def.spec.name);\n config[name] = VariableValueParam;\n });\n return useQueryParams(config, { updateType: 'replaceIn' });\n}\n\nexport function getInitalValuesFromQueryParameters(\n queryParamValues: Record<string, VariableValue>\n): Record<string, VariableValue> {\n const values: Record<string, VariableValue> = {};\n Object.keys(queryParamValues).forEach((key) => {\n const value = queryParamValues[key];\n if (!value) {\n return;\n }\n const name = key.replace(variableQueryParameterPrefix, '');\n values[name] = value;\n });\n return values;\n}\n"],"names":["useQueryParams","variableQueryParameterPrefix","getURLQueryParamName","name","encodeVariableValue","value","Array","isArray","join","decodeVariableValue","values","split","length","VariableValueParam","encode","decode","v","useVariableQueryParams","defs","config","forEach","def","spec","updateType","getInitalValuesFromQueryParameters","queryParamValues","Object","keys","key","replace"],"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,SAA2BA,cAAc,QAAQ,mBAAmB;AAEpE,MAAMC,+BAA+B;AAErC,OAAO,SAASC,qBAAqBC,IAAY;IAC/C,OAAO,GAAGF,+BAA+BE,MAAM;AACjD;AAEA,OAAO,SAASC,oBAAoBC,KAAoB;IACtD,IAAIC,MAAMC,OAAO,CAACF,QAAQ;QACxB,OAAOA,MAAMG,IAAI,CAAC;IACpB;IACA,OAAOH;AACT;AAEA,OAAO,SAASI,oBAAoBJ,KAAa;IAC/C,IAAI,CAACA,OAAO;QACV,OAAO;IACT;IACA,MAAMK,SAASL,MAAMM,KAAK,CAAC;IAC3B,IAAID,OAAOE,MAAM,KAAK,GAAG;QACvB,OAAOF,MAAM,CAAC,EAAE;IAClB;IACA,OAAOA;AACT;AAEA,MAAMG,qBAAsD;IAC1DC,QAAQV;IACRW,QAAQ,CAACC;QACP,IAAI,OAAOA,MAAM,UAAU;YACzB,OAAOP,oBAAoBO;QAC7B;QACA,OAAO;IACT;AACF;AAEA,OAAO,SAASC,uBAAuBC,IAA0B;IAC/D,MAAMC,SAAoD,CAAC;IAC3DD,KAAKE,OAAO,CAAC,CAACC;QACZ,MAAMlB,OAAOD,qBAAqBmB,IAAIC,IAAI,CAACnB,IAAI;QAC/CgB,MAAM,CAAChB,KAAK,GAAGU;IACjB;IACA,OAAOb,eAAemB,QAAQ;QAAEI,YAAY;IAAY;AAC1D;AAEA,OAAO,SAASC,mCACdC,gBAA+C;IAE/C,MAAMf,SAAwC,CAAC;IAC/CgB,OAAOC,IAAI,CAACF,kBAAkBL,OAAO,CAAC,CAACQ;QACrC,MAAMvB,QAAQoB,gBAAgB,CAACG,IAAI;QACnC,IAAI,CAACvB,OAAO;YACV;QACF;QACA,MAAMF,OAAOyB,IAAIC,OAAO,CAAC5B,8BAA8B;QACvDS,MAAM,CAACP,KAAK,GAAGE;IACjB;IACA,OAAOK;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/context/useDashboard.tsx"],"sourcesContent":["// Copyright 2024 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 {\n createPanelRef,\n DashboardResource,\n EphemeralDashboardResource,\n GridDefinition,\n PanelGroupId,\n} from '@perses-dev/core';\nimport { PanelGroupDefinition, useDashboardStore } from './DashboardProvider';\nimport { useVariableDefinitionActions, useVariableDefinitions } from './VariableProvider';\n\nexport function useDashboard(): {\n dashboard: DashboardResource | EphemeralDashboardResource;\n setDashboard: (dashboardResource: DashboardResource | EphemeralDashboardResource) => void;\n} {\n const {\n panels,\n panelGroups,\n panelGroupOrder,\n setDashboard: setDashboardResource,\n kind,\n metadata,\n display,\n duration,\n refreshInterval,\n datasources,\n ttl,\n } = useDashboardStore(\n ({\n panels,\n panelGroups,\n panelGroupOrder,\n setDashboard,\n kind,\n metadata,\n display,\n duration,\n refreshInterval,\n datasources,\n ttl,\n }) => ({\n panels,\n panelGroups,\n panelGroupOrder,\n setDashboard,\n kind,\n metadata,\n display,\n duration,\n refreshInterval,\n datasources,\n ttl,\n })\n );\n const { setVariableDefinitions } = useVariableDefinitionActions();\n const variables = useVariableDefinitions();\n const layouts = convertPanelGroupsToLayouts(panelGroups, panelGroupOrder);\n\n const dashboard =\n kind === 'Dashboard'\n ? ({\n kind,\n metadata,\n spec: {\n display,\n panels,\n layouts,\n variables,\n duration,\n refreshInterval,\n datasources,\n },\n } as DashboardResource)\n : ({\n kind,\n metadata,\n spec: {\n display,\n panels,\n layouts,\n variables,\n duration,\n refreshInterval,\n datasources,\n ttl,\n },\n } as EphemeralDashboardResource);\n\n const setDashboard = (dashboardResource: DashboardResource | EphemeralDashboardResource): void => {\n setVariableDefinitions(dashboardResource.spec.variables);\n setDashboardResource(dashboardResource);\n };\n\n return {\n dashboard,\n setDashboard,\n };\n}\n\nfunction convertPanelGroupsToLayouts(\n panelGroups: Record<number, PanelGroupDefinition>,\n panelGroupOrder: PanelGroupId[]\n): GridDefinition[] {\n const layouts: GridDefinition[] = [];\n panelGroupOrder.map((groupOrderId) => {\n const group = panelGroups[groupOrderId];\n if (group === undefined) {\n throw new Error('panel group not found');\n }\n const { title, isCollapsed, itemLayouts, itemPanelKeys } = group;\n let display = undefined;\n if (title) {\n display = {\n title,\n collapse: {\n open: !isCollapsed,\n },\n };\n }\n const layout: GridDefinition = {\n kind: 'Grid',\n spec: {\n display,\n items: itemLayouts.map((layout) => {\n const panelKey = itemPanelKeys[layout.i];\n if (panelKey === undefined) {\n throw new Error(`Missing panel key of layout ${layout.i}`);\n }\n return {\n x: layout.x,\n y: layout.y,\n width: layout.w,\n height: layout.h,\n content: createPanelRef(panelKey),\n };\n }),\n },\n };\n layouts.push(layout);\n });\n\n return layouts;\n}\n"],"names":["createPanelRef","useDashboardStore","useVariableDefinitionActions","useVariableDefinitions","useDashboard","panels","panelGroups","panelGroupOrder","setDashboard","setDashboardResource","kind","metadata","display","duration","refreshInterval","datasources","ttl","setVariableDefinitions","variables","layouts","convertPanelGroupsToLayouts","dashboard","spec","dashboardResource","map","groupOrderId","group","undefined","Error","title","isCollapsed","itemLayouts","itemPanelKeys","collapse","open","layout","items","panelKey","i","x","y","width","w","height","h","content","push"],"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,SACEA,cAAc,QAKT,mBAAmB;AAC1B,SAA+BC,iBAAiB,QAAQ,sBAAsB;AAC9E,SAASC,4BAA4B,EAAEC,sBAAsB,QAAQ,qBAAqB;AAE1F,OAAO,SAASC;IAId,MAAM,EACJC,MAAM,EACNC,WAAW,EACXC,eAAe,EACfC,cAAcC,oBAAoB,EAClCC,IAAI,EACJC,QAAQ,EACRC,OAAO,EACPC,QAAQ,EACRC,eAAe,EACfC,WAAW,EACXC,GAAG,EACJ,GAAGf,kBACF,CAAC,EACCI,MAAM,EACNC,WAAW,EACXC,eAAe,EACfC,YAAY,EACZE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|
1
|
+
{"version":3,"sources":["../../src/context/useDashboard.tsx"],"sourcesContent":["// Copyright 2024 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 {\n createPanelRef,\n DashboardResource,\n EphemeralDashboardResource,\n GridDefinition,\n PanelGroupId,\n} from '@perses-dev/core';\nimport { PanelGroupDefinition, useDashboardStore } from './DashboardProvider';\nimport { useVariableDefinitionActions, useVariableDefinitions } from './VariableProvider';\n\nexport function useDashboard(): {\n dashboard: DashboardResource | EphemeralDashboardResource;\n setDashboard: (dashboardResource: DashboardResource | EphemeralDashboardResource) => void;\n} {\n const {\n panels,\n panelGroups,\n panelGroupOrder,\n setDashboard: setDashboardResource,\n kind,\n metadata,\n display,\n duration,\n refreshInterval,\n datasources,\n ttl,\n } = useDashboardStore(\n ({\n panels,\n panelGroups,\n panelGroupOrder,\n setDashboard,\n kind,\n metadata,\n display,\n duration,\n refreshInterval,\n datasources,\n ttl,\n }) => ({\n panels,\n panelGroups,\n panelGroupOrder,\n setDashboard,\n kind,\n metadata,\n display,\n duration,\n refreshInterval,\n datasources,\n ttl,\n })\n );\n const { setVariableDefinitions } = useVariableDefinitionActions();\n const variables = useVariableDefinitions();\n const layouts = convertPanelGroupsToLayouts(panelGroups, panelGroupOrder);\n\n const dashboard =\n kind === 'Dashboard'\n ? ({\n kind,\n metadata,\n spec: {\n display,\n panels,\n layouts,\n variables,\n duration,\n refreshInterval,\n datasources,\n },\n } as DashboardResource)\n : ({\n kind,\n metadata,\n spec: {\n display,\n panels,\n layouts,\n variables,\n duration,\n refreshInterval,\n datasources,\n ttl,\n },\n } as EphemeralDashboardResource);\n\n const setDashboard = (dashboardResource: DashboardResource | EphemeralDashboardResource): void => {\n setVariableDefinitions(dashboardResource.spec.variables);\n setDashboardResource(dashboardResource);\n };\n\n return {\n dashboard,\n setDashboard,\n };\n}\n\nfunction convertPanelGroupsToLayouts(\n panelGroups: Record<number, PanelGroupDefinition>,\n panelGroupOrder: PanelGroupId[]\n): GridDefinition[] {\n const layouts: GridDefinition[] = [];\n panelGroupOrder.map((groupOrderId) => {\n const group = panelGroups[groupOrderId];\n if (group === undefined) {\n throw new Error('panel group not found');\n }\n const { title, isCollapsed, itemLayouts, itemPanelKeys } = group;\n let display = undefined;\n if (title) {\n display = {\n title,\n collapse: {\n open: !isCollapsed,\n },\n };\n }\n const layout: GridDefinition = {\n kind: 'Grid',\n spec: {\n display,\n items: itemLayouts.map((layout) => {\n const panelKey = itemPanelKeys[layout.i];\n if (panelKey === undefined) {\n throw new Error(`Missing panel key of layout ${layout.i}`);\n }\n return {\n x: layout.x,\n y: layout.y,\n width: layout.w,\n height: layout.h,\n content: createPanelRef(panelKey),\n };\n }),\n },\n };\n layouts.push(layout);\n });\n\n return layouts;\n}\n"],"names":["createPanelRef","useDashboardStore","useVariableDefinitionActions","useVariableDefinitions","useDashboard","panels","panelGroups","panelGroupOrder","setDashboard","setDashboardResource","kind","metadata","display","duration","refreshInterval","datasources","ttl","setVariableDefinitions","variables","layouts","convertPanelGroupsToLayouts","dashboard","spec","dashboardResource","map","groupOrderId","group","undefined","Error","title","isCollapsed","itemLayouts","itemPanelKeys","collapse","open","layout","items","panelKey","i","x","y","width","w","height","h","content","push"],"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,SACEA,cAAc,QAKT,mBAAmB;AAC1B,SAA+BC,iBAAiB,QAAQ,sBAAsB;AAC9E,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U;gBACRiB;gBACAI,UAAU;oBACRC,MAAM,CAACJ;gBACT;YACF;QACF;QACA,MAAMK,SAAyB;YAC7BzB,MAAM;YACNY,MAAM;gBACJV;gBACAwB,OAAOL,YAAYP,GAAG,CAAC,CAACW;oBACtB,MAAME,WAAWL,aAAa,CAACG,OAAOG,CAAC,CAAC;oBACxC,IAAID,aAAaV,WAAW;wBAC1B,MAAM,IAAIC,MAAM,CAAC,4BAA4B,EAAEO,OAAOG,CAAC,EAAE;oBAC3D;oBACA,OAAO;wBACLC,GAAGJ,OAAOI,CAAC;wBACXC,GAAGL,OAAOK,CAAC;wBACXC,OAAON,OAAOO,CAAC;wBACfC,QAAQR,OAAOS,CAAC;wBAChBC,SAAS7C,eAAeqC;oBAC1B;gBACF;YACF;QACF;QACAlB,QAAQ2B,IAAI,CAACX;IACf;IAEA,OAAOhB;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { GlobalDatasourceResource } from '@perses-dev/core';
|
|
2
2
|
import { DatasourceStoreProviderProps } from '../context';
|
|
3
|
-
export declare const prometheusDemoUrl = "https://prometheus.demo.
|
|
3
|
+
export declare const prometheusDemoUrl = "https://prometheus.demo.prometheus.io";
|
|
4
4
|
export declare const prometheusDemo: GlobalDatasourceResource;
|
|
5
5
|
export declare const defaultDatasourceProps: Pick<DatasourceStoreProviderProps, 'datasourceApi' | 'dashboardResource'>;
|
|
6
6
|
//# sourceMappingURL=datasource-provider.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"datasource-provider.d.ts","sourceRoot":"","sources":["../../src/test/datasource-provider.tsx"],"names":[],"mappings":"AAaA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,4BAA4B,EAAE,MAAM,YAAY,CAAC;AAG1D,eAAO,MAAM,iBAAiB,
|
|
1
|
+
{"version":3,"file":"datasource-provider.d.ts","sourceRoot":"","sources":["../../src/test/datasource-provider.tsx"],"names":[],"mappings":"AAaA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,4BAA4B,EAAE,MAAM,YAAY,CAAC;AAG1D,eAAO,MAAM,iBAAiB,0CAA0C,CAAC;AACzE,eAAO,MAAM,cAAc,EAAE,wBAenB,CAAC;AAKX,eAAO,MAAM,sBAAsB,EAAE,IAAI,CAAC,4BAA4B,EAAE,eAAe,GAAG,mBAAmB,CAqB5G,CAAC"}
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// See the License for the specific language governing permissions and
|
|
12
12
|
// limitations under the License.
|
|
13
13
|
import { getTestDashboard } from './dashboard-provider';
|
|
14
|
-
export const prometheusDemoUrl = 'https://prometheus.demo.
|
|
14
|
+
export const prometheusDemoUrl = 'https://prometheus.demo.prometheus.io';
|
|
15
15
|
export const prometheusDemo = {
|
|
16
16
|
kind: 'GlobalDatasource',
|
|
17
17
|
metadata: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/test/datasource-provider.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 { GlobalDatasourceResource } from '@perses-dev/core';\nimport { DatasourceStoreProviderProps } from '../context';\nimport { getTestDashboard } from './dashboard-provider';\n\nexport const prometheusDemoUrl = 'https://prometheus.demo.
|
|
1
|
+
{"version":3,"sources":["../../src/test/datasource-provider.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 { GlobalDatasourceResource } from '@perses-dev/core';\nimport { DatasourceStoreProviderProps } from '../context';\nimport { getTestDashboard } from './dashboard-provider';\n\nexport const prometheusDemoUrl = 'https://prometheus.demo.prometheus.io';\nexport const prometheusDemo: GlobalDatasourceResource = {\n kind: 'GlobalDatasource',\n metadata: {\n name: 'PrometheusDemo',\n createdAt: '0001-01-01T00:00:00Z',\n updatedAt: '0001-01-01T00:00:00Z',\n version: 0,\n },\n spec: {\n default: true,\n plugin: {\n kind: 'PrometheusDatasource',\n spec: { directUrl: prometheusDemoUrl },\n },\n },\n} as const;\n\n// This default currently defines the bare minimum to get a story working in\n// the `Dashboard` storybook with the Prometheus demo api. We'll likely want\n// to expand it to do more in the future.\nexport const defaultDatasourceProps: Pick<DatasourceStoreProviderProps, 'datasourceApi' | 'dashboardResource'> = {\n dashboardResource: getTestDashboard(),\n datasourceApi: {\n buildProxyUrl: () => '',\n getDatasource: () => {\n return Promise.resolve(undefined);\n },\n getGlobalDatasource: (selector) => {\n if (selector.kind === 'PrometheusDatasource') {\n return Promise.resolve(prometheusDemo);\n }\n\n return Promise.resolve(undefined);\n },\n listDatasources: () => {\n return Promise.resolve([]);\n },\n listGlobalDatasources: () => {\n return Promise.resolve([]);\n },\n },\n};\n"],"names":["getTestDashboard","prometheusDemoUrl","prometheusDemo","kind","metadata","name","createdAt","updatedAt","version","spec","default","plugin","directUrl","defaultDatasourceProps","dashboardResource","datasourceApi","buildProxyUrl","getDatasource","Promise","resolve","undefined","getGlobalDatasource","selector","listDatasources","listGlobalDatasources"],"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;AAIjC,SAASA,gBAAgB,QAAQ,uBAAuB;AAExD,OAAO,MAAMC,oBAAoB,wCAAwC;AACzE,OAAO,MAAMC,iBAA2C;IACtDC,MAAM;IACNC,UAAU;QACRC,MAAM;QACNC,WAAW;QACXC,WAAW;QACXC,SAAS;IACX;IACAC,MAAM;QACJC,SAAS;QACTC,QAAQ;YACNR,MAAM;YACNM,MAAM;gBAAEG,WAAWX;YAAkB;QACvC;IACF;AACF,EAAW;AAEX,4EAA4E;AAC5E,4EAA4E;AAC5E,yCAAyC;AACzC,OAAO,MAAMY,yBAAoG;IAC/GC,mBAAmBd;IACnBe,eAAe;QACbC,eAAe,IAAM;QACrBC,eAAe;YACb,OAAOC,QAAQC,OAAO,CAACC;QACzB;QACAC,qBAAqB,CAACC;YACpB,IAAIA,SAASnB,IAAI,KAAK,wBAAwB;gBAC5C,OAAOe,QAAQC,OAAO,CAACjB;YACzB;YAEA,OAAOgB,QAAQC,OAAO,CAACC;QACzB;QACAG,iBAAiB;YACf,OAAOL,QAAQC,OAAO,CAAC,EAAE;QAC3B;QACAK,uBAAuB;YACrB,OAAON,QAAQC,OAAO,CAAC,EAAE;QAC3B;IACF;AACF,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/panelUtils.ts"],"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 { PanelDefinition } from '@perses-dev/core';\nimport { PanelGroupDefinition, PanelGroupItemLayout } from '../context';\nimport { GRID_LAYOUT_SMALL_BREAKPOINT, GRID_LAYOUT_COLS } from '../constants';\n\n// Given a PanelGroup, will find the Y coordinate for adding a new row to the grid, taking into account the items present\nexport function getYForNewRow(group: PanelGroupDefinition): number {\n let newRowY = 0;\n for (const layout of group.itemLayouts) {\n const itemMaxY = layout.y + layout.h;\n if (itemMaxY > newRowY) {\n newRowY = itemMaxY;\n }\n }\n return newRowY;\n}\n\ntype PanelGroupItemBounds = {\n /**\n * Left horizontal position.\n */\n x1: number;\n /**\n * Right horizontal position.\n */\n x2: number;\n /**\n * Top vertical position.\n */\n y1: number;\n /**\n * Bottom vertical position\n */\n y2: number;\n};\n\nfunction getPanelBounds({ x, y, w, h }: PanelGroupItemLayout): PanelGroupItemBounds {\n return {\n x1: x,\n x2: x + w,\n y1: y,\n y2: y + h,\n };\n}\n\nexport type UnpositionedPanelGroupItemLayout = Omit<PanelGroupItemLayout, 'x' | 'y'>;\n\n/**\n * Inserts a new panel into the layout with placement determined by a specified\n * reference panel. The new panel is placed:\n * - To the right of the reference panel if there is space available without\n * moving other panels.\n * - Otherwise, directly below the reference panel. If other panels are below\n * this location, they will also shift downward because the grid uses\n * vertical-based compacting.\n *\n * @param newLayout - Layout for new panel to insert into the grid.\n * @param referenceLayout - Layout for reference panel used to determine the\n * placement of the new panel.\n * @param itemLayouts - Full grid layout.\n * @returns - Item layouts modified to insert the new panel.\n */\nexport function insertPanelInLayout(\n newLayout: UnpositionedPanelGroupItemLayout,\n referenceLayout: PanelGroupItemLayout,\n itemLayouts: PanelGroupItemLayout[]\n): PanelGroupItemLayout[] {\n const MAX_LAYOUT_WIDTH = GRID_LAYOUT_COLS[GRID_LAYOUT_SMALL_BREAKPOINT];\n\n const referenceBounds = getPanelBounds(referenceLayout);\n\n // Organize layouts based on vertical relation to the item being inserted\n // after.\n const aboveInsertRow: PanelGroupItemLayout[] = [];\n const insertRow: PanelGroupItemLayout[] = [];\n const belowInsertRow: PanelGroupItemLayout[] = [];\n itemLayouts.forEach((itemLayout) => {\n const itemBounds = getPanelBounds(itemLayout);\n\n if (itemBounds.y2 <= referenceBounds.y1) {\n aboveInsertRow.push(itemLayout);\n } else if (itemBounds.y1 >= referenceBounds.y2) {\n belowInsertRow.push(itemLayout);\n } else {\n insertRow.push(itemLayout);\n }\n });\n\n // Cannot safely assume that the order of item layouts array is strictly\n // left to right. Sorting the row by horizontal position to more easily find\n // gaps.\n insertRow.sort((a, b) => a.x - b.x);\n const insertAfterIndex = insertRow.findIndex((item) => item.i === referenceLayout.i);\n\n if (insertAfterIndex === insertRow.length - 1) {\n // Insert to the right when space is available and the reference is the last\n // item in the row.\n if (referenceBounds.x2 + newLayout.w <= MAX_LAYOUT_WIDTH) {\n return [\n ...aboveInsertRow,\n ...insertRow,\n {\n ...newLayout,\n x: referenceBounds.x2,\n y: referenceBounds.y1,\n },\n ...belowInsertRow,\n ];\n }\n } else if (insertAfterIndex >= 0) {\n const nextItem = insertRow[insertAfterIndex + 1];\n\n if (nextItem && getPanelBounds(nextItem).x1 - referenceBounds.x2 >= newLayout.w) {\n // Insert to the right when space is available between the reference and\n // the next item in the row.\n insertRow.splice(insertAfterIndex + 1, 0, {\n ...newLayout,\n x: referenceBounds.x2,\n y: referenceBounds.y1,\n });\n\n return [...aboveInsertRow, ...insertRow, ...belowInsertRow];\n }\n }\n\n // Insert the new item below the original and shift the items below the\n // row where the reference is located.\n return [\n ...aboveInsertRow,\n ...insertRow,\n { x: referenceBounds.x1, y: referenceBounds.y2, ...newLayout },\n ...belowInsertRow.map((itemLayout) => {\n // Note: the grid will not necessarily display all of these items shifted\n // all the way down because of vertical compacting, but shifing their\n // y position ensures the new item gets vertical precedence over items\n // below it in that compacting.\n return { ...itemLayout, y: itemLayout.y + newLayout.h };\n }),\n ];\n}\n\n/**\n * Get a valid panel key, where a valid key:\n * - does not include invalid characters\n * - is unique\n */\nexport function getValidPanelKey(panelKey: string, panels: Record<string, PanelDefinition>): string {\n const uniquePanelKeys = getUniquePanelKeys(panels);\n let normalizedPanelKey = getPanelKeyParts(removeWhiteSpaces(panelKey)).name;\n\n const matchingKey = uniquePanelKeys[normalizedPanelKey];\n if (typeof matchingKey === 'number') {\n normalizedPanelKey += `-${matchingKey + 1}`;\n }\n return normalizedPanelKey;\n}\n\ntype PanelKeyParts = {\n name: string;\n number?: number;\n};\n\nconst removeWhiteSpaces = (str: string): string => {\n return str.replace(/\\s+/g, '');\n};\n\n/**\n * Breaks the specified panel key into the name and the optional `-number` used\n * for deduping panels with the same name.\n */\nfunction getPanelKeyParts(panelKey: string): PanelKeyParts {\n const parts = panelKey.match(/(.+)-([0-9]+)/);\n if (parts && parts[1] && parts[2]) {\n return {\n name: parts[1],\n number: parseInt(parts[2], 10),\n };\n }\n\n return {\n name: panelKey,\n };\n}\n\n// Find all the unique panel keys and the largest number used for each.\n// ex: cpu, cpu-1, cpu-2 count as the same panel key since these panels have the same name\nfunction getUniquePanelKeys(panels: Record<string, PanelDefinition>): Record<string, number> {\n const uniquePanelKeys: Record<string, number> = {};\n Object.keys(panels).forEach((panelKey) => {\n const { name, number } = getPanelKeyParts(panelKey);\n if (uniquePanelKeys[name] === undefined) {\n uniquePanelKeys[name] = 0;\n }\n const currentValue = uniquePanelKeys[name];\n if (typeof currentValue === 'number' && number) {\n // Check for the maximum value because we cannot rely on a sequential\n // set of numbers when panels are modified.\n uniquePanelKeys[name] = Math.max(currentValue, number);\n }\n });\n return uniquePanelKeys;\n}\n"],"names":["GRID_LAYOUT_SMALL_BREAKPOINT","GRID_LAYOUT_COLS","getYForNewRow","group","newRowY","layout","itemLayouts","itemMaxY","y","h","getPanelBounds","x","w","x1","x2","y1","y2","insertPanelInLayout","newLayout","referenceLayout","MAX_LAYOUT_WIDTH","referenceBounds","aboveInsertRow","insertRow","belowInsertRow","forEach","itemLayout","itemBounds","push","sort","a","b","insertAfterIndex","findIndex","item","i","length","nextItem","splice","map","getValidPanelKey","panelKey","panels","uniquePanelKeys","getUniquePanelKeys","normalizedPanelKey","getPanelKeyParts","removeWhiteSpaces","name","matchingKey","str","replace","parts","match","number","parseInt","Object","keys","undefined","currentValue","Math","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;AAIjC,SAASA,4BAA4B,EAAEC,gBAAgB,QAAQ,eAAe;AAE9E,yHAAyH;AACzH,OAAO,SAASC,cAAcC,KAA2B;IACvD,IAAIC,UAAU;IACd,KAAK,MAAMC,UAAUF,MAAMG,WAAW,CAAE;QACtC,MAAMC,WAAWF,OAAOG,CAAC,GAAGH,OAAOI,CAAC;QACpC,IAAIF,WAAWH,SAAS;YACtBA,UAAUG;QACZ;IACF;IACA,OAAOH;AACT;AAqBA,SAASM,eAAe,EAAEC,CAAC,EAAEH,CAAC,EAAEI,CAAC,EAAEH,CAAC,EAAwB;IAC1D,OAAO;QACLI,IAAIF;QACJG,IAAIH,IAAIC;QACRG,IAAIP;QACJQ,IAAIR,IAAIC;IACV;AACF;AAIA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASQ,oBACdC,SAA2C,EAC3CC,eAAqC,EACrCb,WAAmC;IAEnC,MAAMc,mBAAmBnB,gBAAgB,CAACD,6BAA6B;IAEvE,MAAMqB,kBAAkBX,eAAeS;IAEvC,yEAAyE;IACzE,SAAS;IACT,MAAMG,iBAAyC,EAAE;IACjD,MAAMC,YAAoC,EAAE;IAC5C,MAAMC,iBAAyC,EAAE;IACjDlB,YAAYmB,OAAO,CAAC,CAACC;QACnB,MAAMC,aAAajB,eAAegB;QAElC,IAAIC,WAAWX,EAAE,IAAIK,gBAAgBN,EAAE,EAAE;YACvCO,eAAeM,IAAI,CAACF;QACtB,OAAO,IAAIC,WAAWZ,EAAE,IAAIM,gBAAgBL,EAAE,EAAE;YAC9CQ,eAAeI,IAAI,CAACF;QACtB,OAAO;YACL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/utils/panelUtils.ts"],"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 { PanelDefinition } from '@perses-dev/core';\nimport { PanelGroupDefinition, PanelGroupItemLayout } from '../context';\nimport { GRID_LAYOUT_SMALL_BREAKPOINT, GRID_LAYOUT_COLS } from '../constants';\n\n// Given a PanelGroup, will find the Y coordinate for adding a new row to the grid, taking into account the items present\nexport function getYForNewRow(group: PanelGroupDefinition): number {\n let newRowY = 0;\n for (const layout of group.itemLayouts) {\n const itemMaxY = layout.y + layout.h;\n if (itemMaxY > newRowY) {\n newRowY = itemMaxY;\n }\n }\n return newRowY;\n}\n\ntype PanelGroupItemBounds = {\n /**\n * Left horizontal position.\n */\n x1: number;\n /**\n * Right horizontal position.\n */\n x2: number;\n /**\n * Top vertical position.\n */\n y1: number;\n /**\n * Bottom vertical position\n */\n y2: number;\n};\n\nfunction getPanelBounds({ x, y, w, h }: PanelGroupItemLayout): PanelGroupItemBounds {\n return {\n x1: x,\n x2: x + w,\n y1: y,\n y2: y + h,\n };\n}\n\nexport type UnpositionedPanelGroupItemLayout = Omit<PanelGroupItemLayout, 'x' | 'y'>;\n\n/**\n * Inserts a new panel into the layout with placement determined by a specified\n * reference panel. The new panel is placed:\n * - To the right of the reference panel if there is space available without\n * moving other panels.\n * - Otherwise, directly below the reference panel. If other panels are below\n * this location, they will also shift downward because the grid uses\n * vertical-based compacting.\n *\n * @param newLayout - Layout for new panel to insert into the grid.\n * @param referenceLayout - Layout for reference panel used to determine the\n * placement of the new panel.\n * @param itemLayouts - Full grid layout.\n * @returns - Item layouts modified to insert the new panel.\n */\nexport function insertPanelInLayout(\n newLayout: UnpositionedPanelGroupItemLayout,\n referenceLayout: PanelGroupItemLayout,\n itemLayouts: PanelGroupItemLayout[]\n): PanelGroupItemLayout[] {\n const MAX_LAYOUT_WIDTH = GRID_LAYOUT_COLS[GRID_LAYOUT_SMALL_BREAKPOINT];\n\n const referenceBounds = getPanelBounds(referenceLayout);\n\n // Organize layouts based on vertical relation to the item being inserted\n // after.\n const aboveInsertRow: PanelGroupItemLayout[] = [];\n const insertRow: PanelGroupItemLayout[] = [];\n const belowInsertRow: PanelGroupItemLayout[] = [];\n itemLayouts.forEach((itemLayout) => {\n const itemBounds = getPanelBounds(itemLayout);\n\n if (itemBounds.y2 <= referenceBounds.y1) {\n aboveInsertRow.push(itemLayout);\n } else if (itemBounds.y1 >= referenceBounds.y2) {\n belowInsertRow.push(itemLayout);\n } else {\n insertRow.push(itemLayout);\n }\n });\n\n // Cannot safely assume that the order of item layouts array is strictly\n // left to right. Sorting the row by horizontal position to more easily find\n // gaps.\n insertRow.sort((a, b) => a.x - b.x);\n const insertAfterIndex = insertRow.findIndex((item) => item.i === referenceLayout.i);\n\n if (insertAfterIndex === insertRow.length - 1) {\n // Insert to the right when space is available and the reference is the last\n // item in the row.\n if (referenceBounds.x2 + newLayout.w <= MAX_LAYOUT_WIDTH) {\n return [\n ...aboveInsertRow,\n ...insertRow,\n {\n ...newLayout,\n x: referenceBounds.x2,\n y: referenceBounds.y1,\n },\n ...belowInsertRow,\n ];\n }\n } else if (insertAfterIndex >= 0) {\n const nextItem = insertRow[insertAfterIndex + 1];\n\n if (nextItem && getPanelBounds(nextItem).x1 - referenceBounds.x2 >= newLayout.w) {\n // Insert to the right when space is available between the reference and\n // the next item in the row.\n insertRow.splice(insertAfterIndex + 1, 0, {\n ...newLayout,\n x: referenceBounds.x2,\n y: referenceBounds.y1,\n });\n\n return [...aboveInsertRow, ...insertRow, ...belowInsertRow];\n }\n }\n\n // Insert the new item below the original and shift the items below the\n // row where the reference is located.\n return [\n ...aboveInsertRow,\n ...insertRow,\n { x: referenceBounds.x1, y: referenceBounds.y2, ...newLayout },\n ...belowInsertRow.map((itemLayout) => {\n // Note: the grid will not necessarily display all of these items shifted\n // all the way down because of vertical compacting, but shifing their\n // y position ensures the new item gets vertical precedence over items\n // below it in that compacting.\n return { ...itemLayout, y: itemLayout.y + newLayout.h };\n }),\n ];\n}\n\n/**\n * Get a valid panel key, where a valid key:\n * - does not include invalid characters\n * - is unique\n */\nexport function getValidPanelKey(panelKey: string, panels: Record<string, PanelDefinition>): string {\n const uniquePanelKeys = getUniquePanelKeys(panels);\n let normalizedPanelKey = getPanelKeyParts(removeWhiteSpaces(panelKey)).name;\n\n const matchingKey = uniquePanelKeys[normalizedPanelKey];\n if (typeof matchingKey === 'number') {\n normalizedPanelKey += `-${matchingKey + 1}`;\n }\n return normalizedPanelKey;\n}\n\ntype PanelKeyParts = {\n name: string;\n number?: number;\n};\n\nconst removeWhiteSpaces = (str: string): string => {\n return str.replace(/\\s+/g, '');\n};\n\n/**\n * Breaks the specified panel key into the name and the optional `-number` used\n * for deduping panels with the same name.\n */\nfunction getPanelKeyParts(panelKey: string): PanelKeyParts {\n const parts = panelKey.match(/(.+)-([0-9]+)/);\n if (parts && parts[1] && parts[2]) {\n return {\n name: parts[1],\n number: parseInt(parts[2], 10),\n };\n }\n\n return {\n name: panelKey,\n };\n}\n\n// Find all the unique panel keys and the largest number used for each.\n// ex: cpu, cpu-1, cpu-2 count as the same panel key since these panels have the same name\nfunction getUniquePanelKeys(panels: Record<string, PanelDefinition>): Record<string, number> {\n const uniquePanelKeys: Record<string, number> = {};\n Object.keys(panels).forEach((panelKey) => {\n const { name, number } = getPanelKeyParts(panelKey);\n if (uniquePanelKeys[name] === undefined) {\n uniquePanelKeys[name] = 0;\n }\n const currentValue = uniquePanelKeys[name];\n if (typeof currentValue === 'number' && number) {\n // Check for the maximum value because we cannot rely on a sequential\n // set of numbers when panels are modified.\n uniquePanelKeys[name] = Math.max(currentValue, number);\n }\n });\n return uniquePanelKeys;\n}\n"],"names":["GRID_LAYOUT_SMALL_BREAKPOINT","GRID_LAYOUT_COLS","getYForNewRow","group","newRowY","layout","itemLayouts","itemMaxY","y","h","getPanelBounds","x","w","x1","x2","y1","y2","insertPanelInLayout","newLayout","referenceLayout","MAX_LAYOUT_WIDTH","referenceBounds","aboveInsertRow","insertRow","belowInsertRow","forEach","itemLayout","itemBounds","push","sort","a","b","insertAfterIndex","findIndex","item","i","length","nextItem","splice","map","getValidPanelKey","panelKey","panels","uniquePanelKeys","getUniquePanelKeys","normalizedPanelKey","getPanelKeyParts","removeWhiteSpaces","name","matchingKey","str","replace","parts","match","number","parseInt","Object","keys","undefined","currentValue","Math","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;AAIjC,SAASA,4BAA4B,EAAEC,gBAAgB,QAAQ,eAAe;AAE9E,yHAAyH;AACzH,OAAO,SAASC,cAAcC,KAA2B;IACvD,IAAIC,UAAU;IACd,KAAK,MAAMC,UAAUF,MAAMG,WAAW,CAAE;QACtC,MAAMC,WAAWF,OAAOG,CAAC,GAAGH,OAAOI,CAAC;QACpC,IAAIF,WAAWH,SAAS;YACtBA,UAAUG;QACZ;IACF;IACA,OAAOH;AACT;AAqBA,SAASM,eAAe,EAAEC,CAAC,EAAEH,CAAC,EAAEI,CAAC,EAAEH,CAAC,EAAwB;IAC1D,OAAO;QACLI,IAAIF;QACJG,IAAIH,IAAIC;QACRG,IAAIP;QACJQ,IAAIR,IAAIC;IACV;AACF;AAIA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASQ,oBACdC,SAA2C,EAC3CC,eAAqC,EACrCb,WAAmC;IAEnC,MAAMc,mBAAmBnB,gBAAgB,CAACD,6BAA6B;IAEvE,MAAMqB,k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,MAAM,EAAEO,IAAI,EAAEM,MAAM,EAAE,GAAGR,iBAAiBL;QAC1C,IAAIE,eAAe,CAACK,KAAK,KAAKU,WAAW;YACvCf,eAAe,CAACK,KAAK,GAAG;QAC1B;QACA,MAAMW,eAAehB,eAAe,CAACK,KAAK;QAC1C,IAAI,OAAOW,iBAAiB,YAAYL,QAAQ;YAC9C,qEAAqE;YACrE,2CAA2C;YAC3CX,eAAe,CAACK,KAAK,GAAGY,KAAKC,GAAG,CAACF,cAAcL;QACjD;IACF;IACA,OAAOX;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@perses-dev/dashboards",
|
|
3
|
-
"version": "0.51.0-
|
|
3
|
+
"version": "0.51.0-rc.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,25 +29,24 @@
|
|
|
29
29
|
"lint:fix": "eslint --fix src --ext .ts,.tsx"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@perses-dev/components": "0.51.0-
|
|
33
|
-
"@perses-dev/core": "0.51.0-
|
|
34
|
-
"@perses-dev/plugin-system": "0.51.0-
|
|
32
|
+
"@perses-dev/components": "0.51.0-rc.0",
|
|
33
|
+
"@perses-dev/core": "0.51.0-rc.0",
|
|
34
|
+
"@perses-dev/plugin-system": "0.51.0-rc.0",
|
|
35
35
|
"@types/react-grid-layout": "^1.3.2",
|
|
36
|
-
"date-fns": "^
|
|
37
|
-
"immer": "^
|
|
36
|
+
"date-fns": "^4.1.0",
|
|
37
|
+
"immer": "^10.1.1",
|
|
38
38
|
"mdi-material-ui": "^7.9.2",
|
|
39
39
|
"react-grid-layout": "^1.3.4",
|
|
40
40
|
"react-hook-form": "^7.46.1",
|
|
41
41
|
"react-intersection-observer": "^9.4.0",
|
|
42
|
-
"use-immer": "^0.
|
|
42
|
+
"use-immer": "^0.11.0",
|
|
43
43
|
"use-query-params": "^2.1.1",
|
|
44
44
|
"use-resize-observer": "^9.0.0",
|
|
45
45
|
"yaml": "^2.7.0",
|
|
46
46
|
"zustand": "^4.3.3"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
|
-
"@perses-dev/internal-utils": "0.51.0-
|
|
50
|
-
"@perses-dev/storybook": "0.51.0-beta.0",
|
|
49
|
+
"@perses-dev/internal-utils": "0.51.0-rc.0",
|
|
51
50
|
"history": "^5.3.0",
|
|
52
51
|
"intersection-observer": "^0.12.2"
|
|
53
52
|
},
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
// Copyright 2023 The Perses Authors
|
|
2
|
-
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
3
|
-
// you may not use this file except in compliance with the License.
|
|
4
|
-
// You may obtain a copy of the License at
|
|
5
|
-
//
|
|
6
|
-
// http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
-
//
|
|
8
|
-
// Unless required by applicable law or agreed to in writing, software
|
|
9
|
-
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
10
|
-
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
-
// See the License for the specific language governing permissions and
|
|
12
|
-
// limitations under the License.
|
|
13
|
-
"use strict";
|
|
14
|
-
Object.defineProperty(exports, "__esModule", {
|
|
15
|
-
value: true
|
|
16
|
-
});
|
|
17
|
-
Object.defineProperty(exports, "WithDashboard", {
|
|
18
|
-
enumerable: true,
|
|
19
|
-
get: function() {
|
|
20
|
-
return WithDashboard;
|
|
21
|
-
}
|
|
22
|
-
});
|
|
23
|
-
const _jsxruntime = require("react/jsx-runtime");
|
|
24
|
-
const _dashboards = require("@perses-dev/dashboards");
|
|
25
|
-
const _constants = require("./constants");
|
|
26
|
-
// Type guard because storybook types parameters as `any`
|
|
27
|
-
function isWithDashboardParameter(parameter) {
|
|
28
|
-
return !!parameter && typeof parameter === 'object' && 'props' in parameter;
|
|
29
|
-
}
|
|
30
|
-
const WithDashboard = (Story, context)=>{
|
|
31
|
-
const initParameter = context.parameters.withDashboard;
|
|
32
|
-
const parameter = isWithDashboardParameter(initParameter) ? initParameter : undefined;
|
|
33
|
-
const props = parameter?.props;
|
|
34
|
-
return /*#__PURE__*/ (0, _jsxruntime.jsx)(_dashboards.DashboardProvider, {
|
|
35
|
-
initialState: {
|
|
36
|
-
dashboardResource: _constants.EMPTY_DASHBOARD_RESOURCE
|
|
37
|
-
},
|
|
38
|
-
...props,
|
|
39
|
-
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(Story, {})
|
|
40
|
-
});
|
|
41
|
-
};
|