<commit_before>define([
    'jquery',
    'underscore',
    'knockout',
    'knockout-mapping',
    'views/base-manager',
    'viewmodels/alert',
    'viewmodels/alert-json',
    'models/graph',
    'models/report',
    'views/graph/graph-designer/graph-tree',
    'views/graph/graph-designer/node-form',
    'views/graph/graph-manager/branch-list',
    'views/graph/graph-designer/card-tree',
    'views/graph/permission-designer',
    'graph-designer-data',
    'arches',
    'viewmodels/graph-settings',
    'viewmodels/card',
    'view-data',
    'report-templates',
    'bindings/resizable-sidepanel',
    'datatype-config-components',
    'views/components/simple-switch'
], function($, _, ko, koMapping, BaseManagerView, AlertViewModel, JsonErrorAlertViewModel, GraphModel, ReportModel, GraphTree, NodeFormView, BranchListView, CardTreeViewModel, PermissionDesigner, data, arches, GraphSettingsViewModel, CardViewModel, viewData, reportLookup) {
    var GraphDesignerView = BaseManagerView.extend({
        initialize: function(options) {
            var viewModel = options.viewModel;
            viewModel.graphid = ko.observable(data.graphid);
            viewModel.activeTab = ko.observable('graph');
            viewModel.viewState = ko.observable('design');
            viewModel.helpTemplate(viewData.help);
            viewModel.graphSettingsVisible = ko.observable(false);
            viewModel.graph = koMapping.fromJS(data['graph']);
            viewModel.ontologies = ko.observable(data['ontologies']);
            viewModel.ontologyClasses = ko.observable(data['ontologyClasses']);
            viewModel.cardComponents = data.cardComponents;
            viewModel.appliedFunctions = ko.observable(data['appliedFunctions']);

            var resources = ko.utils.arrayFilter(viewData.graphs, function(graph) {
                return graph.isresource;
            });
            var graphs = ko.utils.arrayFilter(viewData.graphs, function(graph) {
                return !graph.isresource;
            });

            var newGraph = function(url, data) {
                data = data || {};
                viewModel.loading(true);
                $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(data),
                    success: function(response) {
                        window.open(arches.urls.graph_designer(response.graphid), '_blank');
                        viewModel.loading(false);
                    },
                    error: function() {
                        viewModel.loading(false);
                    }
                });
            };
            viewModel.newResource = function() {
                newGraph('/graph/new', {isresource: true});
            };
            viewModel.newBranch = function() {
                newGraph('/graph/new', {isresource: false});
            };

            viewModel.exportMappingFile = function(model) {
                window.open(arches.urls.export_mapping_file(viewModel.graph.graphid()), '_blank');
            };

            viewModel.deleteGraph = function() {
                viewModel.alert(new AlertViewModel('ep-alert-red', arches.confirmGraphDelete.title, arches.confirmGraphDelete.text, function() {
                    return;
                }, function(){
                    viewModel.loading(true);
                    $.ajax({
                        type: "DELETE",
                        url: arches.urls.delete_graph(viewModel.graph.graphid()),
                        complete: function(response, status) {
                            viewModel.loading(false);
                            if (status === 'success') {
                                window.location = arches.urls.graph;
                            } else {
                                viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', response.responseJSON));
                            }
                        }
                    });
                }));
            };
            viewModel.cloneGraph = function() {
                newGraph(arches.urls.clone_graph(viewModel.graph.graphid()));
            };
            viewModel.exportGraph = function() {
                window.open(arches.urls.export_graph(viewModel.graph.graphid()), '_blank');
            };
            viewModel.importGraph = function(data, e) {
                var formData = new FormData();
                formData.append("importedGraph", e.target.files[0]);

                $.ajax({
                    type: "POST",
                    url: '/graph/import/',
                    processData: false,
                    data: formData,
                    cache: false,
                    contentType: false,
                    success: function(response) {
                        if (response[0].length != 0) {
                            if (typeof(response[0])) {
                                response = response[0].join('<br />');
                            }
                            viewModel.alert(new AlertViewModel('ep-alert-red', arches.graphImportFailed.title, response));
                        } else {
                            viewModel.loading(false);
                            window.open(arches.urls.graph_designer(response[1].graph_id), '_blank');
                        }
                    },
                    error: function(response) {
                        viewModel.alert(new AlertViewModel('ep-alert-red', arches.graphImportFailed.title, 'Please contact your system administrator for more details.'));
                        viewModel.loading(false);
                    },
                });
            };
            viewModel.importButtonClick = function() {
                $("#fileupload").trigger('click');
            };
            viewModel.deleteInstances = function() {
                viewModel.alert(new AlertViewModel('ep-alert-red', arches.confirmAllResourceDelete.title, arches.confirmAllResourceDelete.text, function() {
                    return;
                }, function(){
                    viewModel.loading(true);
                    $.ajax({
                        type: "DELETE",
                        url: arches.urls.delete_instances(viewModel.graph.graphid()),
                        complete: function(response, status) {
                            viewModel.loading(false);
                            if (status === 'success') {
                                viewModel.alert(new AlertViewModel('ep-alert-blue', response.responseJSON.title, response.responseJSON.message));
                            } else {
                                viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', response.responseJSON));
                            }
                        }
                    });
                }));
            };
            viewModel.graph.ontology = ko.computed(function() {
                return viewModel.ontologies().find(function(obj) {
                    return obj.ontologyid === viewModel.graph.ontology_id();
                });
            });
            viewModel.groupedGraphs = ko.observable({
                groups: [
                    { name: 'Resource Models', items: resources },
                    { name: 'Branches', items: graphs }
                ]
            });

            viewModel.graphid.subscribe(function(graphid) {
                if (graphid && graphid !== '') {
                    viewModel.navigate(arches.urls.graph_designer(graphid));
                }
            });

            viewModel.graphModel = new GraphModel({
                data: data.graph,
                datatypes: data.datatypes,
                ontology_namespaces: data.ontology_namespaces
            });

            viewModel.datatypes = _.keys(viewModel.graphModel.get('datatypelookup'));

            viewModel.graphModel.on('changed', function(model, response) {
                viewModel.alert(null);
                viewModel.loading(false);
                if (response.status !== 200) {
                    viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', response.responseJSON));
                }
            });

            viewModel.graphModel.on('error', function(response) {
                viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', response.responseJSON));
            });

            viewModel.selectedNode = viewModel.graphModel.get('selectedNode');

            viewModel.saveNode = function(node) {
                if (node) {
                    viewModel.loading(true);
                    node.save(function(data) {
                        if (data.responseJSON.success === false || data.status === 500) {
                            viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', data.responseJSON));
                        }
                        else {
                            viewModel.cardTree.updateCards(viewModel.selectedNode().nodeGroupId(), data.responseJSON);
                            viewModel.permissionTree.updateCards(viewModel.selectedNode().nodeGroupId(), data.responseJSON);
                        }
                        viewModel.loading(false);
                    });
                }
            };

            viewModel.saveSelectedNode = function() {
                if (viewModel.selectedNode()) {
                    viewModel.saveNode(viewModel.selectedNode());
                }
            };

            viewModel.cardTree = new CardTreeViewModel({
                graph: viewModel.graph,
                appliedFunctions: viewModel.appliedFunctions,
                graphModel: viewModel.graphModel
            });

            viewModel.permissionTree = new CardTreeViewModel({
                graph: viewModel.graph,
                graphModel: viewModel.graphModel,
                appliedFunctions: viewModel.appliedFunctions,
                multiselect: true
            });

            viewModel.selectedCards = ko.computed(function() {
                var selection = viewModel.permissionTree.selection();
                if (selection) {
                    if (selection.widgets) {
                        return selection;
                    }
                    return selection.parent;
                } else {
                    return null;
                }
            });

            viewModel.selectedCard = ko.computed(function() {
                var selection = viewModel.cardTree.selection();
                if (selection) {
                    if (selection.widgets) {
                        return selection;
                    }
                    return selection.parent;
                } else {
                    return null;
                }
            });

            viewModel.nodeForm = new NodeFormView({
                graph: viewModel.graph,
                graphModel: viewModel.graphModel,
                loading: viewModel.loading,
                node: viewModel.selectedNode,
                appliedFunctions: viewModel.appliedFunctions,
                restrictedNodegroups: data.restrictedNodegroups
            });

            viewModel.branchListView = new BranchListView({
                el: $('#branch-library'),
                branches: data.branches,
                graphModel: viewModel.graphModel,
                loading: viewModel.loading,
                disableAppendButton: ko.computed(function() {
                    // self.node() && self.node().dirty();
                })
            });

            viewModel.permissionsDesigner = new PermissionDesigner({
                cardTree: viewModel.permissionTree
            });

            viewModel.graphSettingsViewModel = new GraphSettingsViewModel({
                designerViewModel: viewModel,
                graph: viewModel.graph,
                graphModel: viewModel.graphModel,
                ontologyClasses: viewModel.ontologyClasses,
                ontologies: viewModel.ontologies,
                ontologyClass: ko.observable(''),
                iconFilter: ko.observable(''),
                rootNodeColor: ko.observable(''),
                "ontology_namespaces": data.ontology_namespaces,
                onReset: function() {
                    var graph = koMapping.toJS(viewModel.graphSettingsViewModel.graph);
                    viewModel.report.resetConfigs(graph.config);
                    viewModel.report.get('template_id')(graph["template_id"]);
                }
            });

            viewModel.report = new ReportModel(_.extend(data, {
                graphModel: viewModel.graphModel,
                cards: viewModel.cardTree.topCards,
                preview: true
            }));

            viewModel.report.configJSON.subscribe(function(config) {
                var graph = koMapping.toJS(viewModel.graphSettingsViewModel.graph);
                graph.config = koMapping.toJS(config);
                koMapping.fromJS(graph, viewModel.graphSettingsViewModel.graph);
            });

            viewModel.report.configJSON.extend({deferred: true});

            viewModel.report.get('template_id').subscribe(function(val) {
                viewModel.graphSettingsViewModel.graph["template_id"](val);
            });

            viewModel.reportLookup = reportLookup;
            viewModel.reportTemplates = _.map(reportLookup, function(report, id) {
                report.id = id;
                return report;
            });

            viewModel.graphTree = new GraphTree({
                graphModel: viewModel.graphModel,
                graphSettings: viewModel.graphSettingsViewModel,
                cardTree: viewModel.cardTree,
                permissionTree: viewModel.permissionTree,
                appliedFunctions: viewModel.appliedFunctions,
                restrictedNodegroups: data.restrictedNodegroups
            });

            viewModel.graphTree.branchListVisible.subscribe(function(visible) {
                if (visible) {
                    viewModel.branchListView.loadDomainConnections();
                }
            }, this);

            viewModel.loadGraphSettings = function() {
                var self = this;
                viewModel.loading(true);
                $.ajax({
                    type: 'GET',
                    url: arches.urls.graph_settings(data.graphid),
                    data: {'search': true, 'csrfmiddlewaretoken': '{{ csrf_token }}'}})
                    .done(function(data) {
                        self.graphSettingsViewModel.resource_data(data.resources);
                        self.graphSettingsViewModel.icon_data(data.icons);
                        self.graphSettingsViewModel.jsonCache(self.graphSettingsViewModel.jsonData());
                        self.graphSettingsViewModel.contentLoading = viewModel.loading;
                        self.graphSettingsVisible(true);
                        viewModel.loading(false);
                    })
                    .fail(function() {
                        throw 'error loading graph settings';
                    });
            };

            var correspondingCard = function(item, cardTree){
                var cardList = cardTree.cachedFlatTree;
                if (cardList === undefined) {
                    var cardList = cardTree.flattenTree(cardTree.topCards(), []);
                    cardTree.cachedFlatTree = cardList;
                }
                var res;
                var matchingWidget;
                if (item && typeof item !== 'string') {
                    if (item.nodeGroupId) { //if the item is a node in graph tree
                        var matchingCards = _.filter(cardList, function(card){
                            return card.nodegroupid === item.nodeGroupId();
                        });
                        _.each(matchingCards, function(card){
                            var match;
                            match = _.find(card.widgets(), function(widget){
                                return widget.node_id() === item.nodeid;
                            });
                            if (match) {
                                matchingWidget = match;
                            }
                        });
                        if (matchingWidget) {
                            res = matchingWidget;
                        } else {
                            res = matchingCards[0];
                        }
                    } else { //if the item is a card or widget in the card tree
                        res = _.find(cardList, function(card){
                            if (item.nodegroupid) {
                                return card.nodegroupid === item.nodegroupid;
                            } else {
                                return card.nodegroupid === item.node.nodeGroupId();
                            }
                        });
                    }
                }
                return res;

            };

            var correspondingNode = function(card, graphTree){
                var nodeMatch;
                nodeMatch = _.find(graphTree.items(), function(node){
                    if (card) {
                        if (card.node) {
                            return node.nodeid === card.node_id();
                        } else {
                            return node.nodeGroupId() === card.nodegroupid && node.nodeid === node.nodeGroupId();
                        }
                    }
                });
                return nodeMatch;
            };

            var updateGraphSelection = function() {
                var matchingNode = correspondingNode(viewModel.cardTree.selection(), viewModel.graphTree);
                if (matchingNode) {
                    viewModel.graphTree.selectItem(matchingNode);
                }
            };

            var updateCardSelection = function() {
                var graphTreeSelection = viewModel.graphTree.selectedItems().length > 0 ? viewModel.graphTree.selectedItems()[0] : null;
                var matchingCard;
                if (graphTreeSelection) {
                    if (graphTreeSelection.istopnode === true) {
                        viewModel.cardTree.selection(viewModel.cardTree.topCards()[0]);
                    } else {
                        matchingCard = correspondingCard(graphTreeSelection, viewModel.cardTree);
                        if (matchingCard) {
                            viewModel.cardTree.selection(matchingCard);
                            viewModel.cardTree.expandToRoot(viewModel.cardTree.selection());
                        }
                    }
                }
            };

            var updatePermissionCardSelection = function() {
                var matchingCard = correspondingCard(viewModel.cardTree.selection(), viewModel.permissionTree);
                if (matchingCard) {
                    viewModel.permissionTree.expandToRoot(matchingCard);
                    viewModel.permissionTree.selection.removeAll();
                    matchingCard.selectChildCards();
                }
            };

            if (viewModel.activeTab() === 'graph') {
                viewModel.loadGraphSettings();
                // here we might load data/views asyncronously
            }

            var loadPermissionData = viewModel.activeTab.subscribe(function(tab) {
                // Loads identities and nodegroup permissions when the permissions tab is opened and then disposes the ko.subscribe.
                if (tab === 'permissions') {
                    viewModel.permissionsDesigner.getPermissionManagerData();
                    loadPermissionData.dispose();
                }
            });

            var helpContentLookup = {
                permissions: {
                    'title': 'xxxx', // dynamic title loading not implemented
                    'template': 'permissions-tab-help',
                },
                graph: {
                    'title': 'xxxx', // dynamic title loading not implemented
                    'template': 'graph-tab-help',
                },
                card: {
                    'title': 'xxxx', // dynamic title loading not implemented
                    'template': 'cards-tab-help',
                }
            };

            viewModel.activeTab.subscribe(function(tab) {
                viewModel.helpTemplate(helpContentLookup[tab]['template']);
                viewModel.getHelp();
                switch (tab) {
                case 'card':
                    updateCardSelection();
                    break;
                case 'graph':
                    updateGraphSelection();
                    break;
                case 'permissions':
                    updatePermissionCardSelection();
                    break;
                default:
                    return;
                }
            });

            viewModel.graphModel.on('select-node', function(node) {
                viewModel.graphTree.expandParentNode(node);
            });

            BaseManagerView.prototype.initialize.apply(this, arguments);
        }
    });

    return new GraphDesignerView();
});
<commit_msg>Removes unused arg<commit_after>define([
    'jquery',
    'underscore',
    'knockout',
    'knockout-mapping',
    'views/base-manager',
    'viewmodels/alert',
    'viewmodels/alert-json',
    'models/graph',
    'models/report',
    'views/graph/graph-designer/graph-tree',
    'views/graph/graph-designer/node-form',
    'views/graph/graph-manager/branch-list',
    'views/graph/graph-designer/card-tree',
    'views/graph/permission-designer',
    'graph-designer-data',
    'arches',
    'viewmodels/graph-settings',
    'viewmodels/card',
    'view-data',
    'report-templates',
    'bindings/resizable-sidepanel',
    'datatype-config-components',
    'views/components/simple-switch'
], function($, _, ko, koMapping, BaseManagerView, AlertViewModel, JsonErrorAlertViewModel, GraphModel, ReportModel, GraphTree, NodeFormView, BranchListView, CardTreeViewModel, PermissionDesigner, data, arches, GraphSettingsViewModel, CardViewModel, viewData, reportLookup) {
    var GraphDesignerView = BaseManagerView.extend({
        initialize: function(options) {
            var viewModel = options.viewModel;
            viewModel.graphid = ko.observable(data.graphid);
            viewModel.activeTab = ko.observable('graph');
            viewModel.viewState = ko.observable('design');
            viewModel.helpTemplate(viewData.help);
            viewModel.graphSettingsVisible = ko.observable(false);
            viewModel.graph = koMapping.fromJS(data['graph']);
            viewModel.ontologies = ko.observable(data['ontologies']);
            viewModel.ontologyClasses = ko.observable(data['ontologyClasses']);
            viewModel.cardComponents = data.cardComponents;
            viewModel.appliedFunctions = ko.observable(data['appliedFunctions']);

            var resources = ko.utils.arrayFilter(viewData.graphs, function(graph) {
                return graph.isresource;
            });
            var graphs = ko.utils.arrayFilter(viewData.graphs, function(graph) {
                return !graph.isresource;
            });

            var newGraph = function(url, data) {
                data = data || {};
                viewModel.loading(true);
                $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(data),
                    success: function(response) {
                        window.open(arches.urls.graph_designer(response.graphid), '_blank');
                        viewModel.loading(false);
                    },
                    error: function() {
                        viewModel.loading(false);
                    }
                });
            };
            viewModel.newResource = function() {
                newGraph('/graph/new', {isresource: true});
            };
            viewModel.newBranch = function() {
                newGraph('/graph/new', {isresource: false});
            };

            viewModel.exportMappingFile = function() {
                window.open(arches.urls.export_mapping_file(viewModel.graph.graphid()), '_blank');
            };

            viewModel.deleteGraph = function() {
                viewModel.alert(new AlertViewModel('ep-alert-red', arches.confirmGraphDelete.title, arches.confirmGraphDelete.text, function() {
                    return;
                }, function(){
                    viewModel.loading(true);
                    $.ajax({
                        type: "DELETE",
                        url: arches.urls.delete_graph(viewModel.graph.graphid()),
                        complete: function(response, status) {
                            viewModel.loading(false);
                            if (status === 'success') {
                                window.location = arches.urls.graph;
                            } else {
                                viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', response.responseJSON));
                            }
                        }
                    });
                }));
            };
            viewModel.cloneGraph = function() {
                newGraph(arches.urls.clone_graph(viewModel.graph.graphid()));
            };
            viewModel.exportGraph = function() {
                window.open(arches.urls.export_graph(viewModel.graph.graphid()), '_blank');
            };
            viewModel.importGraph = function(data, e) {
                var formData = new FormData();
                formData.append("importedGraph", e.target.files[0]);

                $.ajax({
                    type: "POST",
                    url: '/graph/import/',
                    processData: false,
                    data: formData,
                    cache: false,
                    contentType: false,
                    success: function(response) {
                        if (response[0].length != 0) {
                            if (typeof(response[0])) {
                                response = response[0].join('<br />');
                            }
                            viewModel.alert(new AlertViewModel('ep-alert-red', arches.graphImportFailed.title, response));
                        } else {
                            viewModel.loading(false);
                            window.open(arches.urls.graph_designer(response[1].graph_id), '_blank');
                        }
                    },
                    error: function(response) {
                        viewModel.alert(new AlertViewModel('ep-alert-red', arches.graphImportFailed.title, 'Please contact your system administrator for more details.'));
                        viewModel.loading(false);
                    },
                });
            };
            viewModel.importButtonClick = function() {
                $("#fileupload").trigger('click');
            };
            viewModel.deleteInstances = function() {
                viewModel.alert(new AlertViewModel('ep-alert-red', arches.confirmAllResourceDelete.title, arches.confirmAllResourceDelete.text, function() {
                    return;
                }, function(){
                    viewModel.loading(true);
                    $.ajax({
                        type: "DELETE",
                        url: arches.urls.delete_instances(viewModel.graph.graphid()),
                        complete: function(response, status) {
                            viewModel.loading(false);
                            if (status === 'success') {
                                viewModel.alert(new AlertViewModel('ep-alert-blue', response.responseJSON.title, response.responseJSON.message));
                            } else {
                                viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', response.responseJSON));
                            }
                        }
                    });
                }));
            };
            viewModel.graph.ontology = ko.computed(function() {
                return viewModel.ontologies().find(function(obj) {
                    return obj.ontologyid === viewModel.graph.ontology_id();
                });
            });
            viewModel.groupedGraphs = ko.observable({
                groups: [
                    { name: 'Resource Models', items: resources },
                    { name: 'Branches', items: graphs }
                ]
            });

            viewModel.graphid.subscribe(function(graphid) {
                if (graphid && graphid !== '') {
                    viewModel.navigate(arches.urls.graph_designer(graphid));
                }
            });

            viewModel.graphModel = new GraphModel({
                data: data.graph,
                datatypes: data.datatypes,
                ontology_namespaces: data.ontology_namespaces
            });

            viewModel.datatypes = _.keys(viewModel.graphModel.get('datatypelookup'));

            viewModel.graphModel.on('changed', function(model, response) {
                viewModel.alert(null);
                viewModel.loading(false);
                if (response.status !== 200) {
                    viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', response.responseJSON));
                }
            });

            viewModel.graphModel.on('error', function(response) {
                viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', response.responseJSON));
            });

            viewModel.selectedNode = viewModel.graphModel.get('selectedNode');

            viewModel.saveNode = function(node) {
                if (node) {
                    viewModel.loading(true);
                    node.save(function(data) {
                        if (data.responseJSON.success === false || data.status === 500) {
                            viewModel.alert(new JsonErrorAlertViewModel('ep-alert-red', data.responseJSON));
                        }
                        else {
                            viewModel.cardTree.updateCards(viewModel.selectedNode().nodeGroupId(), data.responseJSON);
                            viewModel.permissionTree.updateCards(viewModel.selectedNode().nodeGroupId(), data.responseJSON);
                        }
                        viewModel.loading(false);
                    });
                }
            };

            viewModel.saveSelectedNode = function() {
                if (viewModel.selectedNode()) {
                    viewModel.saveNode(viewModel.selectedNode());
                }
            };

            viewModel.cardTree = new CardTreeViewModel({
                graph: viewModel.graph,
                appliedFunctions: viewModel.appliedFunctions,
                graphModel: viewModel.graphModel
            });

            viewModel.permissionTree = new CardTreeViewModel({
                graph: viewModel.graph,
                graphModel: viewModel.graphModel,
                appliedFunctions: viewModel.appliedFunctions,
                multiselect: true
            });

            viewModel.selectedCards = ko.computed(function() {
                var selection = viewModel.permissionTree.selection();
                if (selection) {
                    if (selection.widgets) {
                        return selection;
                    }
                    return selection.parent;
                } else {
                    return null;
                }
            });

            viewModel.selectedCard = ko.computed(function() {
                var selection = viewModel.cardTree.selection();
                if (selection) {
                    if (selection.widgets) {
                        return selection;
                    }
                    return selection.parent;
                } else {
                    return null;
                }
            });

            viewModel.nodeForm = new NodeFormView({
                graph: viewModel.graph,
                graphModel: viewModel.graphModel,
                loading: viewModel.loading,
                node: viewModel.selectedNode,
                appliedFunctions: viewModel.appliedFunctions,
                restrictedNodegroups: data.restrictedNodegroups
            });

            viewModel.branchListView = new BranchListView({
                el: $('#branch-library'),
                branches: data.branches,
                graphModel: viewModel.graphModel,
                loading: viewModel.loading,
                disableAppendButton: ko.computed(function() {
                    // self.node() && self.node().dirty();
                })
            });

            viewModel.permissionsDesigner = new PermissionDesigner({
                cardTree: viewModel.permissionTree
            });

            viewModel.graphSettingsViewModel = new GraphSettingsViewModel({
                designerViewModel: viewModel,
                graph: viewModel.graph,
                graphModel: viewModel.graphModel,
                ontologyClasses: viewModel.ontologyClasses,
                ontologies: viewModel.ontologies,
                ontologyClass: ko.observable(''),
                iconFilter: ko.observable(''),
                rootNodeColor: ko.observable(''),
                "ontology_namespaces": data.ontology_namespaces,
                onReset: function() {
                    var graph = koMapping.toJS(viewModel.graphSettingsViewModel.graph);
                    viewModel.report.resetConfigs(graph.config);
                    viewModel.report.get('template_id')(graph["template_id"]);
                }
            });

            viewModel.report = new ReportModel(_.extend(data, {
                graphModel: viewModel.graphModel,
                cards: viewModel.cardTree.topCards,
                preview: true
            }));

            viewModel.report.configJSON.subscribe(function(config) {
                var graph = koMapping.toJS(viewModel.graphSettingsViewModel.graph);
                graph.config = koMapping.toJS(config);
                koMapping.fromJS(graph, viewModel.graphSettingsViewModel.graph);
            });

            viewModel.report.configJSON.extend({deferred: true});

            viewModel.report.get('template_id').subscribe(function(val) {
                viewModel.graphSettingsViewModel.graph["template_id"](val);
            });

            viewModel.reportLookup = reportLookup;
            viewModel.reportTemplates = _.map(reportLookup, function(report, id) {
                report.id = id;
                return report;
            });

            viewModel.graphTree = new GraphTree({
                graphModel: viewModel.graphModel,
                graphSettings: viewModel.graphSettingsViewModel,
                cardTree: viewModel.cardTree,
                permissionTree: viewModel.permissionTree,
                appliedFunctions: viewModel.appliedFunctions,
                restrictedNodegroups: data.restrictedNodegroups
            });

            viewModel.graphTree.branchListVisible.subscribe(function(visible) {
                if (visible) {
                    viewModel.branchListView.loadDomainConnections();
                }
            }, this);

            viewModel.loadGraphSettings = function() {
                var self = this;
                viewModel.loading(true);
                $.ajax({
                    type: 'GET',
                    url: arches.urls.graph_settings(data.graphid),
                    data: {'search': true, 'csrfmiddlewaretoken': '{{ csrf_token }}'}})
                    .done(function(data) {
                        self.graphSettingsViewModel.resource_data(data.resources);
                        self.graphSettingsViewModel.icon_data(data.icons);
                        self.graphSettingsViewModel.jsonCache(self.graphSettingsViewModel.jsonData());
                        self.graphSettingsViewModel.contentLoading = viewModel.loading;
                        self.graphSettingsVisible(true);
                        viewModel.loading(false);
                    })
                    .fail(function() {
                        throw 'error loading graph settings';
                    });
            };

            var correspondingCard = function(item, cardTree){
                var cardList = cardTree.cachedFlatTree;
                if (cardList === undefined) {
                    var cardList = cardTree.flattenTree(cardTree.topCards(), []);
                    cardTree.cachedFlatTree = cardList;
                }
                var res;
                var matchingWidget;
                if (item && typeof item !== 'string') {
                    if (item.nodeGroupId) { //if the item is a node in graph tree
                        var matchingCards = _.filter(cardList, function(card){
                            return card.nodegroupid === item.nodeGroupId();
                        });
                        _.each(matchingCards, function(card){
                            var match;
                            match = _.find(card.widgets(), function(widget){
                                return widget.node_id() === item.nodeid;
                            });
                            if (match) {
                                matchingWidget = match;
                            }
                        });
                        if (matchingWidget) {
                            res = matchingWidget;
                        } else {
                            res = matchingCards[0];
                        }
                    } else { //if the item is a card or widget in the card tree
                        res = _.find(cardList, function(card){
                            if (item.nodegroupid) {
                                return card.nodegroupid === item.nodegroupid;
                            } else {
                                return card.nodegroupid === item.node.nodeGroupId();
                            }
                        });
                    }
                }
                return res;

            };

            var correspondingNode = function(card, graphTree){
                var nodeMatch;
                nodeMatch = _.find(graphTree.items(), function(node){
                    if (card) {
                        if (card.node) {
                            return node.nodeid === card.node_id();
                        } else {
                            return node.nodeGroupId() === card.nodegroupid && node.nodeid === node.nodeGroupId();
                        }
                    }
                });
                return nodeMatch;
            };

            var updateGraphSelection = function() {
                var matchingNode = correspondingNode(viewModel.cardTree.selection(), viewModel.graphTree);
                if (matchingNode) {
                    viewModel.graphTree.selectItem(matchingNode);
                }
            };

            var updateCardSelection = function() {
                var graphTreeSelection = viewModel.graphTree.selectedItems().length > 0 ? viewModel.graphTree.selectedItems()[0] : null;
                var matchingCard;
                if (graphTreeSelection) {
                    if (graphTreeSelection.istopnode === true) {
                        viewModel.cardTree.selection(viewModel.cardTree.topCards()[0]);
                    } else {
                        matchingCard = correspondingCard(graphTreeSelection, viewModel.cardTree);
                        if (matchingCard) {
                            viewModel.cardTree.selection(matchingCard);
                            viewModel.cardTree.expandToRoot(viewModel.cardTree.selection());
                        }
                    }
                }
            };

            var updatePermissionCardSelection = function() {
                var matchingCard = correspondingCard(viewModel.cardTree.selection(), viewModel.permissionTree);
                if (matchingCard) {
                    viewModel.permissionTree.expandToRoot(matchingCard);
                    viewModel.permissionTree.selection.removeAll();
                    matchingCard.selectChildCards();
                }
            };

            if (viewModel.activeTab() === 'graph') {
                viewModel.loadGraphSettings();
                // here we might load data/views asyncronously
            }

            var loadPermissionData = viewModel.activeTab.subscribe(function(tab) {
                // Loads identities and nodegroup permissions when the permissions tab is opened and then disposes the ko.subscribe.
                if (tab === 'permissions') {
                    viewModel.permissionsDesigner.getPermissionManagerData();
                    loadPermissionData.dispose();
                }
            });

            var helpContentLookup = {
                permissions: {
                    'title': 'xxxx', // dynamic title loading not implemented
                    'template': 'permissions-tab-help',
                },
                graph: {
                    'title': 'xxxx', // dynamic title loading not implemented
                    'template': 'graph-tab-help',
                },
                card: {
                    'title': 'xxxx', // dynamic title loading not implemented
                    'template': 'cards-tab-help',
                }
            };

            viewModel.activeTab.subscribe(function(tab) {
                viewModel.helpTemplate(helpContentLookup[tab]['template']);
                viewModel.getHelp();
                switch (tab) {
                case 'card':
                    updateCardSelection();
                    break;
                case 'graph':
                    updateGraphSelection();
                    break;
                case 'permissions':
                    updatePermissionCardSelection();
                    break;
                default:
                    return;
                }
            });

            viewModel.graphModel.on('select-node', function(node) {
                viewModel.graphTree.expandParentNode(node);
            });

            BaseManagerView.prototype.initialize.apply(this, arguments);
        }
    });

    return new GraphDesignerView();
});
<|endoftext|>


<commit_before>const gulp = require('gulp');
const watch = require('gulp-watch');
const ghPages = require('gulp-gh-pages-will');
const connect = require('gulp-connect');
const open = require('gulp-open');
require('./gulp/i18n');
require('./gulp/build');
require('./gulp/plato');

gulp.task(
    'connect',
    gulp.series(done => {
        connect.server({
            root      : 'www',
            port      : 8080,
            livereload: true,
        });
        done();
    })
);

gulp.task(
    'open',
    gulp.series(done => {
        gulp.src('www/index.html').pipe(
            open({
                uri: 'http://localhost:8080/',
            })
        );
        done();
    })
);

gulp.task(
    'serve',
    gulp.series('open', 'connect', done => {
        watch(['www/*.html']).pipe(connect.reload());
        done();
    })
);

gulp.task(
    'release-branch',
    gulp.series(() => gulp.src(['404.md', 'LICENSE', 'README.md', 'CNAME', './branch/**']).pipe(ghPages()))
);

gulp.task(
    'release-master',
    gulp.series(() => gulp.src(['404.md', 'LICENSE', 'README.md', 'CNAME', './www/**']).pipe(ghPages()))
);

gulp.task('test-deploy', gulp.series('build-min', 'serve', () => {}));

gulp.task(
    'watch-static',
    gulp.parallel(done => {
        gulp.watch(
            ['static/xml/**/*', 'static/*.html', 'static/css/*.scss'],
            {
                debounceTimeout: 1000,
            },
            gulp.series('build-dev-static')
        );
        done();
    })
);

gulp.task(
    'watch-html',
    gulp.series(done => {
        gulp.watch(
            ['templates/**/*'],
            {
                debounceTimeout: 1000,
            },
            gulp.series('build-dev-html')
        );
        done();
    })
);

gulp.task('watch', gulp.series('build', 'serve', 'watch-static', 'watch-html'));

gulp.task('default', gulp.series('watch'));
<commit_msg>Update gulp scripts<commit_after>const gulp = require('gulp');
const watch = require('gulp-watch');
const ghpages = require('gh-pages');
const connect = require('gulp-connect');
const open = require('gulp-open');
require('./gulp/i18n');
require('./gulp/build');
require('./gulp/plato');

gulp.task(
    'connect',
    gulp.series(done => {
        connect.server({
            root      : 'www',
            port      : 8080,
            livereload: true,
        });
        done();
    })
);

gulp.task(
    'open',
    gulp.series(done => {
        gulp.src('www/index.html').pipe(
            open({
                uri: 'http://localhost:8080/',
            })
        );
        done();
    })
);

gulp.task(
    'serve',
    gulp.series('open', 'connect', done => {
        watch(['www/*.html']).pipe(connect.reload());
        done();
    })
);

gulp.task(
    'release-branch',
    gulp.series(done => {
        const index = process.argv.indexOf('--branch');
        let option = '';
        if (index <= -1) {
            throw 'Please specify branch';
        } else {
            option = process.argv[index + 1];
        }
        ghpages
            .publish('www', {
                dest: option,
                add : true,
            })
            .then(done);
    })
);

gulp.task(
    'release-master',
    gulp.series(done => {
        ghpages
            .publish('./', {
                src: ['404.md', 'LICENSE', 'README.md', 'CNAME'],
                add: true,
            })
            .then(() => {
                ghpages.publish('www', {
                    add: true,
                });
            })
            .then(done);
    })
);

gulp.task('test-deploy', gulp.series('build-min', 'serve', () => {}));

gulp.task(
    'watch-static',
    gulp.parallel(done => {
        gulp.watch(
            ['static/xml/**/*', 'static/*.html', 'static/css/*.scss'],
            {
                debounceTimeout: 1000,
            },
            gulp.series('build-dev-static')
        );
        done();
    })
);

gulp.task(
    'watch-html',
    gulp.series(done => {
        gulp.watch(
            ['templates/**/*'],
            {
                debounceTimeout: 1000,
            },
            gulp.series('build-dev-html')
        );
        done();
    })
);

gulp.task('watch', gulp.series('build', 'serve', 'watch-static', 'watch-html'));

gulp.task('default', gulp.series('watch'));
<|endoftext|>


<commit_before>import * as core from '../../core';

const RenderTexture = core.RenderTexture;
const WebGLRenderer = core.WebGLRenderer;
const Sprite = core.Sprite;

// const tempArray = new Float32Array(4);

export default class LightSpriteRenderer extends core.ObjectRenderer
{
    constructor(renderer)
    {
        super(renderer);
        this.gl = renderer.gl;

        this.middleRenderTexture = RenderTexture.create(renderer.width, renderer.height);
        this.middleSprite = new Sprite(this.middleRenderTexture);
        this.diffuseRenderTexture = RenderTexture.create(2, 2);
        this.normalsRenderTexture = RenderTexture.create(2, 2);
    }

    onContextChange()
    {
        this.contextChanged = true;
    }

    render(sprite)
    {
        if (!sprite.texture._uvs || !sprite.lights) {
            return;
        }

        const renderer = this.renderer;
        const gl = renderer.gl;

        let width;
        let height;

        if (sprite.diffuseTexture) {
            width = sprite.diffuseTexture.width;
            height = sprite.diffuseTexture.height;
            this.diffuseRenderTexture.resize(width, height);
            renderer.render(sprite.diffuseTexture, this.diffuseRenderTexture, true);
        } else {
            // TODO
        }

        if (sprite.normalsTexture) {
            width = sprite.normalsTexture.width;
            height = sprite.normalsTexture.height;
            this.normalsRenderTexture.resize(width, height);
            renderer.render(sprite.normalsTexture, this.normalsRenderTexture, true);
        } else {
            // TODO
        }

        renderer.setObjectRenderer(renderer.plugins.lightsprite);

        const lightCount = sprite.lights.length;

        if (lightCount > 1) {
            renderer.bindRenderTexture(this.middleRenderTexture);
            gl.disable(gl.SCISSOR_TEST);
            renderer.clear(); // [1, 1, 1, 1]);
            gl.enable(gl.SCISSOR_TEST);
        } else {
            renderer.bindRenderTarget(renderer.rootRenderTarget);
        }

        // sprite._renderWebGL = sprite._renderWebGLBakLightSpriteRenderer;
        // renderer.render(sprite);
        // sprite._renderWebGL = LightSpriteRenderer.__renderWebGLSprite;

        const vertexData = sprite.computedGeometry ? sprite.computedGeometry.vertices : sprite.vertexData;
        const uvsData = sprite._texture._uvs;
        const uvsDataNormal = sprite.normalsTexture._texture._uvs;

        const diffuseBaseTexture = this.diffuseRenderTexture.baseTexture;
        const normalsBaseTexture = this.normalsRenderTexture.baseTexture;

        const lights = sprite.lights;

        for (let i = 0; i < lights.length; i++)
        {
            const light = lights[i];
            light.init(renderer, this.contextChanged);

            const shader = light.shader;
            const quad = light.quad;

            const vertices = quad.vertices;
            const uvs = quad.uvs;

            for (let i = 0; i < 8; i++) {
                vertices[i] = vertexData[i];
            }

            // uvs[0] = uvsData.x0;
            // uvs[1] = uvsData.y0;
            // uvs[2] = uvsData.x1;
            // uvs[3] = uvsData.y1;
            // uvs[4] = uvsData.x2;
            // uvs[5] = uvsData.y2;
            // uvs[6] = uvsData.x3;
            // uvs[7] = uvsData.y3;

            // uvs[8] = uvsDataNormal.x0;
            // uvs[9] = uvsDataNormal.y0;
            // uvs[10] = uvsDataNormal.x1;
            // uvs[11] = uvsDataNormal.y1;
            // uvs[12] = uvsDataNormal.x2;
            // uvs[13] = uvsDataNormal.y2;
            // uvs[14] = uvsDataNormal.x3;
            // uvs[15] = uvsDataNormal.y3;
            quad.upload();

            renderer.bindShader(shader);
            renderer.bindVao(quad.vao);

            light.syncShader();

            shader.uniforms.uSampler = renderer.bindTexture(diffuseBaseTexture);
            shader.uniforms.uNormalSampler = renderer.bindTexture(normalsBaseTexture);

            renderer.state.setBlendMode(light.blendMode);

            light.quad.vao.draw(renderer.drawModes[light.drawMode], 6, 0);

            renderer.drawCount++;
        }

        if (lightCount > 1) {
            renderer.bindRenderTarget(renderer.rootRenderTarget);
            renderer.render(this.middleSprite, null, false);
            renderer.drawCount++;
        }

        this.contextChanged = false;
    }

    destroy()
    {
        super.destroy();
        this.diffuseRenderTexture.destroy();
        this.normalsRenderTexture.destroy();
    }

    static applyTo(sprite)
    {
        sprite._renderWebGLBakLightSpriteRenderer = sprite._renderWebGL;
        sprite._renderWebGL = LightSpriteRenderer.__renderWebGLSprite;
    }

    static unapplyTo(sprite)
    {
        if (sprite._renderWebGLBakLightSpriteRenderer) {
            sprite._renderWebGL = sprite._renderWebGLBakLightSpriteRenderer;
            sprite._renderWebGLBakLightSpriteRenderer = null;
        }
    }

    static __renderWebGLSprite(renderer)
    {
        const sprite = this;
        // sprite.calculateVerticesWithoutTransform(true);
        sprite.calculateVertices();
        renderer.setObjectRenderer(renderer.plugins.lightsprite);
        renderer.plugins.lightsprite.render(sprite);
    }
}

WebGLRenderer.registerPlugin('lightsprite', LightSpriteRenderer);

<commit_msg>normals -> normal<commit_after>import * as core from '../../core';

const RenderTexture = core.RenderTexture;
const WebGLRenderer = core.WebGLRenderer;
const Sprite = core.Sprite;

// const tempArray = new Float32Array(4);

export default class LightSpriteRenderer extends core.ObjectRenderer
{
    constructor(renderer)
    {
        super(renderer);
        this.gl = renderer.gl;

        this.middleRenderTexture = RenderTexture.create(renderer.width, renderer.height);
        this.middleSprite = new Sprite(this.middleRenderTexture);
        this.diffuseRenderTexture = RenderTexture.create(2, 2);
        this.normalRenderTexture = RenderTexture.create(2, 2);
    }

    onContextChange()
    {
        this.contextChanged = true;
    }

    render(sprite)
    {
        if (!sprite.texture._uvs || !sprite.lights) {
            return;
        }

        const renderer = this.renderer;
        const gl = renderer.gl;

        let width;
        let height;

        if (sprite.diffuseTexture) {
            width = sprite.diffuseTexture.width;
            height = sprite.diffuseTexture.height;
            this.diffuseRenderTexture.resize(width, height);
            renderer.render(sprite.diffuseTexture, this.diffuseRenderTexture, true);
        } else {
            // TODO
        }

        if (sprite.normalTexture) {
            width = sprite.normalTexture.width;
            height = sprite.normalTexture.height;
            this.normalRenderTexture.resize(width, height);
            renderer.render(sprite.normalTexture, this.normalRenderTexture, true);
        } else {
            // TODO
        }

        renderer.setObjectRenderer(renderer.plugins.lightsprite);

        const lightCount = sprite.lights.length;

        if (lightCount > 1) {
            renderer.bindRenderTexture(this.middleRenderTexture);
            gl.disable(gl.SCISSOR_TEST);
            renderer.clear(); // [1, 1, 1, 1]);
            gl.enable(gl.SCISSOR_TEST);
        } else {
            renderer.bindRenderTarget(renderer.rootRenderTarget);
        }

        // sprite._renderWebGL = sprite._renderWebGLBakLightSpriteRenderer;
        // renderer.render(sprite);
        // sprite._renderWebGL = LightSpriteRenderer.__renderWebGLSprite;

        const vertexData = sprite.computedGeometry ? sprite.computedGeometry.vertices : sprite.vertexData;
        const uvsData = sprite._texture._uvs;
        const uvsDataNormal = sprite.normalTexture._texture._uvs;

        const diffuseBaseTexture = this.diffuseRenderTexture.baseTexture;
        const normalBaseTexture = this.normalRenderTexture.baseTexture;

        const lights = sprite.lights;

        for (let i = 0; i < lights.length; i++)
        {
            const light = lights[i];
            light.init(renderer, this.contextChanged);

            const shader = light.shader;
            const quad = light.quad;

            const vertices = quad.vertices;
            const uvs = quad.uvs;

            for (let i = 0; i < 8; i++) {
                vertices[i] = vertexData[i];
            }

            // uvs[0] = uvsData.x0;
            // uvs[1] = uvsData.y0;
            // uvs[2] = uvsData.x1;
            // uvs[3] = uvsData.y1;
            // uvs[4] = uvsData.x2;
            // uvs[5] = uvsData.y2;
            // uvs[6] = uvsData.x3;
            // uvs[7] = uvsData.y3;

            // uvs[8] = uvsDataNormal.x0;
            // uvs[9] = uvsDataNormal.y0;
            // uvs[10] = uvsDataNormal.x1;
            // uvs[11] = uvsDataNormal.y1;
            // uvs[12] = uvsDataNormal.x2;
            // uvs[13] = uvsDataNormal.y2;
            // uvs[14] = uvsDataNormal.x3;
            // uvs[15] = uvsDataNormal.y3;
            quad.upload();

            renderer.bindShader(shader);
            renderer.bindVao(quad.vao);

            light.syncShader();

            shader.uniforms.uSampler = renderer.bindTexture(diffuseBaseTexture);
            shader.uniforms.uNormalSampler = renderer.bindTexture(normalBaseTexture);

            renderer.state.setBlendMode(light.blendMode);

            light.quad.vao.draw(renderer.drawModes[light.drawMode], 6, 0);

            renderer.drawCount++;
        }

        if (lightCount > 1) {
            renderer.bindRenderTarget(renderer.rootRenderTarget);
            renderer.render(this.middleSprite, null, false);
            renderer.drawCount++;
        }

        this.contextChanged = false;
    }

    destroy()
    {
        super.destroy();
        this.diffuseRenderTexture.destroy();
        this.normalRenderTexture.destroy();
    }

    static applyTo(sprite)
    {
        sprite._renderWebGLBakLightSpriteRenderer = sprite._renderWebGL;
        sprite._renderWebGL = LightSpriteRenderer.__renderWebGLSprite;
    }

    static unapplyTo(sprite)
    {
        if (sprite._renderWebGLBakLightSpriteRenderer) {
            sprite._renderWebGL = sprite._renderWebGLBakLightSpriteRenderer;
            sprite._renderWebGLBakLightSpriteRenderer = null;
        }
    }

    static __renderWebGLSprite(renderer)
    {
        const sprite = this;
        // sprite.calculateVerticesWithoutTransform(true);
        sprite.calculateVertices();
        renderer.setObjectRenderer(renderer.plugins.lightsprite);
        renderer.plugins.lightsprite.render(sprite);
    }
}

WebGLRenderer.registerPlugin('lightsprite', LightSpriteRenderer);

<|endoftext|>


<commit_before>import {
  Mesh,
  BoxBufferGeometry,
  BoxGeometry
} from 'three';

import {MeshComponent} from '../../core/MeshComponent';

class Box extends MeshComponent {
  static defaults = {
    ...MeshComponent.defaults,
    geometry: {
      width: 1,
      height: 1,
      depth: 1
    }
  };

  static instructions = {
    ...MeshComponent.instructions,
    geometry: ['width', 'height', 'depth']
  };

  constructor(params = {}) {
    super(params, Box.defaults, Box.instructions);
  }

  build(params = this.params) {
    const {geometry, material} = this.applyBridge({
      geometry: this.buildGeometry(params),
      material: params.material
    });

    return this.applyBridge({mesh: new Mesh(geometry, material)}).mesh;
  }

  buildGeometry(params = {}) {
    const GConstruct = params.buffer && !params.softbody ? BoxBufferGeometry : BoxGeometry;

    const geometry = new GConstruct(
      params.geometry.width,
      params.geometry.height,
      params.geometry.depth
    );

    if (params.softbody) this.proccessSoftbodyGeometry(geometry);

    return geometry;
  }
}

export {
  Box
};
<commit_msg>Fix Box. Add segments parameters<commit_after>import {
  Mesh,
  BoxBufferGeometry,
  BoxGeometry
} from 'three';

import {MeshComponent} from '../../core/MeshComponent';

class Box extends MeshComponent {
  static defaults = {
    ...MeshComponent.defaults,
    geometry: {
      width: 1,
      height: 1,
      depth: 1,
      widthSegments: 1,
      heightSegments: 1,
      depthSegements: 1
    }
  };

  static instructions = {
    ...MeshComponent.instructions,
    geometry: ['width', 'height', 'depth', 'widthSegments', 'heightSegments', 'depthSegements']
  };

  constructor(params = {}) {
    super(params, Box.defaults, Box.instructions);
  }

  build(params = this.params) {
    const {geometry, material} = this.applyBridge({
      geometry: this.buildGeometry(params),
      material: params.material
    });

    return this.applyBridge({mesh: new Mesh(geometry, material)}).mesh;
  }

  buildGeometry(params = {}) {
    const GConstruct = params.buffer && !params.softbody ? BoxBufferGeometry : BoxGeometry;

    const geometry = new GConstruct(
      params.geometry.width,
      params.geometry.height,
      params.geometry.depth,
      params.geometry.widthSegments,
      params.geometry.heightSegments,
      params.geometry.depthSegments
    );

    if (params.softbody) this.proccessSoftbodyGeometry(geometry);

    return geometry;
  }
}

export {
  Box
};
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var lib = require('./lib');
var compiler = require('./compiler');
var Environment = require('./environment').Environment;

function match(filename, patterns) {
    if (!Array.isArray(patterns)) return false;
    return patterns.some(function (pattern) {
        return filename.match(pattern) !== null;
    });
}

function precompileString(str, opts) {
    opts = opts || {};
    opts.isString = true;
    return precompile(str, opts);
}

function precompile(input, opts) {
    // The following options are available:
    //
    // * name: name of the template (auto-generated when compiling a directory)
    // * isString: input is a string, not a file path
    // * asFunction: generate a callable function
    // * force: keep compiling on error
    // * env: the Environment to use (gets extensions and async filters from it)
    // * include: which file/folders to include (folders are auto-included, files are auto-excluded)
    // * exclude: which file/folders to exclude (folders are auto-included, files are auto-excluded)

    opts = opts || {};
    var env = opts.env || new Environment([]);
    var asyncFilters = env.asyncFilters;
    var extensions = env.extensionsList;

    var pathStats = fs.existsSync(input) && fs.statSync(input);
    var output = '';

    if(opts.isString) {
        if(!opts.name) {
            throw new Error('the "name" option is required when ' +
                            'compiling a string');
        }

        return _precompile(input,
                           opts.name,
                           env,
                           opts.asFunction);
    }
    else if(pathStats.isFile()) {
        return _precompile(fs.readFileSync(input, 'utf-8'),
                           opts.name || input,
                           env,
                           opts.asFunction);
    }
    else if(pathStats.isDirectory()) {
        var templates = [];

        function addTemplates(dir) {
            var files = fs.readdirSync(dir);

            for(var i=0; i<files.length; i++) {
                var filepath = path.join(dir, files[i]);
                var subpath = filepath.substr(path.join(input, '/').length);
                var stat = fs.statSync(filepath);

                if(stat && stat.isDirectory()) {
                    subpath += '/';
                    if (!match(subpath, opts.exclude)) {
                        addTemplates(filepath);
                    }
                }
                else if(match(subpath, opts.include)) {
                    templates.push(filepath);
                }
            }
        }

        addTemplates(input);

        for(var i=0; i<templates.length; i++) {
            var name = templates[i].replace(path.join(input, '/'), '');

            try {
                output += _precompile(fs.readFileSync(templates[i], 'utf-8'),
                                      name,
                                      env,
                                      opts.asFunction);
            } catch(e) {
                if(opts.force) {
                    // Don't stop generating the output if we're
                    // forcing compilation.
                    console.error(e);
                }
                else {
                    throw e;
                }
            }
        }

        return output;
    }
}

function _precompile(str, name, env, asFunction) {
    env = env || new Environment([]);

    var asyncFilters = env.asyncFilters;
    var extensions = env.extensionsList;

    var out = '(function() {' +
        '(window.nunjucksPrecompiled = window.nunjucksPrecompiled || {})' +
        '["' + name.replace(/\\/, '/') + '"] = (function() {';

    out += lib.withPrettyErrors(
        name,
        false,
        function() {
            return compiler.compile(str,
                                    asyncFilters,
                                    extensions,
                                    name);
        }
    );
    out += '})();\n';

    if(asFunction) {
        out += 'return function(ctx, cb) { return nunjucks.render("' + name + '", ctx, cb); }';
    }

    out += '})();\n';
    return out;
}

module.exports = {
    precompile: precompile,
    precompileString: precompileString
}
<commit_msg>add regex g option when handling windows paths<commit_after>var fs = require('fs');
var path = require('path');
var lib = require('./lib');
var compiler = require('./compiler');
var Environment = require('./environment').Environment;

function match(filename, patterns) {
    if (!Array.isArray(patterns)) return false;
    return patterns.some(function (pattern) {
        return filename.match(pattern) !== null;
    });
}

function precompileString(str, opts) {
    opts = opts || {};
    opts.isString = true;
    return precompile(str, opts);
}

function precompile(input, opts) {
    // The following options are available:
    //
    // * name: name of the template (auto-generated when compiling a directory)
    // * isString: input is a string, not a file path
    // * asFunction: generate a callable function
    // * force: keep compiling on error
    // * env: the Environment to use (gets extensions and async filters from it)
    // * include: which file/folders to include (folders are auto-included, files are auto-excluded)
    // * exclude: which file/folders to exclude (folders are auto-included, files are auto-excluded)

    opts = opts || {};
    var env = opts.env || new Environment([]);
    var asyncFilters = env.asyncFilters;
    var extensions = env.extensionsList;

    var pathStats = fs.existsSync(input) && fs.statSync(input);
    var output = '';

    if(opts.isString) {
        if(!opts.name) {
            throw new Error('the "name" option is required when ' +
                            'compiling a string');
        }

        return _precompile(input,
                           opts.name,
                           env,
                           opts.asFunction);
    }
    else if(pathStats.isFile()) {
        return _precompile(fs.readFileSync(input, 'utf-8'),
                           opts.name || input,
                           env,
                           opts.asFunction);
    }
    else if(pathStats.isDirectory()) {
        var templates = [];

        function addTemplates(dir) {
            var files = fs.readdirSync(dir);

            for(var i=0; i<files.length; i++) {
                var filepath = path.join(dir, files[i]);
                var subpath = filepath.substr(path.join(input, '/').length);
                var stat = fs.statSync(filepath);

                if(stat && stat.isDirectory()) {
                    subpath += '/';
                    if (!match(subpath, opts.exclude)) {
                        addTemplates(filepath);
                    }
                }
                else if(match(subpath, opts.include)) {
                    templates.push(filepath);
                }
            }
        }

        addTemplates(input);

        for(var i=0; i<templates.length; i++) {
            var name = templates[i].replace(path.join(input, '/'), '');

            try {
                output += _precompile(fs.readFileSync(templates[i], 'utf-8'),
                                      name,
                                      env,
                                      opts.asFunction);
            } catch(e) {
                if(opts.force) {
                    // Don't stop generating the output if we're
                    // forcing compilation.
                    console.error(e);
                }
                else {
                    throw e;
                }
            }
        }

        return output;
    }
}

function _precompile(str, name, env, asFunction) {
    env = env || new Environment([]);

    var asyncFilters = env.asyncFilters;
    var extensions = env.extensionsList;

    var out = '(function() {' +
        '(window.nunjucksPrecompiled = window.nunjucksPrecompiled || {})' +
        '["' + name.replace(/\\/g, '/') + '"] = (function() {';

    out += lib.withPrettyErrors(
        name,
        false,
        function() {
            return compiler.compile(str,
                                    asyncFilters,
                                    extensions,
                                    name);
        }
    );
    out += '})();\n';

    if(asFunction) {
        out += 'return function(ctx, cb) { return nunjucks.render("' + name + '", ctx, cb); }';
    }

    out += '})();\n';
    return out;
}

module.exports = {
    precompile: precompile,
    precompileString: precompileString
}
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.WireframeGeometry = function ( geometry ) {

	THREE.BufferGeometry.call( this );

	var edge = [ 0, 0 ], hash = {};
	var sortFunction = function ( a, b ) {

		return a - b;

	};

	var keys = [ 'a', 'b', 'c' ];

	if ( geometry instanceof THREE.Geometry ) {

		var vertices = geometry.vertices;
		var faces = geometry.faces;
		var numEdges = 0;

		// allocate maximal size
		var edges = new Uint32Array( 6 * faces.length );

		for ( var i = 0, l = faces.length; i < l; i ++ ) {

			var face = faces[ i ];

			for ( var j = 0; j < 3; j ++ ) {

				edge[ 0 ] = face[ keys[ j ] ];
				edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
				edge.sort( sortFunction );

				var key = edge.toString();

				if ( hash[ key ] === undefined ) {

					edges[ 2 * numEdges ] = edge[ 0 ];
					edges[ 2 * numEdges + 1 ] = edge[ 1 ];
					hash[ key ] = true;
					numEdges ++;

				}

			}

		}

		var coords = new Float32Array( numEdges * 2 * 3 );

		for ( var i = 0, l = numEdges; i < l; i ++ ) {

			for ( var j = 0; j < 2; j ++ ) {

				var vertex = vertices[ edges [ 2 * i + j ] ];

				var index = 6 * i + 3 * j;
				coords[ index + 0 ] = vertex.x;
				coords[ index + 1 ] = vertex.y;
				coords[ index + 2 ] = vertex.z;

			}

		}

		this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );

	} else if ( geometry instanceof THREE.BufferGeometry ) {

		if ( geometry.index !== null ) {

			// Indexed BufferGeometry

			var indices = geometry.index.array;
			var vertices = geometry.attributes.position;
			var drawcalls = geometry.drawcalls;
			var numEdges = 0;

			if ( drawcalls.length === 0 ) {

				geometry.addDrawCall( 0, indices.length );

			}

			// allocate maximal size
			var edges = new Uint32Array( 2 * indices.length );

			for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) {

				var drawcall = drawcalls[ o ];

				var start = drawcall.start;
				var count = drawcall.count;

				for ( var i = start, il = start + count; i < il; i += 3 ) {

					for ( var j = 0; j < 3; j ++ ) {

						edge[ 0 ] = indices[ i + j ];
						edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
						edge.sort( sortFunction );

						var key = edge.toString();

						if ( hash[ key ] === undefined ) {

							edges[ 2 * numEdges ] = edge[ 0 ];
							edges[ 2 * numEdges + 1 ] = edge[ 1 ];
							hash[ key ] = true;
							numEdges ++;

						}

					}

				}

			}

			var coords = new Float32Array( numEdges * 2 * 3 );

			for ( var i = 0, l = numEdges; i < l; i ++ ) {

				for ( var j = 0; j < 2; j ++ ) {

					var index = 6 * i + 3 * j;
					var index2 = edges[ 2 * i + j ];

					coords[ index + 0 ] = vertices.getX( index2 );
					coords[ index + 1 ] = vertices.getY( index2 );
					coords[ index + 2 ] = vertices.getZ( index2 );

				}

			}

			this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );

		} else {

			// non-indexed BufferGeometry

			var vertices = geometry.attributes.position.array;
			var numEdges = vertices.length / 3;
			var numTris = numEdges / 3;

			var coords = new Float32Array( numEdges * 2 * 3 );

			for ( var i = 0, l = numTris; i < l; i ++ ) {

				for ( var j = 0; j < 3; j ++ ) {

					var index = 18 * i + 6 * j;

					var index1 = 9 * i + 3 * j;
					coords[ index + 0 ] = vertices[ index1 ];
					coords[ index + 1 ] = vertices[ index1 + 1 ];
					coords[ index + 2 ] = vertices[ index1 + 2 ];

					var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
					coords[ index + 3 ] = vertices[ index2 ];
					coords[ index + 4 ] = vertices[ index2 + 1 ];
					coords[ index + 5 ] = vertices[ index2 + 2 ];

				}

			}

			this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );

		}

	}

};

THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
<commit_msg>WireframeGeometry: Fixed addGroups() call. Fixes #7200.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.WireframeGeometry = function ( geometry ) {

	THREE.BufferGeometry.call( this );

	var edge = [ 0, 0 ], hash = {};
	var sortFunction = function ( a, b ) {

		return a - b;

	};

	var keys = [ 'a', 'b', 'c' ];

	if ( geometry instanceof THREE.Geometry ) {

		var vertices = geometry.vertices;
		var faces = geometry.faces;
		var numEdges = 0;

		// allocate maximal size
		var edges = new Uint32Array( 6 * faces.length );

		for ( var i = 0, l = faces.length; i < l; i ++ ) {

			var face = faces[ i ];

			for ( var j = 0; j < 3; j ++ ) {

				edge[ 0 ] = face[ keys[ j ] ];
				edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
				edge.sort( sortFunction );

				var key = edge.toString();

				if ( hash[ key ] === undefined ) {

					edges[ 2 * numEdges ] = edge[ 0 ];
					edges[ 2 * numEdges + 1 ] = edge[ 1 ];
					hash[ key ] = true;
					numEdges ++;

				}

			}

		}

		var coords = new Float32Array( numEdges * 2 * 3 );

		for ( var i = 0, l = numEdges; i < l; i ++ ) {

			for ( var j = 0; j < 2; j ++ ) {

				var vertex = vertices[ edges [ 2 * i + j ] ];

				var index = 6 * i + 3 * j;
				coords[ index + 0 ] = vertex.x;
				coords[ index + 1 ] = vertex.y;
				coords[ index + 2 ] = vertex.z;

			}

		}

		this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );

	} else if ( geometry instanceof THREE.BufferGeometry ) {

		if ( geometry.index !== null ) {

			// Indexed BufferGeometry

			var indices = geometry.index.array;
			var vertices = geometry.attributes.position;
			var drawcalls = geometry.drawcalls;
			var numEdges = 0;

			if ( drawcalls.length === 0 ) {

				geometry.addGroup( 0, indices.length );

			}

			// allocate maximal size
			var edges = new Uint32Array( 2 * indices.length );

			for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) {

				var drawcall = drawcalls[ o ];

				var start = drawcall.start;
				var count = drawcall.count;

				for ( var i = start, il = start + count; i < il; i += 3 ) {

					for ( var j = 0; j < 3; j ++ ) {

						edge[ 0 ] = indices[ i + j ];
						edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
						edge.sort( sortFunction );

						var key = edge.toString();

						if ( hash[ key ] === undefined ) {

							edges[ 2 * numEdges ] = edge[ 0 ];
							edges[ 2 * numEdges + 1 ] = edge[ 1 ];
							hash[ key ] = true;
							numEdges ++;

						}

					}

				}

			}

			var coords = new Float32Array( numEdges * 2 * 3 );

			for ( var i = 0, l = numEdges; i < l; i ++ ) {

				for ( var j = 0; j < 2; j ++ ) {

					var index = 6 * i + 3 * j;
					var index2 = edges[ 2 * i + j ];

					coords[ index + 0 ] = vertices.getX( index2 );
					coords[ index + 1 ] = vertices.getY( index2 );
					coords[ index + 2 ] = vertices.getZ( index2 );

				}

			}

			this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );

		} else {

			// non-indexed BufferGeometry

			var vertices = geometry.attributes.position.array;
			var numEdges = vertices.length / 3;
			var numTris = numEdges / 3;

			var coords = new Float32Array( numEdges * 2 * 3 );

			for ( var i = 0, l = numTris; i < l; i ++ ) {

				for ( var j = 0; j < 3; j ++ ) {

					var index = 18 * i + 6 * j;

					var index1 = 9 * i + 3 * j;
					coords[ index + 0 ] = vertices[ index1 ];
					coords[ index + 1 ] = vertices[ index1 + 1 ];
					coords[ index + 2 ] = vertices[ index1 + 2 ];

					var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
					coords[ index + 3 ] = vertices[ index2 ];
					coords[ index + 4 ] = vertices[ index2 + 1 ];
					coords[ index + 5 ] = vertices[ index2 + 2 ];

				}

			}

			this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );

		}

	}

};

THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
<|endoftext|>


<commit_before>import React, { Component } from 'react';

class SearchBar extends Component {
    constructor(props) {
        super(props);

        this.state = { term: 'search term' };
    }

    render() {
        return (

                <input value={this.state.term}
                    onChange={(event) => this.onInputChange(event.target.value)} />

            );

    }

    onInputChange(term) {
        this.setState({term});
        this.props.onSearchTermChange(term);
    }
}

export default SearchBar;<commit_msg>Updated the default search phrase.<commit_after>import React, { Component } from 'react';

class SearchBar extends Component {
    constructor(props) {
        super(props);

        this.state = { term: 'surfboard' };
    }

    render() {
        return (

                <input value={this.state.term}
                    onChange={(event) => this.onInputChange(event.target.value)} />

            );

    }

    onInputChange(term) {
        this.setState({term});
        this.props.onSearchTermChange(term);
    }
}

export default SearchBar;<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash')
  , raf = require('raf/polyfill')
  , Ribcage
  , extendView

Ribcage = {
  initialize: function initialize(opts){

    opts = opts || {}

    // if we need to load data before rendering, do it
    // otherwise, assume we have the data already
    this._dataLoaded = typeof this.loadData !== 'function'

    this._nukeOnRender = opts._nukeOnRender
    // delete would turn this into a "slow object" in V8
    // we can't set to null, b/c a state model can reject extra properties
    if (_.has(opts, '_nukeOnRender')) opts = _.omit(opts, '_nukeOnRender')

    // backbone 1.1+ doesn't auto-set this.options
    this.options = opts

    if (this.beforeInit) this.beforeInit(opts)

    this.template = this.template || opts.template

    if (!this.template) {
      this.template = function template(){
        return ''
      }
    }

    if (this.afterInit) this.afterInit(opts)

    this.render()
  }

, context: function context(){
    var model = this.model ? this.model.toJSON() : {}
      , state = this.state ? this.state.toJSON() : {}

    return _.extend({}, this.options, model, state)
  }

, render: function render(){
    var self = this
      , model = this.model

    if (typeof this.bindEvents === 'function') {
      this.bindEvents()
    }

    if (!this._dataLoaded && typeof this.loadData === 'function') {
      return this.loadData(function dataLoaded(){
        self._dataLoaded = true
        self.render()
      })
    }

    // closing destroys the el, might need to recreate it
    if (!this.el) {
      this._ensureElement()
    }

    if (this.beforeRender) {
      this.beforeRender()
    }

    // Maintainers of legacy code might want to use this
    // but certainly not YOU, young grasshopper!
    if (this._nukeOnRender) {
      this.closeSubviews()
      this.$el.empty()
    }

    if (this.beforeTemplating) {
      model = this.beforeTemplating()
    }

    if (this.context) {
      model = this.context()
    }

    this.$el.html(this.template(model))

    // As soon as the view is bound to DOM, we need to delegate events and re-render all
    // subviews to keep events intact. -cstumph
    this.delegateEvents()
    this.eachSubview(function eachSubviewInRender(view){
      view.render()
    })

    // I'm not happy deferring here, but backbone's
    // event system is based on the DOM, so my hands
    // are tied. - Daniel
    _.defer(function deferSoTheDOMCanCatchup(){
      self.trigger('afterRender')
    })

    if (this.afterRender) {
      this.afterRender()
    }

    return this
  }

, proxy: function proxy(name, view){
    this.listenTo(view, name, function proxiedEventCallback(){
      var args = Array.prototype.slice.call(arguments, 0)
      args.splice(0, 0, name)
      this.trigger.apply(this, args)
    })
  }

, eachSubview: function eachSubview(iterator, context){
    _.each(this.subviews, iterator, context || this)
  }

, _attachSubView: function _attachSubView(view){
    var viewId

    this.subviews = this.subviews || {}
    this.subviewByModelId = this.subviewByModelId || {}

    this.subviews[view.cid] = view

    if (view.model) {
      viewId = view.model.id || view.model.cid
      if (!this.subviewByModelId[viewId]) this.subviewByModelId[viewId] = []

      this.subviewByModelId[viewId].push(view)
    }

    return view
  }

, appendSubview: function appendSubview(view, el){
    el || (el = this.$el)

    this._attachSubView(view)

    // closing a view will remove the el, so ensure we have one before re-attaching
    if (view.options.render || !view.el) view.render()
    el.append(view.el)

    _.defer(function deferSoTheDOMCanCatchup(){
      view.trigger('afterAppend', view)
    })

    if (view.afterAppend) {
      view.afterAppend()
    }
  }

, prependSubview: function prependSubview(view, el){
    el || (el = this.$el)

    this._attachSubView(view)

    // closing a view will remove the el, so ensure we have one before re-attaching
    if (view.options.renderOnAppend || !view.el) view.render()
    el.prepend(view.el)

    _.defer(function deferSoTheDOMCanCatchup(){
      view.trigger('afterPrepend', view)
    })

    if (view.afterPrepend) {
      view.afterPrepend()
    }
  }

, appendSubviews: function appendSubviews(views, el, callback){
    var fragment = document.createDocumentFragment()

    el || (el = this.$el)

    _.each(views, function appendEachView(view){
      this._attachSubView(view)

      // closing a view will remove the el, so ensure we have one before re-attaching
      if (view.options.renderOnAppend || !view.el) view.render()
      fragment.appendChild(view.el)

      _.defer(function deferSoTheDOMCanCatchup(){
        view.trigger('afterAppend', view)
      })

      if (view.afterAppend) {
        view.afterAppend()
      }
    }, this)

    raf.call(window, function onFrame(){
      el[0].appendChild(fragment)
      if (_.isFunction(callback)) callback(views)
    })
  }

, batchAppendSubviews: function batchAppendSubviews(views, el, batchCount, batchCallback, callback){
    var self = this
      , batches = _(views)
                  .groupBy(function groupIntoBatches(view, index){
                    return Math.floor(index / batchCount)
                  })
                  .toArray()
                  .valueOf()

    function appendNextBatch(){
      var batchesLeft = batches.length
        , viewBatch = batchesLeft ? batches.shift() : false

      // with no batches left, just return early
      if (!batchesLeft) {
        // if we have a final callback, call that.
        return typeof callback === 'function'
          ? void callback()
          : void 0
      }

      self.appendSubviews(viewBatch, el, function subviewsAppended(){
        if (typeof batchCallback === 'function') {
          batchCallback(viewBatch)
        }

        appendNextBatch()
      })
    }

    appendNextBatch()
  }

, close: function close(options, callback){
    options || (options = {})

    if (this.beforeClose) this.beforeClose()

    this.closeSubviews({keepDom: true}, _.bind(function onSubviewsClosed(){
      this.stopListening()

      // when the subviews are closed, close the parent
      // keep the DOM elements, b/c it's save to assume that all child DOM
      // is containted by the parent DOM container. This allows us to reduce
      // many DOM removal calls to just one.
      if (!options.keepDom) {
        raf.call(window, function closeRequestAnimationFrame(){
          // remove the from the DOM
          if (this.$el) this.$el.remove()
          // destroy our reference to the DOM node
          this.$el = null
          this.el = null
          if (_.isFunction(callback)) callback()
        }.bind(this))
      }
      else if (_.isFunction(callback)) callback()
    }, this))
  }

, closeSubviews: function closeSubviews(options, callback){
    var subviewCount = _.size(this.subviews)
      , done

    if (_.isFunction(callback)){
      // if there are no subviews to close, just call the callback
      if (!subviewCount) return void callback()
      else done = _.after(subviewCount, callback)
    }

    this.eachSubview(function closeEachSubview(subview){
      subview.close(options, done)
    })

    // empty out our lists of subviews
    this.subviews = {}
    this.subviewByModelId = {}
  }

, detachSubview: function detachSubview(view){
    var msg

    if (this.subviews) {

      if (view && !this.subviews[view.cid]) {
        msg = 'View not found in ' + this.className + '\'s subviews: ' + view.className

        if (view.model) msg += '\n\n' + view.model.toJSON()

        throw new Error(msg)
      }

      // delete makes this into a "slow object" in V8
      // but that's okay b/c any perf gains we'd get would be lost by having to
      // itterate over subviews to remove falsey values.
      delete this.subviews[view.cid]
    }

    view.$el.detach()
  }

, _removeSubviewByModel: function _removeSubviewByModel(model, method){
    var id = model.id
    if (this.subviewByModelId){
      if (!id || !this.subviewByModelId[id]){
        throw new Error('No views with ' + id + ' model id found in ' + this.className + ' subviews')
      }

      _.each(this.subviewByModelId[id], function eachSubviewById(view){
        method.call(this, view)
      }, this)

      // delete would turn this into a "slow object" in V8, so just set to null
      this.subviewByModelId[id] = null
    }

  }

, closeSubviewsByModel: function closeSubviewsByModel(model){
    this._removeSubviewByModel(model, this.close)
  }

, detachSubviewByModel: function detachSubviewByModel(model){
    this._removeSubviewByModel(model, this.detachSubview)
  }

} // end Ribcage{}

extendView = function extendView(view){
  return view.extend(Ribcage)
}

module.exports = extendView
<commit_msg>linter #cleanup<commit_after>'use strict'

var _ = require('lodash')
  , raf = require('raf/polyfill')
  , Ribcage
  , extendView

Ribcage = {
  initialize: function initialize(opts){

    opts = opts || {}

    // if we need to load data before rendering, do it
    // otherwise, assume we have the data already
    this._dataLoaded = typeof this.loadData !== 'function'

    this._nukeOnRender = opts._nukeOnRender
    // delete would turn this into a "slow object" in V8
    // we can't set to null, b/c a state model can reject extra properties
    if (_.has(opts, '_nukeOnRender')) opts = _.omit(opts, '_nukeOnRender')

    // backbone 1.1+ doesn't auto-set this.options
    this.options = opts

    if (this.beforeInit) this.beforeInit(opts)

    this.template = this.template || opts.template

    if (!this.template) {
      this.template = function template(){
        return ''
      }
    }

    if (this.afterInit) this.afterInit(opts)

    this.render()
  }

, context: function context(){
    var model = this.model ? this.model.toJSON() : {}
      , state = this.state ? this.state.toJSON() : {}

    return _.extend({}, this.options, model, state)
  }

, render: function render(){
    var self = this
      , model = this.model

    if (typeof this.bindEvents === 'function') {
      this.bindEvents()
    }

    if (!this._dataLoaded && typeof this.loadData === 'function') {
      return this.loadData(function dataLoaded(){
        self._dataLoaded = true
        self.render()
      })
    }

    // closing destroys the el, might need to recreate it
    if (!this.el) {
      this._ensureElement()
    }

    if (this.beforeRender) {
      this.beforeRender()
    }

    // Maintainers of legacy code might want to use this
    // but certainly not YOU, young grasshopper!
    if (this._nukeOnRender) {
      this.closeSubviews()
      this.$el.empty()
    }

    if (this.beforeTemplating) {
      model = this.beforeTemplating()
    }

    if (this.context) {
      model = this.context()
    }

    this.$el.html(this.template(model))

    // As soon as the view is bound to DOM, we need to delegate events and re-render all
    // subviews to keep events intact. -cstumph
    this.delegateEvents()
    this.eachSubview(function eachSubviewInRender(view){
      view.render()
    })

    // I'm not happy deferring here, but backbone's
    // event system is based on the DOM, so my hands
    // are tied. - Daniel
    _.defer(function deferSoTheDOMCanCatchup(){
      self.trigger('afterRender')
    })

    if (this.afterRender) {
      this.afterRender()
    }

    return this
  }

, proxy: function proxy(name, view){
    this.listenTo(view, name, function proxiedEventCallback(){
      var args = Array.prototype.slice.call(arguments, 0)
      args.splice(0, 0, name)
      this.trigger.apply(this, args)
    })
  }

, eachSubview: function eachSubview(iterator, context){
    _.each(this.subviews, iterator, context || this)
  }

, _attachSubView: function _attachSubView(view){
    var viewId

    this.subviews = this.subviews || {}
    this.subviewByModelId = this.subviewByModelId || {}

    this.subviews[view.cid] = view

    if (view.model) {
      viewId = view.model.id || view.model.cid
      if (!this.subviewByModelId[viewId]) this.subviewByModelId[viewId] = []

      this.subviewByModelId[viewId].push(view)
    }

    return view
  }

, appendSubview: function appendSubview(view, el){
    el || (el = this.$el)

    this._attachSubView(view)

    // closing a view will remove the el, so ensure we have one before re-attaching
    if (view.options.render || !view.el) view.render()
    el.append(view.el)

    _.defer(function deferSoTheDOMCanCatchup(){
      view.trigger('afterAppend', view)
    })

    if (view.afterAppend) {
      view.afterAppend()
    }
  }

, prependSubview: function prependSubview(view, el){
    el || (el = this.$el)

    this._attachSubView(view)

    // closing a view will remove the el, so ensure we have one before re-attaching
    if (view.options.renderOnAppend || !view.el) view.render()
    el.prepend(view.el)

    _.defer(function deferSoTheDOMCanCatchup(){
      view.trigger('afterPrepend', view)
    })

    if (view.afterPrepend) {
      view.afterPrepend()
    }
  }

, appendSubviews: function appendSubviews(views, el, callback){
    var fragment = document.createDocumentFragment()

    el || (el = this.$el)

    _.each(views, function appendEachView(view){
      this._attachSubView(view)

      // closing a view will remove the el, so ensure we have one before re-attaching
      if (view.options.renderOnAppend || !view.el) view.render()
      fragment.appendChild(view.el)

      _.defer(function deferSoTheDOMCanCatchup(){
        view.trigger('afterAppend', view)
      })

      if (view.afterAppend) {
        view.afterAppend()
      }
    }, this)

    raf.call(window, function onFrame(){
      el[0].appendChild(fragment)
      if (_.isFunction(callback)) callback(views)
    })
  }

, batchAppendSubviews: function batchAppendSubviews(views, el, batchCount, batchCallback, callback){
    var self = this
      , batches = _(views)
                  .groupBy(function groupIntoBatches(view, index){
                    return Math.floor(index / batchCount)
                  })
                  .toArray()
                  .valueOf()
      , appendNextBatch = function appendNextBatch(){
      var batchesLeft = batches.length
        , viewBatch = batchesLeft ? batches.shift() : false

      // with no batches left, just return early
      if (!batchesLeft) {
        // if we have a final callback, call that.
        return typeof callback === 'function'
          ? void callback()
          : void 0
      }

      self.appendSubviews(viewBatch, el, function subviewsAppended(){
        if (typeof batchCallback === 'function') {
          batchCallback(viewBatch)
        }

        appendNextBatch()
      })
    }

    appendNextBatch()
  }

, close: function close(options, callback){
    options || (options = {})

    if (this.beforeClose) this.beforeClose()

    this.closeSubviews({keepDom: true}, _.bind(function onSubviewsClosed(){
      this.stopListening()

      // when the subviews are closed, close the parent
      // keep the DOM elements, b/c it's save to assume that all child DOM
      // is containted by the parent DOM container. This allows us to reduce
      // many DOM removal calls to just one.
      if (!options.keepDom) {
        raf.call(window, function closeRequestAnimationFrame(){
          // remove the from the DOM
          if (this.$el) this.$el.remove()
          // destroy our reference to the DOM node
          this.$el = null
          this.el = null
          if (_.isFunction(callback)) callback()
        }.bind(this))
      }
      else if (_.isFunction(callback)) callback()
    }, this))
  }

, closeSubviews: function closeSubviews(options, callback){
    var subviewCount = _.size(this.subviews)
      , done

    if (_.isFunction(callback)){
      // if there are no subviews to close, just call the callback
      if (!subviewCount) return void callback()
      else done = _.after(subviewCount, callback)
    }

    this.eachSubview(function closeEachSubview(subview){
      subview.close(options, done)
    })

    // empty out our lists of subviews
    this.subviews = {}
    this.subviewByModelId = {}
  }

, detachSubview: function detachSubview(view){
    var msg

    if (this.subviews) {
      if (view && !this.subviews[view.cid]) {
        msg = 'View not found in ' + this.className + '\'s subviews: ' + view.className

        if (view.model) msg += '\n\n' + view.model.toJSON()

        throw new Error(msg)
      }

      // delete makes this into a "slow object" in V8
      // but that's okay b/c any perf gains we'd get would be lost by having to
      // itterate over subviews to remove falsey values.
      delete this.subviews[view.cid]
    }

    view.$el.detach()
  }

, _removeSubviewByModel: function _removeSubviewByModel(model, method){
    var id = model.id

    if (this.subviewByModelId){
      if (!id || !this.subviewByModelId[id]){
        throw new Error('No views with ' + id + ' model id found in ' + this.className + ' subviews')
      }

      _.each(this.subviewByModelId[id], function eachSubviewById(view){
        method.call(this, view)
      }, this)

      // delete would turn this into a "slow object" in V8, so just set to null
      this.subviewByModelId[id] = null
    }
  }

, closeSubviewsByModel: function closeSubviewsByModel(model){
    this._removeSubviewByModel(model, this.close)
  }

, detachSubviewByModel: function detachSubviewByModel(model){
    this._removeSubviewByModel(model, this.detachSubview)
  }

}

extendView = function extendView(view){
  return view.extend(Ribcage)
}

module.exports = extendView
<|endoftext|>


<commit_before>/**
 * Created by keyvan on 8/29/16.
 */

import {v1 as neo4j} from 'neo4j-driver';

const neo4jInt = neo4j.int;

const logParams = params => {
    console.log(JSON.stringify(params, null, 2));
    return params;
};

const deepParse = (params, key, func) => {
    let [keyToFind, keyToReplace] = [key, key];
    if (typeof key === 'object') {
        const keys = Object.keys(key);
        if (keys.length !== 1)
            throw new Error(`parse error, invalid key ${JSON.stringify(key)}`);
        keyToFind = keys[0];
        keyToReplace = key[keyToFind];
    }
    if (params[keyToFind])
        if (!Array.isArray(params[keyToFind]))
            params[keyToReplace] = func.apply(params, [params[keyToFind]]);
        else {
            params[keyToReplace] = [];
            for (const value of params[keyToFind])
                params[keyToReplace].push(func.apply(params, [value]))
        }
    for (const innerKey of Object.keys(params))
        if (params[innerKey] !== null && typeof params[innerKey] === 'object')
            deepParse(params[innerKey], key, func);
};

const parseWith = (func) => (...keys) => params => {
    for (const key of keys)
        deepParse(params, key, func);
    return params;
};

const parseNeo4jInts = parseWith(neo4jInt);

const parseIds = parseNeo4jInts;

const parseInts = parseWith(parseInt);

const parseFloats = parseWith(parseFloat);

const parseDates = parseWith(stringOrUnixTime => {
    const parsedInt = parseInt(stringOrUnixTime);
    stringOrUnixTime = parsedInt.toString() !== stringOrUnixTime.toString() || isNaN(parsedInt) ?
        stringOrUnixTime : parsedInt;
    return new Date(stringOrUnixTime);
});

const parseUnixTimes = parseWith(stringOrUnixTime => {
    const parsedInt = parseInt(stringOrUnixTime);
    if (parsedInt.toString() === stringOrUnixTime.toString())
        return neo4jInt(parsedInt);
    return neo4jInt(new Date(stringOrUnixTime).getTime());
});

export {Integer} from 'neo4j-driver/lib/v1/integer';
export {neo4jInt, logParams, parseWith, parseNeo4jInts, parseIds,
    parseInts, parseFloats, parseDates, parseUnixTimes};
<commit_msg>parseWith now parses arrays, error fixed<commit_after>/**
 * Created by keyvan on 8/29/16.
 */

import {v1 as neo4j} from 'neo4j-driver';

const neo4jInt = neo4j.int;

const logParams = params => {
    console.log(JSON.stringify(params, null, 2));
    return params;
};

const deepParse = (params, key, func) => {
    let [keyToFind, keyToReplace] = [key, key];
    if (typeof key === 'object') {
        const keys = Object.keys(key);
        if (keys.length !== 1)
            throw new Error(`parse error, invalid key ${JSON.stringify(key)}`);
        keyToFind = keys[0];
        keyToReplace = key[keyToFind];
    }
    if (params[keyToFind])
        if (!Array.isArray(params[keyToFind]))
            params[keyToReplace] = func.apply(params, [params[keyToFind]]);
        else {
            const toReplace = [];
            for (const value of params[keyToFind])
                toReplace.push(func.apply(params, [value]))
            params[keyToReplace] = toReplace;
        }
    for (const innerKey of Object.keys(params))
        if (params[innerKey] !== null && typeof params[innerKey] === 'object')
            deepParse(params[innerKey], key, func);
};

const parseWith = (func) => (...keys) => params => {
    for (const key of keys)
        deepParse(params, key, func);
    return params;
};

const parseNeo4jInts = parseWith(neo4jInt);

const parseIds = parseNeo4jInts;

const parseInts = parseWith(parseInt);

const parseFloats = parseWith(parseFloat);

const parseDates = parseWith(stringOrUnixTime => {
    const parsedInt = parseInt(stringOrUnixTime);
    stringOrUnixTime = parsedInt.toString() !== stringOrUnixTime.toString() || isNaN(parsedInt) ?
        stringOrUnixTime : parsedInt;
    return new Date(stringOrUnixTime);
});

const parseUnixTimes = parseWith(stringOrUnixTime => {
    const parsedInt = parseInt(stringOrUnixTime);
    if (parsedInt.toString() === stringOrUnixTime.toString())
        return neo4jInt(parsedInt);
    return neo4jInt(new Date(stringOrUnixTime).getTime());
});

export {Integer} from 'neo4j-driver/lib/v1/integer';
export {neo4jInt, logParams, parseWith, parseNeo4jInts, parseIds,
    parseInts, parseFloats, parseDates, parseUnixTimes};
<|endoftext|>