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