@perses-dev/plugin-system 0.53.1 → 0.54.0-beta.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/TimeRangeControls/TimeRangeControls.js +2 -2
- package/dist/cjs/context/ValidationProvider.js +5 -4
- package/dist/cjs/model/index.js +2 -0
- package/dist/cjs/model/log-volume-utils.js +124 -0
- package/dist/cjs/remote/PluginRuntime.js +11 -10
- package/dist/cjs/runtime/TimeRangeProvider/TimeRangeProvider.js +6 -6
- package/dist/cjs/runtime/TimeRangeProvider/query-params.js +7 -7
- package/dist/cjs/runtime/TimeRangeProvider/refresh-interval.js +2 -2
- package/dist/components/CalculationSelector/CalculationSelector.js +1 -1
- package/dist/components/CalculationSelector/CalculationSelector.js.map +1 -1
- package/dist/components/DatasourceEditorForm/DatasourceEditorForm.js.map +1 -1
- package/dist/components/DatasourceSelect/DatasourceSelect.d.ts +1 -1
- package/dist/components/DatasourceSelect/DatasourceSelect.js.map +1 -1
- package/dist/components/HTTPSettingsEditor/HTTPSettingsEditor.js.map +1 -1
- package/dist/components/LegendOptionsEditor/LegendOptionsEditor.js +1 -1
- package/dist/components/LegendOptionsEditor/LegendOptionsEditor.js.map +1 -1
- package/dist/components/MultiQueryEditor/QueryEditorContainer.d.ts +1 -1
- package/dist/components/MultiQueryEditor/QueryEditorContainer.js.map +1 -1
- package/dist/components/PanelSpecEditor/PanelSpecEditor.d.ts +1 -1
- package/dist/components/PanelSpecEditor/PanelSpecEditor.js.map +1 -1
- package/dist/components/PluginEditor/PluginEditor.js.map +1 -1
- package/dist/components/PluginEditor/plugin-editor-api.d.ts +1 -1
- package/dist/components/PluginEditor/plugin-editor-api.js.map +1 -1
- package/dist/components/PluginRegistry/PluginRegistry.js.map +1 -1
- package/dist/components/PluginSpecEditor/PluginSpecEditor.d.ts +1 -1
- package/dist/components/PluginSpecEditor/PluginSpecEditor.js.map +1 -1
- package/dist/components/TimeRangeControls/TimeRangeControls.js +1 -1
- package/dist/components/TimeRangeControls/TimeRangeControls.js.map +1 -1
- package/dist/components/Variables/VariableEditorForm/VariableEditorForm.d.ts +2 -1
- package/dist/components/Variables/VariableEditorForm/VariableEditorForm.d.ts.map +1 -1
- package/dist/components/Variables/VariableEditorForm/VariableEditorForm.js.map +1 -1
- package/dist/components/Variables/VariableEditorForm/VariablePreview.d.ts +1 -1
- package/dist/components/Variables/VariableEditorForm/VariablePreview.js.map +1 -1
- package/dist/components/Variables/VariableEditorForm/variable-editor-form-model.d.ts +1 -1
- package/dist/components/Variables/VariableEditorForm/variable-editor-form-model.js.map +1 -1
- package/dist/components/Variables/variable-model.d.ts +1 -1
- package/dist/components/Variables/variable-model.js.map +1 -1
- package/dist/context/ValidationProvider.d.ts +2 -1
- package/dist/context/ValidationProvider.d.ts.map +1 -1
- package/dist/context/ValidationProvider.js +3 -2
- package/dist/context/ValidationProvider.js.map +1 -1
- package/dist/model/datasource.d.ts +1 -1
- package/dist/model/datasource.js.map +1 -1
- package/dist/model/explore.d.ts +1 -1
- package/dist/model/explore.js.map +1 -1
- package/dist/model/index.d.ts +2 -0
- package/dist/model/index.d.ts.map +1 -1
- package/dist/model/index.js +2 -0
- package/dist/model/index.js.map +1 -1
- package/dist/model/legend.js +1 -1
- package/dist/model/legend.js.map +1 -1
- package/dist/model/log-queries.d.ts +2 -1
- package/dist/model/log-queries.d.ts.map +1 -1
- package/dist/model/log-queries.js.map +1 -1
- package/dist/model/log-volume-utils.d.ts +6 -0
- package/dist/model/log-volume-utils.d.ts.map +1 -0
- package/dist/model/log-volume-utils.js +119 -0
- package/dist/model/log-volume-utils.js.map +1 -0
- package/dist/model/panels.d.ts +1 -1
- package/dist/model/panels.js.map +1 -1
- package/dist/model/plugin-base.d.ts +1 -1
- package/dist/model/plugin-base.js.map +1 -1
- package/dist/model/plugins.d.ts +1 -1
- package/dist/model/plugins.js.map +1 -1
- package/dist/model/profile-queries.d.ts +1 -1
- package/dist/model/profile-queries.js.map +1 -1
- package/dist/model/time-series-queries.d.ts +1 -1
- package/dist/model/time-series-queries.js.map +1 -1
- package/dist/model/trace-queries.d.ts +1 -1
- package/dist/model/trace-queries.js.map +1 -1
- package/dist/model/variables.d.ts +1 -1
- package/dist/model/variables.js.map +1 -1
- package/dist/remote/PluginRuntime.d.ts.map +1 -1
- package/dist/remote/PluginRuntime.js +11 -10
- package/dist/remote/PluginRuntime.js.map +1 -1
- package/dist/runtime/DataQueriesProvider/DataQueriesProvider.d.ts +1 -1
- package/dist/runtime/DataQueriesProvider/DataQueriesProvider.js.map +1 -1
- package/dist/runtime/DataQueriesProvider/model.d.ts +1 -1
- package/dist/runtime/DataQueriesProvider/model.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProvider.d.ts +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProvider.js +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProvider.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProviders.d.ts +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProviders.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeSettingsProvider.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/query-params.d.ts +1 -1
- package/dist/runtime/TimeRangeProvider/query-params.js +1 -1
- package/dist/runtime/TimeRangeProvider/query-params.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/refresh-interval.d.ts +1 -1
- package/dist/runtime/TimeRangeProvider/refresh-interval.js +1 -1
- package/dist/runtime/TimeRangeProvider/refresh-interval.js.map +1 -1
- package/dist/runtime/UsageMetricsProvider.d.ts +1 -1
- package/dist/runtime/UsageMetricsProvider.d.ts.map +1 -1
- package/dist/runtime/UsageMetricsProvider.js +1 -1
- package/dist/runtime/UsageMetricsProvider.js.map +1 -1
- package/dist/runtime/builtin-variables.d.ts +1 -1
- package/dist/runtime/builtin-variables.js.map +1 -1
- package/dist/runtime/datasources.d.ts +1 -1
- package/dist/runtime/datasources.js.map +1 -1
- package/dist/runtime/item-actions.js +1 -1
- package/dist/runtime/item-actions.js.map +1 -1
- package/dist/runtime/log-queries.d.ts +1 -1
- package/dist/runtime/log-queries.js.map +1 -1
- package/dist/runtime/plugin-registry.d.ts +1 -1
- package/dist/runtime/plugin-registry.js.map +1 -1
- package/dist/runtime/profile-queries.d.ts +1 -1
- package/dist/runtime/profile-queries.js.map +1 -1
- package/dist/runtime/time-series-queries.d.ts +1 -1
- package/dist/runtime/time-series-queries.js.map +1 -1
- package/dist/runtime/trace-queries.d.ts +1 -1
- package/dist/runtime/trace-queries.js.map +1 -1
- package/dist/test/mock-data.d.ts +1 -1
- package/dist/test/mock-data.js.map +1 -1
- package/dist/test/utils.js +1 -1
- package/dist/test/utils.js.map +1 -1
- package/dist/test-utils/mock-plugin-registry.js.map +1 -1
- package/dist/utils/action.js.map +1 -1
- package/package.json +8 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/HTTPSettingsEditor/HTTPSettingsEditor.tsx"],"sourcesContent":["// Copyright 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 { RequestHeaders, HTTPDatasourceSpec } from '@perses-dev/core';\nimport { Grid, IconButton, MenuItem, TextField, Typography } from '@mui/material';\nimport React, { Fragment, ReactElement, useState } from 'react';\nimport { produce } from 'immer';\nimport { Controller, useForm, useFieldArray } from 'react-hook-form';\nimport MinusIcon from 'mdi-material-ui/Minus';\nimport PlusIcon from 'mdi-material-ui/Plus';\nimport { OptionsEditorRadios } from '../OptionsEditorRadios';\n\ntype HeaderEntry = {\n name: string;\n value: string;\n};\n\ntype HeaderFormValues = {\n headers: HeaderEntry[];\n};\n\nexport interface HTTPSettingsEditor {\n value: HTTPDatasourceSpec;\n onChange: (next: HTTPDatasourceSpec) => void;\n isReadonly?: boolean;\n initialSpecDirect: HTTPDatasourceSpec;\n initialSpecProxy: HTTPDatasourceSpec;\n}\n\nexport function HTTPSettingsEditor(props: HTTPSettingsEditor): ReactElement {\n const { value, onChange, isReadonly, initialSpecDirect, initialSpecProxy } = props;\n const strDirect = 'Direct access';\n const strProxy = 'Proxy';\n\n // Initialize Proxy mode by default, if neither direct nor proxy mode is selected.\n if (value.directUrl === undefined && value.proxy === undefined) {\n Object.assign(value, initialSpecProxy);\n }\n\n // Use local state to maintain an array of header entries during editing, instead of\n // manipulating a map directly which causes weird UX.\n const headersForm = useForm<HeaderFormValues>({\n defaultValues: {\n headers: Object.entries(value.proxy?.spec.headers ?? {}).map(([name, headerValue]) => ({\n name,\n value: headerValue as string,\n })),\n },\n });\n\n const { fields, append, remove } = useFieldArray({\n control: headersForm.control,\n name: 'headers',\n });\n\n // Watch the headers array for changes to detect duplicates\n const watchedHeaders = headersForm.watch('headers');\n\n // Check for duplicate header names\n // TODO: duplication detection logic to be replaced by proper zod schema validation in the future\n // ref https://github.com/perses/perses/issues/3014\n const nameMap = new Map<string, number>();\n const duplicateNames = new Set<string>();\n watchedHeaders.forEach(({ name }) => {\n if (name !== '') {\n const count = (nameMap.get(name) || 0) + 1;\n nameMap.set(name, count);\n if (count > 1) {\n duplicateNames.add(name);\n }\n }\n });\n const hasDuplicates = duplicateNames.size > 0;\n\n // Sync headers to parent\n const syncHeadersToParent = (headers: HeaderEntry[]): void => {\n const headersObject: RequestHeaders = {};\n headers.forEach(({ name, value: headerValue }) => {\n if (name !== '') {\n headersObject[name] = headerValue;\n }\n });\n\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = Object.keys(headersObject).length > 0 ? headersObject : undefined;\n }\n })\n );\n };\n\n const tabs = [\n {\n label: strProxy,\n content: (\n <>\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.proxy?.spec.url || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.url = e.target.value;\n }\n })\n );\n }}\n sx={{ mb: 2 }}\n />\n )}\n />\n <Typography variant=\"h5\" mb={2}>\n Allowed endpoints\n </Typography>\n <Grid container spacing={2} mb={2}>\n {value.proxy?.spec.allowedEndpoints && value.proxy?.spec.allowedEndpoints.length !== 0 ? (\n value.proxy.spec.allowedEndpoints.map(({ endpointPattern, method }, i) => {\n return (\n <Fragment key={i}>\n <Grid item xs={8}>\n <Controller\n name={`Endpoint pattern ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Endpoint pattern\"\n value={endpointPattern}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: e.target.value,\n method: item.method,\n };\n } else {\n return item;\n }\n }\n );\n }\n })\n );\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={3}>\n <Controller\n name={`Method ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n select\n fullWidth\n label=\"Method\"\n value={method}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: item.endpointPattern,\n method: e.target.value,\n };\n } else {\n return item;\n }\n }\n );\n }\n })\n );\n }}\n >\n <MenuItem value=\"GET\">GET</MenuItem>\n <MenuItem value=\"POST\">POST</MenuItem>\n <MenuItem value=\"PUT\">PUT</MenuItem>\n <MenuItem value=\"PATCH\">PATCH</MenuItem>\n <MenuItem value=\"DELETE\">DELETE</MenuItem>\n </TextField>\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <Controller\n name={`Remove Endpoint ${i}`}\n render={({ field }) => (\n <IconButton\n {...field}\n disabled={isReadonly}\n // Remove the given allowed endpoint from the list\n onClick={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints?.filter((item, itemIndex) => {\n return itemIndex !== i;\n }) || []),\n ];\n }\n })\n );\n }}\n >\n <MinusIcon />\n </IconButton>\n )}\n />\n </Grid>\n </Fragment>\n );\n })\n ) : (\n <Grid item xs={4}>\n <Typography sx={{ fontStyle: 'italic' }}>None</Typography>\n </Grid>\n )}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton\n disabled={isReadonly}\n // Add a new (empty) allowed endpoint to the list\n onClick={() =>\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints ?? []),\n { endpointPattern: '', method: '' },\n ];\n }\n })\n )\n }\n >\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n <Typography variant=\"h5\" mb={2}>\n Request Headers\n </Typography>\n <Grid container spacing={2} mb={2}>\n {fields.length > 0 ? (\n fields.map((field, index) => (\n <Fragment key={field.id}>\n <Grid item xs={4}>\n <Controller\n control={headersForm.control}\n name={`headers.${index}.name`}\n render={({ field: controllerField, fieldState }) => (\n <TextField\n {...controllerField}\n fullWidth\n label=\"Header name\"\n error={!!fieldState.error || duplicateNames.has(controllerField.value)}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n controllerField.onChange(e);\n const updatedHeaders = [...watchedHeaders];\n updatedHeaders[index] = { name: e.target.value, value: updatedHeaders[index]?.value ?? '' };\n syncHeadersToParent(updatedHeaders);\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={7}>\n <Controller\n control={headersForm.control}\n name={`headers.${index}.value`}\n render={({ field: controllerField, fieldState }) => (\n <TextField\n {...controllerField}\n fullWidth\n label=\"Header value\"\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n controllerField.onChange(e);\n const updatedHeaders = [...watchedHeaders];\n updatedHeaders[index] = { name: updatedHeaders[index]?.name ?? '', value: e.target.value };\n syncHeadersToParent(updatedHeaders);\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <IconButton\n disabled={isReadonly}\n aria-label={`Remove header ${watchedHeaders[index]?.name || index}`}\n onClick={() => {\n remove(index);\n const updatedHeaders = watchedHeaders.filter((_, i) => i !== index);\n syncHeadersToParent(updatedHeaders);\n }}\n >\n <MinusIcon />\n </IconButton>\n </Grid>\n </Fragment>\n ))\n ) : (\n <Grid item xs={4}>\n <Typography sx={{ fontStyle: 'italic' }}>None</Typography>\n </Grid>\n )}\n {hasDuplicates && (\n <Grid item xs={12}>\n <Typography variant=\"body2\" color=\"error\">\n Duplicate header names detected. Each header name must be unique.\n </Typography>\n </Grid>\n )}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton disabled={isReadonly} onClick={() => append({ name: '', value: '' })}>\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n\n <Controller\n name=\"Secret\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Secret\"\n value={value.proxy?.spec.secret || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.secret = e.target.value;\n }\n })\n );\n }}\n />\n )}\n />\n </>\n ),\n },\n {\n label: strDirect,\n content: (\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.directUrl || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n draft.directUrl = e.target.value;\n })\n );\n }}\n />\n )}\n />\n ),\n },\n ];\n\n // Use of findIndex instead of providing hardcoded values to avoid desynchronisatio or\n // bug in case the tabs get eventually swapped in the future.\n const directModeId = tabs.findIndex((tab) => tab.label === strDirect);\n const proxyModeId = tabs.findIndex((tab) => tab.label === strProxy);\n\n // Set defaultTab to the mode that this datasource is currently relying on.\n const defaultTab = value.proxy ? proxyModeId : directModeId;\n\n // For better user experience, save previous states in mind for both mode.\n // This avoids losing everything when the user changes their mind back.\n const [previousSpecDirect, setPreviousSpecDirect] = useState(initialSpecDirect);\n const [previousSpecProxy, setPreviousSpecProxy] = useState(initialSpecProxy);\n\n // When changing mode, remove previous mode's config + append default values for the new mode.\n const handleModeChange = (v: number): void => {\n if (tabs[v]?.label === strDirect) {\n setPreviousSpecProxy(value);\n\n // Copy all settings (for example, scrapeInterval), except 'proxy'\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { proxy, ...newValue } = value;\n onChange({ ...newValue, directUrl: previousSpecDirect.directUrl });\n } else if (tabs[v]?.label === strProxy) {\n setPreviousSpecDirect(value);\n\n // Copy all settings (for example, scrapeInterval), except 'directUrl'\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { directUrl, ...newValue } = value;\n onChange({ ...newValue, proxy: previousSpecProxy.proxy });\n }\n };\n\n return (\n <>\n <Typography variant=\"h4\" mt={2}>\n HTTP Settings\n </Typography>\n <OptionsEditorRadios\n isReadonly={isReadonly}\n tabs={tabs}\n defaultTab={defaultTab}\n onModeChange={handleModeChange}\n />\n </>\n );\n}\n"],"names":["Grid","IconButton","MenuItem","TextField","Typography","React","Fragment","useState","produce","Controller","useForm","useFieldArray","MinusIcon","PlusIcon","OptionsEditorRadios","HTTPSettingsEditor","props","value","onChange","isReadonly","initialSpecDirect","initialSpecProxy","strDirect","strProxy","directUrl","undefined","proxy","Object","assign","headersForm","defaultValues","headers","entries","spec","map","name","headerValue","fields","append","remove","control","watchedHeaders","watch","nameMap","Map","duplicateNames","Set","forEach","count","get","set","add","hasDuplicates","size","syncHeadersToParent","headersObject","draft","keys","length","tabs","label","content","render","field","fieldState","fullWidth","url","error","helperText","message","InputProps","readOnly","InputLabelProps","shrink","e","target","sx","mb","variant","container","spacing","allowedEndpoints","endpointPattern","method","i","item","xs","itemIndex","select","disabled","onClick","filter","fontStyle","paddingTop","paddingLeft","index","controllerField","has","updatedHeaders","aria-label","_","id","color","secret","directModeId","findIndex","tab","proxyModeId","defaultTab","previousSpecDirect","setPreviousSpecDirect","previousSpecProxy","setPreviousSpecProxy","handleModeChange","v","newValue","mt","onModeChange"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AA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E;IAC3E,MAAMqF,aAAa3F,MAAMS,KAAK,GAAGiF,cAAcH;IAE/C,0EAA0E;IAC1E,uEAAuE;IACvE,MAAM,CAACK,oBAAoBC,sBAAsB,GAAGvG,SAASa;IAC7D,MAAM,CAAC2F,mBAAmBC,qBAAqB,GAAGzG,SAASc;IAE3D,8FAA8F;IAC9F,MAAM4F,mBAAmB,CAACC;QACxB,IAAIvD,IAAI,CAACuD,EAAE,EAAEtD,UAAUtC,WAAW;YAChC0F,qBAAqB/F;YAErB,kEAAkE;YAClE,6DAA6D;YAC7D,MAAM,EAAES,KAAK,EAAE,GAAGyF,UAAU,GAAGlG;YAC/BC,SAAS;gBAAE,GAAGiG,QAAQ;gBAAE3F,WAAWqF,mBAAmBrF,SAAS;YAAC;QAClE,OAAO,IAAImC,IAAI,CAACuD,EAAE,EAAEtD,UAAUrC,UAAU;YACtCuF,sBAAsB7F;YAEtB,sEAAsE;YACtE,6DAA6D;YAC7D,MAAM,EAAEO,SAAS,EAAE,GAAG2F,UAAU,GAAGlG;YACnCC,SAAS;gBAAE,GAAGiG,QAAQ;gBAAEzF,OAAOqF,kBAAkBrF,KAAK;YAAC;QACzD;IACF;IAEA,qBACE;;0BACE,KAACtB;gBAAW0E,SAAQ;gBAAKsC,IAAI;0BAAG;;0BAGhC,KAACtG;gBACCK,YAAYA;gBACZwC,MAAMA;gBACNiD,YAAYA;gBACZS,cAAcJ;;;;AAItB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/HTTPSettingsEditor/HTTPSettingsEditor.tsx"],"sourcesContent":["// Copyright 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 { RequestHeaders, HTTPDatasourceSpec } from '@perses-dev/core'; // TODO this is the proxy definition that should go to a different lib\nimport { Grid, IconButton, MenuItem, TextField, Typography } from '@mui/material';\nimport React, { Fragment, ReactElement, useState } from 'react';\nimport { produce } from 'immer';\nimport { Controller, useForm, useFieldArray } from 'react-hook-form';\nimport MinusIcon from 'mdi-material-ui/Minus';\nimport PlusIcon from 'mdi-material-ui/Plus';\nimport { OptionsEditorRadios } from '../OptionsEditorRadios';\n\ntype HeaderEntry = {\n name: string;\n value: string;\n};\n\ntype HeaderFormValues = {\n headers: HeaderEntry[];\n};\n\nexport interface HTTPSettingsEditor {\n value: HTTPDatasourceSpec;\n onChange: (next: HTTPDatasourceSpec) => void;\n isReadonly?: boolean;\n initialSpecDirect: HTTPDatasourceSpec;\n initialSpecProxy: HTTPDatasourceSpec;\n}\n\nexport function HTTPSettingsEditor(props: HTTPSettingsEditor): ReactElement {\n const { value, onChange, isReadonly, initialSpecDirect, initialSpecProxy } = props;\n const strDirect = 'Direct access';\n const strProxy = 'Proxy';\n\n // Initialize Proxy mode by default, if neither direct nor proxy mode is selected.\n if (value.directUrl === undefined && value.proxy === undefined) {\n Object.assign(value, initialSpecProxy);\n }\n\n // Use local state to maintain an array of header entries during editing, instead of\n // manipulating a map directly which causes weird UX.\n const headersForm = useForm<HeaderFormValues>({\n defaultValues: {\n headers: Object.entries(value.proxy?.spec.headers ?? {}).map(([name, headerValue]) => ({\n name,\n value: headerValue as string,\n })),\n },\n });\n\n const { fields, append, remove } = useFieldArray({\n control: headersForm.control,\n name: 'headers',\n });\n\n // Watch the headers array for changes to detect duplicates\n const watchedHeaders = headersForm.watch('headers');\n\n // Check for duplicate header names\n // TODO: duplication detection logic to be replaced by proper zod schema validation in the future\n // ref https://github.com/perses/perses/issues/3014\n const nameMap = new Map<string, number>();\n const duplicateNames = new Set<string>();\n watchedHeaders.forEach(({ name }) => {\n if (name !== '') {\n const count = (nameMap.get(name) || 0) + 1;\n nameMap.set(name, count);\n if (count > 1) {\n duplicateNames.add(name);\n }\n }\n });\n const hasDuplicates = duplicateNames.size > 0;\n\n // Sync headers to parent\n const syncHeadersToParent = (headers: HeaderEntry[]): void => {\n const headersObject: RequestHeaders = {};\n headers.forEach(({ name, value: headerValue }) => {\n if (name !== '') {\n headersObject[name] = headerValue;\n }\n });\n\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = Object.keys(headersObject).length > 0 ? headersObject : undefined;\n }\n })\n );\n };\n\n const tabs = [\n {\n label: strProxy,\n content: (\n <>\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.proxy?.spec.url || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.url = e.target.value;\n }\n })\n );\n }}\n sx={{ mb: 2 }}\n />\n )}\n />\n <Typography variant=\"h5\" mb={2}>\n Allowed endpoints\n </Typography>\n <Grid container spacing={2} mb={2}>\n {value.proxy?.spec.allowedEndpoints && value.proxy?.spec.allowedEndpoints.length !== 0 ? (\n value.proxy.spec.allowedEndpoints.map(({ endpointPattern, method }, i) => {\n return (\n <Fragment key={i}>\n <Grid item xs={8}>\n <Controller\n name={`Endpoint pattern ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Endpoint pattern\"\n value={endpointPattern}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: e.target.value,\n method: item.method,\n };\n } else {\n return item;\n }\n }\n );\n }\n })\n );\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={3}>\n <Controller\n name={`Method ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n select\n fullWidth\n label=\"Method\"\n value={method}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: item.endpointPattern,\n method: e.target.value,\n };\n } else {\n return item;\n }\n }\n );\n }\n })\n );\n }}\n >\n <MenuItem value=\"GET\">GET</MenuItem>\n <MenuItem value=\"POST\">POST</MenuItem>\n <MenuItem value=\"PUT\">PUT</MenuItem>\n <MenuItem value=\"PATCH\">PATCH</MenuItem>\n <MenuItem value=\"DELETE\">DELETE</MenuItem>\n </TextField>\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <Controller\n name={`Remove Endpoint ${i}`}\n render={({ field }) => (\n <IconButton\n {...field}\n disabled={isReadonly}\n // Remove the given allowed endpoint from the list\n onClick={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints?.filter((item, itemIndex) => {\n return itemIndex !== i;\n }) || []),\n ];\n }\n })\n );\n }}\n >\n <MinusIcon />\n </IconButton>\n )}\n />\n </Grid>\n </Fragment>\n );\n })\n ) : (\n <Grid item xs={4}>\n <Typography sx={{ fontStyle: 'italic' }}>None</Typography>\n </Grid>\n )}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton\n disabled={isReadonly}\n // Add a new (empty) allowed endpoint to the list\n onClick={() =>\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints ?? []),\n { endpointPattern: '', method: '' },\n ];\n }\n })\n )\n }\n >\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n <Typography variant=\"h5\" mb={2}>\n Request Headers\n </Typography>\n <Grid container spacing={2} mb={2}>\n {fields.length > 0 ? (\n fields.map((field, index) => (\n <Fragment key={field.id}>\n <Grid item xs={4}>\n <Controller\n control={headersForm.control}\n name={`headers.${index}.name`}\n render={({ field: controllerField, fieldState }) => (\n <TextField\n {...controllerField}\n fullWidth\n label=\"Header name\"\n error={!!fieldState.error || duplicateNames.has(controllerField.value)}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n controllerField.onChange(e);\n const updatedHeaders = [...watchedHeaders];\n updatedHeaders[index] = { name: e.target.value, value: updatedHeaders[index]?.value ?? '' };\n syncHeadersToParent(updatedHeaders);\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={7}>\n <Controller\n control={headersForm.control}\n name={`headers.${index}.value`}\n render={({ field: controllerField, fieldState }) => (\n <TextField\n {...controllerField}\n fullWidth\n label=\"Header value\"\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n controllerField.onChange(e);\n const updatedHeaders = [...watchedHeaders];\n updatedHeaders[index] = { name: updatedHeaders[index]?.name ?? '', value: e.target.value };\n syncHeadersToParent(updatedHeaders);\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <IconButton\n disabled={isReadonly}\n aria-label={`Remove header ${watchedHeaders[index]?.name || index}`}\n onClick={() => {\n remove(index);\n const updatedHeaders = watchedHeaders.filter((_, i) => i !== index);\n syncHeadersToParent(updatedHeaders);\n }}\n >\n <MinusIcon />\n </IconButton>\n </Grid>\n </Fragment>\n ))\n ) : (\n <Grid item xs={4}>\n <Typography sx={{ fontStyle: 'italic' }}>None</Typography>\n </Grid>\n )}\n {hasDuplicates && (\n <Grid item xs={12}>\n <Typography variant=\"body2\" color=\"error\">\n Duplicate header names detected. Each header name must be unique.\n </Typography>\n </Grid>\n )}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton disabled={isReadonly} onClick={() => append({ name: '', value: '' })}>\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n\n <Controller\n name=\"Secret\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Secret\"\n value={value.proxy?.spec.secret || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.secret = e.target.value;\n }\n })\n );\n }}\n />\n )}\n />\n </>\n ),\n },\n {\n label: strDirect,\n content: (\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.directUrl || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n draft.directUrl = e.target.value;\n })\n );\n }}\n />\n )}\n />\n ),\n },\n ];\n\n // Use of findIndex instead of providing hardcoded values to avoid desynchronisatio or\n // bug in case the tabs get eventually swapped in the future.\n const directModeId = tabs.findIndex((tab) => tab.label === strDirect);\n const proxyModeId = tabs.findIndex((tab) => tab.label === strProxy);\n\n // Set defaultTab to the mode that this datasource is currently relying on.\n const defaultTab = value.proxy ? proxyModeId : directModeId;\n\n // For better user experience, save previous states in mind for both mode.\n // This avoids losing everything when the user changes their mind back.\n const [previousSpecDirect, setPreviousSpecDirect] = useState(initialSpecDirect);\n const [previousSpecProxy, setPreviousSpecProxy] = useState(initialSpecProxy);\n\n // When changing mode, remove previous mode's config + append default values for the new mode.\n const handleModeChange = (v: number): void => {\n if (tabs[v]?.label === strDirect) {\n setPreviousSpecProxy(value);\n\n // Copy all settings (for example, scrapeInterval), except 'proxy'\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { proxy, ...newValue } = value;\n onChange({ ...newValue, directUrl: previousSpecDirect.directUrl });\n } else if (tabs[v]?.label === strProxy) {\n setPreviousSpecDirect(value);\n\n // Copy all settings (for example, scrapeInterval), except 'directUrl'\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { directUrl, ...newValue } = value;\n onChange({ ...newValue, proxy: previousSpecProxy.proxy });\n }\n };\n\n return (\n <>\n <Typography variant=\"h4\" mt={2}>\n HTTP Settings\n </Typography>\n <OptionsEditorRadios\n isReadonly={isReadonly}\n tabs={tabs}\n defaultTab={defaultTab}\n onModeChange={handleModeChange}\n />\n </>\n );\n}\n"],"names":["Grid","IconButton","MenuItem","TextField","Typography","React","Fragment","useState","produce","Controller","useForm","useFieldArray","MinusIcon","PlusIcon","OptionsEditorRadios","HTTPSettingsEditor","props","value","onChange","isReadonly","initialSpecDirect","initialSpecProxy","strDirect","strProxy","directUrl","undefined","proxy","Object","assign","headersForm","defaultValues","headers","entries","spec","map","name","headerValue","fields","append","remove","control","watchedHeaders","watch","nameMap","Map","duplicateNames","Set","forEach","count","get","set","add","hasDuplicates","size","syncHeadersToParent","headersObject","draft","keys","length","tabs","label","content","render","field","fieldState","fullWidth","url","error","helperText","message","InputProps","readOnly","InputLabelProps","shrink","e","target","sx","mb","variant","container","spacing","allowedEndpoints","endpointPattern","method","i","item","xs","itemIndex","select","disabled","onClick","filter","fontStyle","paddingTop","paddingLeft","index","controllerField","has","updatedHeaders","aria-label","_","id","color","secret","directModeId","findIndex","tab","proxyModeId","defaultTab","previousSpecDirect","setPreviousSpecDirect","previousSpecProxy","setPreviousSpecProxy","handleModeChange","v","newValue","mt","onModeChange"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAGjC,SAASA,IAAI,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,SAAS,EAAEC,UAAU,QAAQ,gBAAgB;AAClF,OAAOC,SAASC,QAAQ,EAAgBC,QAAQ,QAAQ,QAAQ;AAChE,SAASC,OAAO,QAAQ,QAAQ;AAChC,SAASC,UAAU,EAAEC,OAAO,EAAEC,aAAa,QAAQ,kBAAkB;AACrE,OAAOC,eAAe,wBAAwB;AAC9C,OAAOC,cAAc,uBAAuB;AAC5C,SAASC,mBAAmB,QAAQ,yBAAyB;AAmB7D,OAAO,SAASC,mBAAmBC,KAAyB;IAC1D,MAAM,EAAEC,KAAK,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,iBAAiB,EAAEC,gBAAgB,EAAE,GAAGL;IAC7E,MAAMM,YAAY;IAClB,MAAMC,WAAW;IAEjB,kFAAkF;IAClF,IAAIN,MAAMO,SAAS,KAAKC,aAAaR,MAAMS,KAAK,KAAKD,WAAW;QAC9DE,OAAOC,MAAM,CAACX,OAAOI;IACvB;IAEA,oFAAoF;IACpF,qDAAqD;IACrD,MAAMQ,cAAcnB,QAA0B;QAC5CoB,eAAe;YACbC,SAASJ,OAAOK,OAAO,CAACf,MAAMS,KAAK,EAAEO,KAAKF,WAAW,CAAC,GAAGG,GAAG,CAAC,CAAC,CAACC,MAAMC,YAAY,GAAM,CAAA;oBACrFD;oBACAlB,OAAOmB;gBACT,CAAA;QACF;IACF;IAEA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|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
// limitations under the License.
|
|
13
13
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
14
14
|
import { Switch, ToggleButtonGroup, ToggleButton } from '@mui/material';
|
|
15
|
-
import { DEFAULT_LEGEND, getLegendMode, getLegendPosition, getLegendSize } from '@perses-dev/core';
|
|
15
|
+
import { DEFAULT_LEGEND, getLegendMode, getLegendPosition, getLegendSize } from '@perses-dev/core'; // TODO should go to components
|
|
16
16
|
import { ErrorAlert, OptionsEditorControl, OptionsEditorGroup, SettingsAutocomplete } from '@perses-dev/components';
|
|
17
17
|
import { useMemo } from 'react';
|
|
18
18
|
import { LEGEND_MODE_CONFIG, LEGEND_POSITIONS_CONFIG, validateLegendSpec, LEGEND_VALUE_CONFIG, LEGEND_SIZE_CONFIG, comparisonLegends } from '../../model';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/LegendOptionsEditor/LegendOptionsEditor.tsx"],"sourcesContent":["// Copyright 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 { Switch, SwitchProps, ToggleButtonGroup, ToggleButton } from '@mui/material';\nimport { DEFAULT_LEGEND, getLegendMode, getLegendPosition, getLegendSize } from '@perses-dev/core';\nimport { ErrorAlert, OptionsEditorControl, OptionsEditorGroup, SettingsAutocomplete } from '@perses-dev/components';\nimport { ReactElement, useMemo } from 'react';\nimport {\n LEGEND_MODE_CONFIG,\n LEGEND_POSITIONS_CONFIG,\n LegendSpecOptions,\n LegendSingleSelectConfig,\n validateLegendSpec,\n LEGEND_VALUE_CONFIG,\n LegendValue,\n LEGEND_SIZE_CONFIG,\n comparisonLegends,\n ComparisonValues,\n} from '../../model';\n\ntype LegendPositionOption = LegendSingleSelectConfig & { id: LegendSpecOptions['position'] };\n\nconst POSITION_OPTIONS: LegendPositionOption[] = Object.entries(LEGEND_POSITIONS_CONFIG).map(([id, config]) => {\n return {\n id: id as LegendSpecOptions['position'],\n ...config,\n };\n});\n\ntype LegendSizeOption = LegendSingleSelectConfig & { id: Required<LegendSpecOptions>['size'] };\n\nconst SIZE_OPTIONS: LegendSizeOption[] = Object.entries(LEGEND_SIZE_CONFIG).map(([id, config]) => {\n return {\n id: id as Required<LegendSpecOptions>['size'],\n ...config,\n };\n});\n\ntype LegendValueOption = LegendSingleSelectConfig & { id: LegendValue | ComparisonValues };\n\nexport interface LegendOptionsEditorProps {\n value?: LegendSpecOptions;\n onChange: (legend?: LegendSpecOptions) => void;\n showValuesEditor?: boolean;\n calculation?: 'aggregation' | 'comparison';\n}\n\nexport function LegendOptionsEditor({\n value,\n onChange,\n showValuesEditor = true,\n calculation = 'aggregation',\n}: LegendOptionsEditorProps): ReactElement {\n const handleLegendShowChange: SwitchProps['onChange'] = (_: unknown, checked: boolean) => {\n // legend is hidden when legend obj is undefined\n const legendValue = checked === true ? { position: DEFAULT_LEGEND.position } : undefined;\n onChange(legendValue);\n };\n\n const handleLegendPositionChange = (_: unknown, newValue: LegendPositionOption): void => {\n onChange({\n ...value,\n position: newValue.id,\n });\n };\n\n const handleLegendSizeChange = (_: unknown, newValue: LegendSizeOption): void => {\n onChange({\n ...value,\n position: currentPosition,\n size: newValue.id,\n });\n };\n\n const handleLegendValueChange = (_: unknown, newValue: LegendValueOption[]): void => {\n onChange({\n ...value,\n position: currentPosition,\n values: newValue.map((value) => {\n return value.id;\n }),\n });\n };\n\n const isValidLegend = validateLegendSpec(value);\n const currentPosition = getLegendPosition(value?.position);\n const legendPositionConfig = LEGEND_POSITIONS_CONFIG[currentPosition];\n\n const currentMode = getLegendMode(value?.mode);\n\n const currentSize = getLegendSize(value?.size);\n const legendSizeConfig = LEGEND_SIZE_CONFIG[currentSize];\n\n const legendValuesConfig = useMemo(() => {\n const currentValues = value?.values;\n if (!currentValues?.length) return [];\n\n if (calculation === 'aggregation') {\n return currentValues.reduce((result, item) => {\n const config = LEGEND_VALUE_CONFIG[item as LegendValue];\n if (config) {\n result.push({ ...config, id: item });\n }\n return result;\n }, [] as LegendValueOption[]);\n }\n\n return currentValues.map((id) => {\n const { label, description } = comparisonLegends[id as ComparisonValues];\n return {\n id,\n label,\n description,\n };\n });\n }, [calculation, value?.values]);\n\n const valueOptions = useMemo(() => {\n if (calculation === 'aggregation') {\n return Object.entries(LEGEND_VALUE_CONFIG || {}).map(([id, config]) => {\n return {\n id: id as LegendValue,\n ...config,\n };\n });\n }\n\n return Object.entries(comparisonLegends).map(([id, config]) => ({\n id: id as ComparisonValues,\n ...config,\n }));\n }, [calculation]);\n\n return (\n <OptionsEditorGroup title=\"Legend\">\n {!isValidLegend && <ErrorAlert error={{ name: 'invalid-legend', message: 'Invalid legend spec' }} />}\n <OptionsEditorControl label=\"Show\" control={<Switch checked={!!value} onChange={handleLegendShowChange} />} />\n {value && (\n <>\n <OptionsEditorControl\n label=\"Position\"\n control={\n <SettingsAutocomplete\n value={{\n ...legendPositionConfig,\n id: currentPosition,\n }}\n options={POSITION_OPTIONS}\n onChange={handleLegendPositionChange}\n disableClearable\n />\n }\n />\n <OptionsEditorControl\n label=\"Mode\"\n control={\n <ToggleButtonGroup\n color=\"primary\"\n exclusive\n value={currentMode}\n aria-label=\"Mode\"\n onChange={(__, newValue) => {\n onChange({\n ...value,\n position: currentPosition,\n mode: newValue,\n });\n }}\n >\n {Object.entries(LEGEND_MODE_CONFIG).map(([modeId, config]) => (\n <ToggleButton\n key={modeId}\n value={modeId}\n selected={currentMode === modeId}\n aria-label={`display ${modeId} mode`}\n >\n {config.label}\n </ToggleButton>\n ))}\n </ToggleButtonGroup>\n }\n />\n {currentMode === 'table' && (\n <>\n <OptionsEditorControl\n label=\"Size\"\n control={\n <SettingsAutocomplete\n value={{\n ...legendSizeConfig,\n id: currentSize,\n }}\n options={SIZE_OPTIONS}\n onChange={handleLegendSizeChange}\n // TODO: enable sizes for list mode when we normalize the layout of\n // lists to more closely match tables.\n disableClearable\n />\n }\n />\n {showValuesEditor && (\n <OptionsEditorControl\n label=\"Values\"\n control={\n // For some reason, the inferred option type doesn't always seem to work\n // quite right when `multiple` is true. Explicitly setting the generics\n // to work around this.\n <SettingsAutocomplete<LegendValueOption, true, true>\n multiple={true}\n disableCloseOnSelect\n disableClearable\n value={legendValuesConfig}\n options={valueOptions}\n onChange={handleLegendValueChange}\n limitTags={1}\n ChipProps={{\n size: 'small',\n }}\n />\n }\n />\n )}\n </>\n )}\n </>\n )}\n </OptionsEditorGroup>\n );\n}\n"],"names":["Switch","ToggleButtonGroup","ToggleButton","DEFAULT_LEGEND","getLegendMode","getLegendPosition","getLegendSize","ErrorAlert","OptionsEditorControl","OptionsEditorGroup","SettingsAutocomplete","useMemo","LEGEND_MODE_CONFIG","LEGEND_POSITIONS_CONFIG","validateLegendSpec","LEGEND_VALUE_CONFIG","LEGEND_SIZE_CONFIG","comparisonLegends","POSITION_OPTIONS","Object","entries","map","id","config","SIZE_OPTIONS","LegendOptionsEditor","value","onChange","showValuesEditor","calculation","handleLegendShowChange","_","checked","legendValue","position","undefined","handleLegendPositionChange","newValue","handleLegendSizeChange","currentPosition","size","handleLegendValueChange","values","isValidLegend","legendPositionConfig","currentMode","mode","currentSize","legendSizeConfig","legendValuesConfig","currentValues","length","reduce","result","item","push","label","description","valueOptions","title","error","name","message","control","options","disableClearable","color","exclusive","aria-label","__","modeId","selected","multiple","disableCloseOnSelect","limitTags","ChipProps"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2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AU;oCACVC,oBAAoB;oCACpBR,gBAAgB;oCAChBvC,OAAOuB;oCACPe,SAASN;oCACT/B,UAAUc;oCACViC,WAAW;oCACXC,WAAW;wCACTnC,MAAM;oCACR;;;;;;;;;AAWtB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/LegendOptionsEditor/LegendOptionsEditor.tsx"],"sourcesContent":["// Copyright 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 { Switch, SwitchProps, ToggleButtonGroup, ToggleButton } from '@mui/material';\nimport { DEFAULT_LEGEND, getLegendMode, getLegendPosition, getLegendSize } from '@perses-dev/core'; // TODO should go to components\nimport { ErrorAlert, OptionsEditorControl, OptionsEditorGroup, SettingsAutocomplete } from '@perses-dev/components';\nimport { ReactElement, useMemo } from 'react';\nimport {\n LEGEND_MODE_CONFIG,\n LEGEND_POSITIONS_CONFIG,\n LegendSpecOptions,\n LegendSingleSelectConfig,\n validateLegendSpec,\n LEGEND_VALUE_CONFIG,\n LegendValue,\n LEGEND_SIZE_CONFIG,\n comparisonLegends,\n ComparisonValues,\n} from '../../model';\n\ntype LegendPositionOption = LegendSingleSelectConfig & { id: LegendSpecOptions['position'] };\n\nconst POSITION_OPTIONS: LegendPositionOption[] = Object.entries(LEGEND_POSITIONS_CONFIG).map(([id, config]) => {\n return {\n id: id as LegendSpecOptions['position'],\n ...config,\n };\n});\n\ntype LegendSizeOption = LegendSingleSelectConfig & { id: Required<LegendSpecOptions>['size'] };\n\nconst SIZE_OPTIONS: LegendSizeOption[] = Object.entries(LEGEND_SIZE_CONFIG).map(([id, config]) => {\n return {\n id: id as Required<LegendSpecOptions>['size'],\n ...config,\n };\n});\n\ntype LegendValueOption = LegendSingleSelectConfig & { id: LegendValue | ComparisonValues };\n\nexport interface LegendOptionsEditorProps {\n value?: LegendSpecOptions;\n onChange: (legend?: LegendSpecOptions) => void;\n showValuesEditor?: boolean;\n calculation?: 'aggregation' | 'comparison';\n}\n\nexport function LegendOptionsEditor({\n value,\n onChange,\n showValuesEditor = true,\n calculation = 'aggregation',\n}: LegendOptionsEditorProps): ReactElement {\n const handleLegendShowChange: SwitchProps['onChange'] = (_: unknown, checked: boolean) => {\n // legend is hidden when legend obj is undefined\n const legendValue = checked === true ? { position: DEFAULT_LEGEND.position } : undefined;\n onChange(legendValue);\n };\n\n const handleLegendPositionChange = (_: unknown, newValue: LegendPositionOption): void => {\n onChange({\n ...value,\n position: newValue.id,\n });\n };\n\n const handleLegendSizeChange = (_: unknown, newValue: LegendSizeOption): void => {\n onChange({\n ...value,\n position: currentPosition,\n size: newValue.id,\n });\n };\n\n const handleLegendValueChange = (_: unknown, newValue: LegendValueOption[]): void => {\n onChange({\n ...value,\n position: currentPosition,\n values: newValue.map((value) => {\n return value.id;\n }),\n });\n };\n\n const isValidLegend = validateLegendSpec(value);\n const currentPosition = getLegendPosition(value?.position);\n const legendPositionConfig = LEGEND_POSITIONS_CONFIG[currentPosition];\n\n const currentMode = getLegendMode(value?.mode);\n\n const currentSize = getLegendSize(value?.size);\n const legendSizeConfig = LEGEND_SIZE_CONFIG[currentSize];\n\n const legendValuesConfig = useMemo(() => {\n const currentValues = value?.values;\n if (!currentValues?.length) return [];\n\n if (calculation === 'aggregation') {\n return currentValues.reduce((result, item) => {\n const config = LEGEND_VALUE_CONFIG[item as LegendValue];\n if (config) {\n result.push({ ...config, id: item });\n }\n return result;\n }, [] as LegendValueOption[]);\n }\n\n return currentValues.map((id) => {\n const { label, description } = comparisonLegends[id as ComparisonValues];\n return {\n id,\n label,\n description,\n };\n });\n }, [calculation, value?.values]);\n\n const valueOptions = useMemo(() => {\n if (calculation === 'aggregation') {\n return Object.entries(LEGEND_VALUE_CONFIG || {}).map(([id, config]) => {\n return {\n id: id as LegendValue,\n ...config,\n };\n });\n }\n\n return Object.entries(comparisonLegends).map(([id, config]) => ({\n id: id as ComparisonValues,\n ...config,\n }));\n }, [calculation]);\n\n return (\n <OptionsEditorGroup title=\"Legend\">\n {!isValidLegend && <ErrorAlert error={{ name: 'invalid-legend', message: 'Invalid legend spec' }} />}\n <OptionsEditorControl label=\"Show\" control={<Switch checked={!!value} onChange={handleLegendShowChange} />} />\n {value && (\n <>\n <OptionsEditorControl\n label=\"Position\"\n control={\n <SettingsAutocomplete\n value={{\n ...legendPositionConfig,\n id: currentPosition,\n }}\n options={POSITION_OPTIONS}\n onChange={handleLegendPositionChange}\n disableClearable\n />\n }\n />\n <OptionsEditorControl\n label=\"Mode\"\n control={\n <ToggleButtonGroup\n color=\"primary\"\n exclusive\n value={currentMode}\n aria-label=\"Mode\"\n onChange={(__, newValue) => {\n onChange({\n ...value,\n position: currentPosition,\n mode: newValue,\n });\n }}\n >\n {Object.entries(LEGEND_MODE_CONFIG).map(([modeId, config]) => (\n <ToggleButton\n key={modeId}\n value={modeId}\n selected={currentMode === modeId}\n aria-label={`display ${modeId} mode`}\n >\n {config.label}\n </ToggleButton>\n ))}\n </ToggleButtonGroup>\n }\n />\n {currentMode === 'table' && (\n <>\n <OptionsEditorControl\n label=\"Size\"\n control={\n <SettingsAutocomplete\n value={{\n ...legendSizeConfig,\n id: currentSize,\n }}\n options={SIZE_OPTIONS}\n onChange={handleLegendSizeChange}\n // TODO: enable sizes for list mode when we normalize the layout of\n // lists to more closely match tables.\n disableClearable\n />\n }\n />\n {showValuesEditor && (\n <OptionsEditorControl\n label=\"Values\"\n control={\n // For some reason, the inferred option type doesn't always seem to work\n // quite right when `multiple` is true. Explicitly setting the generics\n // to work around this.\n <SettingsAutocomplete<LegendValueOption, true, true>\n multiple={true}\n disableCloseOnSelect\n disableClearable\n value={legendValuesConfig}\n options={valueOptions}\n onChange={handleLegendValueChange}\n limitTags={1}\n ChipProps={{\n size: 'small',\n }}\n />\n }\n />\n )}\n </>\n )}\n </>\n )}\n </OptionsEditorGroup>\n );\n}\n"],"names":["Switch","ToggleButtonGroup","ToggleButton","DEFAULT_LEGEND","getLegendMode","getLegendPosition","getLegendSize","ErrorAlert","OptionsEditorControl","OptionsEditorGroup","SettingsAutocomplete","useMemo","LEGEND_MODE_CONFIG","LEGEND_POSITIONS_CONFIG","validateLegendSpec","LEGEND_VALUE_CONFIG","LEGEND_SIZE_CONFIG","comparisonLegends","POSITION_OPTIONS","Object","entries","map","id","config","SIZE_OPTIONS","LegendOptionsEditor","value","onChange","showValuesEditor","calculation","handleLegendShowChange","_","checked","legendValue","position","undefined","handleLegendPositionChange","newValue","handleLegendSizeChange","currentPosition","size","handleLegendValueChange","values","isValidLegend","legendPositionConfig","currentMode","mode","currentSize","legendSizeConfig","legendValuesConfig","currentValues","length","reduce","result","item","push","label","description","valueOptions","title","error","name","message","control","options","disableClearable","color","exclusive","aria-label","__","modeId","selected","multiple","disableCloseOnSelect","limitTags","ChipProps"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,MAAM,EAAeC,iBAAiB,EAAEC,YAAY,QAAQ,gBAAgB;AACrF,SAASC,cAAc,EAAEC,aAAa,EAAEC,iBAAiB,EAAEC,aAAa,QAAQ,mBAAmB,CAAC,+BAA+B;AACnI,SAASC,UAAU,EAAEC,oBAAoB,EAAEC,kBAAkB,EAAEC,oBAAoB,QAAQ,yBAAyB;AACpH,SAAuBC,OAAO,QAAQ,QAAQ;AAC9C,SACEC,kBAAkB,EAClBC,uBAAuB,EAGvBC,kBAAkB,EAClBC,mBAAmB,EAEnBC,kBAAkB,EAClBC,iBAAiB,QAEZ,c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AIiB;4BACN;4BACAyB,SAAS9C;4BACTS,UAAUS;4BACV6B,gBAAgB;;;kCAItB,KAACzD;wBACCgD,OAAM;wBACNO,uBACE,KAAC9D;4BACCiE,OAAM;4BACNC,SAAS;4BACTzC,OAAOmB;4BACPuB,cAAW;4BACXzC,UAAU,CAAC0C,IAAIhC;gCACbV,SAAS;oCACP,GAAGD,KAAK;oCACRQ,UAAUK;oCACVO,MAAMT;gCACR;4BACF;sCAEClB,OAAOC,OAAO,CAACR,oBAAoBS,GAAG,CAAC,CAAC,CAACiD,QAAQ/C,OAAO,iBACvD,KAACrB;oCAECwB,OAAO4C;oCACPC,UAAU1B,gBAAgByB;oCAC1BF,cAAY,CAAC,QAAQ,EAAEE,OAAO,KAAK,CAAC;8CAEnC/C,OAAOiC,KAAK;mCALRc;;;oBAWdzB,gBAAgB,yBACf;;0CACE,KAACrC;gCACCgD,OAAM;gCACNO,uBACE,KAACrD;oCACCgB,OAAO;wCACL,GAAGsB,gBAAgB;wCACnB1B,IAAIyB;oCACN;oCACAiB,SAASxC;oCACTG,UAAUW;oCACV,mEAAmE;oCACnE,sCAAsC;oCACtC2B,gBAAgB;;;4BAIrBrC,kCACC,KAACpB;gCACCgD,OAAM;gCACNO,SACE,wEAAwE;gCACxE,uEAAuE;gCACvE,uBAAuB;8CACvB,KAACrD;oCACC8D,UAAU;oCACVC,oBAAoB;oCACpBR,gBAAgB;oCAChBvC,OAAOuB;oCACPe,SAASN;oCACT/B,UAAUc;oCACViC,WAAW;oCACXC,WAAW;wCACTnC,MAAM;oCACR;;;;;;;;;AAWtB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import { QueryDefinition, QueryPluginType } from '@perses-dev/
|
|
2
|
+
import { QueryDefinition, QueryPluginType } from '@perses-dev/spec';
|
|
3
3
|
import { QueryData } from '../../runtime';
|
|
4
4
|
import { PluginEditorRef } from '../PluginEditor';
|
|
5
5
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/MultiQueryEditor/QueryEditorContainer.tsx"],"sourcesContent":["// Copyright 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 { produce } from 'immer';\nimport { QueryDefinition, QueryPluginType } from '@perses-dev/core';\nimport { Stack, IconButton, Typography, BoxProps, Box, CircularProgress } from '@mui/material';\nimport DeleteIcon from 'mdi-material-ui/DeleteOutline';\nimport ChevronDown from 'mdi-material-ui/ChevronDown';\nimport ChevronRight from 'mdi-material-ui/ChevronRight';\nimport { forwardRef, ReactElement } from 'react';\nimport AlertIcon from 'mdi-material-ui/Alert';\nimport { InfoTooltip } from '@perses-dev/components';\nimport { QueryData } from '../../runtime';\nimport { PluginEditor, PluginEditorProps, PluginEditorRef } from '../PluginEditor';\n\n/**\n * Properties for {@link QueryEditorContainer}\n */\ninterface QueryEditorContainerProps {\n queryTypes: QueryPluginType[];\n index: number;\n query: QueryDefinition;\n queryResult?: QueryData;\n filteredQueryPlugins?: string[];\n onChange: (index: number, query: QueryDefinition) => void;\n onQueryRun: (index: number, query: QueryDefinition) => void;\n onCollapseExpand: (index: number) => void;\n isCollapsed?: boolean;\n onDelete?: (index: number) => void;\n}\n\n/**\n * Container for a query editor. This component is responsible for rendering the query editor, and make it collapsible\n * to not take too much space.\n * @param queryTypes the supported query types\n * @param index the index of the query in the list\n * @param query the query definition\n * @param isCollapsed whether the query editor is collapsed or not\n * @param onDelete callback when the query is deleted\n * @param onChange callback when the query is changed\n * @param onCollapseExpand callback when the query is collapsed or expanded\n * @constructor\n */\n\nexport const QueryEditorContainer = forwardRef<PluginEditorRef, QueryEditorContainerProps>(\n (props, ref): ReactElement => {\n const {\n queryTypes,\n index,\n query,\n queryResult,\n filteredQueryPlugins,\n isCollapsed,\n onDelete,\n onChange,\n onQueryRun,\n onCollapseExpand,\n } = props;\n return (\n <Stack key={index} spacing={1}>\n <Stack\n direction=\"row\"\n alignItems=\"center\"\n justifyContent=\"space-between\"\n borderBottom={1}\n borderColor={(theme) => theme.palette.divider}\n >\n <Stack direction=\"row\">\n <IconButton size=\"small\" onClick={() => onCollapseExpand(index)}>\n {isCollapsed ? <ChevronRight /> : <ChevronDown />}\n </IconButton>\n <Typography variant=\"overline\" component=\"h4\">\n Query #{index + 1}\n </Typography>\n </Stack>\n <Stack direction=\"row\" alignItems=\"center\">\n {queryResult?.isFetching && <CircularProgress aria-label=\"loading\" size=\"1.125rem\" />}\n {queryResult?.error && (\n <InfoTooltip description={queryResult.error.message}>\n <Stack\n direction=\"row\"\n alignItems=\"center\"\n sx={{\n color: (theme) => theme.palette.error.main,\n }}\n >\n <IconButton\n aria-label=\"query error\"\n size=\"small\"\n sx={{\n color: (theme) => theme.palette.error.main,\n }}\n >\n <AlertIcon />\n </IconButton>\n <Typography\n sx={{\n maxWidth: 300,\n whiteSpace: 'nowrap',\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n '&:hover ::after': { content: '\"Click to copy\"' },\n }}\n >\n {queryResult.error.message}\n </Typography>\n </Stack>\n </InfoTooltip>\n )}\n {onDelete && (\n <IconButton aria-label=\"delete query\" size=\"small\" onClick={() => onDelete && onDelete(index)}>\n <DeleteIcon />\n </IconButton>\n )}\n </Stack>\n </Stack>\n {!isCollapsed && (\n <QueryEditor\n ref={ref}\n queryTypes={queryTypes}\n value={query}\n filteredQueryPlugins={filteredQueryPlugins}\n onChange={(next) => onChange(index, next)}\n onQueryRun={() => onQueryRun(index, query)}\n />\n )}\n </Stack>\n );\n }\n);\n\nQueryEditorContainer.displayName = 'QueryEditorContainer';\n\n// Props on MUI Box that we don't want people to pass because we're either redefining them or providing them in\n// this component\ntype OmittedMuiProps = 'children' | 'value' | 'onChange';\ninterface QueryEditorProps extends Omit<BoxProps, OmittedMuiProps> {\n queryTypes: QueryPluginType[];\n value: QueryDefinition;\n filteredQueryPlugins?: string[];\n onChange: (next: QueryDefinition) => void;\n onQueryRun: () => void;\n}\n\n/**\n * Editor for a query definition. This component is responsible for rendering the plugin editor for the given query.\n * This will allow user to select a plugin extending from the given supported query types, and then edit the plugin\n * spec for this plugin.\n * @param props\n * @constructor\n */\n\nconst QueryEditor = forwardRef<PluginEditorRef, QueryEditorProps>((props, ref): ReactElement => {\n const { queryTypes, value, filteredQueryPlugins, onChange, onQueryRun, ...others } = props;\n\n const handlePluginChange: PluginEditorProps['onChange'] = (next) => {\n onChange(\n produce(value, (draft) => {\n draft.kind = next.selection.type;\n draft.spec.plugin.kind = next.selection.kind;\n draft.spec.plugin.spec = next.spec;\n })\n );\n };\n\n return (\n <Box {...others}>\n <PluginEditor\n ref={ref}\n pluginTypes={queryTypes}\n pluginKindLabel=\"Query Type\"\n value={{\n selection: {\n kind: value.spec.plugin.kind,\n type: value.kind,\n },\n spec: value.spec.plugin.spec,\n }}\n filteredQueryPlugins={filteredQueryPlugins}\n withRunQueryButton\n onRunQuery={onQueryRun}\n onChange={handlePluginChange}\n />\n </Box>\n );\n});\n\nQueryEditor.displayName = 'QueryEditor';\n"],"names":["produce","Stack","IconButton","Typography","Box","CircularProgress","DeleteIcon","ChevronDown","ChevronRight","forwardRef","AlertIcon","InfoTooltip","PluginEditor","QueryEditorContainer","props","ref","queryTypes","index","query","queryResult","filteredQueryPlugins","isCollapsed","onDelete","onChange","onQueryRun","onCollapseExpand","spacing","direction","alignItems","justifyContent","borderBottom","borderColor","theme","palette","divider","size","onClick","variant","component","isFetching","aria-label","error","description","message","sx","color","main","maxWidth","whiteSpace","overflow","textOverflow","content","QueryEditor","value","next","displayName","others","handlePluginChange","draft","kind","selection","type","spec","plugin","pluginTypes","pluginKindLabel","withRunQueryButton","onRunQuery"],"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AAI;YAC5CD,MAAMI,IAAI,CAACC,MAAM,CAACD,IAAI,GAAGR,KAAKQ,IAAI;QACpC;IAEJ;IAEA,qBACE,KAAC1D;QAAK,GAAGoD,MAAM;kBACb,cAAA,KAAC5C;YACCG,KAAKA;YACLiD,aAAahD;YACbiD,iBAAgB;YAChBZ,OAAO;gBACLO,WAAW;oBACTD,MAAMN,MAAMS,IAAI,CAACC,MAAM,CAACJ,IAAI;oBAC5BE,MAAMR,MAAMM,IAAI;gBAClB;gBACAG,MAAMT,MAAMS,IAAI,CAACC,MAAM,CAACD,IAAI;YAC9B;YACA1C,sBAAsBA;YACtB8C,kBAAkB;YAClBC,YAAY3C;YACZD,UAAUkC;;;AAIlB;AAEAL,YAAYG,WAAW,GAAG"}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/MultiQueryEditor/QueryEditorContainer.tsx"],"sourcesContent":["// Copyright 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 { produce } from 'immer';\nimport { QueryDefinition, QueryPluginType } from '@perses-dev/spec';\nimport { Stack, IconButton, Typography, BoxProps, Box, CircularProgress } from '@mui/material';\nimport DeleteIcon from 'mdi-material-ui/DeleteOutline';\nimport ChevronDown from 'mdi-material-ui/ChevronDown';\nimport ChevronRight from 'mdi-material-ui/ChevronRight';\nimport { forwardRef, ReactElement } from 'react';\nimport AlertIcon from 'mdi-material-ui/Alert';\nimport { InfoTooltip } from '@perses-dev/components';\nimport { QueryData } from '../../runtime';\nimport { PluginEditor, PluginEditorProps, PluginEditorRef } from '../PluginEditor';\n\n/**\n * Properties for {@link QueryEditorContainer}\n */\ninterface QueryEditorContainerProps {\n queryTypes: QueryPluginType[];\n index: number;\n query: QueryDefinition;\n queryResult?: QueryData;\n filteredQueryPlugins?: string[];\n onChange: (index: number, query: QueryDefinition) => void;\n onQueryRun: (index: number, query: QueryDefinition) => void;\n onCollapseExpand: (index: number) => void;\n isCollapsed?: boolean;\n onDelete?: (index: number) => void;\n}\n\n/**\n * Container for a query editor. This component is responsible for rendering the query editor, and make it collapsible\n * to not take too much space.\n * @param queryTypes the supported query types\n * @param index the index of the query in the list\n * @param query the query definition\n * @param isCollapsed whether the query editor is collapsed or not\n * @param onDelete callback when the query is deleted\n * @param onChange callback when the query is changed\n * @param onCollapseExpand callback when the query is collapsed or expanded\n * @constructor\n */\n\nexport const QueryEditorContainer = forwardRef<PluginEditorRef, QueryEditorContainerProps>(\n (props, ref): ReactElement => {\n const {\n queryTypes,\n index,\n query,\n queryResult,\n filteredQueryPlugins,\n isCollapsed,\n onDelete,\n onChange,\n onQueryRun,\n onCollapseExpand,\n } = props;\n return (\n <Stack key={index} spacing={1}>\n <Stack\n direction=\"row\"\n alignItems=\"center\"\n justifyContent=\"space-between\"\n borderBottom={1}\n borderColor={(theme) => theme.palette.divider}\n >\n <Stack direction=\"row\">\n <IconButton size=\"small\" onClick={() => onCollapseExpand(index)}>\n {isCollapsed ? <ChevronRight /> : <ChevronDown />}\n </IconButton>\n <Typography variant=\"overline\" component=\"h4\">\n Query #{index + 1}\n </Typography>\n </Stack>\n <Stack direction=\"row\" alignItems=\"center\">\n {queryResult?.isFetching && <CircularProgress aria-label=\"loading\" size=\"1.125rem\" />}\n {queryResult?.error && (\n <InfoTooltip description={queryResult.error.message}>\n <Stack\n direction=\"row\"\n alignItems=\"center\"\n sx={{\n color: (theme) => theme.palette.error.main,\n }}\n >\n <IconButton\n aria-label=\"query error\"\n size=\"small\"\n sx={{\n color: (theme) => theme.palette.error.main,\n }}\n >\n <AlertIcon />\n </IconButton>\n <Typography\n sx={{\n maxWidth: 300,\n whiteSpace: 'nowrap',\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n '&:hover ::after': { content: '\"Click to copy\"' },\n }}\n >\n {queryResult.error.message}\n </Typography>\n </Stack>\n </InfoTooltip>\n )}\n {onDelete && (\n <IconButton aria-label=\"delete query\" size=\"small\" onClick={() => onDelete && onDelete(index)}>\n <DeleteIcon />\n </IconButton>\n )}\n </Stack>\n </Stack>\n {!isCollapsed && (\n <QueryEditor\n ref={ref}\n queryTypes={queryTypes}\n value={query}\n filteredQueryPlugins={filteredQueryPlugins}\n onChange={(next) => onChange(index, next)}\n onQueryRun={() => onQueryRun(index, query)}\n />\n )}\n </Stack>\n );\n }\n);\n\nQueryEditorContainer.displayName = 'QueryEditorContainer';\n\n// Props on MUI Box that we don't want people to pass because we're either redefining them or providing them in\n// this component\ntype OmittedMuiProps = 'children' | 'value' | 'onChange';\ninterface QueryEditorProps extends Omit<BoxProps, OmittedMuiProps> {\n queryTypes: QueryPluginType[];\n value: QueryDefinition;\n filteredQueryPlugins?: string[];\n onChange: (next: QueryDefinition) => void;\n onQueryRun: () => void;\n}\n\n/**\n * Editor for a query definition. This component is responsible for rendering the plugin editor for the given query.\n * This will allow user to select a plugin extending from the given supported query types, and then edit the plugin\n * spec for this plugin.\n * @param props\n * @constructor\n */\n\nconst QueryEditor = forwardRef<PluginEditorRef, QueryEditorProps>((props, ref): ReactElement => {\n const { queryTypes, value, filteredQueryPlugins, onChange, onQueryRun, ...others } = props;\n\n const handlePluginChange: PluginEditorProps['onChange'] = (next) => {\n onChange(\n produce(value, (draft) => {\n draft.kind = next.selection.type;\n draft.spec.plugin.kind = next.selection.kind;\n draft.spec.plugin.spec = next.spec;\n })\n );\n };\n\n return (\n <Box {...others}>\n <PluginEditor\n ref={ref}\n pluginTypes={queryTypes}\n pluginKindLabel=\"Query Type\"\n value={{\n selection: {\n kind: value.spec.plugin.kind,\n type: value.kind,\n },\n spec: value.spec.plugin.spec,\n }}\n filteredQueryPlugins={filteredQueryPlugins}\n withRunQueryButton\n onRunQuery={onQueryRun}\n onChange={handlePluginChange}\n />\n </Box>\n );\n});\n\nQueryEditor.displayName = 'QueryEditor';\n"],"names":["produce","Stack","IconButton","Typography","Box","CircularProgress","DeleteIcon","ChevronDown","ChevronRight","forwardRef","AlertIcon","InfoTooltip","PluginEditor","QueryEditorContainer","props","ref","queryTypes","index","query","queryResult","filteredQueryPlugins","isCollapsed","onDelete","onChange","onQueryRun","onCollapseExpand","spacing","direction","alignItems","justifyContent","borderBottom","borderColor","theme","palette","divider","size","onClick","variant","component","isFetching","aria-label","error","description","message","sx","color","main","maxWidth","whiteSpace","overflow","textOverflow","content","QueryEditor","value","next","displayName","others","handlePluginChange","draft","kind","selection","type","spec","plugin","pluginTypes","pluginKindLabel","withRunQueryButton","onRunQuery"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,OAAO,QAAQ,QAAQ;AAEhC,SAASC,KAAK,EAAEC,UAAU,EAAEC,UAAU,EAAYC,GAAG,EAAEC,gBAAgB,QAAQ,gBAAgB;AAC/F,OAAOC,gBAAgB,gCAAgC;AACvD,OAAOC,iBAAiB,8BAA8B;AACtD,OAAOC,kBAAkB,+BAA+B;AACxD,SAASC,UAAU,QAAsB,QAAQ;AACjD,OAAOC,eAAe,wBAAwB;AAC9C,SAASC,WAAW,QAAQ,yBAAyB;AAErD,SAASC,YAAY,QAA4C,kBAAkB;AAkBnF;;;;;;;;;;;CAWC,GAED,OAAO,MAAMC,qCAAuBJ,WAClC,CAACK,OAAOC;IACN,MAAM,EACJC,UAAU,EACVC,KAAK,EACLC,KAAK,EACLC,WAAW,EACXC,oBAAoB,EACpBC,WAAW,EACXC,QAAQ,EACRC,QAAQ,EACRC,UAAU,EACVC,gBAAgB,EACjB,GAAGX;IACJ,qBACE,MAAC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OAAOqC;gBACpC9B,YAAY,IAAMA,WAAWP,OAAOC;;;OAhE9BD;AAqEhB,GACA;AAEFJ,qBAAqB0C,WAAW,GAAG;AAanC;;;;;;CAMC,GAED,MAAMH,4BAAc3C,WAA8C,CAACK,OAAOC;IACxE,MAAM,EAAEC,UAAU,EAAEqC,KAAK,EAAEjC,oBAAoB,EAAEG,QAAQ,EAAEC,UAAU,EAAE,GAAGgC,QAAQ,GAAG1C;IAErF,MAAM2C,qBAAoD,CAACH;QACzD/B,SACEvB,QAAQqD,OAAO,CAACK;YACdA,MAAMC,IAAI,GAAGL,KAAKM,SAAS,CAACC,IAAI;YAChCH,MAAMI,IAAI,CAACC,MAAM,CAACJ,IAAI,GAAGL,KAAKM,SAAS,CAACD,IAAI;YAC5CD,MAAMI,IAAI,CAACC,MAAM,CAACD,IAAI,GAAGR,KAAKQ,IAAI;QACpC;IAEJ;IAEA,qBACE,KAAC1D;QAAK,GAAGoD,MAAM;kBACb,cAAA,KAAC5C;YACCG,KAAKA;YACLiD,aAAahD;YACbiD,iBAAgB;YAChBZ,OAAO;gBACLO,WAAW;oBACTD,MAAMN,MAAMS,IAAI,CAACC,MAAM,CAACJ,IAAI;oBAC5BE,MAAMR,MAAMM,IAAI;gBAClB;gBACAG,MAAMT,MAAMS,IAAI,CAACC,MAAM,CAACD,IAAI;YAC9B;YACA1C,sBAAsBA;YACtB8C,kBAAkB;YAClBC,YAAY3C;YACZD,UAAUkC;;;AAIlB;AAEAL,YAAYG,WAAW,GAAG"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import { PanelDefinition, PanelEditorValues, QueryDefinition, UnknownSpec } from '@perses-dev/
|
|
2
|
+
import { PanelDefinition, PanelEditorValues, QueryDefinition, UnknownSpec } from '@perses-dev/spec';
|
|
3
3
|
import { Control } from 'react-hook-form';
|
|
4
4
|
import { PluginEditorRef } from '../PluginEditor';
|
|
5
5
|
export interface PanelSpecEditorProps {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/PanelSpecEditor/PanelSpecEditor.tsx"],"sourcesContent":["// Copyright 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 { ErrorAlert, JSONEditor, LinksEditor } from '@perses-dev/components';\nimport { PanelDefinition, PanelEditorValues, QueryDefinition, UnknownSpec } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../../src/components/PanelSpecEditor/PanelSpecEditor.tsx"],"sourcesContent":["// Copyright 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 { ErrorAlert, JSONEditor, LinksEditor } from '@perses-dev/components';\nimport { PanelDefinition, PanelEditorValues, QueryDefinition, UnknownSpec } from '@perses-dev/spec';\nimport { Control, Controller } from 'react-hook-form';\nimport { forwardRef, ReactElement } from 'react';\nimport { QueryCountProvider, useDataQueriesContext, usePlugin } from '../../runtime';\nimport { PanelPlugin } from '../../model';\nimport { OptionsEditorTabsProps, OptionsEditorTabs } from '../OptionsEditorTabs';\nimport { MultiQueryEditor } from '../MultiQueryEditor';\nimport { PluginEditorRef } from '../PluginEditor';\n\nexport interface PanelSpecEditorProps {\n control: Control<PanelEditorValues>;\n panelDefinition: PanelDefinition;\n onQueriesChange: (queries: QueryDefinition[]) => void;\n onQueryRun: (index: number, query: QueryDefinition) => void;\n onPluginSpecChange: (spec: UnknownSpec) => void;\n onJSONChange: (panelDefinitionStr: string) => void;\n}\n\nexport const PanelSpecEditor = forwardRef<PluginEditorRef, PanelSpecEditorProps>((props, ref): ReactElement | null => {\n const { control, panelDefinition, onQueriesChange, onQueryRun, onPluginSpecChange, onJSONChange } = props;\n const { kind } = panelDefinition.spec.plugin;\n const { data: plugin, isLoading, error } = usePlugin('Panel', kind);\n\n const { queryResults } = useDataQueriesContext();\n\n if (error) {\n return <ErrorAlert error={error} />;\n }\n\n if (isLoading) {\n return null;\n }\n\n if (!plugin) {\n throw new Error(`Missing implementation for panel plugin with kind '${kind}'`);\n }\n\n const { panelOptionsEditorComponents, hideQueryEditor } = plugin as PanelPlugin;\n let tabs: OptionsEditorTabsProps['tabs'] = [];\n\n if (!hideQueryEditor) {\n tabs.push({\n label: 'Query',\n content: (\n <Controller\n control={control}\n name=\"panelDefinition.spec.queries\"\n render={({ field }) => (\n <MultiQueryEditor\n ref={ref}\n queryTypes={plugin.supportedQueryTypes ?? []}\n queries={panelDefinition.spec.queries ?? []}\n queryResults={queryResults}\n onChange={(queries) => {\n field.onChange(queries);\n onQueriesChange(queries);\n }}\n onQueryRun={(index, query) => {\n onQueryRun(index, query);\n // If spec has not changed, refetch to update the data\n if (JSON.stringify(panelDefinition.spec.queries?.[index]) === JSON.stringify(query)) {\n queryResults[index]?.refetch?.();\n }\n }}\n />\n )}\n />\n ),\n });\n }\n\n if (panelOptionsEditorComponents) {\n tabs = tabs.concat(\n panelOptionsEditorComponents.map(({ label, content: OptionsEditorComponent }) => ({\n label,\n content: (\n <Controller\n control={control}\n name=\"panelDefinition.spec.plugin.spec\"\n render={({ field }) => (\n <OptionsEditorComponent\n value={panelDefinition.spec.plugin.spec}\n onChange={(spec) => {\n field.onChange(spec);\n onPluginSpecChange(spec);\n }}\n />\n )}\n />\n ),\n }))\n );\n }\n\n // always show json editor and links editor by default\n tabs.push({\n label: 'Links',\n content: <LinksEditor control={control} />,\n });\n tabs.push({\n label: 'JSON',\n content: (\n <Controller\n control={control}\n name=\"panelDefinition\"\n render={({ field }) => (\n <JSONEditor\n maxHeight=\"80vh\"\n value={panelDefinition}\n onChange={(json) => {\n field.onChange(JSON.parse(json));\n onJSONChange(json);\n }}\n />\n )}\n />\n ),\n });\n\n return (\n <QueryCountProvider queryCount={(panelDefinition.spec.queries ?? []).length}>\n <OptionsEditorTabs key={tabs.length} tabs={tabs} />\n </QueryCountProvider>\n );\n});\n\nPanelSpecEditor.displayName = 'PanelSpecEditor';\n"],"names":["ErrorAlert","JSONEditor","LinksEditor","Controller","forwardRef","QueryCountProvider","useDataQueriesContext","usePlugin","OptionsEditorTabs","MultiQueryEditor","PanelSpecEditor","props","ref","control","panelDefinition","onQueriesChange","onQueryRun","onPluginSpecChange","onJSONChange","kind","spec","plugin","data","isLoading","error","queryResults","Error","panelOptionsEditorComponents","hideQueryEditor","tabs","push","label","content","name","render","field","queryTypes","supportedQueryTypes","queries","onChange","index","query","JSON","stringify","refetch","concat","map","OptionsEditorComponent","value","maxHeight","json","parse","queryCount","length","displayName"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,UAAU,EAAEC,UAAU,EAAEC,WAAW,QAAQ,yBAAyB;AAE7E,SAAkBC,UAAU,QAAQ,kBAAkB;AACtD,SAASC,UAAU,QAAsB,QAAQ;AACjD,SAASC,kBAAkB,EAAEC,qBAAqB,EAAEC,SAAS,QAAQ,gBAAgB;AAErF,SAAiCC,iBAAiB,QAAQ,uBAAuB;AACjF,SAASC,gBAAgB,QAAQ,sBAAsB;AAYvD,OAAO,MAAMC,gCAAkBN,WAAkD,CAACO,OAAOC;IACvF,MAAM,EAAEC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MAAM,CAChBlB,6BAA6BmB,GAAG,CAAC,CAAC,EAAEf,KAAK,EAAEC,SAASe,sBAAsB,EAAE,GAAM,CAAA;gBAChFhB;gBACAC,uBACE,KAAC7B;oBACCU,SAASA;oBACToB,MAAK;oBACLC,QAAQ,CAAC,EAAEC,KAAK,EAAE,iBAChB,KAACY;4BACCC,OAAOlC,gBAAgBM,IAAI,CAACC,MAAM,CAACD,IAAI;4BACvCmB,UAAU,CAACnB;gCACTe,MAAMI,QAAQ,CAACnB;gCACfH,mBAAmBG;4BACrB;;;YAKV,CAAA;IAEJ;IAEA,sDAAsD;IACtDS,KAAKC,IAAI,CAAC;QACRC,OAAO;QACPC,uBAAS,KAAC9B;YAAYW,SAASA;;IACjC;IACAgB,KAAKC,IAAI,CAAC;QACRC,OAAO;QACPC,uBACE,KAAC7B;YACCU,SAASA;YACToB,MAAK;YACLC,QAAQ,CAAC,EAAEC,KAAK,EAAE,iBAChB,KAAClC;oBACCgD,WAAU;oBACVD,OAAOlC;oBACPyB,UAAU,CAACW;wBACTf,MAAMI,QAAQ,CAACG,KAAKS,KAAK,CAACD;wBAC1BhC,aAAagC;oBACf;;;IAKV;IAEA,qBACE,KAAC7C;QAAmB+C,YAAY,AAACtC,CAAAA,gBAAgBM,IAAI,CAACkB,OAAO,IAAI,EAAE,AAAD,EAAGe,MAAM;kBACzE,cAAA,KAAC7C;YAAoCqB,MAAMA;WAAnBA,KAAKwB,MAAM;;AAGzC,GAAG;AAEH3C,gBAAgB4C,WAAW,GAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/PluginEditor/PluginEditor.tsx"],"sourcesContent":["// Copyright 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 { Box, Button } from '@mui/material';\nimport Reload from 'mdi-material-ui/Reload';\nimport { ErrorAlert, ErrorBoundary } from '@perses-dev/components';\nimport { ReactElement, useCallback } from 'react';\nimport { UnknownSpec } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../../src/components/PluginEditor/PluginEditor.tsx"],"sourcesContent":["// Copyright 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 { Box, Button } from '@mui/material';\nimport Reload from 'mdi-material-ui/Reload';\nimport { ErrorAlert, ErrorBoundary } from '@perses-dev/components';\nimport { ReactElement, useCallback } from 'react';\nimport { UnknownSpec } from '@perses-dev/spec';\nimport { PluginKindSelect } from '../PluginKindSelect';\nimport { PluginSpecEditor } from '../PluginSpecEditor';\nimport { PluginEditorProps, usePluginEditor } from './plugin-editor-api';\n\n/**\n * A combination `PluginKindSelect` and `PluginSpecEditor` component. This is meant for editing the `plugin` property\n * that's common in our JSON specs where a user selects a plugin `kind` and then edits the `spec` via that plugin's\n * editor component. It takes care of transitioning from one plugin kind to another \"all at once\" so that when the\n * plugin's kind changes, the spec is also changed at the same time so those options editor components don't see a\n * previous plugin's spec state. If you just want this behavior, but in a different UI layout from this, try the\n * `usePluginEditor` hook that powers this component.\n */\n\nexport function PluginEditor(props: PluginEditorProps): ReactElement {\n const {\n value,\n withRunQueryButton = true,\n pluginTypes,\n pluginKindLabel,\n onChange: _,\n isReadonly,\n onRunQuery,\n filteredQueryPlugins,\n ...others\n } = props;\n\n const { pendingSelection, isLoading, error, onSelectionChange, onSpecChange } = usePluginEditor(props);\n\n const handleSpecChange = useCallback(\n (nextSpec: UnknownSpec) => {\n onSpecChange(nextSpec);\n },\n [onSpecChange]\n );\n\n return (\n <Box {...others}>\n <Box\n sx={{\n display: 'flex',\n flexDirection: 'row',\n alignItems: 'center',\n justifyContent: 'space-between',\n gap: 1,\n mb: 1,\n }}\n >\n <PluginKindSelect\n fullWidth={false}\n sx={{ minWidth: 120 }}\n margin=\"dense\"\n label={pluginKindLabel}\n pluginTypes={pluginTypes}\n disabled={isLoading}\n value={pendingSelection ? pendingSelection : value.selection}\n slotProps={{ input: { readOnly: isReadonly } }}\n error={!!error}\n helperText={error?.message}\n onChange={onSelectionChange}\n filteredQueryPlugins={filteredQueryPlugins}\n />\n\n {withRunQueryButton && (\n <Button\n data-testid=\"run_query_button\"\n variant=\"contained\"\n startIcon={<Reload />}\n onClick={onRunQuery}\n disabled={isLoading}\n >\n Run Query\n </Button>\n )}\n </Box>\n\n <ErrorBoundary FallbackComponent={ErrorAlert}>\n <PluginSpecEditor\n pluginSelection={value.selection}\n value={value.spec}\n onChange={handleSpecChange}\n isReadonly={isReadonly}\n />\n </ErrorBoundary>\n </Box>\n );\n}\n"],"names":["Box","Button","Reload","ErrorAlert","ErrorBoundary","useCallback","PluginKindSelect","PluginSpecEditor","usePluginEditor","PluginEditor","props","value","withRunQueryButton","pluginTypes","pluginKindLabel","onChange","_","isReadonly","onRunQuery","filteredQueryPlugins","others","pendingSelection","isLoading","error","onSelectionChange","onSpecChange","handleSpecChange","nextSpec","sx","display","flexDirection","alignItems","justifyContent","gap","mb","fullWidth","minWidth","margin","label","disabled","selection","slotProps","input","readOnly","helperText","message","data-testid","variant","startIcon","onClick","FallbackComponent","pluginSelection","spec"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E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KAAC9C;wBACZ+C,SAAS/B;wBACTqB,UAAUjB;kCACX;;;;0BAML,KAAClB;gBAAc8C,mBAAmB/C;0BAChC,cAAA,KAACI;oBACC4C,iBAAiBxC,MAAM6B,SAAS;oBAChC7B,OAAOA,MAAMyC,IAAI;oBACjBrC,UAAUW;oBACVT,YAAYA;;;;;AAKtB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/PluginEditor/plugin-editor-api.ts"],"sourcesContent":["// Copyright 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 { BoxProps } from '@mui/material';\nimport { UnknownSpec } from '@perses-dev/core';\nimport { useState, useRef, useEffect } from 'react';\nimport { produce } from 'immer';\nimport { PanelPlugin, PluginType } from '../../model';\nimport { PluginKindSelectProps } from '../PluginKindSelect';\nimport { PluginSpecEditorProps } from '../PluginSpecEditor';\nimport { usePlugin, usePluginRegistry } from '../../runtime';\nimport { useEvent } from '../../utils';\n\nexport interface PluginEditorSelection {\n type: PluginType;\n kind: string;\n}\n\nexport interface PluginEditorValue {\n selection: PluginEditorSelection;\n spec: UnknownSpec;\n}\n\n// Props on MUI Box that we don't want people to pass because we're either redefining them or providing them in\n// this component\ntype OmittedMuiProps = 'children' | 'value' | 'onChange';\n\nexport interface PluginEditorProps extends Omit<BoxProps, OmittedMuiProps> {\n pluginTypes: PluginType[];\n pluginKindLabel: string;\n value: PluginEditorValue;\n isReadonly?: boolean;\n withRunQueryButton?: boolean;\n filteredQueryPlugins?: string[];\n onChange: (next: PluginEditorValue) => void;\n onRunQuery?: () => void;\n}\n\nexport interface PluginEditorRef {\n flushChanges?: () => void;\n}\n\ntype PreviousSpecState = Record<string, Record<string, UnknownSpec>>;\ntype HideQueryEditorState = Record<string, boolean>;\n\n/**\n * Props needed by the usePluginEditor hook.\n */\nexport type UsePluginEditorProps = Pick<PluginEditorProps, 'pluginTypes' | 'value' | 'onChange'> & {\n onHideQueryEditorChange?: (isHidden: boolean) => void;\n};\n\n/**\n * Returns the state/handlers that power the `PluginEditor` component. Useful for custom components that want to provide\n * a different UI, but want the same behavior of changing `kind` and `spec` together on plugin kind changes. Also\n * remembers previous `spec` values that it's seen, allowing and restores those values if a user switches the plugin\n * kind back.\n */\nexport function usePluginEditor(props: UsePluginEditorProps): {\n pendingSelection?: PluginEditorSelection;\n isLoading: boolean;\n error: Error | null;\n onSelectionChange: (s: PluginEditorSelection) => void;\n onSpecChange: (next: UnknownSpec) => void;\n rememberCurrentSpecState: () => void;\n} {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n const { pluginTypes, value, onHideQueryEditorChange = (): void => {} } = props; // setting onHideQueryEditorChange to empty function here because useEvent requires a function\n\n // Keep a stable reference, so we don't run the effect below when we don't need to\n const onChange = useEvent(props.onChange);\n const onHideQuery = useEvent(onHideQueryEditorChange);\n\n // The previous spec state for PluginType and kind and a helper function for remembering current values\n const prevSpecState = useRef<PreviousSpecState>({\n [value.selection.type]: { [value.selection.kind]: value.spec },\n });\n const rememberCurrentSpecState = useEvent(() => {\n let byPluginType = prevSpecState.current[value.selection.type];\n if (byPluginType === undefined) {\n byPluginType = {};\n prevSpecState.current[value.selection.type] = byPluginType;\n }\n byPluginType[value.selection.kind] = value.spec;\n });\n\n // The previous hide query state for each panel kind\n const hideQueryState = useRef<HideQueryEditorState>({\n [value.selection.kind]: false,\n });\n\n const { defaultPluginKinds } = usePluginRegistry();\n const defaultPluginType = pluginTypes[0];\n const defaultPluginKind = defaultPluginType ? defaultPluginKinds?.[defaultPluginType] : undefined;\n const defaultPluginSelection =\n defaultPluginType && defaultPluginKind\n ? {\n type: defaultPluginType,\n kind: defaultPluginKind,\n }\n : undefined;\n const initPendingSelection = !value.selection && defaultPluginSelection ? defaultPluginSelection : undefined;\n\n // When kind changes and we haven't loaded that plugin before, we will need to enter a \"pending\" state so that we\n // can generate proper initial spec values that match the new plugin kind\n const [pendingSelection, setPendingSelection] = useState<PluginEditorSelection | undefined>(initPendingSelection);\n\n // Take a default kind in case user write explicitly an empty kind in the initial value\n useEffect(() => {\n if (value.selection.kind === '') {\n value.selection.kind = defaultPluginKind || '';\n }\n }, [value.selection, defaultPluginKind]);\n\n const { data: plugin, isFetching, error } = usePlugin(pendingSelection?.type, pendingSelection?.kind || '');\n\n useEffect(() => {\n // Nothing to do if no new plugin kind is pending\n if (!pendingSelection) return;\n\n // Can't get spec value until we have a plugin\n if (plugin === undefined || isFetching) return;\n\n // Fire an onChange to change to the pending kind with initial values from the plugin\n rememberCurrentSpecState();\n onChange({\n selection: pendingSelection,\n spec: plugin.createInitialOptions ? plugin.createInitialOptions() : {},\n });\n\n if (pendingSelection.type === 'Panel') {\n const panelPlugin = plugin as PanelPlugin;\n hideQueryState.current[pendingSelection.kind] = !!panelPlugin.hideQueryEditor;\n if (!!panelPlugin.hideQueryEditor !== hideQueryState.current[value.selection.kind]) {\n onHideQuery(!!panelPlugin.hideQueryEditor);\n }\n }\n setPendingSelection(undefined);\n }, [\n pendingSelection,\n plugin,\n isFetching,\n rememberCurrentSpecState,\n onChange,\n onHideQuery,\n hideQueryState,\n value.selection,\n ]);\n\n /**\n * When the user tries to change the plugin kind, make sure we have the correct spec for that plugin kind before we\n * make the switch.\n */\n const onSelectionChange: PluginKindSelectProps['onChange'] = (nextSelection) => {\n // If we already have state for this plugin type/kind from a previous selection, just use it\n const previousState = prevSpecState.current[nextSelection.type]?.[nextSelection.kind];\n if (previousState !== undefined) {\n rememberCurrentSpecState();\n onChange({\n selection: nextSelection,\n spec: previousState,\n });\n } else {\n // Otherwise, kick off the async loading process\n setPendingSelection(nextSelection);\n }\n\n if (\n nextSelection.type === 'Panel' &&\n hideQueryState.current[nextSelection.kind] !== undefined &&\n hideQueryState.current[value.selection.kind] !== hideQueryState.current[nextSelection.kind]\n ) {\n onHideQuery(!!hideQueryState.current[nextSelection.kind]);\n }\n };\n\n /**\n * Spec changes are independent and always just set the spec state.\n */\n const onSpecChange: PluginSpecEditorProps['onChange'] = (next) => {\n onChange(\n produce(value, (draft) => {\n draft.spec = next;\n })\n );\n };\n\n return {\n pendingSelection,\n isLoading: isFetching,\n error,\n onSelectionChange,\n onSpecChange,\n rememberCurrentSpecState,\n };\n}\n"],"names":["useState","useRef","useEffect","produce","usePlugin","usePluginRegistry","useEvent","usePluginEditor","props","pluginTypes","value","onHideQueryEditorChange","onChange","onHideQuery","prevSpecState","selection","type","kind","spec","rememberCurrentSpecState","byPluginType","current","undefined","hideQueryState","defaultPluginKinds","defaultPluginType","defaultPluginKind","defaultPluginSelection","initPendingSelection","pendingSelection","setPendingSelection","data","plugin","isFetching","error","createInitialOptions","panelPlugin","hideQueryEditor","onSelectionChange","nextSelection","previousState","onSpecChange","next","draft","isLoading"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAIjC,SAASA,QAAQ,EAAEC,MAAM,EAAEC,SAAS,QAAQ,QAAQ;AACpD,SAASC,OAAO,QAAQ,QAAQ;AAIhC,SAASC,SAAS,EAAEC,iBAAiB,QAAQ,gBAAgB;AAC7D,SAASC,QAAQ,QAAQ,cAAc;AAyCvC;;;;;CAKC,GACD,OAAO,SAASC,gBAAgBC,KAA2B;IAQzD,gEAAgE;IAChE,MAAM,EAAEC,WAAW,EAAEC,KAAK,EAAEC,0BAA0B,KAAa,CAAC,EAAE,GAAGH,OAAO,8FAA8F;IAE9K,kFAAkF;IAClF,MAAMI,WAAWN,SAASE,MAAMI,QAAQ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;IAEA;;GAEC,GACD,MAAMwB,eAAkD,CAACC;QACvD9B,SACET,QAAQO,OAAO,CAACiC;YACdA,MAAMzB,IAAI,GAAGwB;QACf;IAEJ;IAEA,OAAO;QACLb;QACAe,WAAWX;QACXC;QACAI;QACAG;QACAtB;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/PluginEditor/plugin-editor-api.ts"],"sourcesContent":["// Copyright 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 { BoxProps } from '@mui/material';\nimport { UnknownSpec } from '@perses-dev/spec';\nimport { useState, useRef, useEffect } from 'react';\nimport { produce } from 'immer';\nimport { PanelPlugin, PluginType } from '../../model';\nimport { PluginKindSelectProps } from '../PluginKindSelect';\nimport { PluginSpecEditorProps } from '../PluginSpecEditor';\nimport { usePlugin, usePluginRegistry } from '../../runtime';\nimport { useEvent } from '../../utils';\n\nexport interface PluginEditorSelection {\n type: PluginType;\n kind: string;\n}\n\nexport interface PluginEditorValue {\n selection: PluginEditorSelection;\n spec: UnknownSpec;\n}\n\n// Props on MUI Box that we don't want people to pass because we're either redefining them or providing them in\n// this component\ntype OmittedMuiProps = 'children' | 'value' | 'onChange';\n\nexport interface PluginEditorProps extends Omit<BoxProps, OmittedMuiProps> {\n pluginTypes: PluginType[];\n pluginKindLabel: string;\n value: PluginEditorValue;\n isReadonly?: boolean;\n withRunQueryButton?: boolean;\n filteredQueryPlugins?: string[];\n onChange: (next: PluginEditorValue) => void;\n onRunQuery?: () => void;\n}\n\nexport interface PluginEditorRef {\n flushChanges?: () => void;\n}\n\ntype PreviousSpecState = Record<string, Record<string, UnknownSpec>>;\ntype HideQueryEditorState = Record<string, boolean>;\n\n/**\n * Props needed by the usePluginEditor hook.\n */\nexport type UsePluginEditorProps = Pick<PluginEditorProps, 'pluginTypes' | 'value' | 'onChange'> & {\n onHideQueryEditorChange?: (isHidden: boolean) => void;\n};\n\n/**\n * Returns the state/handlers that power the `PluginEditor` component. Useful for custom components that want to provide\n * a different UI, but want the same behavior of changing `kind` and `spec` together on plugin kind changes. Also\n * remembers previous `spec` values that it's seen, allowing and restores those values if a user switches the plugin\n * kind back.\n */\nexport function usePluginEditor(props: UsePluginEditorProps): {\n pendingSelection?: PluginEditorSelection;\n isLoading: boolean;\n error: Error | null;\n onSelectionChange: (s: PluginEditorSelection) => void;\n onSpecChange: (next: UnknownSpec) => void;\n rememberCurrentSpecState: () => void;\n} {\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n const { pluginTypes, value, onHideQueryEditorChange = (): void => {} } = props; // setting onHideQueryEditorChange to empty function here because useEvent requires a function\n\n // Keep a stable reference, so we don't run the effect below when we don't need to\n const onChange = useEvent(props.onChange);\n const onHideQuery = useEvent(onHideQueryEditorChange);\n\n // The previous spec state for PluginType and kind and a helper function for remembering current values\n const prevSpecState = useRef<PreviousSpecState>({\n [value.selection.type]: { [value.selection.kind]: value.spec },\n });\n const rememberCurrentSpecState = useEvent(() => {\n let byPluginType = prevSpecState.current[value.selection.type];\n if (byPluginType === undefined) {\n byPluginType = {};\n prevSpecState.current[value.selection.type] = byPluginType;\n }\n byPluginType[value.selection.kind] = value.spec;\n });\n\n // The previous hide query state for each panel kind\n const hideQueryState = useRef<HideQueryEditorState>({\n [value.selection.kind]: false,\n });\n\n const { defaultPluginKinds } = usePluginRegistry();\n const defaultPluginType = pluginTypes[0];\n const defaultPluginKind = defaultPluginType ? defaultPluginKinds?.[defaultPluginType] : undefined;\n const defaultPluginSelection =\n defaultPluginType && defaultPluginKind\n ? {\n type: defaultPluginType,\n kind: defaultPluginKind,\n }\n : undefined;\n const initPendingSelection = !value.selection && defaultPluginSelection ? defaultPluginSelection : undefined;\n\n // When kind changes and we haven't loaded that plugin before, we will need to enter a \"pending\" state so that we\n // can generate proper initial spec values that match the new plugin kind\n const [pendingSelection, setPendingSelection] = useState<PluginEditorSelection | undefined>(initPendingSelection);\n\n // Take a default kind in case user write explicitly an empty kind in the initial value\n useEffect(() => {\n if (value.selection.kind === '') {\n value.selection.kind = defaultPluginKind || '';\n }\n }, [value.selection, defaultPluginKind]);\n\n const { data: plugin, isFetching, error } = usePlugin(pendingSelection?.type, pendingSelection?.kind || '');\n\n useEffect(() => {\n // Nothing to do if no new plugin kind is pending\n if (!pendingSelection) return;\n\n // Can't get spec value until we have a plugin\n if (plugin === undefined || isFetching) return;\n\n // Fire an onChange to change to the pending kind with initial values from the plugin\n rememberCurrentSpecState();\n onChange({\n selection: pendingSelection,\n spec: plugin.createInitialOptions ? plugin.createInitialOptions() : {},\n });\n\n if (pendingSelection.type === 'Panel') {\n const panelPlugin = plugin as PanelPlugin;\n hideQueryState.current[pendingSelection.kind] = !!panelPlugin.hideQueryEditor;\n if (!!panelPlugin.hideQueryEditor !== hideQueryState.current[value.selection.kind]) {\n onHideQuery(!!panelPlugin.hideQueryEditor);\n }\n }\n setPendingSelection(undefined);\n }, [\n pendingSelection,\n plugin,\n isFetching,\n rememberCurrentSpecState,\n onChange,\n onHideQuery,\n hideQueryState,\n value.selection,\n ]);\n\n /**\n * When the user tries to change the plugin kind, make sure we have the correct spec for that plugin kind before we\n * make the switch.\n */\n const onSelectionChange: PluginKindSelectProps['onChange'] = (nextSelection) => {\n // If we already have state for this plugin type/kind from a previous selection, just use it\n const previousState = prevSpecState.current[nextSelection.type]?.[nextSelection.kind];\n if (previousState !== undefined) {\n rememberCurrentSpecState();\n onChange({\n selection: nextSelection,\n spec: previousState,\n });\n } else {\n // Otherwise, kick off the async loading process\n setPendingSelection(nextSelection);\n }\n\n if (\n nextSelection.type === 'Panel' &&\n hideQueryState.current[nextSelection.kind] !== undefined &&\n hideQueryState.current[value.selection.kind] !== hideQueryState.current[nextSelection.kind]\n ) {\n onHideQuery(!!hideQueryState.current[nextSelection.kind]);\n }\n };\n\n /**\n * Spec changes are independent and always just set the spec state.\n */\n const onSpecChange: PluginSpecEditorProps['onChange'] = (next) => {\n onChange(\n produce(value, (draft) => {\n draft.spec = next;\n })\n );\n };\n\n return {\n pendingSelection,\n isLoading: isFetching,\n error,\n onSelectionChange,\n onSpecChange,\n rememberCurrentSpecState,\n };\n}\n"],"names":["useState","useRef","useEffect","produce","usePlugin","usePluginRegistry","useEvent","usePluginEditor","props","pluginTypes","value","onHideQueryEditorChange","onChange","onHideQuery","prevSpecState","selection","type","kind","spec","rememberCurrentSpecState","byPluginType","current","undefined","hideQueryState","defaultPluginKinds","defaultPluginType","defaultPluginKind","defaultPluginSelection","initPendingSelection","pendingSelection","setPendingSelection","data","plugin","isFetching","error","createInitialOptions","panelPlugin","hideQueryEditor","onSelectionChange","nextSelection","previousState","onSpecChange","next","draft","isLoading"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAIjC,SAASA,QAAQ,EAAEC,MAAM,EAAEC,SAAS,QAAQ,QAAQ;AACpD,SAASC,OAAO,QAAQ,QAAQ;AAIhC,SAASC,SAAS,EAAEC,iBAAiB,QAAQ,gBAAgB;AAC7D,SAASC,QAAQ,QAAQ,cAAc;AAyCvC;;;;;CAKC,GACD,OAAO,SAASC,gBAAgBC,KAA2B;IAQzD,gEAAgE;IAChE,MAAM,EAAEC,WAAW,EAAEC,KAAK,EAAEC,0BAA0B,KAAa,CAAC,EAAE,GAAGH,OAAO,8FAA8F;IAE9K,kFAAkF;IAClF,MAAMI,WAAWN,SAASE,MAAMI,QAAQ;IACxC,MAAMC,cAAcP,SAASK;IAE7B,uGAAuG;IACvG,MA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,QAAQO,OAAO,CAACiC;YACdA,MAAMzB,IAAI,GAAGwB;QACf;IAEJ;IAEA,OAAO;QACLb;QACAe,WAAWX;QACXC;QACAI;QACAG;QACAtB;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/PluginRegistry/PluginRegistry.tsx"],"sourcesContent":["// Copyright 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 { UnknownSpec } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../../src/components/PluginRegistry/PluginRegistry.tsx"],"sourcesContent":["// Copyright 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 { UnknownSpec } from '@perses-dev/spec';\nimport { useRef, useCallback, useMemo, ReactNode, ReactElement } from 'react';\nimport {\n PluginModuleResource,\n PluginType,\n PluginImplementation,\n Plugin,\n PluginLoader,\n DefaultPluginKinds,\n} from '../../model';\nimport { PluginRegistryContext } from '../../runtime';\nimport { useEvent } from '../../utils';\nimport { usePluginIndexes, getTypeAndKindKey } from './plugin-indexes';\n\nexport interface PluginRegistryProps {\n pluginLoader: PluginLoader;\n defaultPluginKinds?: DefaultPluginKinds;\n children?: ReactNode;\n}\n\n/**\n * PluginRegistryContext provider that keeps track of all available plugins and provides an API for getting them or\n * querying the metadata about them.\n */\nexport function PluginRegistry(props: PluginRegistryProps): ReactElement {\n const {\n pluginLoader: { getInstalledPlugins, importPluginModule },\n children,\n defaultPluginKinds,\n } = props;\n\n const getPluginIndexes = usePluginIndexes(getInstalledPlugins);\n\n // De-dupe calls to import plugin modules\n const importCache = useRef(new Map<PluginModuleResource, Promise<unknown>>());\n\n // Do useEvent here since this accesses the importPluginModule prop and we want a stable reference to it for the\n // callback below\n const loadPluginModule = useEvent((resource: PluginModuleResource) => {\n let request = importCache.current.get(resource);\n if (request === undefined) {\n request = importPluginModule(resource);\n importCache.current.set(resource, request);\n\n // Remove failed requests from the cache so they can potentially be retried\n request.catch(() => importCache.current.delete(resource));\n }\n return request;\n });\n\n const getPlugin = useCallback(\n async <T extends PluginType>(kind: T, name: string): Promise<PluginImplementation<T>> => {\n // Get the indexes of the installed plugins\n const pluginIndexes = await getPluginIndexes();\n\n // Figure out what module the plugin is in by looking in the index\n const typeAndKindKey = getTypeAndKindKey(kind, name);\n const resource = pluginIndexes.pluginResourcesByNameAndKind.get(typeAndKindKey);\n if (resource === undefined) {\n throw new Error(`A ${name} plugin for kind '${kind}' is not installed`);\n }\n\n // Treat the plugin module as a bunch of named exports that have plugins\n const pluginModule = (await loadPluginModule(resource)) as Record<string, Plugin<UnknownSpec>>;\n\n // We currently assume that plugin modules will have named exports that match the kinds they handle\n const plugin = pluginModule[name];\n if (plugin === undefined) {\n throw new Error(\n `The ${name} plugin for kind '${kind}' is missing from the ${resource.metadata.name} plugin module`\n );\n }\n\n return plugin as PluginImplementation<T>;\n },\n [getPluginIndexes, loadPluginModule]\n );\n\n const listPluginMetadata = useCallback(\n async (pluginTypes: PluginType[]) => {\n const pluginIndexes = await getPluginIndexes();\n return pluginTypes.flatMap((type) => pluginIndexes.pluginMetadataByKind.get(type) ?? []);\n },\n [getPluginIndexes]\n );\n\n // Create the registry's context value and render\n const context = useMemo(\n () => ({ getPlugin, listPluginMetadata, defaultPluginKinds }),\n [getPlugin, listPluginMetadata, defaultPluginKinds]\n );\n return <PluginRegistryContext.Provider value={context}>{children}</PluginRegistryContext.Provider>;\n}\n"],"names":["useRef","useCallback","useMemo","PluginRegistryContext","useEvent","usePluginIndexes","getTypeAndKindKey","PluginRegistry","props","pluginLoader","getInstalledPlugins","importPluginModule","children","defaultPluginKinds","getPluginIndexes","importCache","Map","loadPluginModule","resource","request","current","get","undefined","set","catch","delete","getPlugin","kind","name","pluginIndexes","typeAndKindKey","pluginResourcesByNameAndKind","Error","pluginModule","plugin","metadata","listPluginMetadata","pluginTypes","flatMap","type","pluginMetadataByKind","context","Provider","value"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAGjC,SAASA,MAAM,EAAEC,WAAW,EAAEC,OAAO,QAAiC,QAAQ;AAS9E,SAASC,qBAAqB,QAAQ,gBAAgB;AACtD,SAASC,QAAQ,QAAQ,cAAc;AACvC,SAASC,gBAAgB,EAAEC,iBAAiB,QAAQ,mBAAmB;AAQvE;;;CAGC,GACD,OAAO,SAASC,eAAeC,KAA0B;IACvD,MAAM,EACJC,cAAc,EAAEC,mBAAmB,EAAEC,kBAAkB,EAAE,EACzDC,QAAQ,EACRC,kBAAkB,EACnB,GAAGL;IAEJ,MAAMM,mBAAmBT,iBAAiBK;IAE1C,yCAAyC;IACzC,MAAMK,cAAcf,OAAO,IAAIgB;IAE/B,gHAAgH;IAChH,iBAAiB;IACjB,MAAMC,mBAAmBb,SAAS,CAACc;QACjC,IAAIC,UAAUJ,YAAYK,OAAO,CAACC,GAAG,CAACH;QACtC,IAAIC,YAAYG,WAAW;YACzBH,UAAUR,mBAAmBO;YAC7BH,YAAYK,OAAO,CAACG,GAAG,CAACL,UAAUC;YAElC,2EAA2E;YAC3EA,QAAQK,KAAK,CAAC,IAAMT,YAAYK,OAAO,CAACK,MAAM,CAACP;QACjD;QACA,OAAOC;IACT;IAEA,MAAMO,YAAYzB,YAChB,OAA6B0B,MAASC;QACpC,2CAA2C;QAC3C,MAAMC,gBAAgB,MAAMf;QAE5B,kEAAkE;QAClE,MAAMgB,iBAAiBxB,kBAAkBqB,MAAMC;QAC/C,MAAMV,WAAWW,cAAcE,4BAA4B,CAACV,GAAG,CAACS;QAChE,IAAIZ,aAAaI,WAAW;YAC1B,MAAM,IAAIU,MAAM,CAAC,EAAE,EAAEJ,KAAK,kBAAkB,EAAED,KAAK,kBAAkB,CAAC;QACxE;QAEA,wEAAwE;QACxE,MAAMM,eAAgB,MAAMhB,iBAAiBC;QAE7C,mGAAmG;QACnG,MAAMgB,SAASD,YAAY,CAACL,KAAK;QACjC,IAAIM,WAAWZ,WAAW;YACxB,MAAM,IAAIU,MACR,CAAC,IAAI,EAAEJ,KAAK,kBAAkB,EAAED,KAAK,sBAAsB,EAAET,SAASiB,QAAQ,CAACP,IAAI,CAAC,cAAc,CAAC;QAEvG;QAEA,OAAOM;IACT,GACA;QAACpB;QAAkBG;KAAiB;IAGtC,MAAMmB,qBAAqBnC,YACzB,OAAOoC;QACL,MAAMR,gBAAgB,MAAMf;QAC5B,OAAOuB,YAAYC,OAAO,CAAC,CAACC,OAASV,cAAcW,oBAAoB,CAACnB,GAAG,CAACkB,SAAS,EAAE;IACzF,GACA;QAACzB;KAAiB;IAGpB,iDAAiD;IACjD,MAAM2B,UAAUvC,QACd,IAAO,CAAA;YAAEwB;YAAWU;YAAoBvB;QAAmB,CAAA,GAC3D;QAACa;QAAWU;QAAoBvB;KAAmB;IAErD,qBAAO,KAACV,sBAAsBuC,QAAQ;QAACC,OAAOF;kBAAU7B;;AAC1D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/PluginSpecEditor/PluginSpecEditor.tsx"],"sourcesContent":["// Copyright 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 { ErrorAlert } from '@perses-dev/components';\nimport { UnknownSpec } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../../src/components/PluginSpecEditor/PluginSpecEditor.tsx"],"sourcesContent":["// Copyright 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 { ErrorAlert } from '@perses-dev/components';\nimport { UnknownSpec } from '@perses-dev/spec';\nimport { ReactElement } from 'react';\nimport { CircularProgress, Stack } from '@mui/material';\nimport { OptionsEditorProps } from '../../model';\nimport { usePlugin } from '../../runtime';\nimport { PluginEditorSelection } from '../PluginEditor';\n\nexport interface PluginSpecEditorProps extends OptionsEditorProps<UnknownSpec> {\n pluginSelection: PluginEditorSelection;\n isEditor?: boolean;\n}\n\nexport function PluginSpecEditor(props: PluginSpecEditorProps): ReactElement | null {\n const {\n pluginSelection: { type: pluginType, kind: pluginKind },\n ...others\n } = props;\n const { data: plugin, isLoading, error } = usePlugin(pluginType, pluginKind);\n\n if (error) {\n return <ErrorAlert error={error} />;\n }\n\n if (isLoading) {\n return (\n <Stack width=\"100%\" sx={{ alignItems: 'center', justifyContent: 'center' }}>\n <CircularProgress />\n </Stack>\n );\n }\n\n if (!plugin) {\n throw new Error(`Missing implementation for ${pluginType} plugin with kind '${pluginKind}'`);\n }\n\n if (pluginType === 'Panel') {\n throw new Error('This editor should not be used for panel type. Please use Panel Spec Editor instead.');\n }\n const { OptionsEditorComponent } = plugin;\n\n return OptionsEditorComponent ? <OptionsEditorComponent {...others} /> : null;\n}\n"],"names":["ErrorAlert","CircularProgress","Stack","usePlugin","PluginSpecEditor","props","pluginSelection","type","pluginType","kind","pluginKind","others","data","plugin","isLoading","error","width","sx","alignItems","justifyContent","Error","OptionsEditorComponent"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,UAAU,QAAQ,yBAAyB;AAGpD,SAASC,gBAAgB,EAAEC,KAAK,QAAQ,gBAAgB;AAExD,SAASC,SAAS,QAAQ,gBAAgB;AAQ1C,OAAO,SAASC,iBAAiBC,KAA4B;IAC3D,MAAM,EACJC,iBAAiB,EAAEC,MAAMC,UAAU,EAAEC,MAAMC,UAAU,EAAE,EACvD,GAAGC,QACJ,GAAGN;IACJ,MAAM,EAAEO,MAAMC,MAAM,EAAEC,SAAS,EAAEC,KAAK,EAAE,GAAGZ,UAAUK,YAAYE;IAEjE,IAAIK,OAAO;QACT,qBAAO,KAACf;YAAWe,OAAOA;;IAC5B;IAEA,IAAID,WAAW;QACb,qBACE,KAACZ;YAAMc,OAAM;YAAOC,IAAI;gBAAEC,YAAY;gBAAUC,gBAAgB;YAAS;sBACvE,cAAA,KAAClB;;IAGP;IAEA,IAAI,CAACY,QAAQ;QACX,MAAM,IAAIO,MAAM,CAAC,2BAA2B,EAAEZ,WAAW,mBAAmB,EAAEE,WAAW,CAAC,CAAC;IAC7F;IAEA,IAAIF,eAAe,SAAS;QAC1B,MAAM,IAAIY,MAAM;IAClB;IACA,MAAM,EAAEC,sBAAsB,EAAE,GAAGR;IAEnC,OAAOQ,uCAAyB,KAACA;QAAwB,GAAGV,MAAM;SAAO;AAC3E"}
|
|
@@ -18,7 +18,7 @@ import ZoomIn from 'mdi-material-ui/PlusCircleOutline';
|
|
|
18
18
|
import ZoomOut from 'mdi-material-ui/MinusCircleOutline';
|
|
19
19
|
import { Stack } from '@mui/material';
|
|
20
20
|
import { RefreshIntervalPicker, InfoTooltip, ToolbarIconButton, TimeRangeSelector, getTimeZoneOptions, buildRelativeTimeOption } from '@perses-dev/components';
|
|
21
|
-
import { parseDurationString } from '@perses-dev/
|
|
21
|
+
import { parseDurationString } from '@perses-dev/spec';
|
|
22
22
|
import { useCallback } from 'react';
|
|
23
23
|
import { TOOLTIP_TEXT } from '../../constants';
|
|
24
24
|
import { useTimeRange, useShowCustomTimeRangeSetting, useTimeRangeOptionsSetting, useShowZoomRangeSetting } from '../../runtime';
|