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 } from '@grafana/ui';
  14. import { UrlQueryValue } from '@grafana/runtime';
  15. import { KIOSK_MODE_TV, DashboardMeta } from 'app/types';
  16. import { toUtc, DateTimeInput, dateTime, isDateTime } from '@grafana/ui/src/utils/moment_wrapper';
  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. this.sortPanelsByGridPos();
  285. this.events.emit('repeats-processed');
  286. }
  287. processRepeats() {
  288. if (this.snapshot || this.templating.list.length === 0) {
  289. return;
  290. }
  291. this.cleanUpRepeats();
  292. this.iteration = (this.iteration || new Date().getTime()) + 1;
  293. for (let i = 0; i < this.panels.length; i++) {
  294. const panel = this.panels[i];
  295. if (panel.repeat) {
  296. this.repeatPanel(panel, i);
  297. }
  298. }
  299. this.sortPanelsByGridPos();
  300. this.events.emit('repeats-processed');
  301. }
  302. cleanUpRowRepeats(rowPanels: PanelModel[]) {
  303. const panelsToRemove = [];
  304. for (let i = 0; i < rowPanels.length; i++) {
  305. const panel = rowPanels[i];
  306. if (!panel.repeat && panel.repeatPanelId) {
  307. panelsToRemove.push(panel);
  308. }
  309. }
  310. _.pull(rowPanels, ...panelsToRemove);
  311. _.pull(this.panels, ...panelsToRemove);
  312. }
  313. processRowRepeats(row: PanelModel) {
  314. if (this.snapshot || this.templating.list.length === 0) {
  315. return;
  316. }
  317. let rowPanels = row.panels;
  318. if (!row.collapsed) {
  319. const rowPanelIndex = _.findIndex(this.panels, (p: PanelModel) => p.id === row.id);
  320. rowPanels = this.getRowPanels(rowPanelIndex);
  321. }
  322. this.cleanUpRowRepeats(rowPanels);
  323. for (let i = 0; i < rowPanels.length; i++) {
  324. const panel = rowPanels[i];
  325. if (panel.repeat) {
  326. const panelIndex = _.findIndex(this.panels, (p: PanelModel) => p.id === panel.id);
  327. this.repeatPanel(panel, panelIndex);
  328. }
  329. }
  330. }
  331. getPanelRepeatClone(sourcePanel: PanelModel, valueIndex: number, sourcePanelIndex: number) {
  332. // if first clone return source
  333. if (valueIndex === 0) {
  334. return sourcePanel;
  335. }
  336. const clone = new PanelModel(sourcePanel.getSaveModel());
  337. clone.id = this.getNextPanelId();
  338. // insert after source panel + value index
  339. this.panels.splice(sourcePanelIndex + valueIndex, 0, clone);
  340. clone.repeatIteration = this.iteration;
  341. clone.repeatPanelId = sourcePanel.id;
  342. clone.repeat = null;
  343. return clone;
  344. }
  345. getRowRepeatClone(sourceRowPanel: PanelModel, valueIndex: number, sourcePanelIndex: number) {
  346. // if first clone return source
  347. if (valueIndex === 0) {
  348. if (!sourceRowPanel.collapsed) {
  349. const rowPanels = this.getRowPanels(sourcePanelIndex);
  350. sourceRowPanel.panels = rowPanels;
  351. }
  352. return sourceRowPanel;
  353. }
  354. const clone = new PanelModel(sourceRowPanel.getSaveModel());
  355. // for row clones we need to figure out panels under row to clone and where to insert clone
  356. let rowPanels: PanelModel[], insertPos: number;
  357. if (sourceRowPanel.collapsed) {
  358. rowPanels = _.cloneDeep(sourceRowPanel.panels);
  359. clone.panels = rowPanels;
  360. // insert copied row after preceding row
  361. insertPos = sourcePanelIndex + valueIndex;
  362. } else {
  363. rowPanels = this.getRowPanels(sourcePanelIndex);
  364. clone.panels = _.map(rowPanels, (panel: PanelModel) => panel.getSaveModel());
  365. // insert copied row after preceding row's panels
  366. insertPos = sourcePanelIndex + (rowPanels.length + 1) * valueIndex;
  367. }
  368. this.panels.splice(insertPos, 0, clone);
  369. this.updateRepeatedPanelIds(clone);
  370. return clone;
  371. }
  372. repeatPanel(panel: PanelModel, panelIndex: number) {
  373. const variable: any = _.find(this.templating.list, { name: panel.repeat } as any);
  374. if (!variable) {
  375. return;
  376. }
  377. if (panel.type === 'row') {
  378. this.repeatRow(panel, panelIndex, variable);
  379. return;
  380. }
  381. const selectedOptions = this.getSelectedVariableOptions(variable);
  382. const maxPerRow = panel.maxPerRow || 4;
  383. let xPos = 0;
  384. let yPos = panel.gridPos.y;
  385. for (let index = 0; index < selectedOptions.length; index++) {
  386. const option = selectedOptions[index];
  387. let copy;
  388. copy = this.getPanelRepeatClone(panel, index, panelIndex);
  389. copy.scopedVars = copy.scopedVars || {};
  390. copy.scopedVars[variable.name] = option;
  391. if (panel.repeatDirection === REPEAT_DIR_VERTICAL) {
  392. if (index > 0) {
  393. yPos += copy.gridPos.h;
  394. }
  395. copy.gridPos.y = yPos;
  396. } else {
  397. // set width based on how many are selected
  398. // assumed the repeated panels should take up full row width
  399. copy.gridPos.w = Math.max(GRID_COLUMN_COUNT / selectedOptions.length, GRID_COLUMN_COUNT / maxPerRow);
  400. copy.gridPos.x = xPos;
  401. copy.gridPos.y = yPos;
  402. xPos += copy.gridPos.w;
  403. // handle overflow by pushing down one row
  404. if (xPos + copy.gridPos.w > GRID_COLUMN_COUNT) {
  405. xPos = 0;
  406. yPos += copy.gridPos.h;
  407. }
  408. }
  409. }
  410. // Update gridPos for panels below
  411. const yOffset = yPos - panel.gridPos.y;
  412. if (yOffset > 0) {
  413. const panelBelowIndex = panelIndex + selectedOptions.length;
  414. for (let i = panelBelowIndex; i < this.panels.length; i++) {
  415. this.panels[i].gridPos.y += yOffset;
  416. }
  417. }
  418. }
  419. repeatRow(panel: PanelModel, panelIndex: number, variable: any) {
  420. const selectedOptions = this.getSelectedVariableOptions(variable);
  421. let yPos = panel.gridPos.y;
  422. function setScopedVars(panel: PanelModel, variableOption: any) {
  423. panel.scopedVars = panel.scopedVars || {};
  424. panel.scopedVars[variable.name] = variableOption;
  425. }
  426. for (let optionIndex = 0; optionIndex < selectedOptions.length; optionIndex++) {
  427. const option = selectedOptions[optionIndex];
  428. const rowCopy = this.getRowRepeatClone(panel, optionIndex, panelIndex);
  429. setScopedVars(rowCopy, option);
  430. const rowHeight = this.getRowHeight(rowCopy);
  431. const rowPanels = rowCopy.panels || [];
  432. let panelBelowIndex;
  433. if (panel.collapsed) {
  434. // For collapsed row just copy its panels and set scoped vars and proper IDs
  435. _.each(rowPanels, (rowPanel: PanelModel, i: number) => {
  436. setScopedVars(rowPanel, option);
  437. if (optionIndex > 0) {
  438. this.updateRepeatedPanelIds(rowPanel, true);
  439. }
  440. });
  441. rowCopy.gridPos.y += optionIndex;
  442. yPos += optionIndex;
  443. panelBelowIndex = panelIndex + optionIndex + 1;
  444. } else {
  445. // insert after 'row' panel
  446. const insertPos = panelIndex + (rowPanels.length + 1) * optionIndex + 1;
  447. _.each(rowPanels, (rowPanel: PanelModel, i: number) => {
  448. setScopedVars(rowPanel, option);
  449. if (optionIndex > 0) {
  450. const cloneRowPanel = new PanelModel(rowPanel);
  451. this.updateRepeatedPanelIds(cloneRowPanel, true);
  452. // For exposed row additionally set proper Y grid position and add it to dashboard panels
  453. cloneRowPanel.gridPos.y += rowHeight * optionIndex;
  454. this.panels.splice(insertPos + i, 0, cloneRowPanel);
  455. }
  456. });
  457. rowCopy.panels = [];
  458. rowCopy.gridPos.y += rowHeight * optionIndex;
  459. yPos += rowHeight;
  460. panelBelowIndex = insertPos + rowPanels.length;
  461. }
  462. // Update gridPos for panels below
  463. for (let i = panelBelowIndex; i < this.panels.length; i++) {
  464. this.panels[i].gridPos.y += yPos;
  465. }
  466. }
  467. }
  468. updateRepeatedPanelIds(panel: PanelModel, repeatedByRow?: boolean) {
  469. panel.repeatPanelId = panel.id;
  470. panel.id = this.getNextPanelId();
  471. panel.repeatIteration = this.iteration;
  472. if (repeatedByRow) {
  473. panel.repeatedByRow = true;
  474. } else {
  475. panel.repeat = null;
  476. }
  477. return panel;
  478. }
  479. getSelectedVariableOptions(variable: any) {
  480. let selectedOptions: any[];
  481. if (variable.current.text === 'All') {
  482. selectedOptions = variable.options.slice(1, variable.options.length);
  483. } else {
  484. selectedOptions = _.filter(variable.options, { selected: true });
  485. }
  486. return selectedOptions;
  487. }
  488. getRowHeight(rowPanel: PanelModel): number {
  489. if (!rowPanel.panels || rowPanel.panels.length === 0) {
  490. return 0;
  491. }
  492. const rowYPos = rowPanel.gridPos.y;
  493. const positions = _.map(rowPanel.panels, 'gridPos');
  494. const maxPos = _.maxBy(positions, (pos: GridPos) => {
  495. return pos.y + pos.h;
  496. });
  497. return maxPos.y + maxPos.h - rowYPos;
  498. }
  499. removePanel(panel: PanelModel) {
  500. const index = _.indexOf(this.panels, panel);
  501. this.panels.splice(index, 1);
  502. this.events.emit('panel-removed', panel);
  503. }
  504. removeRow(row: PanelModel, removePanels: boolean) {
  505. const needToogle = (!removePanels && row.collapsed) || (removePanels && !row.collapsed);
  506. if (needToogle) {
  507. this.toggleRow(row);
  508. }
  509. this.removePanel(row);
  510. }
  511. expandRows() {
  512. for (let i = 0; i < this.panels.length; i++) {
  513. const panel = this.panels[i];
  514. if (panel.type !== 'row') {
  515. continue;
  516. }
  517. if (panel.collapsed) {
  518. this.toggleRow(panel);
  519. }
  520. }
  521. }
  522. collapseRows() {
  523. for (let i = 0; i < this.panels.length; i++) {
  524. const panel = this.panels[i];
  525. if (panel.type !== 'row') {
  526. continue;
  527. }
  528. if (!panel.collapsed) {
  529. this.toggleRow(panel);
  530. }
  531. }
  532. }
  533. setPanelFocus(id: number) {
  534. this.meta.focusPanelId = id;
  535. }
  536. updateSubmenuVisibility() {
  537. this.meta.submenuEnabled = (() => {
  538. if (this.links.length > 0) {
  539. return true;
  540. }
  541. const visibleVars = _.filter(this.templating.list, (variable: any) => variable.hide !== 2);
  542. if (visibleVars.length > 0) {
  543. return true;
  544. }
  545. const visibleAnnotations = _.filter(this.annotations.list, (annotation: any) => annotation.hide !== true);
  546. if (visibleAnnotations.length > 0) {
  547. return true;
  548. }
  549. return false;
  550. })();
  551. }
  552. getPanelInfoById(panelId: number) {
  553. for (let i = 0; i < this.panels.length; i++) {
  554. if (this.panels[i].id === panelId) {
  555. return {
  556. panel: this.panels[i],
  557. index: i,
  558. };
  559. }
  560. }
  561. return null;
  562. }
  563. duplicatePanel(panel: PanelModel) {
  564. const newPanel = panel.getSaveModel();
  565. newPanel.id = this.getNextPanelId();
  566. delete newPanel.repeat;
  567. delete newPanel.repeatIteration;
  568. delete newPanel.repeatPanelId;
  569. delete newPanel.scopedVars;
  570. if (newPanel.alert) {
  571. delete newPanel.thresholds;
  572. }
  573. delete newPanel.alert;
  574. // does it fit to the right?
  575. if (panel.gridPos.x + panel.gridPos.w * 2 <= GRID_COLUMN_COUNT) {
  576. newPanel.gridPos.x += panel.gridPos.w;
  577. } else {
  578. // add below
  579. newPanel.gridPos.y += panel.gridPos.h;
  580. }
  581. this.addPanel(newPanel);
  582. return newPanel;
  583. }
  584. formatDate(date: DateTimeInput, format?: string) {
  585. date = isDateTime(date) ? date : dateTime(date);
  586. format = format || 'YYYY-MM-DD HH:mm:ss';
  587. const timezone = this.getTimezone();
  588. return timezone === 'browser' ? dateTime(date).format(format) : toUtc(date).format(format);
  589. }
  590. destroy() {
  591. this.events.removeAllListeners();
  592. for (const panel of this.panels) {
  593. panel.destroy();
  594. }
  595. }
  596. toggleRow(row: PanelModel) {
  597. const rowIndex = _.indexOf(this.panels, row);
  598. if (row.collapsed) {
  599. row.collapsed = false;
  600. const hasRepeat = _.some(row.panels as PanelModel[], (p: PanelModel) => p.repeat);
  601. if (row.panels.length > 0) {
  602. // Use first panel to figure out if it was moved or pushed
  603. const firstPanel = row.panels[0];
  604. const yDiff = firstPanel.gridPos.y - (row.gridPos.y + row.gridPos.h);
  605. // start inserting after row
  606. let insertPos = rowIndex + 1;
  607. // y max will represent the bottom y pos after all panels have been added
  608. // needed to know home much panels below should be pushed down
  609. let yMax = row.gridPos.y;
  610. for (const panel of row.panels) {
  611. // make sure y is adjusted (in case row moved while collapsed)
  612. // console.log('yDiff', yDiff);
  613. panel.gridPos.y -= yDiff;
  614. // insert after row
  615. this.panels.splice(insertPos, 0, new PanelModel(panel));
  616. // update insert post and y max
  617. insertPos += 1;
  618. yMax = Math.max(yMax, panel.gridPos.y + panel.gridPos.h);
  619. }
  620. const pushDownAmount = yMax - row.gridPos.y - 1;
  621. // push panels below down
  622. for (let panelIndex = insertPos; panelIndex < this.panels.length; panelIndex++) {
  623. this.panels[panelIndex].gridPos.y += pushDownAmount;
  624. }
  625. row.panels = [];
  626. if (hasRepeat) {
  627. this.processRowRepeats(row);
  628. }
  629. }
  630. // sort panels
  631. this.sortPanelsByGridPos();
  632. // emit change event
  633. this.events.emit('row-expanded');
  634. return;
  635. }
  636. const rowPanels = this.getRowPanels(rowIndex);
  637. // remove panels
  638. _.pull(this.panels, ...rowPanels);
  639. // save panel models inside row panel
  640. row.panels = _.map(rowPanels, (panel: PanelModel) => panel.getSaveModel());
  641. row.collapsed = true;
  642. // emit change event
  643. this.events.emit('row-collapsed');
  644. }
  645. /**
  646. * Will return all panels after rowIndex until it encounters another row
  647. */
  648. getRowPanels(rowIndex: number): PanelModel[] {
  649. const rowPanels = [];
  650. for (let index = rowIndex + 1; index < this.panels.length; index++) {
  651. const panel = this.panels[index];
  652. // break when encountering another row
  653. if (panel.type === 'row') {
  654. break;
  655. }
  656. // this panel must belong to row
  657. rowPanels.push(panel);
  658. }
  659. return rowPanels;
  660. }
  661. on(eventName: string, callback: Function) {
  662. this.events.on(eventName, callback);
  663. }
  664. off(eventName: string, callback?: Function) {
  665. this.events.off(eventName, callback);
  666. }
  667. cycleGraphTooltip() {
  668. this.graphTooltip = (this.graphTooltip + 1) % 3;
  669. }
  670. sharedTooltipModeEnabled() {
  671. return this.graphTooltip > 0;
  672. }
  673. sharedCrosshairModeOnly() {
  674. return this.graphTooltip === 1;
  675. }
  676. getRelativeTime(date: DateTimeInput) {
  677. date = isDateTime(date) ? date : dateTime(date);
  678. return this.timezone === 'browser' ? dateTime(date).fromNow() : toUtc(date).fromNow();
  679. }
  680. isTimezoneUtc() {
  681. return this.getTimezone() === 'utc';
  682. }
  683. isSnapshot() {
  684. return this.snapshot !== undefined;
  685. }
  686. getTimezone() {
  687. return this.timezone ? this.timezone : contextSrv.user.timezone;
  688. }
  689. private updateSchema(old: any) {
  690. const migrator = new DashboardMigrator(this);
  691. migrator.updateSchema(old);
  692. }
  693. resetOriginalTime() {
  694. this.originalTime = _.cloneDeep(this.time);
  695. }
  696. hasTimeChanged() {
  697. return !_.isEqual(this.time, this.originalTime);
  698. }
  699. resetOriginalVariables() {
  700. this.originalTemplating = _.map(this.templating.list, (variable: any) => {
  701. return {
  702. name: variable.name,
  703. type: variable.type,
  704. current: _.cloneDeep(variable.current),
  705. filters: _.cloneDeep(variable.filters),
  706. };
  707. });
  708. }
  709. hasVariableValuesChanged() {
  710. if (this.templating.list.length !== this.originalTemplating.length) {
  711. return false;
  712. }
  713. const updated = _.map(this.templating.list, (variable: any) => {
  714. return {
  715. name: variable.name,
  716. type: variable.type,
  717. current: _.cloneDeep(variable.current),
  718. filters: _.cloneDeep(variable.filters),
  719. };
  720. });
  721. return !_.isEqual(updated, this.originalTemplating);
  722. }
  723. autoFitPanels(viewHeight: number, kioskMode?: UrlQueryValue) {
  724. const currentGridHeight = Math.max(
  725. ...this.panels.map(panel => {
  726. return panel.gridPos.h + panel.gridPos.y;
  727. })
  728. );
  729. const navbarHeight = 55;
  730. const margin = 20;
  731. const submenuHeight = 50;
  732. let visibleHeight = viewHeight - navbarHeight - margin;
  733. // Remove submenu height if visible
  734. if (this.meta.submenuEnabled && !kioskMode) {
  735. visibleHeight -= submenuHeight;
  736. }
  737. // add back navbar height
  738. if (kioskMode && kioskMode !== KIOSK_MODE_TV) {
  739. visibleHeight += navbarHeight;
  740. }
  741. const visibleGridHeight = Math.floor(visibleHeight / (GRID_CELL_HEIGHT + GRID_CELL_VMARGIN));
  742. const scaleFactor = currentGridHeight / visibleGridHeight;
  743. this.panels.forEach((panel, i) => {
  744. panel.gridPos.y = Math.round(panel.gridPos.y / scaleFactor) || 1;
  745. panel.gridPos.h = Math.round(panel.gridPos.h / scaleFactor) || 1;
  746. });
  747. }
  748. templateVariableValueUpdated() {
  749. this.processRepeats();
  750. this.events.emit('template-variable-value-updated');
  751. }
  752. expandParentRowFor(panelId: number) {
  753. for (const panel of this.panels) {
  754. if (panel.collapsed) {
  755. for (const rowPanel of panel.panels) {
  756. if (rowPanel.id === panelId) {
  757. this.toggleRow(panel);
  758. return;
  759. }
  760. }
  761. }
  762. }
  763. }
  764. toggleLegendsForAll() {
  765. const panelsWithLegends = this.panels.filter(panel => {
  766. return panel.legend !== undefined && panel.legend !== null;
  767. });
  768. // determine if more panels are displaying legends or not
  769. const onCount = panelsWithLegends.filter(panel => panel.legend.show).length;
  770. const offCount = panelsWithLegends.length - onCount;
  771. const panelLegendsOn = onCount >= offCount;
  772. for (const panel of panelsWithLegends) {
  773. panel.legend.show = !panelLegendsOn;
  774. panel.render();
  775. }
  776. }
  777. }