DashboardModel.ts 25 KB

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