<commit_before>/**
 * Builds full page project browser
 */
'use strict';

var Treebeard = require('treebeard');   // Uses treebeard, installed as plugin
var $ = require('jquery');  // jQuery
var m = require('mithril'); // exposes mithril methods, useful for redraw etc.
var ProjectOrganizer = require('js/project-organizer');
var $osf = require('js/osfHelpers');

var LinkObject = function (type, data, label, index) {
    var self = this;
    self.id = getUID();
    self.type = type;
    self.data = data;
    self.label = label;
    self.index = index;  // For breadcrumbs to cut off when clicking parent level
    self.generateLink = function () {
        if (self.type === 'collection'){
            return $osf.apiV2Url(self.data.path, {
                    query : self.data.query
                }
            );
        }
        else if (self.type === 'tag') {
            return $osf.apiV2Url('nodes/', { query : {'filter[tags]' : self.data.tag , 'related_counts' : true}});
        }
        else if (self.type === 'name') {
            return $osf.apiV2Url('users/' + self.data.id + '/nodes/', { query : {'related_counts' : true}});
        }
        else if (self.type === 'node') {
            return $osf.apiV2Url('nodes/' + self.data.uid + '/children/', { query : { 'related_counts' : true }});
        }
        // If nothing
        throw new Error('Link could not be generated from linkObject data');
    };
    self.link = self.generateLink();
};

var Activity = function(date, text, meta) {
    this.date = date;
    this.text = text;
    this.meta = meta;
};

if (!window.fileBrowserCounter) {
    window.fileBrowserCounter = 0;
}
function getUID() {
    window.fileBrowserCounter = window.fileBrowserCounter + 1;
    return window.fileBrowserCounter;
}

/**
 * Initialize File Browser. Prepeares an option object within FileBrowser
 * @constructor
 */
var FileBrowser = {
    controller : function (options) {
        var self = this;
        self.wrapperSelector = options.wrapperSelector;  // For encapsulating each implementation of this component in multiple use
        self.currentLink = ''; // Save the link to compare if a new link is being requested and avoid multiple calls
        self.reload = m.prop(false); // Gets set to true when treebeard link changes and it needs to be redrawn
        self.nonLoadTemplate = m.prop(m('', 'Loading')); // Template for when data is not available or error happens

        // VIEW STATES
        self.showInfo = m.prop(false); // Show the info panel
        self.showSidebar = m.prop(true); // Show the links with collections etc. used in narrow views
        self.showCollectionMenu = m.prop(false); // Show hide ellipsis menu for collections
        self.collectionMenuObject = m.prop({item : {label:null}, x : 0, y : 0}); // Collection object to complete actions on menu

        // DEFAULT DATA -- to be switched with server response
        self.collections = [
            new LinkObject('collection', { path : 'users/me/nodes/', query : { 'related_counts' : true }, systemCollection : true}, 'All My Projects'),
            new LinkObject('collection', { path : 'registrations/', query : { 'related_counts' : true }, systemCollection : true}, 'All My Registrations'),
            new LinkObject('collection', { path : 'users/me/nodes/', query : { 'related_counts' : true }, systemCollection : false}, 'Everything'),
        ];
        self.breadcrumbs = m.prop([
            new LinkObject('collection', { path : 'users/me/nodes/', query : { 'related_counts' : true }, systemCollection : true}, 'All My Projects'),
        ]);
        self.nameFilters = [
            new LinkObject('name', { id : '8q36f', query : { 'related_counts' : true }}, '<NAME>'),
        ];
        self.tagFilters = [
            new LinkObject('tag', { tag : 'something', query : { 'related_counts' : true }}, 'Something Else'),
        ];
        self.data = m.prop([]);
        self.activityLogs = m.prop([
            new Activity('2015-08-19 01:34 PM', '<NAME> added a comment to Dashboard Redesign Proposal', {}),
        ]);

        self.updateFilesData = function(linkObject) {
            if (linkObject.link !== self.currentLink) {
                self.updateBreadcrumbs(linkObject);
                self.updateList(linkObject.link);
                self.currentLink = linkObject.link;
            }
            self.showSidebar(false);
        };

        // INFORMATION PANEL
        self.selected = m.prop([]);
        self.updateSelected = function(selectedList){
            // If single project is selected, get activity
            if(selectedList.length === 1){
                self.activityLogs([
                    new Activity('2015-08-19 01:34 PM', '<NAME> added a comment to Dashboard Redesign Proposal', {}),
                    new Activity('2015-08-19 01:34 PM', '<NAME> added a page to Dashboard Redesign Proposal wiki', {})
                ]);
            }
            self.selected(selectedList);
        };

        // USER FILTER
        self.activeFilter = m.prop(1);
        self.updateFilter = function(filter) {
            self.activeFilter(filter.data.id);
            self.updateFilesData(filter);
        };


        // Refresh the Grid
        self.updateList = function(url){
            var xhrconfig = function (xhr) {
                xhr.withCredentials = true;
            };
            m.request({method : 'GET', url : url, config : xhrconfig})
                .then(function(value){
                    value.data.map(function(item){
                        item.kind = 'folder';
                        item.uid = item.id;
                        item.name = item.attributes.title;
                        item.date = new $osf.FormattableDate(item.attributes.date_modified);

                        // TODO: Dummy data, remove this when api is ready
                        item.contributors = [{
                            id: '8q36f',
                            name : 'Dummy User'
                        }];
                    });
                self.data(value);
                self.reload(true);
            }, function(result){
                    self.nonLoadTemplate(m('.fb-error.text-danger', [
                        m('p','Projects couldn\'t load.'),
                        m('p', m('.btn.btn-link', { onclick : self.updateFilter.bind(null, self.collections[0])},' Reload \'All My Projects\''))
                    ]));
                    console.error(result);
                    throw new Error('Receiving initial data for File Browser failed. Please check your url');
                });
        };


        // BREADCRUMBS
        self.updateBreadcrumbs = function(linkObject){
            if (linkObject.type === 'collection' || linkObject.type === 'name' || linkObject.type === 'tag'){
                self.breadcrumbs([linkObject]);
                return;
            }
            if (linkObject.placement === 'breadcrumb'){
                self.breadcrumbs().splice(linkObject.index+1, self.breadcrumbs().length-linkObject.index-1);
                return;
            }
            if(linkObject.ancestors.length > 0){
                linkObject.ancestors.forEach(function(item){
                    var ancestorLink = new LinkObject('node', item.data, item.data.name);
                    self.breadcrumbs().push(ancestorLink);
                });
            }
            self.breadcrumbs().push(linkObject);
        }.bind(self);

        self.sidebarInit = function (element, isInit) {
            if(!isInit){
                $('[data-toggle="tooltip"]').tooltip();
            }
        };

        self.updateCollectionMenu = function (item, event) {
            var x = event.x - 4;
            var y = event.y-275;
            if (event.view.innerWidth < 767){
                x = x-115;
                y = y-80;
            }
            self.showCollectionMenu(true);
            self.collectionMenuObject({
                item : item,
                x : x,
                y : y
            });
        };
        self.init = function () {
            var loadUrl = $osf.apiV2Url(self.collections[0].data.path, {
                query : self.collections[0].data.query
            });
            self.updateList(loadUrl);<commit_msg>Add request for collection list<commit_after>/**
 * Builds full page project browser
 */
'use strict';

var Treebeard = require('treebeard');   // Uses treebeard, installed as plugin
var $ = require('jquery');  // jQuery
var m = require('mithril'); // exposes mithril methods, useful for redraw etc.
var ProjectOrganizer = require('js/project-organizer');
var $osf = require('js/osfHelpers');

var LinkObject = function (type, data, label, index) {
    var self = this;
    self.id = getUID();
    self.type = type;
    self.data = data;
    self.label = label;
    self.index = index;  // For breadcrumbs to cut off when clicking parent level
    self.generateLink = function () {
        if (self.type === 'collection'){
            return $osf.apiV2Url(self.data.path, {
                    query : self.data.query
                }
            );
        }
        else if (self.type === 'tag') {
            return $osf.apiV2Url('nodes/', { query : {'filter[tags]' : self.data.tag , 'related_counts' : true}});
        }
        else if (self.type === 'name') {
            return $osf.apiV2Url('users/' + self.data.id + '/nodes/', { query : {'related_counts' : true}});
        }
        else if (self.type === 'node') {
            return $osf.apiV2Url('nodes/' + self.data.uid + '/children/', { query : { 'related_counts' : true }});
        }
        // If nothing
        throw new Error('Link could not be generated from linkObject data');
    };
    self.link = self.generateLink();
};

var Activity = function(date, text, meta) {
    this.date = date;
    this.text = text;
    this.meta = meta;
};

if (!window.fileBrowserCounter) {
    window.fileBrowserCounter = 0;
}
function getUID() {
    window.fileBrowserCounter = window.fileBrowserCounter + 1;
    return window.fileBrowserCounter;
}

var xhrconfig = function (xhr) {
    xhr.withCredentials = true;
};

/**
 * Initialize File Browser. Prepeares an option object within FileBrowser
 * @constructor
 */
var FileBrowser = {
    controller : function (options) {
        var self = this;
        self.wrapperSelector = options.wrapperSelector;  // For encapsulating each implementation of this component in multiple use
        self.currentLink = ''; // Save the link to compare if a new link is being requested and avoid multiple calls
        self.reload = m.prop(false); // Gets set to true when treebeard link changes and it needs to be redrawn
        self.nonLoadTemplate = m.prop(m('', 'Loading')); // Template for when data is not available or error happens

        // VIEW STATES
        self.showInfo = m.prop(false); // Show the info panel
        self.showSidebar = m.prop(true); // Show the links with collections etc. used in narrow views
        self.showCollectionMenu = m.prop(false); // Show hide ellipsis menu for collections
        self.collectionMenuObject = m.prop({item : {label:null}, x : 0, y : 0}); // Collection object to complete actions on menu

        // Default system collections
        self.collections = [
            new LinkObject('collection', { path : 'users/me/nodes/', query : { 'related_counts' : true }, systemCollection : true}, 'All My Projects'),
            new LinkObject('collection', { path : 'registrations/', query : { 'related_counts' : true }, systemCollection : true}, 'All My Registrations'),
        ];

        var collectionsUrl = $osf.apiV2Url('collections/', { query : {'related_counts' : true}});
        m.request({method : 'GET', url : collectionsUrl, config : xhrconfig}).then(function(result){
            console.log(result);
           result.data.forEach(function(node){
               self.collections.push(new LinkObject('collection', { path : 'collections/' + node.id + '/', query : { 'related_counts' : true }, systemCollection : false}, node.attributes.title));
           });
        });

        self.breadcrumbs = m.prop([
            new LinkObject('collection', { path : 'users/me/nodes/', query : { 'related_counts' : true }, systemCollection : true}, 'All My Projects'),
        ]);
        self.nameFilters = [
            new LinkObject('name', { id : '8q36f', query : { 'related_counts' : true }}, '<NAME>'),
        ];
        self.tagFilters = [
            new LinkObject('tag', { tag : 'something', query : { 'related_counts' : true }}, 'Something Else'),
        ];
        self.data = m.prop([]);
        self.activityLogs = m.prop([
            new Activity('2015-08-19 01:34 PM', '<NAME> added a comment to Dashboard Redesign Proposal', {}),
        ]);

        self.updateFilesData = function(linkObject) {
            if (linkObject.link !== self.currentLink) {
                self.updateBreadcrumbs(linkObject);
                self.updateList(linkObject.link);
                self.currentLink = linkObject.link;
            }
            self.showSidebar(false);
        };

        // INFORMATION PANEL
        self.selected = m.prop([]);
        self.updateSelected = function(selectedList){
            // If single project is selected, get activity
            if(selectedList.length === 1){
                self.activityLogs([
                    new Activity('2015-08-19 01:34 PM', '<NAME> added a comment to Dashboard Redesign Proposal', {}),
                    new Activity('2015-08-19 01:34 PM', '<NAME> added a page to Dashboard Redesign Proposal wiki', {})
                ]);
            }
            self.selected(selectedList);
        };

        // USER FILTER
        self.activeFilter = m.prop(1);
        self.updateFilter = function(filter) {
            self.activeFilter(filter.data.id);
            self.updateFilesData(filter);
        };


        // Refresh the Grid
        self.updateList = function(url){
            m.request({method : 'GET', url : url, config : xhrconfig})
                .then(function(value){
                    value.data.map(function(item){
                        item.kind = 'folder';
                        item.uid = item.id;
                        item.name = item.attributes.title;
                        item.date = new $osf.FormattableDate(item.attributes.date_modified);

                        // TODO: Dummy data, remove this when api is ready
                        item.contributors = [{
                            id: '8q36f',
                            name : 'Dummy User'
                        }];
                    });
                self.data(value);
                self.reload(true);
            }, function(result){
                    self.nonLoadTemplate(m('.fb-error.text-danger', [
                        m('p','Projects couldn\'t load.'),
                        m('p', m('.btn.btn-link', { onclick : self.updateFilter.bind(null, self.collections[0])},' Reload \'All My Projects\''))
                    ]));
                    console.error(result);
                    throw new Error('Receiving initial data for File Browser failed. Please check your url');
                });
        };


        // BREADCRUMBS
        self.updateBreadcrumbs = function(linkObject){
            if (linkObject.type === 'collection' || linkObject.type === 'name' || linkObject.type === 'tag'){
                self.breadcrumbs([linkObject]);
                return;
            }
            if (linkObject.placement === 'breadcrumb'){
                self.breadcrumbs().splice(linkObject.index+1, self.breadcrumbs().length-linkObject.index-1);
                return;
            }
            if(linkObject.ancestors.length > 0){
                linkObject.ancestors.forEach(function(item){
                    var ancestorLink = new LinkObject('node', item.data, item.data.name);
                    self.breadcrumbs().push(ancestorLink);
                });
            }
            self.breadcrumbs().push(linkObject);
        }.bind(self);

        self.sidebarInit = function (element, isInit) {
            if(!isInit){
                $('[data-toggle="tooltip"]').tooltip();
                $('.fb-collections ul>li').droppable({
                    //accept: '.tb-td',
                    hoverClass: 'bg-color-hover',
                    drop: function( event, ui ) {
                       console.log('dropped', event, ui);
                    }
                });
            }
        };

        self.updateCollectionMenu = function (item, event) {
            var x = event.x - 4;
            var y = event.y-275;
            if (event.view.innerWidth < 767){
                x = x-115;
                y = y-80;
            }
            self.showCollectionMenu(true);
            self.collectionMenuObject({
                item : item,
                x : x,
                y : y
            });
        };
        self.init = function () {
            var loadUrl = $osf.apiV2Url(self.collections[0].data.path, {
                query : self.collections[0].data.query
            });
            self.updateList(loadUrl);
{'fraction_non_alphanumeric': 0.13185598790205316, 'fraction_numerical': 0.008317338451695458, 'mean_word_length': 1.7971368147063609, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5303425', 'n_tokens_mistral': 4808, 'n_tokens_neox': 4590, 'n_words': 1136}