Package Mananger
[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 = [];
126 this.filesState = {};
127 this.downloadJobs = {};
128 //End File manager values
129 this.bindListeners({
130 onResize: PanelResizeAction.RESIZE,
131 editCatalogItem: CatalogItemsActions.EDIT_CATALOG_ITEM,
132 catalogItemMetaDataChanged: CatalogItemsActions.CATALOG_ITEM_META_DATA_CHANGED,
133 catalogItemDescriptorChanged: CatalogItemsActions.CATALOG_ITEM_DESCRIPTOR_CHANGED,
134 toggleShowMoreInfo: CanvasEditorActions.TOGGLE_SHOW_MORE_INFO,
135 showMoreInfo: CanvasEditorActions.SHOW_MORE_INFO,
136 showLessInfo: CanvasEditorActions.SHOW_LESS_INFO,
137 applyDefaultLayout: CanvasEditorActions.APPLY_DEFAULT_LAYOUT,
138 addVirtualLinkDescriptor: CanvasEditorActions.ADD_VIRTUAL_LINK_DESCRIPTOR,
139 addForwardingGraphDescriptor: CanvasEditorActions.ADD_FORWARDING_GRAPH_DESCRIPTOR,
140 addVirtualDeploymentDescriptor: CanvasEditorActions.ADD_VIRTUAL_DEPLOYMENT_DESCRIPTOR,
141 selectModel: ComposerAppActions.SELECT_MODEL,
142 outlineModel: ComposerAppActions.OUTLINE_MODEL,
143 showError: ComposerAppActions.SHOW_ERROR,
144 clearError: ComposerAppActions.CLEAR_ERROR,
145 setDragState: ComposerAppActions.SET_DRAG_STATE,
146 filterCatalogByType: CatalogFilterActions.FILTER_BY_TYPE,
147 setCanvasZoom: CanvasEditorActions.SET_CANVAS_ZOOM,
148 showJsonViewer: ComposerAppActions.SHOW_JSON_VIEWER,
149 closeJsonViewer: ComposerAppActions.CLOSE_JSON_VIEWER,
150 toggleCanvasPanelTray: CanvasPanelTrayActions.TOGGLE_OPEN_CLOSE,
151 openCanvasPanelTray: CanvasPanelTrayActions.OPEN,
152 closeCanvasPanelTray: CanvasPanelTrayActions.CLOSE,
153 enterFullScreenMode: ComposerAppActions.ENTER_FULL_SCREEN_MODE,
154 exitFullScreenMode: ComposerAppActions.EXIT_FULL_SCREEN_MODE,
155 showAssets: ComposerAppActions.showAssets,
156 showDescriptor: ComposerAppActions.showDescriptor,
157 getFilelistSuccess: FileManagerActions.getFilelistSuccess,
158 updateFileLocationInput: FileManagerActions.updateFileLocationInput,
159 sendDownloadFileRequst: FileManagerActions.sendDownloadFileRequst,
160 addFileSuccess: FileManagerActions.addFileSuccess,
161 deletePackageFile: FileManagerActions.deletePackageFile,
162 deleteFileSuccess: FileManagerActions.deleteFileSuccess,
163 closeFileManagerSockets: FileManagerActions.closeFileManagerSockets,
164 openFileManagerSockets: FileManagerActions.openFileManagerSockets,
165 openDownloadMonitoringSocketSuccess: FileManagerActions.openDownloadMonitoringSocketSuccess,
166 getFilelistSocketSuccess: FileManagerActions.getFilelistSocketSuccess
167 });
168 this.exportPublicMethods({
169 closeFileManagerSockets: this.closeFileManagerSockets.bind(this)
170 })
171 }
172
173 onResize(e) {
174 if (e.type === 'resize-manager.resize.catalog-panel') {
175 const layout = Object.assign({}, this.layout);
176 layout.left = Math.max(0, layout.left - e.moved.x);
177 if (layout.left !== this.layout.left) {
178 this.setState({layout: layout});
179 }
180 } else if (e.type === 'resize-manager.resize.details-panel') {
181 const layout = Object.assign({}, this.layout);
182 layout.right = Math.max(0, layout.right + e.moved.x);
183 if (layout.right !== this.layout.right) {
184 this.setState({layout: layout});
185 }
186 } else if (/^resize-manager\.resize\.canvas-panel-tray/.test(e.type)) {
187 const layout = Object.assign({}, this.layout);
188 layout.bottom = Math.max(25, layout.bottom + e.moved.y);
189 if (layout.bottom !== this.layout.bottom) {
190 const zoom = autoZoomCanvasScale(layout.bottom) ;
191 if (this.zoom !== zoom) {
192 this.setState({layout: layout, zoom: zoom});
193 } else {
194 this.setState({layout: layout});
195 }
196 }
197 } else if (e.type !== 'resize') {
198 console.log('no resize handler for ', e.type, '. Do you need to add a handler in ComposerAppStore::onResize()?')
199 }
200 SelectionManager.refreshOutline();
201 }
202
203 updateItem(item) {
204 if(!document.body.classList.contains('resizing')) {
205 this.setState({item: _.cloneDeep(item)});
206 }
207 SelectionManager.refreshOutline();
208 }
209
210 editCatalogItem(item) {
211 let self = this;
212 if (item && item.uiState) {
213 item.uiState.isOpenForEdit = true;
214 if (item.uiState.type !== 'nsd') {
215 this.closeCanvasPanelTray();
216 }
217 }
218 SelectionManager.select(item);
219 this.updateItem(item);
220 this.openFileManagerSockets(item)
221 }
222 catalogItemMetaDataChanged(item) {
223 this.updateItem(item);
224 }
225
226 catalogItemDescriptorChanged(itemDescriptor) {
227 this.catalogItemMetaDataChanged(itemDescriptor.model);
228 }
229
230 showMoreInfo() {
231 this.setState({showMore: true});
232 }
233
234 showLessInfo() {
235 this.setState({showMore: false});
236 }
237
238 showError(data) {
239 NotificationError.defer({msg: data.errorMessage, type: 'error'})
240 // this.setState({message: data.errorMessage, messageType: 'error'});
241 }
242
243 clearError() {
244 this.setState({message: '', messageType: ''});
245 }
246
247 toggleShowMoreInfo() {
248 this.setState({showMore: !this.showMore});
249 }
250
251 applyDefaultLayout() {
252 if (this.item && this.item.uiState && this.item.uiState.containerPositionMap) {
253 if (!_.isEmpty(this.item.uiState.containerPositionMap)) {
254 this.item.uiState.containerPositionMap = {};
255 CatalogItemsActions.catalogItemMetaDataChanged.defer(this.item);
256 }
257 }
258 }
259
260 addVirtualLinkDescriptor(dropCoordinates = null) {
261 let vld;
262 if (this.item) {
263 if (this.item.uiState.type === 'nsd') {
264 const nsdc = DescriptorModelFactory.newNetworkService(this.item);
265 vld = nsdc.createVld();
266 } else if (this.item.uiState.type === 'vnfd') {
267 const vnfd = DescriptorModelFactory.newVirtualNetworkFunction(this.item);
268 vld = vnfd.createVld();
269 }
270 if (vld) {
271 vld.uiState.dropCoordinates = dropCoordinates;
272 SelectionManager.clearSelectionAndRemoveOutline();
273 SelectionManager.addSelection(vld);
274 this.updateItem(vld.getRoot().model);
275 CatalogItemsActions.catalogItemDescriptorChanged.defer(vld.getRoot());
276 }
277 }
278 }
279
280 addForwardingGraphDescriptor(dropCoordinates = null) {
281 if (this.item && this.item.uiState.type === 'nsd') {
282 const nsdc = DescriptorModelFactory.newNetworkService(this.item);
283 const fg = nsdc.createVnffgd();
284 fg.uiState.dropCoordinates = dropCoordinates;
285 SelectionManager.clearSelectionAndRemoveOutline();
286 SelectionManager.addSelection(fg);
287 this.updateItem(nsdc.model);
288 CatalogItemsActions.catalogItemDescriptorChanged.defer(nsdc);
289 }
290 }
291
292 addVirtualDeploymentDescriptor(dropCoordinates = null) {
293 if (this.item.uiState.type === 'vnfd') {
294 const vnfd = DescriptorModelFactory.newVirtualNetworkFunction(this.item);
295 const vdu = vnfd.createVdu();
296 vdu.uiState.dropCoordinates = dropCoordinates;
297 SelectionManager.clearSelectionAndRemoveOutline();
298 SelectionManager.addSelection(vdu);
299 this.updateItem(vdu.getRoot().model);
300 CatalogItemsActions.catalogItemDescriptorChanged.defer(vdu.getRoot());
301 }
302 }
303
304 selectModel(container) {
305 if (SelectionManager.select(container)) {
306 const model = DescriptorModelFactory.isContainer(container) ? container.getRoot().model : container;
307 this.catalogItemMetaDataChanged(model);
308 }
309 }
310
311 outlineModel(obj) {
312 const uid = UID.from(obj);
313 requestAnimationFrame(() => {
314 SelectionManager.outline(Array.from(document.querySelectorAll(`[data-uid="${uid}"]`)));
315 });
316 }
317
318 clearSelection() {
319 SelectionManager.clearSelectionAndRemoveOutline();
320 this.catalogItemMetaDataChanged(this.item);
321 }
322
323 setDragState(dragState) {
324 this.setState({drag: dragState});
325 }
326
327 filterCatalogByType(typeValue) {
328 this.setState({filterCatalogByTypeValue: typeValue})
329 }
330
331 setCanvasZoom(zoom) {
332 this.setState({zoom: zoom});
333 }
334
335 showJsonViewer() {
336 this.setState({showJSONViewer: true});
337 }
338
339 closeJsonViewer() {
340 this.setState({showJSONViewer: false});
341 }
342
343 toggleCanvasPanelTray() {
344 const layout = this.layout;
345 if (layout.bottom > 25) {
346 this.closeCanvasPanelTray();
347 } else {
348 this.openCanvasPanelTray();
349 }
350 }
351
352 openCanvasPanelTray() {
353 const layout = {
354 left: this.layout.left,
355 right: this.layout.right,
356 bottom: 300
357 };
358 const zoom = defaults.defaultPanelTrayOpenZoom;
359 if (this.zoom !== zoom) {
360 this.setState({layout: layout, zoom: zoom, restoreZoom: this.zoom});
361 } else {
362 this.setState({layout: layout});
363 }
364 }
365
366 closeCanvasPanelTray() {
367 const layout = {
368 left: this.layout.left,
369 right: this.layout.right,
370 bottom: 25
371 };
372 const zoom = this.restoreZoom || autoZoomCanvasScale(layout.bottom);
373 if (this.zoom !== zoom) {
374 this.setState({layout: layout, zoom: zoom, restoreZoom: null});
375 } else {
376 this.setState({layout: layout, restoreZoom: null});
377 }
378 }
379
380 enterFullScreenMode() {
381
382 /**
383 * https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
384 * This is an experimental api but works our target browsers and ignored by others
385 */
386 const eventNames = ['fullscreenchange', 'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange'];
387
388 const appRoot = document.body;//.getElementById('RIFT_wareLaunchpadComposerAppRoot');
389
390 const comp = this;
391
392 function onFullScreenChange() {
393
394 if (isFullScreen()) {
395 const layout = comp.layout;
396 const restoreLayout = _.cloneDeep(layout);
397 uiTransientState.restoreLayout = restoreLayout;
398 layout.left = 0;
399 layout.right = 0;
400 comp.setState({fullScreenMode: true, layout: layout, restoreLayout: restoreLayout});
401 } else {
402 comp.setState({fullScreenMode: false, layout: uiTransientState.restoreLayout});
403 }
404
405 }
406
407 if (this.fullScreenMode === false) {
408
409 if (appRoot.requestFullscreen) {
410 appRoot.requestFullscreen();
411 } else if (appRoot.msRequestFullscreen) {
412 appRoot.msRequestFullscreen();
413 } else if (appRoot.mozRequestFullScreen) {
414 appRoot.mozRequestFullScreen();
415 } else if (appRoot.webkitRequestFullscreen) {
416 appRoot.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
417 }
418
419 eventNames.map(name => {
420 document.removeEventListener(name, onFullScreenChange);
421 document.addEventListener(name, onFullScreenChange);
422 });
423
424 }
425
426 }
427
428 exitFullScreenMode() {
429
430 if (document.exitFullscreen) {
431 document.exitFullscreen();
432 } else if (document.msExitFullscreen) {
433 document.msExitFullscreen();
434 } else if (document.mozCancelFullScreen) {
435 document.mozCancelFullScreen();
436 } else if (document.webkitExitFullscreen) {
437 document.webkitExitFullscreen();
438 }
439
440 this.setState({fullScreenMode: false});
441
442 }
443 showAssets() {
444 this.setState({
445 panelTabShown: 'assets'
446 });
447 }
448 showDescriptor() {
449 this.setState({
450 panelTabShown: 'descriptor'
451 });
452 }
453
454 //File Manager methods
455 getFilelistSuccess(data) {
456 let self = this;
457 let filesState = null;
458 if (self.fileMonitoringSocketID) {
459 filesState = addInputState( _.cloneDeep(this.filesState),data);
460 // filesState = _.merge(self.filesState, addInputState({},data));
461 let normalizedData = normalizeTree(data);
462 this.setState({
463 files: {
464 data: _.mergeWith(normalizedData.data, self.files.data, function(obj, src) {
465 return _.uniqBy(obj? obj.concat(src) : src, 'name');
466 }),
467 id: self.files.id || normalizedData.id
468 },
469 filesState: filesState
470 });
471 }
472 function normalizeTree(data) {
473 let f = {
474 id:[],
475 data:{}
476 };
477 data.contents.map(getContents);
478 function getContents(d) {
479 if(d.hasOwnProperty('contents')) {
480 let contents = [];
481 d.contents.map(function(c,i) {
482 if (!c.hasOwnProperty('contents')) {
483 contents.push(c);
484 } else {
485 getContents(c);
486 }
487 })
488 f.id.push(d.name);
489 f.data[d.name] = contents;
490 }
491 }
492 return f;
493 }
494 function addInputState(obj, d) {
495 d.newFile = '';
496 if(d.hasOwnProperty('contents')) {
497 d.contents.map(addInputState.bind(null, obj))
498 }
499 if(!obj[d.name]) {
500 obj[d.name] = '';
501 }
502 return obj;
503 }
504 }
505 sendDownloadFileRequst(data) {
506 let id = data.id || this.item.id;
507 let type = data.type || this.item.uiState.type;
508 let path = data.path;
509 let url = data.url;
510 this.getInstance().addFile(id, type, path, url);
511 }
512 updateFileLocationInput = (data) => {
513 let name = data.name;
514 let value = data.value;
515 var filesState = _.cloneDeep(this.filesState);
516 filesState[name] = value;
517 this.setState({
518 filesState: filesState
519 });
520 }
521 addFileSuccess = (data) => {
522 let path = data.path;
523 let fileName = data.fileName;
524 let files = _.cloneDeep(this.files);
525 let loadingIndex = files.data[path].push({
526 status: 'DOWNLOADING',
527 name: path + '/' + fileName
528 }) - 1;
529 this.setState({files: files});
530
531 }
532 startWatchingJob = () => {
533 let ws = window.multiplexer.channel(this.jobSocketId);
534 this.setState({
535 jobSocket:null
536 })
537 }
538 openDownloadMonitoringSocketSuccess = (id) => {
539 let self = this;
540 let ws = window.multiplexer.channel(id);
541 let downloadJobs = _.cloneDeep(self.downloadJobs);
542 let newFiles = {};
543 ws.onmessage = (socket) => {
544 if (self.files && self.files.length > 0) {
545 let jobs = [];
546 try {
547 jobs = JSON.parse(socket.data);
548 } catch(e) {}
549 newFiles = _.cloneDeep(self.files);
550 jobs.map(function(j) {
551 //check if not in completed state
552 let fullPath = j['package-path'];
553 let path = fullPath.split('/');
554 let fileName = path.pop();
555 path = path.join('/');
556 let index = _.findIndex(self.files.data[path], function(o){
557 return fullPath == o.name
558 });
559 if((index > -1) && newFiles.data[path][index]) {
560 newFiles.data[path][index].status = j.status
561 } else {
562 if(j.status.toUpperCase() == 'LOADING...' || j.status.toUpperCase() == 'IN_PROGRESS') {
563 newFiles.data[path].push({
564 status: j.status,
565 name: fullPath
566 })
567 } else {
568 // if ()
569 }
570 }
571 })
572 self.setState({
573 files: newFiles
574 })
575 // console.log(JSON.parse(socket.data));
576 }
577 }
578 this.setState({
579 jobSocketId: id,
580 jobSocket: ws
581 })
582
583 }
584 getFilelistSocketSuccess = (id) => {
585 let self = this;
586 let ws = window.multiplexer.channel(id);
587 ws.onmessage = (socket) => {
588 if (self.fileMonitoringSocketID) {
589 let data = [];
590 try {
591 data = JSON.parse(socket.data);
592 } catch(e) {}
593 self.getFilelistSuccess(data)
594 }
595 }
596
597 this.setState({
598 fileMonitoringSocketID: id,
599 fileMonitoringSocket: ws
600 })
601
602 }
603 closeFileManagerSockets() {
604 this.fileMonitoringSocketID = null;
605 this.setState({
606 jobSocketId : null,
607 fileMonitoringSocketID : null
608 // jobSocket : null,
609 // fileMonitoringSocket : null,
610 });
611 this.jobSocket && this.jobSocket.close();
612 this.fileMonitoringSocket && this.fileMonitoringSocket.close();
613 console.log('closing');
614 }
615 openFileManagerSockets(i) {
616 let self = this;
617 let item = i || self.item;
618 this.files = {data:[]};
619 // this.closeFileManagerSockets();
620 this.getInstance().openFileMonitoringSocket(item.id, item.uiState.type).then(function() {
621 // // self.getInstance().openDownloadMonitoringSocket(item.id);
622 });
623 this.getInstance().openDownloadMonitoringSocket(item.id);
624 }
625 endWatchingJob(id) {
626
627 }
628 deletePackageFile(name) {
629 let id = this.item.id;
630 let type = this.item.uiState.type;
631 this.getInstance().deleteFile(id, type, name);
632 }
633 deleteFileSuccess = (data) => {
634 let path = data.path.split('/')
635 let files = _.cloneDeep(this.files);
636 path.pop();
637 path = path.join('/');
638 let pathFiles = files.data[path]
639 _.remove(pathFiles, function(c) {
640 return c.name == data.path;
641 });
642
643 this.setState({
644 files: files
645 })
646 }
647 }
648
649 export default alt.createStore(ComposerAppStore, 'ComposerAppStore');