DashboardModel.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. // Libaries
  2. import _ from 'lodash';
  3. // Constants
  4. import { DEFAULT_ANNOTATION_COLOR } from '@grafana/ui';
  5. import { GRID_COLUMN_COUNT, REPEAT_DIR_VERTICAL, GRID_CELL_HEIGHT, GRID_CELL_VMARGIN } from 'app/core/constants';
  6. // Utils & Services
  7. import { Emitter } from 'app/core/utils/emitter';
  8. import { contextSrv } from 'app/core/services/context_srv';
  9. import sortByKeys from 'app/core/utils/sort_by_keys';
  10. // Types
  11. import { PanelModel, GridPos } from './PanelModel';
  12. import { DashboardMigrator } from './DashboardMigrator';
  13. import { TimeRange, TimeZone } from '@grafana/data';
  14. import { UrlQueryValue } from '@grafana/runtime';
  15. import { KIOSK_MODE_TV, DashboardMeta } from 'app/types';
  16. import { toUtc, DateTimeInput, dateTime, isDateTime } from '@grafana/data';
  17. export interface CloneOptions {
  18. saveVariables?: boolean;
  19. saveTimerange?: boolean;
  20. message?: string;
  21. }
  22. export class DashboardModel {
  23. id: any;
  24. uid: string;
  25. title: string;
  26. autoUpdate: any;
  27. description: any;
  28. tags: any;
  29. style: any;
  30. timezone: any;
  31. editable: any;
  32. graphTooltip: any;
  33. time: any;
  34. private originalTime: any;
  35. timepicker: any;
  36. templating: { list: any[] };
  37. private originalTemplating: any;
  38. annotations: { list: any[] };
  39. refresh: any;
  40. snapshot: any;
  41. schemaVersion: number;
  42. version: number;
  43. revision: number;
  44. links: any;
  45. gnetId: any;
  46. panels: PanelModel[];
  47. // ------------------
  48. // not persisted
  49. // ------------------
  50. // repeat process cycles
  51. iteration: number;
  52. meta: DashboardMeta;
  53. events: Emitter;
  54. static nonPersistedProperties: { [str: string]: boolean } = {
  55. events: true,
  56. meta: true,
  57. panels: true, // needs special handling
  58. templating: true, // needs special handling
  59. originalTime: true,
  60. originalTemplating: true,
  61. };
  62. constructor(data: any, meta?: DashboardMeta) {
  63. if (!data) {
  64. data = {};
  65. }
  66. this.events = new Emitter();
  67. this.id = data.id || null;
  68. this.uid = data.uid || null;
  69. this.revision = data.revision;
  70. this.title = data.title || 'No Title';
  71. this.autoUpdate = data.autoUpdate;
  72. this.description = data.description;
  73. this.tags = data.tags || [];
  74. this.style = data.style || 'dark';
  75. this.timezone = data.timezone || '';
  76. this.editable = data.editable !== false;
  77. this.graphTooltip = data.graphTooltip || 0;
  78. this.time = data.time || { from: 'now-6h', to: 'now' };
  79. this.timepicker = data.timepicker || {};
  80. this.templating = this.ensureListExist(data.templating);
  81. this.annotations = this.ensureListExist(data.annotations);
  82. this.refresh = data.refresh;
  83. this.snapshot = data.snapshot;
  84. this.schemaVersion = data.schemaVersion || 0;
  85. this.version = data.version || 0;
  86. this.links = data.links || [];
  87. this.gnetId = data.gnetId || null;
  88. this.panels = _.map(data.panels || [], (panelData: any) => new PanelModel(panelData));
  89. this.resetOriginalVariables();
  90. this.resetOriginalTime();
  91. this.initMeta(meta);
  92. this.updateSchema(data);
  93. this.addBuiltInAnnotationQuery();
  94. this.sortPanelsByGridPos();
  95. }
  96. addBuiltInAnnotationQuery() {
  97. let found = false;
  98. for (const item of this.annotations.list) {
  99. if (item.builtIn === 1) {
  100. found = true;
  101. break;
  102. }
  103. }
  104. if (found) {
  105. return;
  106. }
  107. this.annotations.list.unshift({
  108. datasource: '-- Grafana --',
  109. name: 'Annotations & Alerts',
  110. type: 'dashboard',
  111. iconColor: DEFAULT_ANNOTATION_COLOR,
  112. enable: true,
  113. hide: true,
  114. builtIn: 1,
  115. });
  116. }
  117. private initMeta(meta: DashboardMeta) {
  118. meta = meta || {};
  119. meta.canShare = meta.canShare !== false;
  120. meta.canSave = meta.canSave !== false;
  121. meta.canStar = meta.canStar !== false;
  122. meta.canEdit = meta.canEdit !== false;
  123. meta.showSettings = meta.canEdit;
  124. meta.canMakeEditable = meta.canSave && !this.editable;
  125. meta.fullscreen = false;
  126. meta.isEditing = false;
  127. if (!this.editable) {
  128. meta.canEdit = false;
  129. meta.canDelete = false;
  130. meta.canSave = false;
  131. }
  132. this.meta = meta;
  133. }
  134. // cleans meta data and other non persistent state
  135. getSaveModelClone(options?: CloneOptions) {
  136. const defaults = _.defaults(options || {}, {
  137. saveVariables: true,
  138. saveTimerange: true,
  139. });
  140. // make clone
  141. let copy: any = {};
  142. for (const property in this) {
  143. if (DashboardModel.nonPersistedProperties[property] || !this.hasOwnProperty(property)) {
  144. continue;
  145. }
  146. copy[property] = _.cloneDeep(this[property]);
  147. }
  148. // get variable save models
  149. copy.templating = {
  150. list: _.map(this.templating.list, (variable: any) =>
  151. variable.getSaveModel ? variable.getSaveModel() : variable
  152. ),
  153. };
  154. if (!defaults.saveVariables) {
  155. for (let i = 0; i < copy.templating.list.length; i++) {
  156. const current = copy.templating.list[i];
  157. const original: any = _.find(this.originalTemplating, { name: current.name, type: current.type });
  158. if (!original) {
  159. continue;
  160. }
  161. if (current.type === 'adhoc') {
  162. copy.templating.list[i].filters = original.filters;
  163. } else {
  164. copy.templating.list[i].current = original.current;
  165. }
  166. }
  167. }
  168. if (!defaults.saveTimerange) {
  169. copy.time = this.originalTime;
  170. }
  171. // get panel save models
  172. copy.panels = _.chain(this.panels)
  173. .filter((panel: PanelModel) => panel.type !== 'add-panel')
  174. .map((panel: PanelModel) => panel.getSaveModel())
  175. .value();
  176. // sort by keys
  177. copy = sortByKeys(copy);
  178. return copy;
  179. }
  180. setViewMode(panel: PanelModel, fullscreen: boolean, isEditing: boolean) {
  181. this.meta.fullscreen = fullscreen;
  182. this.meta.isEditing = isEditing && this.meta.canEdit;
  183. panel.setViewMode(fullscreen, this.meta.isEditing);
  184. this.events.emit('view-mode-changed', panel);
  185. }
  186. timeRangeUpdated(timeRange: TimeRange) {
  187. this.events.emit('time-range-updated', timeRange);
  188. }
  189. startRefresh() {
  190. this.events.emit('refresh');
  191. for (const panel of this.panels) {
  192. if (!this.otherPanelInFullscreen(panel)) {
  193. panel.refresh();
  194. }
  195. }
  196. }
  197. render() {
  198. this.events.emit('render');
  199. for (const panel of this.panels) {
  200. panel.render();
  201. }
  202. }
  203. panelInitialized(panel: PanelModel) {
  204. panel.initialized();
  205. if (!this.otherPanelInFullscreen(panel)) {
  206. panel.refresh();
  207. }
  208. }
  209. otherPanelInFullscreen(panel: PanelModel) {
  210. return this.meta.fullscreen && !panel.fullscreen;
  211. }
  212. private ensureListExist(data: any) {
  213. if (!data) {
  214. data = {};
  215. }
  216. if (!data.list) {
  217. data.list = [];
  218. }
  219. return data;
  220. }
  221. getNextPanelId() {
  222. let max = 0;
  223. for (const panel of this.panels) {
  224. if (panel.id > max) {
  225. max = panel.id;
  226. }
  227. if (panel.collapsed) {
  228. for (const rowPanel of panel.panels) {
  229. if (rowPanel.id > max) {
  230. max = rowPanel.id;
  231. }
  232. }
  233. }
  234. }
  235. return max + 1;
  236. }
  237. forEachPanel(callback: (panel: PanelModel, index: number) => void) {
  238. for (let i = 0; i < this.panels.length; i++) {
  239. callback(this.panels[i], i);
  240. }
  241. }
  242. getPanelById(id: number): PanelModel {
  243. for (const panel of this.panels) {
  244. if (panel.id === id) {
  245. return panel;
  246. }
  247. }
  248. return null;
  249. }
  250. addPanel(panelData: any) {
  251. panelData.id = this.getNextPanelId();
  252. const panel = new PanelModel(panelData);
  253. this.panels.unshift(panel);
  254. this.sortPanelsByGridPos();
  255. this.events.emit('panel-added', panel);
  256. }
  257. sortPanelsByGridPos() {
  258. this.panels.sort((panelA, panelB) => {
  259. if (panelA.gridPos.y === panelB.gridPos.y) {
  260. return panelA.gridPos.x - panelB.gridPos.x;
  261. } else {
  262. return panelA.gridPos.y - panelB.gridPos.y;
  263. }
  264. });
  265. }
  266. cleanUpRepeats() {
  267. if (this.snapshot || this.templating.list.length === 0) {
  268. return;
  269. }
  270. this.iteration = (this.iteration || new Date().getTime()) + 1;
  271. const panelsToRemove = [];
  272. // cleanup scopedVars
  273. for (const panel of this.panels) {
  274. delete panel.scopedVars;
  275. }
  276. for (let i = 0; i < this.panels.length; i++) {
  277. const panel = this.panels[i];
  278. if ((!panel.repeat || panel.repeatedByRow) && panel.repeatPanelId && panel.repeatIteration !== this.iteration) {
  279. panelsToRemove.push(panel);
  280. }
  281. }
  282. // remove panels
  283. _.pull(this.panels, ...panelsToRemove);
  284. panelsToRemove.map(p => p.destroy());
  285. this.sortPanelsByGridPos();
  286. this.events.emit('repeats-processed');
  287. }
  288. processRepeats() {
  289. if (this.snapshot || this.templating.list.length === 0) {
  290. return;
  291. }
  292. this.cleanUpRepeats();
  293. this.iteration = (this.iteration || new Date().getTime()) + 1;
  294. for (let i = 0; i < this.panels.length; i++) {
  295. const panel = this.panels[i];
  296. if (panel.repeat) {
  297. this.repeatPanel(panel, i);
  298. }
  299. }
  300. this.sortPanelsByGridPos();
  301. this.events.emit('repeats-processed');
  302. }
  303. cleanUpRowRepeats(rowPanels: PanelModel[]) {
  304. const panelsToRemove = [];
  305. for (let i = 0; i < rowPanels.length; i++) {
  306. const panel = rowPanels[i];
  307. if (!panel.repeat && panel.repeatPanelId) {
  308. panelsToRemove.push(panel);
  309. }
  310. }
  311. _.pull(rowPanels, ...panelsToRemove);
  312. _.pull(this.panels, ...panelsToRemove);
  313. }
  314. processRowRepeats(row: PanelModel) {
  315. if (this.snapshot || this.templating.list.length === 0) {
  316. return;
  317. }
  318. let rowPanels = row.panels;
  319. if (!row.collapsed) {
  320. const rowPanelIndex = _.findIndex(this.panels, (p: PanelModel) => p.id === row.id);
  321. rowPanels = this.getRowPanels(rowPanelIndex);
  322. }
  323. this.cleanUpRowRepeats(rowPanels);
  324. for (let i = 0; i < rowPanels.length; i++) {
  325. const panel = rowPanels[i];
  326. if (panel.repeat) {
  327. const panelIndex = _.findIndex(this.panels, (p: PanelModel) => p.id === panel.id);
  328. this.repeatPanel(panel, panelIndex);
  329. }
  330. }
  331. }
  332. getPanelRepeatClone(sourcePanel: PanelModel, valueIndex: number, sourcePanelIndex: number) {
  333. // if first clone return source
  334. if (valueIndex === 0) {
  335. return sourcePanel;
  336. }
  337. const clone = new PanelModel(sourcePanel.getSaveModel());
  338. clone.id = this.getNextPanelId();
  339. // insert after source panel + value index
  340. this.panels.splice(sourcePanelIndex + valueIndex, 0, clone);
  341. clone.repeatIteration = this.iteration;
  342. clone.repeatPanelId = sourcePanel.id;
  343. clone.repeat = null;
  344. return clone;
  345. }
  346. getRowRepeatClone(sourceRowPanel: PanelModel, valueIndex: number, sourcePanelIndex: number) {
  347. // if first clone return source
  348. if (valueIndex === 0) {
  349. if (!sourceRowPanel.collapsed) {
  350. const rowPanels = this.getRowPanels(sourcePanelIndex);
  351. sourceRowPanel.panels = rowPanels;
  352. }
  353. return sourceRowPanel;
  354. }
  355. const clone = new PanelModel(sourceRowPanel.getSaveModel());
  356. // for row clones we need to figure out panels under row to clone and where to insert clone
  357. let rowPanels: PanelModel[], insertPos: number;
  358. if (sourceRowPanel.collapsed) {
  359. rowPanels = _.cloneDeep(sourceRowPanel.panels);
  360. clone.panels = rowPanels;
  361. // insert copied row after preceding row
  362. insertPos = sourcePanelIndex + valueIndex;
  363. } else {
  364. rowPanels = this.getRowPanels(sourcePanelIndex);
  365. clone.panels = _.map(rowPanels, (panel: PanelModel) => panel.getSaveModel());
  366. // insert copied row after preceding row's panels
  367. insertPos = sourcePanelIndex + (rowPanels.length + 1) * valueIndex;
  368. }
  369. this.panels.splice(insertPos, 0, clone);
  370. this.updateRepeatedPanelIds(clone);
  371. return clone;
  372. }
  373. repeatPanel(panel: PanelModel, panelIndex: number) {
  374. const variable: any = _.find(this.templating.list, { name: panel.repeat } as any);
  375. if (!variable) {
  376. return;
  377. }
  378. if (panel.type === 'row') {
  379. this.repeatRow(panel, panelIndex, variable);
  380. return;
  381. }
  382. const selectedOptions = this.getSelectedVariableOptions(variable);
  383. const maxPerRow = panel.maxPerRow || 4;
  384. let xPos = 0;
  385. let yPos = panel.gridPos.y;
  386. for (let index = 0; index < selectedOptions.length; index++) {
  387. const option = selectedOptions[index];
  388. let copy;
  389. copy = this.getPanelRepeatClone(panel, index, panelIndex);
  390. copy.scopedVars = copy.scopedVars || {};
  391. copy.scopedVars[variable.name] = option;
  392. if (panel.repeatDirection === REPEAT_DIR_VERTICAL) {
  393. if (index > 0) {
  394. yPos += copy.gridPos.h;
  395. }
  396. copy.gridPos.y = yPos;
  397. } else {
  398. // set width based on how many are selected
  399. // assumed the repeated panels should take up full row width
  400. copy.gridPos.w = Math.max(GRID_COLUMN_COUNT / selectedOptions.length, GRID_COLUMN_COUNT / maxPerRow);
  401. copy.gridPos.x = xPos;
  402. copy.gridPos.y = yPos;
  403. xPos += copy.gridPos.w;
  404. // handle overflow by pushing down one row
  405. if (xPos + copy.gridPos.w > GRID_COLUMN_COUNT) {
  406. xPos = 0;
  407. yPos += copy.gridPos.h;
  408. }
  409. }
  410. }
  411. // Update gridPos for panels below
  412. const yOffset = yPos - panel.gridPos.y;
  413. if (yOffset > 0) {
  414. const panelBelowIndex = panelIndex + selectedOptions.length;
  415. for (let i = panelBelowIndex; i < this.panels.length; i++) {
  416. this.panels[i].gridPos.y += yOffset;
  417. }
  418. }
  419. }
  420. repeatRow(panel: PanelModel, panelIndex: number, variable: any) {
  421. const selectedOptions = this.getSelectedVariableOptions(variable);
  422. let yPos = panel.gridPos.y;
  423. function setScopedVars(panel: PanelModel, variableOption: any) {
  424. panel.scopedVars = panel.scopedVars || {};
  425. panel.scopedVars[variable.name] = variableOption;
  426. }
  427. for (let optionIndex = 0; optionIndex < selectedOptions.length; optionIndex++) {
  428. const option = selectedOptions[optionIndex];
  429. const rowCopy = this.getRowRepeatClone(panel, optionIndex, panelIndex);
  430. setScopedVars(rowCopy, option);
  431. const rowHeight = this.getRowHeight(rowCopy);
  432. const rowPanels = rowCopy.panels || [];
  433. let panelBelowIndex;
  434. if (panel.collapsed) {
  435. // For collapsed row just copy its panels and set scoped vars and proper IDs
  436. _.each(rowPanels, (rowPanel: PanelModel, i: number) => {
  437. setScopedVars(rowPanel, option);
  438. if (optionIndex > 0) {
  439. this.updateRepeatedPanelIds(rowPanel, true);
  440. }
  441. });
  442. rowCopy.gridPos.y += optionIndex;
  443. yPos += optionIndex;
  444. panelBelowIndex = panelIndex + optionIndex + 1;
  445. } else {
  446. // insert after 'row' panel
  447. const insertPos = panelIndex + (rowPanels.length + 1) * optionIndex + 1;
  448. _.each(rowPanels, (rowPanel: PanelModel, i: number) => {
  449. setScopedVars(rowPanel, option);
  450. if (optionIndex > 0) {
  451. const cloneRowPanel = new PanelModel(rowPanel);
  452. this.updateRepeatedPanelIds(cloneRowPanel, true);
  453. // For exposed row additionally set proper Y grid position and add it to dashboard panels
  454. cloneRowPanel.gridPos.y += rowHeight * optionIndex;
  455. this.panels.splice(insertPos + i, 0, cloneRowPanel);
  456. }
  457. });
  458. rowCopy.panels = [];
  459. rowCopy.gridPos.y += rowHeight * optionIndex;
  460. yPos += rowHeight;
  461. panelBelowIndex = insertPos + rowPanels.length;
  462. }
  463. // Update gridPos for panels below
  464. for (let i = panelBelowIndex; i < this.panels.length; i++) {
  465. this.panels[i].gridPos.y += yPos;
  466. }
  467. }
  468. }
  469. updateRepeatedPanelIds(panel: PanelModel, repeatedByRow?: boolean) {
  470. panel.repeatPanelId = panel.id;
  471. panel.id = this.getNextPanelId();
  472. panel.repeatIteration = this.iteration;
  473. if (repeatedByRow) {
  474. panel.repeatedByRow = true;
  475. } else {
  476. panel.repeat = null;
  477. }
  478. return panel;
  479. }
  480. getSelectedVariableOptions(variable: any) {
  481. let selectedOptions: any[];
  482. if (variable.current.text === 'All') {
  483. selectedOptions = variable.options.slice(1, variable.options.length);
  484. } else {
  485. selectedOptions = _.filter(variable.options, { selected: true });
  486. }
  487. return selectedOptions;
  488. }
  489. getRowHeight(rowPanel: PanelModel): number {
  490. if (!rowPanel.panels || rowPanel.panels.length === 0) {
  491. return 0;
  492. }
  493. const rowYPos = rowPanel.gridPos.y;
  494. const positions = _.map(rowPanel.panels, 'gridPos');
  495. const maxPos = _.maxBy(positions, (pos: GridPos) => {
  496. return pos.y + pos.h;
  497. });
  498. return maxPos.y + maxPos.h - rowYPos;
  499. }
  500. removePanel(panel: PanelModel) {
  501. const index = _.indexOf(this.panels, panel);
  502. this.panels.splice(index, 1);
  503. this.events.emit('panel-removed', panel);
  504. }
  505. removeRow(row: PanelModel, removePanels: boolean) {
  506. const needToogle = (!removePanels && row.collapsed) || (removePanels && !row.collapsed);
  507. if (needToogle) {
  508. this.toggleRow(row);
  509. }
  510. this.removePanel(row);
  511. }
  512. expandRows() {
  513. for (let i = 0; i < this.panels.length; i++) {
  514. const panel = this.panels[i];
  515. if (panel.type !== 'row') {
  516. continue;
  517. }
  518. if (panel.collapsed) {
  519. this.toggleRow(panel);
  520. }
  521. }
  522. }
  523. collapseRows() {
  524. for (let i = 0; i < this.panels.length; i++) {
  525. const panel = this.panels[i];
  526. if (panel.type !== 'row') {
  527. continue;
  528. }
  529. if (!panel.collapsed) {
  530. this.toggleRow(panel);
  531. }
  532. }
  533. }
  534. setPanelFocus(id: number) {
  535. this.meta.focusPanelId = id;
  536. }
  537. updateSubmenuVisibility() {
  538. this.meta.submenuEnabled = (() => {
  539. if (this.links.length > 0) {
  540. return true;
  541. }
  542. const visibleVars = _.filter(this.templating.list, (variable: any) => variable.hide !== 2);
  543. if (visibleVars.length > 0) {
  544. return true;
  545. }
  546. const visibleAnnotations = _.filter(this.annotations.list, (annotation: any) => annotation.hide !== true);
  547. if (visibleAnnotations.length > 0) {
  548. return true;
  549. }
  550. return false;
  551. })();
  552. }
  553. getPanelInfoById(panelId: number) {
  554. for (let i = 0; i < this.panels.length; i++) {
  555. if (this.panels[i].id === panelId) {
  556. return {
  557. panel: this.panels[i],
  558. index: i,
  559. };
  560. }
  561. }
  562. return null;
  563. }
  564. duplicatePanel(panel: PanelModel) {
  565. const newPanel = panel.getSaveModel();
  566. newPanel.id = this.getNextPanelId();
  567. delete newPanel.repeat;
  568. delete newPanel.repeatIteration;
  569. delete newPanel.repeatPanelId;
  570. delete newPanel.scopedVars;
  571. if (newPanel.alert) {
  572. delete newPanel.thresholds;
  573. }
  574. delete newPanel.alert;
  575. // does it fit to the right?
  576. if (panel.gridPos.x + panel.gridPos.w * 2 <= GRID_COLUMN_COUNT) {
  577. newPanel.gridPos.x += panel.gridPos.w;
  578. } else {
  579. // add below
  580. newPanel.gridPos.y += panel.gridPos.h;
  581. }
  582. this.addPanel(newPanel);
  583. return newPanel;
  584. }
  585. formatDate(date: DateTimeInput, format?: string) {
  586. date = isDateTime(date) ? date : dateTime(date);
  587. format = format || 'YYYY-MM-DD HH:mm:ss';
  588. const timezone = this.getTimezone();
  589. return timezone === 'browser' ? dateTime(date).format(format) : toUtc(date).format(format);
  590. }
  591. destroy() {
  592. this.events.removeAllListeners();
  593. for (const panel of this.panels) {
  594. panel.destroy();
  595. }
  596. }
  597. toggleRow(row: PanelModel) {
  598. const rowIndex = _.indexOf(this.panels, row);
  599. if (row.collapsed) {
  600. row.collapsed = false;
  601. const hasRepeat = _.some(row.panels as PanelModel[], (p: PanelModel) => p.repeat);
  602. if (row.panels.length > 0) {
  603. // Use first panel to figure out if it was moved or pushed
  604. const firstPanel = row.panels[0];
  605. const yDiff = firstPanel.gridPos.y - (row.gridPos.y + row.gridPos.h);
  606. // start inserting after row
  607. let insertPos = rowIndex + 1;
  608. // y max will represent the bottom y pos after all panels have been added
  609. // needed to know home much panels below should be pushed down
  610. let yMax = row.gridPos.y;
  611. for (const panel of row.panels) {
  612. // make sure y is adjusted (in case row moved while collapsed)
  613. // console.log('yDiff', yDiff);
  614. panel.gridPos.y -= yDiff;
  615. // insert after row
  616. this.panels.splice(insertPos, 0, new PanelModel(panel));
  617. // update insert post and y max
  618. insertPos += 1;
  619. yMax = Math.max(yMax, panel.gridPos.y + panel.gridPos.h);
  620. }
  621. const pushDownAmount = yMax - row.gridPos.y - 1;
  622. // push panels below down
  623. for (let panelIndex = insertPos; panelIndex < this.panels.length; panelIndex++) {
  624. this.panels[panelIndex].gridPos.y += pushDownAmount;
  625. }
  626. row.panels = [];
  627. if (hasRepeat) {
  628. this.processRowRepeats(row);
  629. }
  630. }
  631. // sort panels
  632. this.sortPanelsByGridPos();
  633. // emit change event
  634. this.events.emit('row-expanded');
  635. return;
  636. }
  637. const rowPanels = this.getRowPanels(rowIndex);
  638. // remove panels
  639. _.pull(this.panels, ...rowPanels);
  640. // save panel models inside row panel
  641. row.panels = _.map(rowPanels, (panel: PanelModel) => panel.getSaveModel());
  642. row.collapsed = true;
  643. // emit change event
  644. this.events.emit('row-collapsed');
  645. }
  646. /**
  647. * Will return all panels after rowIndex until it encounters another row
  648. */
  649. getRowPanels(rowIndex: number): PanelModel[] {
  650. const rowPanels = [];
  651. for (let index = rowIndex + 1; index < this.panels.length; index++) {
  652. const panel = this.panels[index];
  653. // break when encountering another row
  654. if (panel.type === 'row') {
  655. break;
  656. }
  657. // this panel must belong to row
  658. rowPanels.push(panel);
  659. }
  660. return rowPanels;
  661. }
  662. on(eventName: string, callback: (payload?: any) => void) {
  663. this.events.on(eventName, callback);
  664. }
  665. off(eventName: string, callback?: (payload?: any) => void) {
  666. this.events.off(eventName, callback);
  667. }
  668. cycleGraphTooltip() {
  669. this.graphTooltip = (this.graphTooltip + 1) % 3;
  670. }
  671. sharedTooltipModeEnabled() {
  672. return this.graphTooltip > 0;
  673. }
  674. sharedCrosshairModeOnly() {
  675. return this.graphTooltip === 1;
  676. }
  677. getRelativeTime(date: DateTimeInput) {
  678. date = isDateTime(date) ? date : dateTime(date);
  679. return this.timezone === 'browser' ? dateTime(date).fromNow() : toUtc(date).fromNow();
  680. }
  681. isTimezoneUtc() {
  682. return this.getTimezone() === 'utc';
  683. }
  684. isSnapshot() {
  685. return this.snapshot !== undefined;
  686. }
  687. getTimezone(): TimeZone {
  688. return (this.timezone ? this.timezone : contextSrv.user.timezone) as TimeZone;
  689. }
  690. private updateSchema(old: any) {
  691. const migrator = new DashboardMigrator(this);
  692. migrator.updateSchema(old);
  693. }
  694. resetOriginalTime() {
  695. this.originalTime = _.cloneDeep(this.time);
  696. }
  697. hasTimeChanged() {
  698. return !_.isEqual(this.time, this.originalTime);
  699. }
  700. resetOriginalVariables() {
  701. this.originalTemplating = _.map(this.templating.list, (variable: any) => {
  702. return {
  703. name: variable.name,
  704. type: variable.type,
  705. current: _.cloneDeep(variable.current),
  706. filters: _.cloneDeep(variable.filters),
  707. };
  708. });
  709. }
  710. hasVariableValuesChanged() {
  711. if (this.templating.list.length !== this.originalTemplating.length) {
  712. return false;
  713. }
  714. const updated = _.map(this.templating.list, (variable: any) => {
  715. return {
  716. name: variable.name,
  717. type: variable.type,
  718. current: _.cloneDeep(variable.current),
  719. filters: _.cloneDeep(variable.filters),
  720. };
  721. });
  722. return !_.isEqual(updated, this.originalTemplating);
  723. }
  724. autoFitPanels(viewHeight: number, kioskMode?: UrlQueryValue) {
  725. const currentGridHeight = Math.max(
  726. ...this.panels.map(panel => {
  727. return panel.gridPos.h + panel.gridPos.y;
  728. })
  729. );
  730. const navbarHeight = 55;
  731. const margin = 20;
  732. const submenuHeight = 50;
  733. let visibleHeight = viewHeight - navbarHeight - margin;
  734. // Remove submenu height if visible
  735. if (this.meta.submenuEnabled && !kioskMode) {
  736. visibleHeight -= submenuHeight;
  737. }
  738. // add back navbar height
  739. if (kioskMode && kioskMode !== KIOSK_MODE_TV) {
  740. visibleHeight += navbarHeight;
  741. }
  742. const visibleGridHeight = Math.floor(visibleHeight / (GRID_CELL_HEIGHT + GRID_CELL_VMARGIN));
  743. const scaleFactor = currentGridHeight / visibleGridHeight;
  744. this.panels.forEach((panel, i) => {
  745. panel.gridPos.y = Math.round(panel.gridPos.y / scaleFactor) || 1;
  746. panel.gridPos.h = Math.round(panel.gridPos.h / scaleFactor) || 1;
  747. });
  748. }
  749. templateVariableValueUpdated() {
  750. this.processRepeats();
  751. this.events.emit('template-variable-value-updated');
  752. }
  753. expandParentRowFor(panelId: number) {
  754. for (const panel of this.panels) {
  755. if (panel.collapsed) {
  756. for (const rowPanel of panel.panels) {
  757. if (rowPanel.id === panelId) {
  758. this.toggleRow(panel);
  759. return;
  760. }
  761. }
  762. }
  763. }
  764. }
  765. toggleLegendsForAll() {
  766. const panelsWithLegends = this.panels.filter(panel => {
  767. return panel.legend !== undefined && panel.legend !== null;
  768. });
  769. // determine if more panels are displaying legends or not
  770. const onCount = panelsWithLegends.filter(panel => panel.legend.show).length;
  771. const offCount = panelsWithLegends.length - onCount;
  772. const panelLegendsOn = onCount >= offCount;
  773. for (const panel of panelsWithLegends) {
  774. panel.legend.show = !panelLegendsOn;
  775. panel.render();
  776. }
  777. }
  778. }