grafana/public/app/features/dashboard/state/PanelModel.ts

687 lines
17 KiB
TypeScript
Raw Normal View History

import { cloneDeep, defaultsDeep, isArray, isEqual, keys } from 'lodash';
import { v4 as uuidv4 } from 'uuid';
import {
DataConfigSource,
DataFrameDTO,
Templating: Migrates some variable types from Angular to React/Redux (#22434) * Refactor: Adds variables in state to TemplateSrv * Refactor: Introduces some typings and structures * Refactor: Introduces picker to adapter * Refactor: Removes useState and introduces contains instead * Refactor: Introduces Variable Editor * Refactor: Adds uuid and simplifies state * Refactor: Consolidates to VariableRenderer * Refactor: Adds name change capability * Refactor: Adds variableMiddleware * Refactor: Adds ability to change Angular type to type in State * Fix: Fixes so we check for duplicate names * Refactor: Adds ability to change State type to type in Angular * Refactor: Updates name in dashboard templating list * Refactor: Adds label change to VariableEditor * Refactor: Adds hide change to VariableEditor * Refactor: Adds update ability * Refactor: Adds tooltip * Refactor: Adds SelectionOptionsEditor * Refactor: Adds query editor and validation * Refactor: Adds regex and sort to editor * Refactor: Adds Selection options * Refactor: Adds Varible Values Previewer * Refactor: Changes from array in state to Record * Refactor: Removes getVariableAtIndex from templateSrv * Tests: Fixs broken tests * Chore: Fixes duplicate merge import * Refactor: Removes strict null errors * Refactor: Adds duplicate variable * Refactor: Adds remove variable * Refactor: Adds change order of variables * Refactor: Adds add new variable * Chore: Fixes Prettier formatting * Refactor: Adds VariablePicker * Fixed so sub menu is displayed when we only have redux template variables. * removed unused variable. * tags will be visibile in the new react picker. * added some nice colors to the tags. * Added thunk for selecting a tag. * Refactor: Cleans up templating state when dashboard unloads * Refactor: Adds save capabilities for variables in state * added possibility to select tag. * Added so you can deselect a tag. * Fixed issue with coloring on top. * minor refactoring to make the code more slim. * Refactor: Fixes dispatch return and copy of variable * selecting options when tag i selected * small refactoring. * fixed so we use options. * Refactor: Adds getValueForUrl capabilities * first implementation of keyboard navigation on picker. * removed comment. * fixed so you can toggle all options. * Refactor: Simplified state handling using Redux Toolkit and flat reducer structure * Refactor: Adds sharedTemplatingReducer and queryVariableReducer * Tests: Fixs broken tests * Chore: Removes some strict null errors * Tests: Fix broken tests * Refactor: Splitted QueryVariablePicker into smaller components * Refactor: Moves linktext and selected tags to component instead * Fix: Fixes the ability to have multiple dropdowns opened at same time * Fix: Fixes onKeyDown from prev refactor * Refactor: Adds searchfilter searching * Tests: Fixes after running e2e tests * Refactor: Adds an attempt to solve dependencies at startup * Refactor: Adds feature toggle * Refactor: Resets all angular files to master * Refactor: Move stuff to query folder * Refactor: Initial commit for SubMenu component * Refactor: Updated DashboardModel with new list * Refactor: Adds feature toggle to dashboard model and friends * Refactor: Adds picker to SubMenu * Refactor: Fixes styling on SubMenu * Refactor: Fixes processvariables * Refactor: Initial EditorList skeleton * Refactor: Refactors out VariableEditorList and VariableEditorContainer * Refactor: Adds New variable functionality * Refactor: Adds registred types * Refactor: Adds edit existing variable functionality * Refactor: Changes params to thunks * Refactor: Small fix for cleaning up state when clicking update/add * Refactor: Better typings for outer containers * Refactor: Adds change order functionality * Refactor: Removed notify angular args * Change so the url is in sync with the redux template variables. * Adding support for saving proper values and checking changes. * Refactor: Adds duplicate variable functionality * Feature: Adds remove variable functionality * Refactor: Small refactor so e2e tests work as before * Refactor: Returns null if no visible variables * Refactor: Adds annotations to SubMenu * Refactor: Fixes toggling of annotations in SubMenu * added dashboard links to new submehu. * Refactor: Small refactor breaking up into smaller components * Fix: Fixes infinite recursive loop when changing varible name * Templating: Do not mutate location query state * Refactor: Fixes minor timing issue when adding new variable * Refactor: removes initialization in variable_srv constructor * Refactor: Suggestion on how to handle templating.list in DashboardExporter * Refactor: Adds getVariables typings and changes ChangeTracker and ShareSnapshotCtrl * Refactor: Adds getVariable on DashboardModel and changes DashboardMigrator * Fix: Fixes repeated panels * wip: starting to add custom variable type. * Refactor: Merging two different toVariablePayload functions * Tests: Fixes broken tests * Fix: Reduces strict null errors * Tests: Initial commit and fixes strange dependency order * Tests: Covers sharedTemplatingReducer with tests * Refactor: Rename state/index.ts => state/reducers.ts as every where else * Refactor: Renames and moves adapters.ts * Tests: Adds tests for templatingReducer * Tests: Adds intitial tests for queryVariableReducer * starting to ad custom variable. * Tests: Adds more queryVariableReducer tests * Added support for custom variable. Next up applying some DRY principles and refactoring. * fixed compile issue. * added todo. * Tests: Fixes broken test * Tests: Covers queryVariableReducer with tests and fixed a couple of bugs * Fix: Fixes broken test * Fix: Reduces strict null errors * change so custom won't be depending on anything elese. * fixed descriptions. * removed unused dependency. * Fixed issue when adding a new variable and editor is being unmount twice. * fixed issue with select option loop. * changed so we update query on typing in editor and removed it from component state. * Moved runQuery up one level in the component tree. * renamed action and moved it to custom actions. * moved applyStateChanges to shared code. * removed todo comment. * first stab on moving picker to more general. * Refactor: Changes so we always show variables type * removed duplicate code regarding picker. * Did some renamings. * Feature: Adds text box variable type * moved tests from query reducer to picker reducer. * Removed picker from VariableState. * removed reference to picker. * Some more refactorings of the picker reducer + actions. * Chore: Refactors away editor state to its own state slice (#22515) * Refactor: Inital move, tests not working * Tests: Adds editorReducer tests * Refactor: Cleaning up * Refactor: Moves logic to thunk instead * Refactor: Initial commit * Refactor: Combines reducers to one state * Refactor: Adds combine reducers * moved navigation logic flow to a thunk instead of in the component. * fixed issue with rendering picker link. * Refactor: Removes variable prop from templating.variables * refactored and removed some more code. * Feature: adds Constant variable type * fixed so tags can be selected. * Fix: fixes default hide for constant and enum order * fixed so tags works again. * Fix: fixes so we use Angular editor when newVariables is not defined * Fix: fixes wrong hide default for Constant variable * Fix: fixes bug when using duplicate button * Fix: changes action id * Tests: prepares for newVariables * Chore: reduces strict null errors * Refactor: removes uuidInEditorReducer for simplification * Chore: changes after PR comments * Chore: uses getConfig instead of config * Tests: fixes so e2e tests check for feature toggle and fixed initLock bug * Refactor: changes so sharedReducer uses createSlice instead * Refactor: changes textBoxVariableReducer to use creactSlice instead * Refactor: changes queryBoxVariableReducer to use creactSlice instead * Refactor: changes customVariableReducer to use creactSlice instead * Refactor: changes constantVariableReducer to use creactSlice instead * Refactor: moves types to specific types.ts files instead * changed so we use queryValue stored on the variable to populate options input when opening picker. * Feature: adds the ability to test templating thunks using real store and middleware * Chore: cleans up unused import * excluded queryValue from the getSaveModel * Refactor: adds whenAsyncActionIsDispatched to reduxTester * Tests: adds initial tests for processVariables * Added reducer tests for constant variable. * added tests for custom reducer. * added tets for texbox reducer. * Tests: adds more tests for ProcessVariable * Refactor: fixes processVariable flow so we do notrun updateOptions twice * Tests: finishes tests for processVariables and removed skip test * added actions tests for custom and constant. * Tests: adds tests for setOptionFromUrl * Tests: adds a naive variable mock builder * Tests: adds tests for validateVariableSelectionState * added tests for query variable actions. * added last test for query actions. * added more tests. * some more tests. * fixed typing errors. * Fixed issues with variable tags. Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com> Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
2020-03-10 02:53:41 -05:00
DataLink,
DataLinkBuiltInVars,
DataQuery,
DataTransformerConfig,
EventBusSrv,
FieldConfigSource,
Templating: Migrates some variable types from Angular to React/Redux (#22434) * Refactor: Adds variables in state to TemplateSrv * Refactor: Introduces some typings and structures * Refactor: Introduces picker to adapter * Refactor: Removes useState and introduces contains instead * Refactor: Introduces Variable Editor * Refactor: Adds uuid and simplifies state * Refactor: Consolidates to VariableRenderer * Refactor: Adds name change capability * Refactor: Adds variableMiddleware * Refactor: Adds ability to change Angular type to type in State * Fix: Fixes so we check for duplicate names * Refactor: Adds ability to change State type to type in Angular * Refactor: Updates name in dashboard templating list * Refactor: Adds label change to VariableEditor * Refactor: Adds hide change to VariableEditor * Refactor: Adds update ability * Refactor: Adds tooltip * Refactor: Adds SelectionOptionsEditor * Refactor: Adds query editor and validation * Refactor: Adds regex and sort to editor * Refactor: Adds Selection options * Refactor: Adds Varible Values Previewer * Refactor: Changes from array in state to Record * Refactor: Removes getVariableAtIndex from templateSrv * Tests: Fixs broken tests * Chore: Fixes duplicate merge import * Refactor: Removes strict null errors * Refactor: Adds duplicate variable * Refactor: Adds remove variable * Refactor: Adds change order of variables * Refactor: Adds add new variable * Chore: Fixes Prettier formatting * Refactor: Adds VariablePicker * Fixed so sub menu is displayed when we only have redux template variables. * removed unused variable. * tags will be visibile in the new react picker. * added some nice colors to the tags. * Added thunk for selecting a tag. * Refactor: Cleans up templating state when dashboard unloads * Refactor: Adds save capabilities for variables in state * added possibility to select tag. * Added so you can deselect a tag. * Fixed issue with coloring on top. * minor refactoring to make the code more slim. * Refactor: Fixes dispatch return and copy of variable * selecting options when tag i selected * small refactoring. * fixed so we use options. * Refactor: Adds getValueForUrl capabilities * first implementation of keyboard navigation on picker. * removed comment. * fixed so you can toggle all options. * Refactor: Simplified state handling using Redux Toolkit and flat reducer structure * Refactor: Adds sharedTemplatingReducer and queryVariableReducer * Tests: Fixs broken tests * Chore: Removes some strict null errors * Tests: Fix broken tests * Refactor: Splitted QueryVariablePicker into smaller components * Refactor: Moves linktext and selected tags to component instead * Fix: Fixes the ability to have multiple dropdowns opened at same time * Fix: Fixes onKeyDown from prev refactor * Refactor: Adds searchfilter searching * Tests: Fixes after running e2e tests * Refactor: Adds an attempt to solve dependencies at startup * Refactor: Adds feature toggle * Refactor: Resets all angular files to master * Refactor: Move stuff to query folder * Refactor: Initial commit for SubMenu component * Refactor: Updated DashboardModel with new list * Refactor: Adds feature toggle to dashboard model and friends * Refactor: Adds picker to SubMenu * Refactor: Fixes styling on SubMenu * Refactor: Fixes processvariables * Refactor: Initial EditorList skeleton * Refactor: Refactors out VariableEditorList and VariableEditorContainer * Refactor: Adds New variable functionality * Refactor: Adds registred types * Refactor: Adds edit existing variable functionality * Refactor: Changes params to thunks * Refactor: Small fix for cleaning up state when clicking update/add * Refactor: Better typings for outer containers * Refactor: Adds change order functionality * Refactor: Removed notify angular args * Change so the url is in sync with the redux template variables. * Adding support for saving proper values and checking changes. * Refactor: Adds duplicate variable functionality * Feature: Adds remove variable functionality * Refactor: Small refactor so e2e tests work as before * Refactor: Returns null if no visible variables * Refactor: Adds annotations to SubMenu * Refactor: Fixes toggling of annotations in SubMenu * added dashboard links to new submehu. * Refactor: Small refactor breaking up into smaller components * Fix: Fixes infinite recursive loop when changing varible name * Templating: Do not mutate location query state * Refactor: Fixes minor timing issue when adding new variable * Refactor: removes initialization in variable_srv constructor * Refactor: Suggestion on how to handle templating.list in DashboardExporter * Refactor: Adds getVariables typings and changes ChangeTracker and ShareSnapshotCtrl * Refactor: Adds getVariable on DashboardModel and changes DashboardMigrator * Fix: Fixes repeated panels * wip: starting to add custom variable type. * Refactor: Merging two different toVariablePayload functions * Tests: Fixes broken tests * Fix: Reduces strict null errors * Tests: Initial commit and fixes strange dependency order * Tests: Covers sharedTemplatingReducer with tests * Refactor: Rename state/index.ts => state/reducers.ts as every where else * Refactor: Renames and moves adapters.ts * Tests: Adds tests for templatingReducer * Tests: Adds intitial tests for queryVariableReducer * starting to ad custom variable. * Tests: Adds more queryVariableReducer tests * Added support for custom variable. Next up applying some DRY principles and refactoring. * fixed compile issue. * added todo. * Tests: Fixes broken test * Tests: Covers queryVariableReducer with tests and fixed a couple of bugs * Fix: Fixes broken test * Fix: Reduces strict null errors * change so custom won't be depending on anything elese. * fixed descriptions. * removed unused dependency. * Fixed issue when adding a new variable and editor is being unmount twice. * fixed issue with select option loop. * changed so we update query on typing in editor and removed it from component state. * Moved runQuery up one level in the component tree. * renamed action and moved it to custom actions. * moved applyStateChanges to shared code. * removed todo comment. * first stab on moving picker to more general. * Refactor: Changes so we always show variables type * removed duplicate code regarding picker. * Did some renamings. * Feature: Adds text box variable type * moved tests from query reducer to picker reducer. * Removed picker from VariableState. * removed reference to picker. * Some more refactorings of the picker reducer + actions. * Chore: Refactors away editor state to its own state slice (#22515) * Refactor: Inital move, tests not working * Tests: Adds editorReducer tests * Refactor: Cleaning up * Refactor: Moves logic to thunk instead * Refactor: Initial commit * Refactor: Combines reducers to one state * Refactor: Adds combine reducers * moved navigation logic flow to a thunk instead of in the component. * fixed issue with rendering picker link. * Refactor: Removes variable prop from templating.variables * refactored and removed some more code. * Feature: adds Constant variable type * fixed so tags can be selected. * Fix: fixes default hide for constant and enum order * fixed so tags works again. * Fix: fixes so we use Angular editor when newVariables is not defined * Fix: fixes wrong hide default for Constant variable * Fix: fixes bug when using duplicate button * Fix: changes action id * Tests: prepares for newVariables * Chore: reduces strict null errors * Refactor: removes uuidInEditorReducer for simplification * Chore: changes after PR comments * Chore: uses getConfig instead of config * Tests: fixes so e2e tests check for feature toggle and fixed initLock bug * Refactor: changes so sharedReducer uses createSlice instead * Refactor: changes textBoxVariableReducer to use creactSlice instead * Refactor: changes queryBoxVariableReducer to use creactSlice instead * Refactor: changes customVariableReducer to use creactSlice instead * Refactor: changes constantVariableReducer to use creactSlice instead * Refactor: moves types to specific types.ts files instead * changed so we use queryValue stored on the variable to populate options input when opening picker. * Feature: adds the ability to test templating thunks using real store and middleware * Chore: cleans up unused import * excluded queryValue from the getSaveModel * Refactor: adds whenAsyncActionIsDispatched to reduxTester * Tests: adds initial tests for processVariables * Added reducer tests for constant variable. * added tests for custom reducer. * added tets for texbox reducer. * Tests: adds more tests for ProcessVariable * Refactor: fixes processVariable flow so we do notrun updateOptions twice * Tests: finishes tests for processVariables and removed skip test * added actions tests for custom and constant. * Tests: adds tests for setOptionFromUrl * Tests: adds a naive variable mock builder * Tests: adds tests for validateVariableSelectionState * added tests for query variable actions. * added last test for query actions. * added more tests. * some more tests. * fixed typing errors. * Fixed issues with variable tags. Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com> Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
2020-03-10 02:53:41 -05:00
PanelPlugin,
PanelPluginDataSupport,
ScopedVars,
urlUtil,
PanelModel as IPanelModel,
DataSourceRef,
} from '@grafana/data';
import { getTemplateSrv, RefreshEvent } from '@grafana/runtime';
import config from 'app/core/config';
import { safeStringifyValue } from 'app/core/utils/explore';
import { getNextRefIdChar } from 'app/core/utils/query';
import { QueryGroupOptions } from 'app/types';
import {
PanelOptionsChangedEvent,
PanelQueriesChangedEvent,
PanelTransformationsChangedEvent,
RenderEvent,
} from 'app/types/events';
import { PanelModelLibraryPanel } from '../../library-panels/types';
import { PanelQueryRunner } from '../../query/state/PanelQueryRunner';
import { getVariablesUrlParams } from '../../variables/getAllVariableValuesForUrl';
import { getTimeSrv } from '../services/TimeSrv';
import { TimeOverrideResult } from '../utils/panel';
import {
filterFieldConfigOverrides,
getPanelOptionsWithDefaults,
isStandardFieldProp,
restoreCustomOverrideRules,
} from './getPanelOptionsWithDefaults';
export interface GridPos {
2017-10-10 02:34:14 -05:00
x: number;
y: number;
w: number;
h: number;
2017-10-16 02:55:55 -05:00
static?: boolean;
}
type RunPanelQueryOptions = {
/** @deprecate */
dashboardId: number;
dashboardUID: string;
dashboardTimezone: string;
timeData: TimeOverrideResult;
width: number;
publicDashboardAccessToken?: string;
};
const notPersistedProperties: { [str: string]: boolean } = {
events: true,
isViewing: true,
2017-12-20 05:33:33 -06:00
isEditing: true,
isInView: true,
hasRefreshed: true,
cachedPluginOptions: true,
plugin: true,
queryRunner: true,
replaceVariables: true,
configRev: true,
hasSavedPanelEditChange: true,
getDisplayTitle: true,
dataSupport: true,
key: true,
};
// For angular panels we need to clean up properties when changing type
// To make sure the change happens without strange bugs happening when panels use same
// named property with different type / value expectations
// This is not required for react panels
const mustKeepProps: { [str: string]: boolean } = {
id: true,
gridPos: true,
type: true,
title: true,
scopedVars: true,
repeat: true,
repeatPanelId: true,
repeatDirection: true,
repeatedByRow: true,
minSpan: true,
collapsed: true,
panels: true,
targets: true,
datasource: true,
timeFrom: true,
timeShift: true,
hideTimeOverride: true,
description: true,
links: true,
fullscreen: true,
isEditing: true,
hasRefreshed: true,
events: true,
cacheTimeout: true,
cachedPluginOptions: true,
2018-12-06 03:34:27 -06:00
transparent: true,
2019-03-22 15:45:09 -05:00
pluginVersion: true,
queryRunner: true,
transformations: true,
FieldOverrides: Move FieldConfigSource from fieldOptions to PanelModel.fieldConfig (#22600) * Apply field overrides in PanelChrome * Move applyFieldOverrides to panel query runner * Review updates * Make sure overrides are applied back on souce panel when exiting the new edit mode * TS ignores in est * Make field display work in viz repeater * Review updates * Review and test updates * Change the way overrides and trransformations are retrieved in PQR * Add fieldConfig property to PanelModel * Dashboard migration v1 * Use field config when exiting new panel edit mode * Gauge - use fieldConfig from panel model * FieldDisplayOptions - don's extend FieldConfigSource * Fix fieldDisplay ts * StatPanel updated * Stat panel defaults applied * Table2 panel options update * React graph updates * BarGauge updated * PieChart, Gauge, BarGauge and Stat updates * PieChart - remove field config defaults from options * FieldDisplayEditor - remove unused methos * PanelModel - remove debugger * Remove fieldConfig from field options when migrating dashboard * Update data links migrations * Update fieldDisaplay tests to respect new fieldConfig * Update dashboard schema version in snapshots * Fix BarGaugePanel test * Rebase fixes * Add onFieldConfigChange to PanelProps type * Update shared single stat migration * Pass PanelModel instead of options only for panel type change handler [breaking] * Renames * Don't mutate panel options * Migrations update * Remove obsolete snap * Minor updates after review * Fix null checks * Temporarily (until we decide to switch to new pane edit) bring back old aditors * Temporarily rename ValueMappingEditor and MappingRow to Legacy* * Migrations update * Updae setFieldConfigDefaults API * Update the way field config defaults are applied * Use standard field config for gauge, bar gauge and stat panels * refactoring * Revert dashboard fieldOptions migrations as those are handled by single stat migrator * Fix ts in tests * Strict null fix and some minor fixes Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
2020-03-19 05:50:31 -05:00
fieldConfig: true,
maxDataPoints: true,
interval: true,
replaceVariables: true,
libraryPanel: true,
getDisplayTitle: true,
configRev: true,
key: true,
};
const defaults: any = {
gridPos: { x: 0, y: 0, h: 3, w: 6 },
targets: [{ refId: 'A' }],
cachedPluginOptions: {},
2018-12-06 03:34:27 -06:00
transparent: false,
options: {},
fieldConfig: {
defaults: {},
overrides: [],
},
title: '',
};
export class PanelModel implements DataConfigSource, IPanelModel {
/* persisted id, used in URL to identify a panel */
id!: number;
gridPos!: GridPos;
type!: string;
title!: string;
alert?: any;
2019-03-04 03:42:59 -06:00
scopedVars?: ScopedVars;
repeat?: string;
repeatIteration?: number;
repeatPanelId?: number;
repeatDirection?: string;
repeatedByRow?: boolean;
maxPerRow?: number;
2017-10-17 07:53:52 -05:00
collapsed?: boolean;
panels?: PanelModel[];
declare targets: DataQuery[];
transformations?: DataTransformerConfig[];
datasource: DataSourceRef | null = null;
thresholds?: any;
2019-03-22 15:45:09 -05:00
pluginVersion?: string;
snapshotData?: DataFrameDTO[];
timeFrom?: any;
timeShift?: any;
hideTimeOverride?: any;
declare options: {
2019-02-18 04:40:25 -06:00
[key: string]: any;
};
declare fieldConfig: FieldConfigSource;
maxDataPoints?: number | null;
interval?: string | null;
description?: string;
Graph: Add data links feature (click on graph) (#17267) * WIP: initial panel links editor * WIP: Added dashboard migration to new panel drilldown link schema * Make link_srv interpolate new variables * Fix failing tests * Drilldown: Add context menu to graph viz (#17284) * Add simple context menu for adding graph annotations and showing drilldown links * Close graph context menu when user start scrolling * Move context menu component to grafana/ui * Make graph context menu appear on click, use cmd/ctrl click for quick annotations * Move graph context menu controller to separate file * Drilldown: datapoint variables interpolation (#17328) * Add simple context menu for adding graph annotations and showing drilldown links * Close graph context menu when user start scrolling * Move context menu component to grafana/ui * Make graph context menu appear on click, use cmd/ctrl click for quick annotations * Add util for absolute time range transformation * Add series name and datapoint timestamp interpolation * Rename drilldown link variables tot snake case, use const values instead of strings in tests * Bring LinkSrv.getPanelLinkAnchorInfo for compatibility reasons and add deprecation warning * Rename seriesLabel to seriesName * Drilldown: use separate editors for panel and series links (#17355) * Use correct target ini context menu links * Rename PanelLinksEditor to DrilldownLinksEditor and mote it to grafana/ui * Expose DrilldownLinksEditor as an angular directive * Enable visualization specifix drilldown links * Props interfaces rename * Drilldown: Add variables suggestion and syntax highlighting for drilldown link editor (#17391) * Add variables suggestion in drilldown link editor * Enable prism * Fix backspace not working * Move slate value helpers to grafana/ui * Add syntax higlighting for links input * Rename drilldown link components to data links * Add template variabe suggestions * Bugfix * Fix regexp not working in Firefox * Display correct links in panel header corner * bugfix * bugfix * Bugfix * Context menu UI tweaks * Use data link terminology instead of drilldown * DataLinks: changed autocomplete syntax * Use singular form for data link * Use the same syntax higlighting for built-in and template variables in data links editor * UI improvements to context menu * UI review tweaks * Tweak layout of data link editor * Fix vertical spacing * Remove data link header in context menu * Remove pointer cursor from series label in context menu * Fix variable selection on click * DataLinks: migrations for old links * Update docs about data links * Use value time instead of time range when interpolating datapoint timestamp * Remove not used util * Update docs * Moved icon a bit more down * Interpolate value ts only when using __value_time variable * Bring href property back to LinkModel * Add any type annotations * Fix TS error on slate's Value type * minor changes
2019-06-25 04:38:51 -05:00
links?: DataLink[];
declare transparent: boolean;
libraryPanel?: { uid: undefined; name: string; version?: number } | PanelModelLibraryPanel;
autoMigrateFrom?: string;
// non persisted
isViewing = false;
isEditing = false;
isInView = false;
configRev = 0; // increments when configs change
hasSavedPanelEditChange?: boolean;
hasRefreshed?: boolean;
cacheTimeout?: string | null;
cachedPluginOptions: Record<string, PanelOptionsCache> = {};
Templating: Migrates some variable types from Angular to React/Redux (#22434) * Refactor: Adds variables in state to TemplateSrv * Refactor: Introduces some typings and structures * Refactor: Introduces picker to adapter * Refactor: Removes useState and introduces contains instead * Refactor: Introduces Variable Editor * Refactor: Adds uuid and simplifies state * Refactor: Consolidates to VariableRenderer * Refactor: Adds name change capability * Refactor: Adds variableMiddleware * Refactor: Adds ability to change Angular type to type in State * Fix: Fixes so we check for duplicate names * Refactor: Adds ability to change State type to type in Angular * Refactor: Updates name in dashboard templating list * Refactor: Adds label change to VariableEditor * Refactor: Adds hide change to VariableEditor * Refactor: Adds update ability * Refactor: Adds tooltip * Refactor: Adds SelectionOptionsEditor * Refactor: Adds query editor and validation * Refactor: Adds regex and sort to editor * Refactor: Adds Selection options * Refactor: Adds Varible Values Previewer * Refactor: Changes from array in state to Record * Refactor: Removes getVariableAtIndex from templateSrv * Tests: Fixs broken tests * Chore: Fixes duplicate merge import * Refactor: Removes strict null errors * Refactor: Adds duplicate variable * Refactor: Adds remove variable * Refactor: Adds change order of variables * Refactor: Adds add new variable * Chore: Fixes Prettier formatting * Refactor: Adds VariablePicker * Fixed so sub menu is displayed when we only have redux template variables. * removed unused variable. * tags will be visibile in the new react picker. * added some nice colors to the tags. * Added thunk for selecting a tag. * Refactor: Cleans up templating state when dashboard unloads * Refactor: Adds save capabilities for variables in state * added possibility to select tag. * Added so you can deselect a tag. * Fixed issue with coloring on top. * minor refactoring to make the code more slim. * Refactor: Fixes dispatch return and copy of variable * selecting options when tag i selected * small refactoring. * fixed so we use options. * Refactor: Adds getValueForUrl capabilities * first implementation of keyboard navigation on picker. * removed comment. * fixed so you can toggle all options. * Refactor: Simplified state handling using Redux Toolkit and flat reducer structure * Refactor: Adds sharedTemplatingReducer and queryVariableReducer * Tests: Fixs broken tests * Chore: Removes some strict null errors * Tests: Fix broken tests * Refactor: Splitted QueryVariablePicker into smaller components * Refactor: Moves linktext and selected tags to component instead * Fix: Fixes the ability to have multiple dropdowns opened at same time * Fix: Fixes onKeyDown from prev refactor * Refactor: Adds searchfilter searching * Tests: Fixes after running e2e tests * Refactor: Adds an attempt to solve dependencies at startup * Refactor: Adds feature toggle * Refactor: Resets all angular files to master * Refactor: Move stuff to query folder * Refactor: Initial commit for SubMenu component * Refactor: Updated DashboardModel with new list * Refactor: Adds feature toggle to dashboard model and friends * Refactor: Adds picker to SubMenu * Refactor: Fixes styling on SubMenu * Refactor: Fixes processvariables * Refactor: Initial EditorList skeleton * Refactor: Refactors out VariableEditorList and VariableEditorContainer * Refactor: Adds New variable functionality * Refactor: Adds registred types * Refactor: Adds edit existing variable functionality * Refactor: Changes params to thunks * Refactor: Small fix for cleaning up state when clicking update/add * Refactor: Better typings for outer containers * Refactor: Adds change order functionality * Refactor: Removed notify angular args * Change so the url is in sync with the redux template variables. * Adding support for saving proper values and checking changes. * Refactor: Adds duplicate variable functionality * Feature: Adds remove variable functionality * Refactor: Small refactor so e2e tests work as before * Refactor: Returns null if no visible variables * Refactor: Adds annotations to SubMenu * Refactor: Fixes toggling of annotations in SubMenu * added dashboard links to new submehu. * Refactor: Small refactor breaking up into smaller components * Fix: Fixes infinite recursive loop when changing varible name * Templating: Do not mutate location query state * Refactor: Fixes minor timing issue when adding new variable * Refactor: removes initialization in variable_srv constructor * Refactor: Suggestion on how to handle templating.list in DashboardExporter * Refactor: Adds getVariables typings and changes ChangeTracker and ShareSnapshotCtrl * Refactor: Adds getVariable on DashboardModel and changes DashboardMigrator * Fix: Fixes repeated panels * wip: starting to add custom variable type. * Refactor: Merging two different toVariablePayload functions * Tests: Fixes broken tests * Fix: Reduces strict null errors * Tests: Initial commit and fixes strange dependency order * Tests: Covers sharedTemplatingReducer with tests * Refactor: Rename state/index.ts => state/reducers.ts as every where else * Refactor: Renames and moves adapters.ts * Tests: Adds tests for templatingReducer * Tests: Adds intitial tests for queryVariableReducer * starting to ad custom variable. * Tests: Adds more queryVariableReducer tests * Added support for custom variable. Next up applying some DRY principles and refactoring. * fixed compile issue. * added todo. * Tests: Fixes broken test * Tests: Covers queryVariableReducer with tests and fixed a couple of bugs * Fix: Fixes broken test * Fix: Reduces strict null errors * change so custom won't be depending on anything elese. * fixed descriptions. * removed unused dependency. * Fixed issue when adding a new variable and editor is being unmount twice. * fixed issue with select option loop. * changed so we update query on typing in editor and removed it from component state. * Moved runQuery up one level in the component tree. * renamed action and moved it to custom actions. * moved applyStateChanges to shared code. * removed todo comment. * first stab on moving picker to more general. * Refactor: Changes so we always show variables type * removed duplicate code regarding picker. * Did some renamings. * Feature: Adds text box variable type * moved tests from query reducer to picker reducer. * Removed picker from VariableState. * removed reference to picker. * Some more refactorings of the picker reducer + actions. * Chore: Refactors away editor state to its own state slice (#22515) * Refactor: Inital move, tests not working * Tests: Adds editorReducer tests * Refactor: Cleaning up * Refactor: Moves logic to thunk instead * Refactor: Initial commit * Refactor: Combines reducers to one state * Refactor: Adds combine reducers * moved navigation logic flow to a thunk instead of in the component. * fixed issue with rendering picker link. * Refactor: Removes variable prop from templating.variables * refactored and removed some more code. * Feature: adds Constant variable type * fixed so tags can be selected. * Fix: fixes default hide for constant and enum order * fixed so tags works again. * Fix: fixes so we use Angular editor when newVariables is not defined * Fix: fixes wrong hide default for Constant variable * Fix: fixes bug when using duplicate button * Fix: changes action id * Tests: prepares for newVariables * Chore: reduces strict null errors * Refactor: removes uuidInEditorReducer for simplification * Chore: changes after PR comments * Chore: uses getConfig instead of config * Tests: fixes so e2e tests check for feature toggle and fixed initLock bug * Refactor: changes so sharedReducer uses createSlice instead * Refactor: changes textBoxVariableReducer to use creactSlice instead * Refactor: changes queryBoxVariableReducer to use creactSlice instead * Refactor: changes customVariableReducer to use creactSlice instead * Refactor: changes constantVariableReducer to use creactSlice instead * Refactor: moves types to specific types.ts files instead * changed so we use queryValue stored on the variable to populate options input when opening picker. * Feature: adds the ability to test templating thunks using real store and middleware * Chore: cleans up unused import * excluded queryValue from the getSaveModel * Refactor: adds whenAsyncActionIsDispatched to reduxTester * Tests: adds initial tests for processVariables * Added reducer tests for constant variable. * added tests for custom reducer. * added tets for texbox reducer. * Tests: adds more tests for ProcessVariable * Refactor: fixes processVariable flow so we do notrun updateOptions twice * Tests: finishes tests for processVariables and removed skip test * added actions tests for custom and constant. * Tests: adds tests for setOptionFromUrl * Tests: adds a naive variable mock builder * Tests: adds tests for validateVariableSelectionState * added tests for query variable actions. * added last test for query actions. * added more tests. * some more tests. * fixed typing errors. * Fixed issues with variable tags. Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com> Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
2020-03-10 02:53:41 -05:00
legend?: { show: boolean; sort?: string; sortDesc?: boolean };
plugin?: PanelPlugin;
/**
* Unique in application state, this is used as redux key for panel and for redux panel state
* Change will cause unmount and re-init of panel
*/
key: string;
/**
* The PanelModel event bus only used for internal and legacy angular support.
* The EventBus passed to panels is based on the dashboard event model.
*/
events: EventBusSrv;
private queryRunner?: PanelQueryRunner;
constructor(model: any) {
this.events = new EventBusSrv();
this.restoreModel(model);
this.replaceVariables = this.replaceVariables.bind(this);
this.key = uuidv4();
}
/** Given a persistened PanelModel restores property values */
restoreModel(model: any) {
// Start with clean-up
for (const property in this) {
if (notPersistedProperties[property] || !this.hasOwnProperty(property)) {
continue;
}
if (model[property]) {
continue;
}
if (typeof (this as any)[property] === 'function') {
continue;
}
if (typeof (this as any)[property] === 'symbol') {
continue;
}
delete (this as any)[property];
}
// copy properties from persisted model
2018-08-29 07:26:50 -05:00
for (const property in model) {
(this as any)[property] = model[property];
}
2017-10-12 14:37:27 -05:00
switch (this.type) {
case 'graph':
if (config?.featureToggles?.autoMigrateGraphPanels) {
this.autoMigrateFrom = this.type;
this.type = 'timeseries';
}
break;
case 'heatmap-new':
this.autoMigrateFrom = this.type;
this.type = 'heatmap';
break;
}
2018-06-26 09:32:01 -05:00
// defaults
defaultsDeep(this, cloneDeep(defaults));
// queries must have refId
this.ensureQueryIds();
}
generateNewKey() {
this.key = uuidv4();
}
ensureQueryIds() {
if (this.targets && isArray(this.targets)) {
for (const query of this.targets) {
if (!query.refId) {
2019-03-18 05:17:58 -05:00
query.refId = getNextRefIdChar(this.targets);
}
}
}
}
getOptions() {
return this.options;
2018-11-05 10:46:09 -06:00
}
get hasChanged(): boolean {
return this.configRev > 0;
}
2018-11-05 10:46:09 -06:00
updateOptions(options: object) {
this.options = options;
this.configRev++;
this.events.publish(new PanelOptionsChangedEvent());
FieldOverrides: Move FieldConfigSource from fieldOptions to PanelModel.fieldConfig (#22600) * Apply field overrides in PanelChrome * Move applyFieldOverrides to panel query runner * Review updates * Make sure overrides are applied back on souce panel when exiting the new edit mode * TS ignores in est * Make field display work in viz repeater * Review updates * Review and test updates * Change the way overrides and trransformations are retrieved in PQR * Add fieldConfig property to PanelModel * Dashboard migration v1 * Use field config when exiting new panel edit mode * Gauge - use fieldConfig from panel model * FieldDisplayOptions - don's extend FieldConfigSource * Fix fieldDisplay ts * StatPanel updated * Stat panel defaults applied * Table2 panel options update * React graph updates * BarGauge updated * PieChart, Gauge, BarGauge and Stat updates * PieChart - remove field config defaults from options * FieldDisplayEditor - remove unused methos * PanelModel - remove debugger * Remove fieldConfig from field options when migrating dashboard * Update data links migrations * Update fieldDisaplay tests to respect new fieldConfig * Update dashboard schema version in snapshots * Fix BarGaugePanel test * Rebase fixes * Add onFieldConfigChange to PanelProps type * Update shared single stat migration * Pass PanelModel instead of options only for panel type change handler [breaking] * Renames * Don't mutate panel options * Migrations update * Remove obsolete snap * Minor updates after review * Fix null checks * Temporarily (until we decide to switch to new pane edit) bring back old aditors * Temporarily rename ValueMappingEditor and MappingRow to Legacy* * Migrations update * Updae setFieldConfigDefaults API * Update the way field config defaults are applied * Use standard field config for gauge, bar gauge and stat panels * refactoring * Revert dashboard fieldOptions migrations as those are handled by single stat migrator * Fix ts in tests * Strict null fix and some minor fixes Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
2020-03-19 05:50:31 -05:00
this.render();
}
updateFieldConfig(config: FieldConfigSource) {
this.fieldConfig = config;
this.configRev++;
this.events.publish(new PanelOptionsChangedEvent());
FieldOverrides: Move FieldConfigSource from fieldOptions to PanelModel.fieldConfig (#22600) * Apply field overrides in PanelChrome * Move applyFieldOverrides to panel query runner * Review updates * Make sure overrides are applied back on souce panel when exiting the new edit mode * TS ignores in est * Make field display work in viz repeater * Review updates * Review and test updates * Change the way overrides and trransformations are retrieved in PQR * Add fieldConfig property to PanelModel * Dashboard migration v1 * Use field config when exiting new panel edit mode * Gauge - use fieldConfig from panel model * FieldDisplayOptions - don's extend FieldConfigSource * Fix fieldDisplay ts * StatPanel updated * Stat panel defaults applied * Table2 panel options update * React graph updates * BarGauge updated * PieChart, Gauge, BarGauge and Stat updates * PieChart - remove field config defaults from options * FieldDisplayEditor - remove unused methos * PanelModel - remove debugger * Remove fieldConfig from field options when migrating dashboard * Update data links migrations * Update fieldDisaplay tests to respect new fieldConfig * Update dashboard schema version in snapshots * Fix BarGaugePanel test * Rebase fixes * Add onFieldConfigChange to PanelProps type * Update shared single stat migration * Pass PanelModel instead of options only for panel type change handler [breaking] * Renames * Don't mutate panel options * Migrations update * Remove obsolete snap * Minor updates after review * Fix null checks * Temporarily (until we decide to switch to new pane edit) bring back old aditors * Temporarily rename ValueMappingEditor and MappingRow to Legacy* * Migrations update * Updae setFieldConfigDefaults API * Update the way field config defaults are applied * Use standard field config for gauge, bar gauge and stat panels * refactoring * Revert dashboard fieldOptions migrations as those are handled by single stat migrator * Fix ts in tests * Strict null fix and some minor fixes Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
2020-03-19 05:50:31 -05:00
this.resendLastResult();
2018-11-05 10:46:09 -06:00
this.render();
}
getSaveModel() {
2017-10-10 10:57:53 -05:00
const model: any = {};
2018-08-29 07:26:50 -05:00
for (const property in this) {
if (notPersistedProperties[property] || !this.hasOwnProperty(property)) {
continue;
}
if (isEqual(this[property], defaults[property])) {
continue;
}
model[property] = cloneDeep(this[property]);
}
2017-10-10 10:57:53 -05:00
return model;
}
setIsViewing(isViewing: boolean) {
this.isViewing = isViewing;
}
updateGridPos(newPos: GridPos, manuallyUpdated = true) {
if (
newPos.x === this.gridPos.x &&
newPos.y === this.gridPos.y &&
newPos.h === this.gridPos.h &&
newPos.w === this.gridPos.w
) {
return;
}
this.gridPos.x = newPos.x;
this.gridPos.y = newPos.y;
this.gridPos.w = newPos.w;
this.gridPos.h = newPos.h;
if (manuallyUpdated) {
this.configRev++;
}
2017-10-11 14:36:03 -05:00
}
2017-10-16 09:09:23 -05:00
runAllPanelQueries({
dashboardId,
dashboardUID,
dashboardTimezone,
timeData,
width,
publicDashboardAccessToken,
}: RunPanelQueryOptions) {
this.getQueryRunner().run({
datasource: this.datasource,
queries: this.targets,
panelId: this.id,
dashboardId: dashboardId,
dashboardUID: dashboardUID,
publicDashboardAccessToken,
timezone: dashboardTimezone,
timeRange: timeData.timeRange,
timeInfo: timeData.timeInfo,
maxDataPoints: this.maxDataPoints || Math.floor(width),
minInterval: this.interval,
scopedVars: this.scopedVars,
cacheTimeout: this.cacheTimeout,
transformations: this.transformations,
});
}
refresh() {
this.hasRefreshed = true;
this.events.publish(new RefreshEvent());
}
render() {
if (!this.hasRefreshed) {
this.refresh();
} else {
this.events.publish(new RenderEvent());
}
}
private getOptionsToRemember() {
return Object.keys(this).reduce((acc, property) => {
if (notPersistedProperties[property] || mustKeepProps[property]) {
return acc;
}
return {
...acc,
[property]: (this as any)[property],
};
}, {});
}
private restorePanelOptions(pluginId: string) {
const prevOptions = this.cachedPluginOptions[pluginId];
if (!prevOptions) {
return;
}
Object.keys(prevOptions.properties).map((property) => {
(this as any)[property] = prevOptions.properties[property];
});
FieldOverrides: Move FieldConfigSource from fieldOptions to PanelModel.fieldConfig (#22600) * Apply field overrides in PanelChrome * Move applyFieldOverrides to panel query runner * Review updates * Make sure overrides are applied back on souce panel when exiting the new edit mode * TS ignores in est * Make field display work in viz repeater * Review updates * Review and test updates * Change the way overrides and trransformations are retrieved in PQR * Add fieldConfig property to PanelModel * Dashboard migration v1 * Use field config when exiting new panel edit mode * Gauge - use fieldConfig from panel model * FieldDisplayOptions - don's extend FieldConfigSource * Fix fieldDisplay ts * StatPanel updated * Stat panel defaults applied * Table2 panel options update * React graph updates * BarGauge updated * PieChart, Gauge, BarGauge and Stat updates * PieChart - remove field config defaults from options * FieldDisplayEditor - remove unused methos * PanelModel - remove debugger * Remove fieldConfig from field options when migrating dashboard * Update data links migrations * Update fieldDisaplay tests to respect new fieldConfig * Update dashboard schema version in snapshots * Fix BarGaugePanel test * Rebase fixes * Add onFieldConfigChange to PanelProps type * Update shared single stat migration * Pass PanelModel instead of options only for panel type change handler [breaking] * Renames * Don't mutate panel options * Migrations update * Remove obsolete snap * Minor updates after review * Fix null checks * Temporarily (until we decide to switch to new pane edit) bring back old aditors * Temporarily rename ValueMappingEditor and MappingRow to Legacy* * Migrations update * Updae setFieldConfigDefaults API * Update the way field config defaults are applied * Use standard field config for gauge, bar gauge and stat panels * refactoring * Revert dashboard fieldOptions migrations as those are handled by single stat migrator * Fix ts in tests * Strict null fix and some minor fixes Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
2020-03-19 05:50:31 -05:00
this.fieldConfig = restoreCustomOverrideRules(this.fieldConfig, prevOptions.fieldConfig);
}
applyPluginOptionDefaults(plugin: PanelPlugin, isAfterPluginChange: boolean) {
const options = getPanelOptionsWithDefaults({
plugin,
currentOptions: this.options,
currentFieldConfig: this.fieldConfig,
isAfterPluginChange: isAfterPluginChange,
});
this.fieldConfig = options.fieldConfig;
this.options = options.options;
}
pluginLoaded(plugin: PanelPlugin) {
this.plugin = plugin;
const version = getPluginVersion(plugin);
if (this.autoMigrateFrom) {
const wasAngular = this.autoMigrateFrom === 'graph';
this.callPanelTypeChangeHandler(
plugin,
this.autoMigrateFrom,
this.getOptionsToRemember(), // old options
wasAngular
);
delete this.autoMigrateFrom;
}
Graph Panel: use FieldConfig for displayName and DataLinks (#25917) * graph with new controls * graph with new controls * Fix categories * fix test imports * Chore: Fix spelling (#25905) * grafana-ui: Make output chunks correct (#25922) * Explore/Loki: Show results of instant queries only in table and time series only in graph (#25845) * Show results of instant queries only in table and rest in graph * Add type to QueryResultMeta * Update log row hover background only if context is not open * Revert "Update log row hover background only if context is not open" This reverts commit 144197c9540565273515a6d7dd38d3e12a436f05. * Explore/Loki: Fix field type in table for instant queries (#25907) * Update field type for instant queries to number * Remove fieldtype as in prometheus * Revert "Remove fieldtype as in prometheus" This reverts commit f887ad1125deb1053e33f7ef385d5f518ac27892. * Chore: Disable scopelint for tests (#25923) Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * grafana/ui: Fix storybook dev (#25928) * Minimize css and js only for storybook build * Update CodeEditor story, make it internal * Update storybook webpack config * TimeZonePicker: added possibility to toggle if internal time zones should be included or not. (#25934) * made some small adjustments after feedback. * made the flag optional. * Docker: Upgrade to base on Alpine 3.12 (#25936) Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * DataLinks: Add internal links in table and allow custom query (#25613) * Add internal links in table and with custom query * Add specific types for internal and external link * Change the datalink types to be more backward compatible * Refactor the link utils for explore * Add internal linking to table panels * Fix derived field condition * Prettify * Add and fix tests * Prettify * Fix imports and tests * Remove unused type * Update packages/grafana-data/src/types/explore.ts Co-authored-by: Dominik Prokop <dominik.prokop@grafana.com> * Update packages/grafana-data/src/types/explore.ts Co-authored-by: Dominik Prokop <dominik.prokop@grafana.com> Co-authored-by: Dominik Prokop <dominik.prokop@grafana.com> * CircleCI: Upgrade grabpl (#25939) Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com> * Provisioning: Use folders structure from the file system to create desired folders in dashboard provisioning. (#23117) Fixes #12016 * Added options to customize chart data listening (#25918) * Explore: Remove legend formatting when switching from panel to Explore (#25848) * Remove legend formatting when switching from panel to explore * Add test coverage * Query history: Add search for query history and starred queries (#25747) * Add searching functionality to Queries tab * Implement search for starred queries * Update tests and add test coverage for searching * Changes based on provided feedback * Remove redundant storing of results * Update naming of onSearchFilterChange function in tests * Update filterQueriesBySearchFilter function * Update filterQueriesBySearchFilter function * Debounce search * Remove console.log() * Use useDebouncedCallback * Update tests, remove redundant props * When in starred, search only in starred * Add timefilter as dependency * Remove redundant dependency, refactor * Grafana-UI: Add FileUpload (#25835) * Grafana UI: Setup component * Grafana UI: DashboardFileUpload => FileUpload * Grafana UI: Expand docs * Grafana UI: Add className * Grafana UI: Update import * Grafana UI: Clarify props * Update packages/grafana-ui/src/components/FileUpload/FileUpload.tsx Co-authored-by: Tobias Skarhed <1438972+tskarhed@users.noreply.github.com> * Grafana UI: Style icon * Grafana UI: Show uploaded file name * Grafana UI: Add tests * Grafana UI: Add useStyles + useCallback * Grafana UI: Remove stylesFactory * Grafana UI: Revert to useTheme Co-authored-by: Tobias Skarhed <1438972+tskarhed@users.noreply.github.com> * Fix: Value mappings match against string values (#25929) * Use standard input for value mappings value * add test and case for matching string values * re add number on rangemap * remove FieldTypeNumber required * Docs: Changelog update 7.05 & latest.json update (#25941) * Docs: Changelog update for 7.0.5 * Update latest.json * Fixed alignment * Stackdriver: Rename Stackdriver to Google Cloud Monitoring (#25807) * Update backend * Update frontend * Keep old plugin id * Update docs * Place doc images to a new directory * Legacy support for stackdriver-auto alignment * Consistent plugin name * Apply suggestions from code review Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com> Co-authored-by: Tobias Skarhed <1438972+tskarhed@users.noreply.github.com> * Update docs * Update public/app/plugins/datasource/cloud-monitoring/README.md Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com> * Add reference to the data source formerly being named Stackdriver * Update pkg/models/datasource.go Co-authored-by: Carl Bergquist <carl@grafana.com> * Fix gofmt Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com> Co-authored-by: Tobias Skarhed <1438972+tskarhed@users.noreply.github.com> Co-authored-by: Carl Bergquist <carl@grafana.com> * Fix strict null errors that resulted from search (#25950) * Arrow: when exporting arrow use the calculated names (#25871) * PanelHeader: Fixed loading icon position (#25949) * PanelHeader: Fixed loading icon position * revert back to text weak color * Azure/Log Analytics: return more error information (#25937) When there is an error message in the HTTP response, this copies that error so it is relayed to the user by being shown in the frontend. This also makes it so when there is an error the interpolated query string (ExecutedQueryString) is returned so users can see it in the query inspector. * Azure: Multiple dimension support for Azure Monitor Service (#25947) Azure Monitor (metrics) support multiple dimensions instead of just one. Co-authored-by: Ryan McKinley <ryantxu@gmail.com> * Docs: Update alert-list-panel.md (#25779) Fixed minor typo and format updates * Docs: Update add-a-panel.md (#25780) * Linting fixes for the provisioning package (#25690) * Chore: whatwg-fetch version bump (#25952) * Use latest fetch polyfill/shim * Updated lockfile * Monaco: option to hide line numbers (#25920) * Docs: Reorganize reference topics (#25915) * moved annotations.md * Update annotations.md * moved dashboard_folders.md * moved dashboard_history.md * moved playlist.md * moved search.md * migrations test * docs: spelling (#24383) * Docs: spelling * Docs: spelling (contribute/ directory) * Drop whats-new-in changes * migrations test Co-authored-by: Dominik Prokop <dominik.prokop@grafana.com> Co-authored-by: Richard Hartmann <RichiH@users.noreply.github.com> Co-authored-by: Ivana Huckova <30407135+ivanahuckova@users.noreply.github.com> Co-authored-by: Arve Knudsen <arve.knudsen@gmail.com> Co-authored-by: Marcus Andersson <marcus.andersson@grafana.com> Co-authored-by: Andrej Ocenas <mr.ocenas@gmail.com> Co-authored-by: Maksim Nabokikh <32434187+nabokihms@users.noreply.github.com> Co-authored-by: Steven Vachon <contact@svachon.com> Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> Co-authored-by: Tobias Skarhed <1438972+tskarhed@users.noreply.github.com> Co-authored-by: Peter Holmberg <peterholmberg@users.noreply.github.com> Co-authored-by: Torkel Ödegaard <torkel@grafana.com> Co-authored-by: Sofia Papagiannaki <papagian@users.noreply.github.com> Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com> Co-authored-by: Carl Bergquist <carl@grafana.com> Co-authored-by: Kyle Brandt <kyle@grafana.com> Co-authored-by: Diana Payton <52059945+oddlittlebird@users.noreply.github.com> Co-authored-by: Josh Soref <jsoref@users.noreply.github.com>
2020-07-01 02:39:06 -05:00
if (plugin.onPanelMigration) {
if (version !== this.pluginVersion) {
this.options = plugin.onPanelMigration(this);
this.pluginVersion = version;
}
}
this.applyPluginOptionDefaults(plugin, false);
this.resendLastResult();
}
clearPropertiesBeforePluginChange() {
// remove panel type specific options
for (const key of keys(this)) {
if (mustKeepProps[key]) {
continue;
}
delete (this as any)[key];
}
this.options = {};
// clear custom options
this.fieldConfig = {
defaults: {
...this.fieldConfig.defaults,
custom: {},
},
// filter out custom overrides
overrides: filterFieldConfigOverrides(this.fieldConfig.overrides, isStandardFieldProp),
};
}
// Let panel plugins inspect options from previous panel and keep any that it can use
private callPanelTypeChangeHandler(
newPlugin: PanelPlugin,
oldPluginId: string,
oldOptions: any,
wasAngular: boolean
) {
if (newPlugin.onPanelTypeChanged) {
const prevOptions = wasAngular ? { angular: oldOptions } : oldOptions.options;
Object.assign(this.options, newPlugin.onPanelTypeChanged(this, oldPluginId, prevOptions, this.fieldConfig));
}
}
changePlugin(newPlugin: PanelPlugin) {
const pluginId = newPlugin.meta.id;
const oldOptions: any = this.getOptionsToRemember();
const prevFieldConfig = this.fieldConfig;
const oldPluginId = this.type;
const wasAngular = this.isAngularPlugin();
this.cachedPluginOptions[oldPluginId] = {
properties: oldOptions,
fieldConfig: prevFieldConfig,
};
this.clearPropertiesBeforePluginChange();
this.restorePanelOptions(pluginId);
2019-02-21 06:43:36 -06:00
// Potentially modify current options
this.callPanelTypeChangeHandler(newPlugin, oldPluginId, oldOptions, wasAngular);
// switch
this.type = pluginId;
this.plugin = newPlugin;
this.configRev++;
this.applyPluginOptionDefaults(newPlugin, true);
if (newPlugin.onPanelMigration) {
this.pluginVersion = getPluginVersion(newPlugin);
2019-02-21 06:43:36 -06:00
}
2018-07-09 11:17:51 -05:00
}
updateQueries(options: QueryGroupOptions) {
const { dataSource } = options;
this.datasource = {
uid: dataSource.uid,
type: dataSource.type,
};
this.cacheTimeout = options.cacheTimeout;
this.timeFrom = options.timeRange?.from;
this.timeShift = options.timeRange?.shift;
this.hideTimeOverride = options.timeRange?.hide;
this.interval = options.minInterval;
this.maxDataPoints = options.maxDataPoints;
this.targets = options.queries;
this.configRev++;
this.events.publish(new PanelQueriesChangedEvent());
}
2018-12-12 01:54:12 -06:00
addQuery(query?: Partial<DataQuery>) {
2018-12-11 06:36:44 -06:00
query = query || { refId: 'A' };
2019-03-18 05:17:58 -05:00
query.refId = getNextRefIdChar(this.targets);
this.targets.push(query as DataQuery);
this.configRev++;
2018-12-11 06:36:44 -06:00
}
changeQuery(query: DataQuery, index: number) {
// ensure refId is maintained
query.refId = this.targets[index].refId;
this.configRev++;
// update query in array
this.targets = this.targets.map((item, itemIndex) => {
if (itemIndex === index) {
return query;
}
return item;
});
}
getEditClone() {
const sourceModel = this.getSaveModel();
const clone = new PanelModel(sourceModel);
clone.isEditing = true;
clone.plugin = this.plugin;
const sourceQueryRunner = this.getQueryRunner();
// Copy last query result
clone.getQueryRunner().useLastResultFrom(sourceQueryRunner);
return clone;
}
getTransformations() {
return this.transformations;
}
getFieldOverrideOptions() {
if (!this.plugin) {
return undefined;
}
return {
fieldConfig: this.fieldConfig,
replaceVariables: this.replaceVariables,
fieldConfigRegistry: this.plugin.fieldConfigRegistry,
theme: config.theme2,
};
}
getDataSupport(): PanelPluginDataSupport {
return this.plugin?.dataSupport ?? { annotations: false, alertStates: false };
}
getQueryRunner(): PanelQueryRunner {
if (!this.queryRunner) {
this.queryRunner = new PanelQueryRunner(this);
}
return this.queryRunner;
}
hasTitle() {
return this.title && this.title.length > 0;
}
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 10:28:46 -05:00
isAngularPlugin(): boolean {
return (this.plugin && this.plugin.angularPanelCtrl) !== undefined;
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 10:28:46 -05:00
}
2017-10-16 09:09:23 -05:00
destroy() {
this.events.removeAllListeners();
if (this.queryRunner) {
this.queryRunner.destroy();
}
2017-10-16 09:09:23 -05:00
}
setTransformations(transformations: DataTransformerConfig[]) {
this.transformations = transformations;
this.resendLastResult();
this.configRev++;
this.events.publish(new PanelTransformationsChangedEvent());
}
setProperty(key: keyof this, value: any) {
this[key] = value;
this.configRev++;
PanelEdit: v8 Panel Edit UX (#32124) * Initial commit * Progress * Update * Progress * updates * Minor fix * fixed ts issue * fixed e2e tests * More explorations * Making progress * Panel options and field options unified * With nested categories * Starting to find something * fix paddings * Progress * Breakthrough ux layout * Progress * Updates * New way of composing options with search * added regex search * Refactoring to react note tree * Show overrides * Adding overrides radio button support * Added popular view * Separate stat/gauge/bargauge options into value options and display options * Initial work on getting library panels into viz picker flow * Fixed issues switching to panel library panel * Move search input put of LibraryPanelsView * Changing design again to have content inside boxes * Style updates * Refactoring to fix scroll issue * Option category naming * Fixed FilterInput issue * Updated snapshots * Fix padding * Updated viz picker design * Unify library panel an viz picker card * Updated card with delete action * Major refactoring back to an object model instead of searching and filtering react node tree * More refactoring * Show option category in label when searching * Nice logic for categories rendering when searching or when only child * Make getSuggestions more lazy for DataLinksEditor * Add missing repeat options and handle conditional options * Prepping options category to be more flexibly and control state from outside * Added option count to search result * Minor style tweak * Added button to close viz picker * Rewrote overrides to enable searching overrides * New search engine and tests * Searching overrides works * Hide radio buttons while searching * Added angular options back * Added memoize for all options so they are not rebuilt for every search key stroke * Added back support for category counters * Started unit test work * Refactoring and base popular options list * Initial update to e2e test, more coming to add e2e test for search features * Minor fix * Review updates * Fixing category open states * Unit test progress * Do not show visualization list mode radio button if library panels is not enabled * Use boolean * More unit tests * Increase library panels per page count and give search focus when switching list mode * field config change test and search test * Feedback updates * Minor tweaks * Minor refactorings * More minimal override collapse state
2021-03-25 02:33:13 -05:00
// Custom handling of repeat dependent options, handled here as PanelEditor can
// update one key at a time right now
if (key === 'repeat') {
if (this.repeat && !this.repeatDirection) {
this.repeatDirection = 'h';
} else if (!this.repeat) {
delete this.repeatDirection;
delete this.maxPerRow;
}
}
}
replaceVariables(value: string, extraVars: ScopedVars | undefined, format?: string | Function) {
const lastRequest = this.getQueryRunner().getLastRequest();
const vars: ScopedVars = Object.assign({}, this.scopedVars, lastRequest?.scopedVars, extraVars);
const allVariablesParams = getVariablesUrlParams(vars);
const variablesQuery = urlUtil.toUrlParams(allVariablesParams);
const timeRangeUrl = urlUtil.toUrlParams(getTimeSrv().timeRangeForUrl());
vars[DataLinkBuiltInVars.keepTime] = {
text: timeRangeUrl,
value: timeRangeUrl,
};
vars[DataLinkBuiltInVars.includeVars] = {
text: variablesQuery,
value: variablesQuery,
};
return getTemplateSrv().replace(value, vars, format);
}
resendLastResult() {
if (!this.plugin) {
return;
}
this.getQueryRunner().resendLastResult();
}
/*
* This is the title used when displaying the title in the UI so it will include any interpolated variables.
* If you need the raw title without interpolation use title property instead.
* */
getDisplayTitle(): string {
return this.replaceVariables(this.title, undefined, 'text');
}
2017-10-10 02:34:14 -05:00
}
function getPluginVersion(plugin: PanelPlugin): string {
return plugin && plugin.meta.info.version ? plugin.meta.info.version : config.buildInfo.version;
}
interface PanelOptionsCache {
properties: any;
fieldConfig: FieldConfigSource;
}
// For cases where we immediately want to stringify the panel model without cloning each property
export function stringifyPanelModel(panel: PanelModel) {
const model: any = {};
Object.entries(panel)
.filter(
([prop, val]) => !notPersistedProperties[prop] && panel.hasOwnProperty(prop) && !isEqual(val, defaults[prop])
)
.forEach(([k, v]) => {
model[k] = v;
});
return safeStringifyValue(model);
}