156fe76b7fe3e25e5e536c252006e48f6b875996
[osm/UI.git] / skyquake / plugins / composer / src / src / stores / ComposerAppStore.js
1
2 /*
3 *
4 * Copyright 2016 RIFT.IO Inc
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 */
19 'use strict';
20
21 import _ from 'lodash'
22 import d3 from 'd3'
23 import alt from '../alt'
24 import UID from '../libraries/UniqueId'
25 import DescriptorModelFactory from '../libraries/model/DescriptorModelFactory'
26 import PanelResizeAction from '../actions/PanelResizeAction'
27 import CatalogItemsActions from '../actions/CatalogItemsActions'
28 import CanvasEditorActions from '../actions/CanvasEditorActions'
29 import ComposerAppActions from '../actions/ComposerAppActions'
30 import CatalogFilterActions from '../actions/CatalogFilterActions'
31 import CanvasPanelTrayActions from '../actions/CanvasPanelTrayActions'
32 import SelectionManager from '../libraries/SelectionManager'
33 import CatalogDataStore from '../stores/CatalogDataStore'
34 import isFullScreen from '../libraries/isFullScreen'
35
36 import FileManagerSource from '../components/filemanager/FileManagerSource';
37 import FileManagerActions from '../components/filemanager/FileManagerActions';
38
39 import React from 'react';
40
41 //Hack for crouton fix. Should eventually put composer in skyquake alt context
42 import SkyquakeComponent from 'widgets/skyquake_container/skyquakeComponent.jsx';
43 let NotificationError = null;
44 class ComponentBridge extends React.Component {
45 constructor(props) {
46 super(props);
47 NotificationError = this.props.flux.actions.global.showNotification;
48 }
49 render(){
50 return <i></i>
51 }
52 }
53 const getDefault = (name, defaultValue) => {
54 const val = window.localStorage.getItem('defaults-' + name);
55 if (val) {
56 if (_.isNumber(val)) {
57 if (val < 0) {
58 return setDefault(name, 0);
59 }
60 }
61 return Number(val);
62 }
63 setDefault(name, defaultValue);
64 return defaultValue;
65 };
66
67 const setDefault = (name, defaultValue) => {
68 window.localStorage.setItem('defaults-' + name, defaultValue);
69 return defaultValue;
70 };
71
72 /* the top and bottom positions are managed by css; requires div to be display: absolute*/
73 const defaults = {
74 left: getDefault('catalog-panel-start-width', 300),
75 right: getDefault('details-panel-start-width', 365),
76 bottom: 25 + getDefault('defaults-forwarding-graphs-panel-start-height', 0),
77 showMore: false,
78 zoom: getDefault('zoom', 100),
79 filterCatalogBy: 'nsd',
80 defaultPanelTrayOpenZoom: (() => {
81 let zoom = parseFloat(getDefault('panel-tray-zoom', 75));
82 if (isNaN(zoom)) {
83 zoom = 75;
84 }
85 zoom = Math.min(100, zoom);
86 zoom = Math.max(25, zoom);
87 setDefault('panel-tray-zoom', zoom);
88 return zoom;
89 })()
90 };
91
92 const autoZoomCanvasScale = d3.scale.linear().domain([0, 300]).range([100, 50]).clamp(true);
93
94 const uiTransientState = {};
95
96 class ComposerAppStore {
97
98 constructor() {
99 //Bridge for crouton fix
100 this.ComponentBridgeElement = SkyquakeComponent(ComponentBridge);
101
102 this.exportAsync(FileManagerSource)
103 // the catalog item currently being edited in the composer
104 this.item = null;
105 // the left and right sides of the canvas area
106 this.layout = {
107 left: defaults.left,
108 right: defaults.right,
109 bottom: defaults.bottom
110 };
111 uiTransientState.restoreLayout = this.layout;
112 this.zoom = defaults.zoom;
113 this.showMore = defaults.showMore;
114 this.filterCatalogByTypeValue = defaults.filterCatalogBy;
115 // transient ui state
116 this.drag = null;
117 this.message = '';
118 this.messageType = '';
119 this.showJSONViewer = false;
120 this.showClassifiers = {};
121 this.editPathsMode = false;
122 this.fullScreenMode = false;
123 this.panelTabShown = 'descriptor';
124 //File manager values
125 this.files = false;
126 this.filesState = {};
127 this.downloadJobs = {};
128 this.displayedPanel = 'forwarding' //or parameter
129 //End File manager values
130 this.bindListeners({
131 onResize: PanelResizeAction.RESIZE,
132 editCatalogItem: CatalogItemsActions.EDIT_CATALOG_ITEM,
133 catalogItemMetaDataChanged: CatalogItemsActions.CATALOG_ITEM_META_DATA_CHANGED,
134 catalogItemDescriptorChanged: CatalogItemsActions.CATALOG_ITEM_DESCRIPTOR_CHANGED,
135 toggleShowMoreInfo: CanvasEditorActions.TOGGLE_SHOW_MORE_INFO,
136 showMoreInfo: CanvasEditorActions.SHOW_MORE_INFO,
137 showLessInfo: CanvasEditorActions.SHOW_LESS_INFO,
138 applyDefaultLayout: CanvasEditorActions.APPLY_DEFAULT_LAYOUT,
139 addVirtualLinkDescriptor: CanvasEditorActions.ADD_VIRTUAL_LINK_DESCRIPTOR,
140 addForwardingGraphDescriptor: CanvasEditorActions.ADD_FORWARDING_GRAPH_DESCRIPTOR,
141 addVirtualDeploymentDescriptor: CanvasEditorActions.ADD_VIRTUAL_DEPLOYMENT_DESCRIPTOR,
142 selectModel: ComposerAppActions.SELECT_MODEL,
143 outlineModel: ComposerAppActions.OUTLINE_MODEL,
144 showError: ComposerAppActions.SHOW_ERROR,
145 clearError: ComposerAppActions.CLEAR_ERROR,
146 setDragState: ComposerAppActions.SET_DRAG_STATE,
147 filterCatalogByType: CatalogFilterActions.FILTER_BY_TYPE,
148 setCanvasZoom: CanvasEditorActions.SET_CANVAS_ZOOM,
149 showJsonViewer: ComposerAppActions.SHOW_JSON_VIEWER,
150 closeJsonViewer: ComposerAppActions.CLOSE_JSON_VIEWER,
151 toggleCanvasPanelTray: CanvasPanelTrayActions.TOGGLE_OPEN_CLOSE,
152 openCanvasPanelTray: CanvasPanelTrayActions.OPEN,
153 closeCanvasPanelTray: CanvasPanelTrayActions.CLOSE,
154 enterFullScreenMode: ComposerAppActions.ENTER_FULL_SCREEN_MODE,
155 exitFullScreenMode: ComposerAppActions.EXIT_FULL_SCREEN_MODE,
156 showAssets: ComposerAppActions.showAssets,
157 showDescriptor: ComposerAppActions.showDescriptor,
158 getFilelistSuccess: FileManagerActions.getFilelistSuccess,
159 updateFileLocationInput: FileManagerActions.updateFileLocationInput,
160 sendDownloadFileRequst: FileManagerActions.sendDownloadFileRequst,
161 addFileSuccess: FileManagerActions.addFileSuccess,
162 deletePackageFile: FileManagerActions.deletePackageFile,
163 deleteFileSuccess: FileManagerActions.deleteFileSuccess,
164 closeFileManagerSockets: FileManagerActions.closeFileManagerSockets,
165 openFileManagerSockets: FileManagerActions.openFileManagerSockets,
166 openDownloadMonitoringSocketSuccess: FileManagerActions.openDownloadMonitoringSocketSuccess,
167 getFilelistSocketSuccess: FileManagerActions.getFilelistSocketSuccess
168 });
169 this.exportPublicMethods({
170 closeFileManagerSockets: this.closeFileManagerSockets.bind(this)
171 })
172 }
173
174 onResize(e) {
175 if (e.type === 'resize-manager.resize.catalog-panel') {
176 const layout = Object.assign({}, this.layout);
177 layout.left = Math.max(0, layout.left - e.moved.x);
178 if (layout.left !== this.layout.left) {
179 this.setState({layout: layout});
180 }
181 } else if (e.type === 'resize-manager.resize.details-panel') {
182 const layout = Object.assign({}, this.layout);
183 layout.right = Math.max(0, layout.right + e.moved.x);
184 if (layout.right !== this.layout.right) {
185 this.setState({layout: layout});
186 }
187 } else if (/^resize-manager\.resize\.canvas-panel-tray/.test(e.type)) {
188 const layout = Object.assign({}, this.layout);
189 layout.bottom = Math.max(25, layout.bottom + e.moved.y);
190 if (layout.bottom !== this.layout.bottom) {
191 const zoom = autoZoomCanvasScale(layout.bottom) ;
192 if (this.zoom !== zoom) {
193 this.setState({layout: layout, zoom: zoom});
194 } else {
195 this.setState({layout: layout});
196 }
197 }
198 } else if (e.type !== 'resize') {
199 console.log('no resize handler for ', e.type, '. Do you need to add a handler in ComposerAppStore::onResize()?')
200 }
201 SelectionManager.refreshOutline();
202 }
203
204 updateItem(item) {
205 if(!document.body.classList.contains('resizing')) {
206 this.setState({item: _.cloneDeep(item)});
207 }
208 SelectionManager.refreshOutline();
209 }
210
211 editCatalogItem(item) {
212 let self = this;
213 self.closeFileManagerSockets();
214 if (item && item.uiState) {
215 item.uiState.isOpenForEdit = true;
216 if (item.uiState.type !== 'nsd') {
217 this.closeCanvasPanelTray();
218 }
219 }
220 SelectionManager.select(item);
221 this.updateItem(item);
222 this.openFileManagerSockets(item)
223 }
224 catalogItemMetaDataChanged(item) {
225 this.updateItem(item);
226 }
227
228 catalogItemDescriptorChanged(itemDescriptor) {
229 this.catalogItemMetaDataChanged(itemDescriptor.model);
230 }
231
232 showMoreInfo() {
233 this.setState({showMore: true});
234 }
235
236 showLessInfo() {
237 this.setState({showMore: false});
238 }
239
240 showError(data) {
241 NotificationError.defer({msg: data.errorMessage, type: 'error'})
242 // this.setState({message: data.errorMessage, messageType: 'error'});
243 }
244
245 clearError() {
246 this.setState({message: '', messageType: ''});
247 }
248
249 toggleShowMoreInfo() {
250 this.setState({showMore: !this.showMore});
251 }
252
253 applyDefaultLayout() {
254 if (this.item && this.item.uiState && this.item.uiState.containerPositionMap) {
255 if (!_.isEmpty(this.item.uiState.containerPositionMap)) {
256 this.item.uiState.containerPositionMap = {};
257 CatalogItemsActions.catalogItemMetaDataChanged.defer(this.item);
258 }
259 }
260 }
261
262 addVirtualLinkDescriptor(dropCoordinates = null) {
263 let vld;
264 if (this.item) {
265 if (this.item.uiState.type === 'nsd') {
266 const nsdc = DescriptorModelFactory.newNetworkService(this.item);
267 vld = nsdc.createVld();
268 } else if (this.item.uiState.type === 'vnfd') {
269 const vnfd = DescriptorModelFactory.newVirtualNetworkFunction(this.item);
270 vld = vnfd.createVld();
271 }
272 if (vld) {
273 vld.uiState.dropCoordinates = dropCoordinates;
274 SelectionManager.clearSelectionAndRemoveOutline();
275 SelectionManager.addSelection(vld);
276 this.updateItem(vld.getRoot().model);
277 CatalogItemsActions.catalogItemDescriptorChanged.defer(vld.getRoot());
278 }
279 }
280 }
281
282 addForwardingGraphDescriptor(dropCoordinates = null) {
283 if (this.item && this.item.uiState.type === 'nsd') {
284 const nsdc = DescriptorModelFactory.newNetworkService(this.item);
285 const fg = nsdc.createVnffgd();
286 fg.uiState.dropCoordinates = dropCoordinates;
287 SelectionManager.clearSelectionAndRemoveOutline();
288 SelectionManager.addSelection(fg);
289 this.updateItem(nsdc.model);
290 CatalogItemsActions.catalogItemDescriptorChanged.defer(nsdc);
291 }
292 }
293
294 addVirtualDeploymentDescriptor(dropCoordinates = null) {
295 if (this.item.uiState.type === 'vnfd') {
296 const vnfd = DescriptorModelFactory.newVirtualNetworkFunction(this.item);
297 const vdu = vnfd.createVdu();
298 vdu.uiState.dropCoordinates = dropCoordinates;
299 SelectionManager.clearSelectionAndRemoveOutline();
300 SelectionManager.addSelection(vdu);
301 this.updateItem(vdu.getRoot().model);
302 CatalogItemsActions.catalogItemDescriptorChanged.defer(vdu.getRoot());
303 }
304 }
305
306 selectModel(container) {
307 if (SelectionManager.select(container)) {
308 const model = DescriptorModelFactory.isContainer(container) ? container.getRoot().model : container;
309 this.catalogItemMetaDataChanged(model);
310 }
311 }
312
313 outlineModel(obj) {
314 const uid = UID.from(obj);
315 requestAnimationFrame(() => {
316 SelectionManager.outline(Array.from(document.querySelectorAll(`[data-uid="${uid}"]`)));
317 });
318 }
319
320 clearSelection() {
321 SelectionManager.clearSelectionAndRemoveOutline();
322 this.catalogItemMetaDataChanged(this.item);
323 }
324
325 setDragState(dragState) {
326 this.setState({drag: dragState});
327 }
328
329 filterCatalogByType(typeValue) {
330 this.setState({filterCatalogByTypeValue: typeValue})
331 }
332
333 setCanvasZoom(zoom) {
334 this.setState({zoom: zoom});
335 }
336
337 showJsonViewer() {
338 this.setState({showJSONViewer: true});
339 }
340
341 closeJsonViewer() {
342 this.setState({showJSONViewer: false});
343 }
344
345 toggleCanvasPanelTray(event) {
346 const layout = this.layout;
347 const attrMap = event.target.attributes;
348 let panelEvent = null;
349 for(let k in attrMap) {
350 if(attrMap[k].name == 'data-event') {
351 panelEvent = attrMap[k].nodeValue;
352 }
353 }
354 if ((layout.bottom > 25) && ((panelEvent == this.displayedPanel) || panelEvent == 'arrow')) {
355 this.closeCanvasPanelTray();
356 } else {
357 this.openCanvasPanelTray();
358 }
359 if(panelEvent != 'arrow'){
360 this.setState({displayedPanel: panelEvent})
361 }
362 }
363
364 openCanvasPanelTray() {
365 const layout = {
366 left: this.layout.left,
367 right: this.layout.right,
368 bottom: 300
369 };
370 const zoom = defaults.defaultPanelTrayOpenZoom;
371 if (this.zoom !== zoom) {
372 this.setState({layout: layout, zoom: zoom, restoreZoom: this.zoom});
373 } else {
374 this.setState({layout: layout});
375 }
376 }
377
378 closeCanvasPanelTray() {
379 const layout = {
380 left: this.layout.left,
381 right: this.layout.right,
382 bottom: 25
383 };
384 const zoom = this.restoreZoom || autoZoomCanvasScale(layout.bottom);
385 if (this.zoom !== zoom) {
386 this.setState({layout: layout, zoom: zoom, restoreZoom: null});
387 } else {
388 this.setState({layout: layout, restoreZoom: null});
389 }
390 }
391
392 enterFullScreenMode() {
393
394 /**
395 * https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
396 * This is an experimental api but works our target browsers and ignored by others
397 */
398 const eventNames = ['fullscreenchange', 'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange'];
399
400 const appRoot = document.body;//.getElementById('RIFT_wareLaunchpadComposerAppRoot');
401
402 const comp = this;
403
404 function onFullScreenChange() {
405
406 if (isFullScreen()) {
407 const layout = comp.layout;
408 const restoreLayout = _.cloneDeep(layout);
409 uiTransientState.restoreLayout = restoreLayout;
410 layout.left = 0;
411 layout.right = 0;
412 comp.setState({fullScreenMode: true, layout: layout, restoreLayout: restoreLayout});
413 } else {
414 comp.setState({fullScreenMode: false, layout: uiTransientState.restoreLayout});
415 }
416
417 }
418
419 if (this.fullScreenMode === false) {
420
421 if (appRoot.requestFullscreen) {
422 appRoot.requestFullscreen();
423 } else if (appRoot.msRequestFullscreen) {
424 appRoot.msRequestFullscreen();
425 } else if (appRoot.mozRequestFullScreen) {
426 appRoot.mozRequestFullScreen();
427 } else if (appRoot.webkitRequestFullscreen) {
428 appRoot.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
429 }
430
431 eventNames.map(name => {
432 document.removeEventListener(name, onFullScreenChange);
433 document.addEventListener(name, onFullScreenChange);
434 });
435
436 }
437
438 }
439
440 exitFullScreenMode() {
441
442 if (document.exitFullscreen) {
443 document.exitFullscreen();
444 } else if (document.msExitFullscreen) {
445 document.msExitFullscreen();
446 } else if (document.mozCancelFullScreen) {
447 document.mozCancelFullScreen();
448 } else if (document.webkitExitFullscreen) {
449 document.webkitExitFullscreen();
450 }
451
452 this.setState({fullScreenMode: false});
453
454 }
455 showAssets() {
456 this.setState({
457 panelTabShown: 'assets'
458 });
459 }
460 showDescriptor() {
461 this.setState({
462 panelTabShown: 'descriptor'
463 });
464 }
465
466 //File Manager methods
467 getFilelistSuccess(data) {
468 let self = this;
469 let filesState = null;
470 if (self.fileMonitoringSocketID) {
471 let newState = {};
472 if(data.hasOwnProperty('contents')) {
473 filesState = addInputState( _.cloneDeep(this.filesState),data);
474 // filesState = _.merge(self.filesState, addInputState({},data));
475 let normalizedData = normalizeTree(data);
476 newState = {
477 files: {
478 data: _.mergeWith(normalizedData.data, self.files.data, function(obj, src) {
479 return _.uniqBy(obj? obj.concat(src) : src, 'name');
480 }),
481 id: self.files.id || normalizedData.id
482 },
483 filesState: filesState
484 }
485 } else {
486 newState = {
487 files: false
488 }
489 }
490
491 this.setState(newState);
492 }
493 function normalizeTree(data) {
494 let f = {
495 id:[],
496 data:{}
497 };
498 data.contents.map(getContents);
499 function getContents(d) {
500 if(d.hasOwnProperty('contents')) {
501 let contents = [];
502 d.contents.map(function(c,i) {
503 if (!c.hasOwnProperty('contents')) {
504 contents.push(c);
505 } else {
506 getContents(c);
507 }
508 })
509 f.id.push(d.name);
510 f.data[d.name] = contents;
511 }
512 }
513 return f;
514 }
515 function addInputState(obj, d) {
516 d.newFile = '';
517 if(d.hasOwnProperty('contents')) {
518 d.contents.map(addInputState.bind(null, obj))
519 }
520 if(!obj[d.name]) {
521 obj[d.name] = '';
522 }
523 return obj;
524 }
525 }
526 sendDownloadFileRequst(data) {
527 let id = data.id || this.item.id;
528 let type = data.type || this.item.uiState.type;
529 let path = data.path;
530 let url = data.url;
531 this.getInstance().addFile(id, type, path, url);
532 }
533 updateFileLocationInput = (data) => {
534 let name = data.name;
535 let value = data.value;
536 var filesState = _.cloneDeep(this.filesState);
537 filesState[name] = value;
538 this.setState({
539 filesState: filesState
540 });
541 }
542 addFileSuccess = (data) => {
543 let path = data.path;
544 let fileName = data.fileName;
545 let files = _.cloneDeep(this.files);
546 let loadingIndex = files.data[path].push({
547 status: 'DOWNLOADING',
548 name: path + '/' + fileName
549 }) - 1;
550 this.setState({files: files});
551
552 }
553 startWatchingJob = () => {
554 let ws = window.multiplexer.channel(this.jobSocketId);
555 this.setState({
556 jobSocket:null
557 })
558 }
559 openDownloadMonitoringSocketSuccess = (id) => {
560 let self = this;
561 let ws = window.multiplexer.channel(id);
562 let downloadJobs = _.cloneDeep(self.downloadJobs);
563 let newFiles = false;
564 ws.onmessage = (socket) => {
565 if (self.files && self.files.length > 0) {
566 let jobs = [];
567 try {
568 jobs = JSON.parse(socket.data);
569 } catch(e) {}
570 newFiles = _.cloneDeep(self.files);
571 jobs.map(function(j) {
572 //check if not in completed state
573 let fullPath = j['package-path'];
574 let path = fullPath.split('/');
575 let fileName = path.pop();
576 path = path.join('/');
577 let index = _.findIndex(self.files.data[path], function(o){
578 return fullPath == o.name
579 });
580 if((index > -1) && newFiles.data[path][index]) {
581 newFiles.data[path][index].status = j.status
582 } else {
583 if(j.status.toUpperCase() == 'LOADING...' || j.status.toUpperCase() == 'IN_PROGRESS') {
584 newFiles.data[path].push({
585 status: j.status,
586 name: fullPath
587 })
588 } else {
589 // if ()
590 }
591 }
592 })
593 self.setState({
594 files: newFiles
595 })
596 // console.log(JSON.parse(socket.data));
597 }
598 }
599 this.setState({
600 jobSocketId: id,
601 jobSocket: ws
602 })
603
604 }
605 getFilelistSocketSuccess = (id) => {
606 let self = this;
607 let ws = window.multiplexer.channel(id);
608 ws.onmessage = (socket) => {
609 if (self.fileMonitoringSocketID) {
610 let data = [];
611 try {
612 data = JSON.parse(socket.data);
613 } catch(e) {}
614 self.getFilelistSuccess(data)
615 }
616 }
617
618 this.setState({
619 fileMonitoringSocketID: id,
620 fileMonitoringSocket: ws
621 })
622
623 }
624 closeFileManagerSockets() {
625 this.fileMonitoringSocketID = null;
626 this.setState({
627 jobSocketId : null,
628 fileMonitoringSocketID : null
629 // jobSocket : null,
630 // fileMonitoringSocket : null,
631 });
632 this.jobSocket && this.jobSocket.close();
633 this.fileMonitoringSocket && this.fileMonitoringSocket.close();
634 console.log('closing');
635 }
636 openFileManagerSockets(i) {
637 let self = this;
638 let item = i || self.item;
639 // this.closeFileManagerSockets();
640 this.getInstance().openFileMonitoringSocket(item.id, item.uiState.type).then(function() {
641 // // self.getInstance().openDownloadMonitoringSocket(item.id);
642 });
643 this.getInstance().openDownloadMonitoringSocket(item.id);
644 }
645 endWatchingJob(id) {
646
647 }
648 deletePackageFile(name) {
649 let id = this.item.id;
650 let type = this.item.uiState.type;
651 this.getInstance().deleteFile(id, type, name);
652 }
653 deleteFileSuccess = (data) => {
654 let path = data.path.split('/')
655 let files = _.cloneDeep(this.files);
656 path.pop();
657 path = path.join('/');
658 let pathFiles = files.data[path]
659 _.remove(pathFiles, function(c) {
660 return c.name == data.path;
661 });
662
663 this.setState({
664 files: files
665 })
666 }
667 }
668
669 export default alt.createStore(ComposerAppStore, 'ComposerAppStore');