<commit_before>/*
 * grunt-phantomas
 * https://github.com/stefanjudis/grunt-phantomas
 *
 * Copyright (c) 2013 stefan judis
 * Licensed under the MIT license.
 */

'use strict';

var Promise = require( 'bluebird' );
var fs      = Promise.promisifyAll( require( 'fs' ) );
var path    = Promise.promisifyAll( require( 'path' ) );

var ASSETS_PATH = path.resolve(
                    __dirname, '../public/'
                  );

/**
 * Path to the Phantomas executable
 * @type {String}
 */
var PHANTOMAS_PATH = path.resolve(
                        __dirname, '../../node_modules/.bin/phantomas'
                      );

/**
 * Path to index template
 * @type {String}
 */
var TEMPLATE_FILE = path.resolve(
                      __dirname,
                      '../tpl/index.tpl'
                    );

/**
 * Constructor for Phantomas
 *
 * @param {Object}   grunt   grunt
 * @param {Object}   options options
 * @param {Function} done    callback to be called when everything is done
 *                           or an error appeared
 *
 * @tested
 */
var Phantomas = function( grunt, options, done ) {
  this.grunt    = grunt;
  this.options  = options;
  this.done     = done;
  this.dataPath = path.normalize( this.options.indexPath + 'data/' );
};

/**
 * Copy all needed assets from 'tasks/public'
 * to specified index path
 *
 * - phantomas.css
 */
Phantomas.prototype.copyAssets = function() {
  this.grunt.log.subhead( 'PHANTOMAS ASSETS COPYING STARTED.' );

  return new Promise( function( resolve ) {
    if ( !fs.existsSync( this.options.indexPath + '/public' ) ) {
    fs.mkdirSync( this.options.indexPath + '/public' );
    }

    this.copyStyles();
    this.copyScripts();

    resolve();
  }.bind( this ) );
};

/**
 * Copy script files and create needed folders
 *
 * - d3.min.js
 */
Phantomas.prototype.copyScripts = function() {
  if ( !fs.existsSync( this.options.indexPath + '/public/scripts' ) ) {
    fs.mkdirSync( this.options.indexPath + '/public/scripts' );
  }

  var d3 = fs.readFileSync(
    path.normalize( ASSETS_PATH + '/scripts/d3.min.js' )
  );

  fs.writeFileSync(
    path.normalize( this.options.indexPath + '/public/scripts/d3.min.js' ),
    d3
  );

  this.grunt.log.ok(
    'Phantomas copied asset to \'' + this.options.indexPath + 'public/scripts/d3.min.js\'.'
  );

  var phantomas = fs.readFileSync(
    path.normalize( ASSETS_PATH + '/scripts/phantomas.min.js' )
  );

  fs.writeFileSync(
    path.normalize( this.options.indexPath + '/public/scripts/phantomas.min.js' ),
    phantomas
  );

  this.grunt.log.ok(
    'Phantomas copied asset to \'' + this.options.indexPath + 'public/scripts/phantomas.min.js\'.'
  );
};

/**
 * Copy styles file and create needed folders
 */
Phantomas.prototype.copyStyles = function() {
  if ( !fs.existsSync( this.options.indexPath + '/public/styles' ) ) {
    fs.mkdirSync( this.options.indexPath + '/public/styles' );
  }

  var styles = fs.readFileSync(
    path.normalize( ASSETS_PATH + '/styles/phantomas.css' )
  );

  fs.writeFileSync(
    path.normalize( this.options.indexPath + '/public/styles/phantomas.css' ),
    styles
  );

  this.grunt.log.ok(
    'Phantomas copied asset to \'' + this.options.indexPath + 'public/styles/phantomas.css\'.'
  );
};

/**
 * Write phantomas result to json file
 *
 * @param  {String}  result phantomas result
 * @return {Promise}        Promise
 *
 * @tested
 */
Phantomas.prototype.createDataJson = function( result ) {
  return new Promise( function( resolve ) {
    fs.writeFileAsync(
      this.dataPath + ( +new Date() ) + '.json',
      result
    )
      .then( resolve );
  }.bind( this ) );
};

/**
 * Create data directory in index path
 * if it doesn't exist yet
 *
 * TODO -> put it together with 'createDataDirectory'
 *
 * @return {Promise} Promise
 *
 * @tested
 */
Phantomas.prototype.createDataDirectory = function() {
  return new Promise( function( resolve ) {
    var exists = fs.existsSync( this.dataPath );

    if ( exists ) {
      resolve();
    } else {
      fs.mkdirSync(
        path.normalize(
          this.options.indexPath + 'data'
        )
      );

      resolve();
    }
  }.bind( this ) );
};

/**
 * Create index directory to make sure
 * files are writable according to set
 * indexPath
 *
 * TODO -> put it together with 'createDataDirectory'
 *
 * @return {Promise} Promise
 */
Phantomas.prototype.createIndexDirectory = function() {
  return new Promise( function( resolve ) {
    var exists = fs.existsSync( this.options.indexPath );

    if ( exists ) {
      resolve();
    } else {
      fs.mkdirSync(
        path.normalize(
          this.options.indexPath
        )
      );

      resolve();
    }
  }.bind( this ) );
}

/**
 * Write final index.html file and
 * handle all metrics
 *
 * @param  {Array}   files content of all metric files
 * @return {Promise}       Promise
 */
Phantomas.prototype.createIndexHtml = function( files ) {
  return new Promise( function( resolve ) {
    this.grunt.log.subhead( 'PHANTOMAS index.html WRITING STARTED.' );

    this.grunt.file.write(
      this.options.indexPath + 'index.html',
      this.grunt.template.process(
        this.grunt.file.read( TEMPLATE_FILE ),
        { data : {
          results : files
        } }
      )
    );

    this.grunt.log.ok(
      'Phantomas created new \'index.html\' at \'' + this.options.indexPath + '\'.'
    );

    resolve();

  }.bind( this ) );
};

/**
 * Simple getter to build up command line
 * options for process spawn and to have it
 * on a clear place
 *
 * @tested
 */
Phantomas.prototype.getPhantomasProcessArguments = function() {
  return [
    '--url',
    this.options.url,
    '--format',
    'json'
  ].concat( this.options.raw );
};

/**
 * Handle the result of the given phantomas
 * process call and work with it
 *
 * - write json to disk to keep track of progress
 * - create index html
 *
 * @param  {String} result result
 */
Phantomas.prototype.handleData = function( result ) {
  // check if data directory already exists
  // if not create it
  this.createIndexDirectory().bind( this )
      .then( this.createDataDirectory )
      // write new json file with metrics data
      .then( function() {
        this.createDataJson( result );
      } )
      // write a new index.html with all data json
      // files injected
      .then( this.readMetricsFiles )
      // write html file and produce
      // nice graphics
      .then( this.createIndexHtml )
      // copy all asset files over to
      // wished index path
      .then( this.copyAssets )
      // yeah we're done
      .then( this.showSuccessMessage )
      // catch general bluebird error
      .catch( Promise.RejectionError, function ( e ) {
          console.error( 'unable to write file, because: ', e.message );
      } )
      // catch unknown error
      .catch( function( e ) {
        console.log( ':/' );
        console.log( e );
      } )
      .done();
};

/**
 * General function to start the whole thingy
 */
Phantomas.prototype.kickOff = function() {
  this.grunt.log.subhead( 'PHANTOMAS SYSTEM CALL STARTED' );

  this.grunt.log.verbose.writeln(
    'Executing phantoms with following parameters:\n' +
    this.getPhantomasProcessArguments().join( ' ' )
  );

  this.grunt.util.spawn( {
    cmd  : PHANTOMAS_PATH,
    args : this.getPhantomasProcessArguments()
  }, function( error, result ) {
    if ( error ) {
      this.grunt.fatal( error );
    }

    this.grunt.log.ok( 'Phantomas executation successful.');

    this.handleData( result );
  }.bind( this ) );
};

/**
 * Handle the path of a metrics file and read it
 *
 * @param  {String} file file path to metrics file
 * @return {Promise}     Promise
 *
 * @tested
 */
Phantomas.prototype.readMetricsFile = function( file ) {
  return new Promise( function( resolve, reject ) {
    fs.readFileAsync(
      this.dataPath + file,
      { encoding : 'utf8'}
    ).bind( this )
      .then( function( data ) {
        try {
          data = JSON.parse( data );
        } catch( e ) {
          // if it's not valid json
          // let's fail
          reject( e );
        }
        // set internal timestamp to work with it
        // on frontend side later on
        data.timestamp = +file.replace( /\.json/gi, '' );

        resolve( data );
      } );
  }.bind( this ) );
};

/**
 * Get data of all metrics files
 * included in data folder
 *
 * @return {Promise} Promise
 */
Phantomas.prototype.readMetricsFiles = function() {
  return new Promise( function( resolve ) {
    fs.readdirAsync( this.dataPath ).bind( this )
      .then( function( files ) {
        files = files.filter( function( file ) {
          return file.match( /\.json/gi );
        } );

        files = files.map( function( file ) {
            return this.readMetricsFile( file );
        }, this );

        Promise.all( files ).bind( this )
          .then( resolve );
      } );
  }.bind( this ) );
};

/**
 * Show final message and call grunt task callback afterwards
 *
 * @tested
 */
Phantomas.prototype.showSuccessMessage = function() {
  this.grunt.log.subhead( 'FINISHED PHANTOMAS.' );

  this.done();
};

module.exports = Phantomas;
<commit_msg>jshint<commit_after>/*
 * grunt-phantomas
 * https://github.com/stefanjudis/grunt-phantomas
 *
 * Copyright (c) 2013 stefan judis
 * Licensed under the MIT license.
 */

'use strict';

var Promise = require( 'bluebird' );
var fs      = Promise.promisifyAll( require( 'fs' ) );
var path    = Promise.promisifyAll( require( 'path' ) );

var ASSETS_PATH = path.resolve(
                    __dirname, '../public/'
                  );

/**
 * Path to the Phantomas executable
 * @type {String}
 */
var PHANTOMAS_PATH = path.resolve(
                        __dirname, '../../node_modules/.bin/phantomas'
                      );

/**
 * Path to index template
 * @type {String}
 */
var TEMPLATE_FILE = path.resolve(
                      __dirname,
                      '../tpl/index.tpl'
                    );

/**
 * Constructor for Phantomas
 *
 * @param {Object}   grunt   grunt
 * @param {Object}   options options
 * @param {Function} done    callback to be called when everything is done
 *                           or an error appeared
 *
 * @tested
 */
var Phantomas = function( grunt, options, done ) {
  this.grunt    = grunt;
  this.options  = options;
  this.done     = done;
  this.dataPath = path.normalize( this.options.indexPath + 'data/' );
};

/**
 * Copy all needed assets from 'tasks/public'
 * to specified index path
 *
 * - phantomas.css
 */
Phantomas.prototype.copyAssets = function() {
  this.grunt.log.subhead( 'PHANTOMAS ASSETS COPYING STARTED.' );

  return new Promise( function( resolve ) {
    if ( !fs.existsSync( this.options.indexPath + '/public' ) ) {
    fs.mkdirSync( this.options.indexPath + '/public' );
    }

    this.copyStyles();
    this.copyScripts();

    resolve();
  }.bind( this ) );
};

/**
 * Copy script files and create needed folders
 *
 * - d3.min.js
 */
Phantomas.prototype.copyScripts = function() {
  if ( !fs.existsSync( this.options.indexPath + '/public/scripts' ) ) {
    fs.mkdirSync( this.options.indexPath + '/public/scripts' );
  }

  var d3 = fs.readFileSync(
    path.normalize( ASSETS_PATH + '/scripts/d3.min.js' )
  );

  fs.writeFileSync(
    path.normalize( this.options.indexPath + '/public/scripts/d3.min.js' ),
    d3
  );

  this.grunt.log.ok(
    'Phantomas copied asset to \'' + this.options.indexPath + 'public/scripts/d3.min.js\'.'
  );

  var phantomas = fs.readFileSync(
    path.normalize( ASSETS_PATH + '/scripts/phantomas.min.js' )
  );

  fs.writeFileSync(
    path.normalize( this.options.indexPath + '/public/scripts/phantomas.min.js' ),
    phantomas
  );

  this.grunt.log.ok(
    'Phantomas copied asset to \'' + this.options.indexPath + 'public/scripts/phantomas.min.js\'.'
  );
};

/**
 * Copy styles file and create needed folders
 */
Phantomas.prototype.copyStyles = function() {
  if ( !fs.existsSync( this.options.indexPath + '/public/styles' ) ) {
    fs.mkdirSync( this.options.indexPath + '/public/styles' );
  }

  var styles = fs.readFileSync(
    path.normalize( ASSETS_PATH + '/styles/phantomas.css' )
  );

  fs.writeFileSync(
    path.normalize( this.options.indexPath + '/public/styles/phantomas.css' ),
    styles
  );

  this.grunt.log.ok(
    'Phantomas copied asset to \'' + this.options.indexPath + 'public/styles/phantomas.css\'.'
  );
};

/**
 * Write phantomas result to json file
 *
 * @param  {String}  result phantomas result
 * @return {Promise}        Promise
 *
 * @tested
 */
Phantomas.prototype.createDataJson = function( result ) {
  return new Promise( function( resolve ) {
    fs.writeFileAsync(
      this.dataPath + ( +new Date() ) + '.json',
      result
    )
      .then( resolve );
  }.bind( this ) );
};

/**
 * Create data directory in index path
 * if it doesn't exist yet
 *
 * TODO -> put it together with 'createDataDirectory'
 *
 * @return {Promise} Promise
 *
 * @tested
 */
Phantomas.prototype.createDataDirectory = function() {
  return new Promise( function( resolve ) {
    var exists = fs.existsSync( this.dataPath );

    if ( exists ) {
      resolve();
    } else {
      fs.mkdirSync(
        path.normalize(
          this.options.indexPath + 'data'
        )
      );

      resolve();
    }
  }.bind( this ) );
};

/**
 * Create index directory to make sure
 * files are writable according to set
 * indexPath
 *
 * TODO -> put it together with 'createDataDirectory'
 *
 * @return {Promise} Promise
 */
Phantomas.prototype.createIndexDirectory = function() {
  return new Promise( function( resolve ) {
    var exists = fs.existsSync( this.options.indexPath );

    if ( exists ) {
      resolve();
    } else {
      fs.mkdirSync(
        path.normalize(
          this.options.indexPath
        )
      );

      resolve();
    }
  }.bind( this ) );
};

/**
 * Write final index.html file and
 * handle all metrics
 *
 * @param  {Array}   files content of all metric files
 * @return {Promise}       Promise
 */
Phantomas.prototype.createIndexHtml = function( files ) {
  return new Promise( function( resolve ) {
    this.grunt.log.subhead( 'PHANTOMAS index.html WRITING STARTED.' );

    this.grunt.file.write(
      this.options.indexPath + 'index.html',
      this.grunt.template.process(
        this.grunt.file.read( TEMPLATE_FILE ),
        { data : {
          results : files
        } }
      )
    );

    this.grunt.log.ok(
      'Phantomas created new \'index.html\' at \'' + this.options.indexPath + '\'.'
    );

    resolve();

  }.bind( this ) );
};

/**
 * Simple getter to build up command line
 * options for process spawn and to have it
 * on a clear place
 *
 * @tested
 */
Phantomas.prototype.getPhantomasProcessArguments = function() {
  return [
    '--url',
    this.options.url,
    '--format',
    'json'
  ].concat( this.options.raw );
};

/**
 * Handle the result of the given phantomas
 * process call and work with it
 *
 * - write json to disk to keep track of progress
 * - create index html
 *
 * @param  {String} result result
 */
Phantomas.prototype.handleData = function( result ) {
  // check if data directory already exists
  // if not create it
  this.createIndexDirectory().bind( this )
      .then( this.createDataDirectory )
      // write new json file with metrics data
      .then( function() {
        this.createDataJson( result );
      } )
      // write a new index.html with all data json
      // files injected
      .then( this.readMetricsFiles )
      // write html file and produce
      // nice graphics
      .then( this.createIndexHtml )
      // copy all asset files over to
      // wished index path
      .then( this.copyAssets )
      // yeah we're done
      .then( this.showSuccessMessage )
      // catch general bluebird error
      .catch( Promise.RejectionError, function ( e ) {
          console.error( 'unable to write file, because: ', e.message );
      } )
      // catch unknown error
      .catch( function( e ) {
        console.log( ':/' );
        console.log( e );
      } )
      .done();
};

/**
 * General function to start the whole thingy
 */
Phantomas.prototype.kickOff = function() {
  this.grunt.log.subhead( 'PHANTOMAS SYSTEM CALL STARTED' );

  this.grunt.log.verbose.writeln(
    'Executing phantoms with following parameters:\n' +
    this.getPhantomasProcessArguments().join( ' ' )
  );

  this.grunt.util.spawn( {
    cmd  : PHANTOMAS_PATH,
    args : this.getPhantomasProcessArguments()
  }, function( error, result ) {
    if ( error ) {
      this.grunt.fatal( error );
    }

    this.grunt.log.ok( 'Phantomas executation successful.');

    this.handleData( result );
  }.bind( this ) );
};

/**
 * Handle the path of a metrics file and read it
 *
 * @param  {String} file file path to metrics file
 * @return {Promise}     Promise
 *
 * @tested
 */
Phantomas.prototype.readMetricsFile = function( file ) {
  return new Promise( function( resolve, reject ) {
    fs.readFileAsync(
      this.dataPath + file,
      { encoding : 'utf8'}
    ).bind( this )
      .then( function( data ) {
        try {
          data = JSON.parse( data );
        } catch( e ) {
          // if it's not valid json
          // let's fail
          reject( e );
        }
        // set internal timestamp to work with it
        // on frontend side later on
        data.timestamp = +file.replace( /\.json/gi, '' );

        resolve( data );
      } );
  }.bind( this ) );
};

/**
 * Get data of all metrics files
 * included in data folder
 *
 * @return {Promise} Promise
 */
Phantomas.prototype.readMetricsFiles = function() {
  return new Promise( function( resolve ) {
    fs.readdirAsync( this.dataPath ).bind( this )
      .then( function( files ) {
        files = files.filter( function( file ) {
          return file.match( /\.json/gi );
        } );

        files = files.map( function( file ) {
            return this.readMetricsFile( file );
        }, this );

        Promise.all( files ).bind( this )
          .then( resolve );
      } );
  }.bind( this ) );
};

/**
 * Show final message and call grunt task callback afterwards
 *
 * @tested
 */
Phantomas.prototype.showSuccessMessage = function() {
  this.grunt.log.subhead( 'FINISHED PHANTOMAS.' );

  this.done();
};

module.exports = Phantomas;
<|endoftext|>


<commit_before>/*
 * grunt-plugin-pandoc
 * https://github.com/eaperson/grunt-plugin-pandoc
 *
 * Copyright (c) 2015 Erik Pearson
 * Licensed under the MIT license.
 */
module.exports = function (grunt) {
    'use strict';

    var childproc = require('child_process');

    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('plugin_pandoc', 'Grunt plugin for running pandoc', function () {
        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options({
            punctuation: '.',
            separator: ', '
        });

        // Iterate over all specified file groups.
        this.files.forEach(function (fileGroup) {
            // Concat specified files.
            var src = fileGroup.src.filter(function (filepath) {
                // Warn on and remove invalid source files (if nonull was set).
                if (!grunt.file.exists(filepath)) {
                    grunt.log.warn('Source file "' + filepath + '" not found.');
                    return false;
                } else {
                    return true;
                }
            }).forEach(function (filepath) {
                grunt.log.writeln('Input file: ' + filepath);
                grunt.log.writeln('Dest dir: ' + fileGroup.dest);
            });

//                map(function (filepath) {
//                // Read file source.
//                return grunt.file.read(filepath);
//            }).join(grunt.util.normalizelf(options.separator));

            // Handle options.
            //src += options.punctuation;

            // Write the destination file.
            // grunt.file.write(f.dest, src);

            // Print a success message.
            // grunt.log.writeln('File "' + fileGroup.dest + '" created.');
            grunt.log.writeln('File group ' + fileGroup.dest + 'done.');
        });
    });

};
<commit_msg>adjust for cwd<commit_after>/*
 * grunt-plugin-pandoc
 * https://github.com/eaperson/grunt-plugin-pandoc
 *
 * Copyright (c) 2015 Erik Pearson
 * Licensed under the MIT license.
 */
module.exports = function (grunt) {
    'use strict';

    var childproc = require('child_process');

    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('plugin_pandoc', 'Grunt plugin for running pandoc', function () {
        // Merge task-specific and/or target-specific options with these defaults.
        var options = this.options({
            punctuation: '.',
            separator: ', '
        });

        // Iterate over all specified file groups.
        this.files.forEach(function (fileGroup) {
            // Concat specified files.
            var src = fileGroup.src.filter(function (filepath) {
                // Warn on and remove invalid source files (if nonull was set).
                var realFilepath = fileGroup.cwd ? [fileGroup.cwd, filepath].join('/') : filepath;
                if (!grunt.file.exists(realFilepath)) {
                    grunt.log.warn('Source file "' + filepath + '" not found.');
                    return false;
                } else {
                    return true;
                }
            }).forEach(function (realFilepath) {
                grunt.log.writeln('Input file: ' + realFilepath);
                grunt.log.writeln('Dest dir: ' + fileGroup.dest);
            });

//                map(function (filepath) {
//                // Read file source.
//                return grunt.file.read(filepath);
//            }).join(grunt.util.normalizelf(options.separator));

            // Handle options.
            //src += options.punctuation;

            // Write the destination file.
            // grunt.file.write(f.dest, src);

            // Print a success message.
            // grunt.log.writeln('File "' + fileGroup.dest + '" created.');
            grunt.log.writeln('File group ' + fileGroup.dest + 'done.');
        });
    });

};
<|endoftext|>


<commit_before>/*
 * Copyright 2015-2016 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html} from "lit";
import {classMap} from "lit/directives/class-map.js";
import UtilsNew from "../../../core/utilsNew.js";
import "./variant-interpreter-browser-rd.js";
import "./variant-interpreter-browser-cancer.js";
import "./variant-interpreter-browser-rearrangement.js";

class VariantInterpreterBrowser extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            cellbaseClient: {
                type: Object
            },
            clinicalAnalysis: {
                type: Object
            },
            clinicalAnalysisId: {
                type: String
            },
            settings: {
                type: Object
            }
            // query: {
            //     type: Object
            // },
            // config: {
            //     type: Object
            // }
        };
    }

    _init() {
        this._prefix = UtilsNew.randomString(8);

        this.activeTab = {"VariantBrowser": true}; // default active tab
        this.showRearrangementBrowser = true;
    }

    updated(changedProperties) {
        if (changedProperties.has("settings")) {
            this.settingsObserver();
        }
        if (changedProperties.has("clinicalAnalysis")) {
            this.clinicalAnalysisObserver();
        }
        if (changedProperties.has("clinicalAnalysisId")) {
            this.clinicalAnalysisIdObserver();
        }
    }

    settingsObserver() {
        if (this.clinicalAnalysis) {
            const type = this.clinicalAnalysis.type.toUpperCase();
            if (["SINGLE", "FAMILY", "CANCER"].includes(type)) {
                this._browserSettings = this.settings.browsers[type];
            } else {
                console.error("Unexpected Case Type");
            }
        }
        this.requestUpdate();
    }

    clinicalAnalysisObserver() {
        if (this.clinicalAnalysis) {
            switch (this.clinicalAnalysis.type.toUpperCase()) {
                case "SINGLE":
                case "FAMILY":
                    this._sample = this.clinicalAnalysis.proband.samples[0];
                    this.activeTab = {"VariantBrowser": true};
                    break;
                case "CANCER":
                    this._somaticSample = this.clinicalAnalysis.proband.samples.find(s => s.somatic);
                    this._germlineSample = this.clinicalAnalysis.proband.samples.find(s => !s.somatic);
                    this.activeTab = {"CancerSomaticVariantBrowser": true};
                    break;
            }
        }
        this.requestUpdate();
    }

    clinicalAnalysisIdObserver() {
        if (this.opencgaSession && this.clinicalAnalysisId) {
            this.opencgaSession.opencgaClient.clinical().info(this.clinicalAnalysisId, {study: this.opencgaSession.study.fqn})
                .then(response => {
                    this.clinicalAnalysis = response.responses[0].results[0];
                    this.clinicalAnalysisObserver();
                })
                .catch(response => {
                    console.error("An error occurred fetching clinicalAnalysis: ", response);
                });
        }
    }

    _changeTab(e) {
        e.preventDefault();

        const tabId = e.currentTarget.dataset.id;
        const navTabs = $(`#${this._prefix}QcTabs > .nav-tabs > .content-pills`, this);
        const contentTabs = $(`#${this._prefix}QcTabs > .content-tab-wrapper > .tab-pane`, this);
        if (!e.currentTarget?.className?.split(" ")?.includes("disabled")) {
            navTabs.removeClass("active");
            contentTabs.removeClass("active");
            $("#" + this._prefix + tabId).addClass("active");
            for (const tab in this.activeTab) {
                if (Object.prototype.hasOwnProperty.call(this.activeTab, tab)) {
                    this.activeTab[tab] = false;
                }
            }
            this.activeTab[tabId] = true;
            this.requestUpdate();
        }
    }

    onClinicalAnalysisUpdate(e) {
        this.dispatchEvent(new CustomEvent("clinicalAnalysisUpdate", {
            detail: {
                clinicalAnalysis: e.detail.clinicalAnalysis
            },
            bubbles: true,
            composed: true
        }));
    }

    render() {
        // Check Project exists
        if (!this.opencgaSession.project) {
            return html`

No public projects available to browse. Please login to continue

            `;
        }

        if (!this.clinicalAnalysis) {
            return html`

No Case found

`;
        }

        if (!this.clinicalAnalysis.proband?.samples?.length) {
            return html`

 No sample available for Proband

            `;
        }

        return this.clinicalAnalysis ? html`

                        ${this.clinicalAnalysis.type.toUpperCase() === "SINGLE" || this.clinicalAnalysis.type.toUpperCase() === "FAMILY" ?
                            html`

                                    Variant Browser

` :
                            null
                        }

                        ${this.clinicalAnalysis.type.toUpperCase() === "CANCER" ?
                            html`

                                    Somatic Variant Browser

                                ${this.showRearrangementBrowser ?
                                    html`

                                            Somatic Rearrangement Variant Browser

` :
                                    null
                                }
                                ${this._germlineSample ?
                                    html`

                                            Germline Variant Browser

` :
                                    null
                                }` :
                            null
                        }

                    ${this.clinicalAnalysis.type.toUpperCase() === "SINGLE" || this.clinicalAnalysis.type.toUpperCase() === "FAMILY" ?
                        html`

                                <tool-header title="Variant Browser - ${this._sample?.id}" class="bg-white"></tool-header>
                                <variant-interpreter-browser-rd .opencgaSession="${this.opencgaSession}"
                                                                .clinicalAnalysis="${this.clinicalAnalysis}"
                                                                .query="${this.query}"
                                                                .cellbaseClient="${this.cellbaseClient}"
                                                                .settings="${this._browserSettings}"
                                                                @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}"
                                                                @samplechange="${this.onSampleChange}">
                                </variant-interpreter-browser-rd>

` :
                        null
                    }
                    ${this.clinicalAnalysis.type.toUpperCase() === "CANCER" ?
                        html`

                                <tool-header title="Somatic Variant Browser - ${this._somaticSample?.id}" class="bg-white"></tool-header>
                                <variant-interpreter-browser-cancer .opencgaSession="${this.opencgaSession}"
                                                                    .clinicalAnalysis="${this.clinicalAnalysis}"
                                                                    .query="${this.query}"
                                                                    .cellbaseClient="${this.cellbaseClient}"
                                                                    .settings="${this._browserSettings}"
                                                                    @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}">
                                </variant-interpreter-browser-cancer>

                            ${this.showRearrangementBrowser ?
                                html`

                                        <tool-header title="Somatic Rearrangement Variant Browser - ${this._somaticSample?.id}" class="bg-white"></tool-header>
                                        <variant-interpreter-browser-rearrangement .opencgaSession="${this.opencgaSession}"
                                                                                .clinicalAnalysis="${this.clinicalAnalysis}"
                                                                                .query="${this.query}"
                                                                                .cellbaseClient="${this.cellbaseClient}"
                                                                                @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}">
                                        </variant-interpreter-browser-rearrangement>

` :
                                null
                            }

                            ${false && this._germlineSample ? // Check Germline sample exist
                                html`

                                        <tool-header title="Germline Variant Browser - ${this._germlineSample?.id}" class="bg-white"></tool-header>
                                        <variant-interpreter-browser-rd .opencgaSession="${this.opencgaSession}"
                                                                        .clinicalAnalysis="${this.clinicalAnalysis}"
                                                                        .query="${this.query}"
                                                                        .cellbaseClient="${this.cellbaseClient}"
                                                                        .settings="${this._config}"
                                                                        @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}"
                                                                        @samplechange="${this.onSampleChange}">
                                        </variant-interpreter-browser-rd>

` :
                                null
                            }
                            ` :
                        null
                    }

        ` : null;
    }

}

customElements.define("variant-interpreter-browser", VariantInterpreterBrowser);
<commit_msg>wc: migrate variant interpreter browser to detail-tabs (#259)<commit_after>/*
 * Copyright 2015-2016 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html} from "lit";
import UtilsNew from "../../../core/utilsNew.js";
import LitUtils from "../../commons/utils/lit-utils.js";
import "./variant-interpreter-browser-rd.js";
import "./variant-interpreter-browser-cancer.js";
import "./variant-interpreter-browser-rearrangement.js";
import "../../commons/view/detail-tabs.js";

class VariantInterpreterBrowser extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            cellbaseClient: {
                type: Object
            },
            clinicalAnalysis: {
                type: Object
            },
            clinicalAnalysisId: {
                type: String
            },
            settings: {
                type: Object
            }
            // query: {
            //     type: Object
            // },
            // config: {
            //     type: Object
            // }
        };
    }

    _init() {
        this._prefix = UtilsNew.randomString(8);

        this.showRearrangementBrowser = true;
        this._config = this.getDefaultConfig();
    }

    update(changedProperties) {
        if (changedProperties.has("settings")) {
            this.settingsObserver();
        }

        if (changedProperties.has("clinicalAnalysis")) {
            this.clinicalAnalysisObserver();
        }

        if (changedProperties.has("clinicalAnalysisId")) {
            this.clinicalAnalysisIdObserver();
        }

        super.update(changedProperties);
    }

    settingsObserver() {
        if (this.clinicalAnalysis) {
            const type = this.clinicalAnalysis.type.toUpperCase();
            if (["SINGLE", "FAMILY", "CANCER"].includes(type)) {
                this._browserSettings = this.settings.browsers[type];
            } else {
                console.error("Unexpected Case Type");
            }
        }
        this.requestUpdate();
    }

    clinicalAnalysisObserver() {
        if (this.clinicalAnalysis) {
            switch (this.clinicalAnalysis.type.toUpperCase()) {
                case "SINGLE":
                case "FAMILY":
                    this._sample = this.clinicalAnalysis.proband.samples[0];
                    break;
                case "CANCER":
                    this._somaticSample = this.clinicalAnalysis.proband.samples.find(s => s.somatic);
                    this._germlineSample = this.clinicalAnalysis.proband.samples.find(s => !s.somatic);
                    break;
            }
            this._config = this.getDefaultConfig();
        }
        this.requestUpdate();
    }

    clinicalAnalysisIdObserver() {
        if (this.opencgaSession && this.clinicalAnalysisId) {
            this.opencgaSession.opencgaClient.clinical().info(this.clinicalAnalysisId, {study: this.opencgaSession.study.fqn})
                .then(response => {
                    this.clinicalAnalysis = response.responses[0].results[0];
                    this.clinicalAnalysisObserver();
                })
                .catch(response => {
                    console.error("An error occurred fetching clinicalAnalysis: ", response);
                });
        }
    }

    onClinicalAnalysisUpdate(e) {
        LitUtils.dispatchEventCustom(this, "clinicalAnalysisUpdate", null, null, {
            clinicalAnalysis: e.detail.clinicalAnalysis,
        });
    }

    render() {
        // Check if project exists
        if (!this.opencgaSession?.project) {
            return html`

No public projects available to browse. Please login to continue

            `;
        }

        if (!this.clinicalAnalysis) {
            return html`

No Case found

`;
        }

        if (!this.clinicalAnalysis.proband?.samples?.length) {
            return html`

                     No sample available for Proband

            `;
        }

        return html`
            <detail-tabs
                .data="${this.clinicalAnalysis}"
                .config="${this._config}"
                .opencgaSession="${this.opencgaSession}">
            </detail-tabs>
        `;
    }

    getDefaultConfig() {
        const items = [];

        // Check for clinicalAnalysis
        if (this.clinicalAnalysis) {
            const type = this.clinicalAnalysis.type.toUpperCase();

            if (type === "SINGLE" || type === "FAMILY") {
                items.push({
                    id: "variant-browser",
                    name: "Variant Browser",
                    active: true,
                    render: (clinicalAnalysis, active, opencgaSession) => {
                        return html`

                                <tool-header title="Variant Browser - ${this._sample?.id}" class="bg-white"></tool-header>
                                <variant-interpreter-browser-rd
                                    .opencgaSession="${opencgaSession}"
                                    .clinicalAnalysis="${clinicalAnalysis}"
                                    .query="${this.query}"
                                    .cellbaseClient="${this.cellbaseClient}"
                                    .settings="${this._browserSettings}"
                                    @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}"
                                    @samplechange="${this.onSampleChange}">
                                </variant-interpreter-browser-rd>

                        `;
                    },
                });
            } else if (type === "CANCER") {

                // Add somatic variant browser
                items.push({
                    id: "cancer-somatic-variant-browser",
                    name: "Somatic Variant Browser",
                    active: true,
                    render: (clinicalAnalysis, active, opencgaSession) => {
                        return html`

                                <tool-header title="Somatic Variant Browser - ${this._somaticSample?.id}" class="bg-white"></tool-header>
                                <variant-interpreter-browser-cancer
                                    .opencgaSession="${opencgaSession}"
                                    .clinicalAnalysis="${clinicalAnalysis}"
                                    .query="${this.query}"
                                    .cellbaseClient="${this.cellbaseClient}"
                                    .settings="${this._browserSettings}"
                                    @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}">
                                </variant-interpreter-browser-cancer>

                        `;
                    },
                });

                // Check for adding rearrangements variant browser
                if (this.showRearrangementBrowser) {
                    items.push({
                        id: "cancer-somatic-rearrangement-variant-browser",
                        name: "Somatic Rearrangement Variant Browser",
                        render: (clinicalAnalysis, active, opencgaSession) => {
                            return html`

                                    <tool-header title="Somatic Rearrangement Variant Browser - ${this._somaticSample?.id}" class="bg-white"></tool-header>
                                    <variant-interpreter-browser-rearrangement
                                        .opencgaSession="${opencgaSession}"
                                        .clinicalAnalysis="${clinicalAnalysis}"
                                        .query="${this.query}"
                                        .cellbaseClient="${this.cellbaseClient}"
                                        @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}">
                                    </variant-interpreter-browser-rearrangement>

                            `;
                        },
                    });
                }

                // Check for adding germline browser
                // TODO: this has been disabled by default
                // eslint-disable-next-line no-constant-condition
                if (false && this._germlineSample) {
                    items.push({
                        id: "cancer-germline-variant-browser",
                        name: "Germline Variant Browser",
                        render: (clinicalAnalysis, active, opencgaSession) => {
                            return html`

                                    <tool-header title="Germline Variant Browser - ${this._germlineSample?.id}" class="bg-white"></tool-header>
                                    <variant-interpreter-browser-rd
                                        .opencgaSession="${opencgaSession}"
                                        .clinicalAnalysis="${clinicalAnalysis}"
                                        .query="${this.query}"
                                        .cellbaseClient="${this.cellbaseClient}"
                                        .settings="${this._config}"
                                        @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}"
                                        @samplechange="${this.onSampleChange}">
                                    </variant-interpreter-browser-rd>

                            `;
                        },
                    });
                }
            }
        }

        // Return tabs configuration
        return {
            // title: "Variant Interperter Browser",
            display: {
                align: "center",
            },
            items: items,
        };
    }

}

customElements.define("variant-interpreter-browser", VariantInterpreterBrowser);
<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");
var util = require("util");
var async = require("async");

var servlet = require("./lib/servlet");

module.exports = function (grunt) {
    grunt.registerMultiTask("sling-content", function () {
        var options = this.options({
            host: "localhost",
            port: 8080,
            user: "admin",
            pass: "admin"
        });

        var done = this.async();

        var postServlet = new servlet.Post(options);

        this.files.forEach(postRoots);

        function postRoots(file) {
            file.src.forEach(function (root) {
                if (grunt.file.exists(root) === false) {
                    grunt.fail.fatal("The directory " + root + " does not exist");
                }

                if (grunt.file.isDir(root) === false) {
                    grunt.file.fatal("The path " + root + " is not a directory");
                }
            });

            var tasks = file.src.map(function (directory) {
                return createRootDirectoryTask(directory, "/");
            });

            async.parallel(tasks, done);
        }

        function createRootDirectoryTask(root, resource) {
            return function (done) {
                postRecursively(root, resource, done);
            };
        }

        function postRecursively(root, resource, done) {

            // Read content of the current directory

            var children = fs.readdirSync(root);

            // Filter out files

            var files = children.filter(function (child) {
                return grunt.file.isFile(root, child) && path.extname(child) !== ".json";
            });

            // Filter out directories

            var directories = children.filter(function (child) {
                return grunt.file.isDir(root, child);
            });

            // Filter out descriptors

            var descriptors = children.filter(function (child) {
                return grunt.file.isFile(root, child) && path.extname(child) === ".json";
            });

            // Create a descriptor map (base name -> json content)

            function toDescriptorMap(map, descriptor) {
                var base = path.basename(descriptor, ".json");
                var json = grunt.file.readJSON(path.join(root, descriptor));

                map[base] = json;

                return map;
            }

            var descriptorMap = descriptors.reduce(toDescriptorMap, {});

            // Return an object with properties for the selected file

            function propertiesFor(name, initial) {
                var base = path.basename(name, path.extname(name));

                var descriptor = descriptorMap[base] || {};

                function toProperties(map, name) {
                    map[name] = descriptor[name];
                    return map;
                }

                return Object.keys(descriptor).reduce(toProperties, initial || {});
            }

            // Creates a task to create/update a file

            function toFileTasks(file) {
                return function (done) {
                    grunt.log.writeln("File: " + path.join(root, file));
                    postServlet.createFile(resource, path.join(root, file), propertiesFor(file), done);
                };
            }

            var fileTasks = files.map(toFileTasks);

            // Creates a task to create/update a folder

            function toDirectoryTask(directory) {
                return function (done) {
                    grunt.log.writeln("Dir : " + path.join(root, directory));
                    postServlet.create(resource + directory, propertiesFor(directory), done);
                };
            }

            var directoryTasks = directories.map(toDirectoryTask);

            // Creates a task to create/update generic nodes

            function unusedDescriptor(name) {
                var usedForDirectories = directories.some(function (directory) {
                    return directory === name;
                });

                var usedForFiles = files.some(function (file) {
                    return path.basename(file, path.extname(file)) === name;
                });

                return !usedForFiles && !usedForDirectories;
            }

            function toNodeTask(name) {
                return function (done) {
                    grunt.log.writeln("Node: " + path.join(root, name + ".json"));
                    postServlet.create(resource + name, propertiesFor(name), done);
                };
            }

            var nodeTasks = Object.keys(descriptorMap).filter(unusedDescriptor).map(toNodeTask);

            // Executes every task in parallel

            async.parallel(fileTasks.concat(nodeTasks).concat(directoryTasks), recurseSubdirectories);

            // When work is done in this directory, recurse in subdirectories

            function recurseSubdirectories(err) {
                if (err) {
                    return done(err);
                }

                var tasks = directories.map(function (directory) {
                    return createRootDirectoryTask(path.join(root, directory), resource + directory + "/");
                });

                async.parallel(tasks, done);
            }
        }
    });
};<commit_msg>Use sling:Folder as primary type for folders - closes #1<commit_after>var fs = require("fs");
var path = require("path");
var util = require("util");
var async = require("async");

var servlet = require("./lib/servlet");

module.exports = function (grunt) {
    grunt.registerMultiTask("sling-content", function () {
        var options = this.options({
            host: "localhost",
            port: 8080,
            user: "admin",
            pass: "admin"
        });

        var done = this.async();

        var postServlet = new servlet.Post(options);

        this.files.forEach(postRoots);

        function postRoots(file) {
            file.src.forEach(function (root) {
                if (grunt.file.exists(root) === false) {
                    grunt.fail.fatal("The directory " + root + " does not exist");
                }

                if (grunt.file.isDir(root) === false) {
                    grunt.file.fatal("The path " + root + " is not a directory");
                }
            });

            var tasks = file.src.map(function (directory) {
                return createRootDirectoryTask(directory, "/");
            });

            async.parallel(tasks, done);
        }

        function createRootDirectoryTask(root, resource) {
            return function (done) {
                postRecursively(root, resource, done);
            };
        }

        function postRecursively(root, resource, done) {

            // Read content of the current directory

            var children = fs.readdirSync(root);

            // Filter out files

            var files = children.filter(function (child) {
                return grunt.file.isFile(root, child) && path.extname(child) !== ".json";
            });

            // Filter out directories

            var directories = children.filter(function (child) {
                return grunt.file.isDir(root, child);
            });

            // Filter out descriptors

            var descriptors = children.filter(function (child) {
                return grunt.file.isFile(root, child) && path.extname(child) === ".json";
            });

            // Create a descriptor map (base name -> json content)

            function toDescriptorMap(map, descriptor) {
                var base = path.basename(descriptor, ".json");
                var json = grunt.file.readJSON(path.join(root, descriptor));

                map[base] = json;

                return map;
            }

            var descriptorMap = descriptors.reduce(toDescriptorMap, {});

            // Return an object with properties for the selected file

            function propertiesFor(name, initial) {
                var base = path.basename(name, path.extname(name));

                var descriptor = descriptorMap[base] || {};

                function toProperties(map, name) {
                    map[name] = descriptor[name];
                    return map;
                }

                return Object.keys(descriptor).reduce(toProperties, initial || {});
            }

            // Creates a task to create/update a file

            function toFileTasks(file) {
                return function (done) {
                    grunt.log.writeln("File: " + path.join(root, file));
                    postServlet.createFile(resource, path.join(root, file), propertiesFor(file), done);
                };
            }

            var fileTasks = files.map(toFileTasks);

            // Creates a task to create/update a folder

            function toDirectoryTask(directory) {
                return function (done) {
                    grunt.log.writeln("Dir : " + path.join(root, directory));

                    var properties = propertiesFor(directory, {
                        "jcr:primaryType": "sling:Folder"
                    });

                    postServlet.create(resource + directory, properties, done);
                };
            }

            var directoryTasks = directories.map(toDirectoryTask);

            // Creates a task to create/update generic nodes

            function unusedDescriptor(name) {
                var usedForDirectories = directories.some(function (directory) {
                    return directory === name;
                });

                var usedForFiles = files.some(function (file) {
                    return path.basename(file, path.extname(file)) === name;
                });

                return !usedForFiles && !usedForDirectories;
            }

            function toNodeTask(name) {
                return function (done) {
                    grunt.log.writeln("Node: " + path.join(root, name + ".json"));
                    postServlet.create(resource + name, propertiesFor(name), done);
                };
            }

            var nodeTasks = Object.keys(descriptorMap).filter(unusedDescriptor).map(toNodeTask);

            // Executes every task in parallel

            async.parallel(fileTasks.concat(nodeTasks).concat(directoryTasks), recurseSubdirectories);

            // When work is done in this directory, recurse in subdirectories

            function recurseSubdirectories(err) {
                if (err) {
                    return done(err);
                }

                var tasks = directories.map(function (directory) {
                    return createRootDirectoryTask(path.join(root, directory), resource + directory + "/");
                });

                async.parallel(tasks, done);
            }
        }
    });
};<|endoftext|>


<commit_before>define( 'providers/colabs',
[ 'providers', 'jquery', 'gizmo/superdesk',

  config.guiJs('livedesk', 'models/blog'),
  config.guiJs('livedesk', 'models/collaborator'),

  'providers/colabs/adaptor',
  'tmpl!livedesk>providers/colabs',
  'tmpl!livedesk>providers/colabs/items' ],

function(providers, $, giz, Blog, Collaborator)
{
    var config = { updateInterval: 10 },
        colabsList = [],
        updateInterval = 0,
        intervalRunning = false,
        updateItemCount = 0;

    // single post item view
    var PostView = giz.View.extend
    ({
        init: function(opts)
        {
            this.model.on('update', this.render, this);
			this.model.on('read', this.render, this);
        },
        render: function()
        {
            var self = this;
            $.tmpl( 'livedesk>providers/colabs/items', {Posts: this.model.feed('json')}, function(e, o)
            {
                self.setElement(o);
                // make draggable
                self.el.hasClass('draggable') && self.el.draggable
                ({
                    helper: 'clone',
                    appendTo: 'body',
                    zIndex: 2700,
                    start: function(){ $(this).data('post', providers.colabs.adaptor.universal(this)); }
                });
            });
            return self;
        }
    }),
    // main view
    ColabView = giz.View.extend
    ({
        namespace: 'livedesk',
        events:
        {
            //'.collaborators-header .feed-info .label': {'click': 'toggleHeader'},
            '.new-results': {'update': 'showNewResults'}
        },

        toggleHeader: function()
        {
            var colabId = $(this).attr('data-colab-id'),
                posts = $(this).parents('.collaborators-header')
                            .nextAll('.search-result-list').find('li[data-colab-id='+colabId+']');

            if($(this).data('is-off'))
            {
                posts.show();
                $(this).addClass('label-info').data('is-off', false);
            }
            else
            {
                posts.hide();
                $(this).removeClass('label-info').data('is-off', true);
            }
        },
        /*!
         * @param e event
         * @param count
         * @param callback
         * @param wether to do update auto. or add a click-to-show button
         */
        showNewResults: function(e, count, callback, auto)
        {
            var self = $('.new-results', this.el),
                cb = function()
                {
                    self.addClass('hide');
                    callback.apply(this);
                };
            auto ? cb() : self.removeClass('hide').text( count+" "+_('new items! Update') ).one('click.livedesk', cb);
        },

        init: function()
        {
            $('.search-result-list', this.el).html('');

            $(this.el).on('click', '.collaborators-header .feed-info .label', this.toggleHeader);

            var blog = giz.Auth(new Blog(this.blogUrl)), // autheticated blog model
                self = this;

            self.el.html('
'+_('Loading collaborators...')+'
');

            self.colabsList = [];

            blog.on('read', function()
            {
                var collaborators = this.get('Collaborator');
                collaborators.on('read', function()
                {
                    self.colabsList = this;
                    self.setupHeader.call(self, this);
                    self.setupColabStream.call(self, this);
                });
                collaborators.xfilter('Person.Id', 'Person.FullName', 'Person.EMail', 'Post').sync();
            });
            blog.sync();
        },

        update: function()
        {
            this.colabsList.each(function()
            {
                // get post list and sync it with the server
                this.get('Post').xfilter('*').sync({data: {'startEx.cId': this._latestPost}});
            });
        },

        /*!
         * display list header
         */
        setupHeader: function(colabs)
        {
            $(this.el).tmpl('livedesk>providers/colabs', {Colabs: colabs.feed('json', true)});
        },
        /*!
         * initial - initial count of collaborators
         */
        readPostsHandle: function(initial, colab)
        {
            // list of new posts to append
            var appendPosts = [],
                self = this;
            this.each(function()
            {
                if( $.inArray( this.get('Id'), colab._viewModels ) === -1 )
                {
                    appendPosts.push(this);
                    colab._viewModels.push(this.get('Id'));
                }
                colab._latestPost = Math.max(colab._latestPost, parseInt(this.get('CId')));
            });
            updateItemCount += appendPosts.length;

            appendPosts.length && $('.new-results', self.el).trigger('update.livedesk', [updateItemCount, function()
            {
                $(appendPosts).each(function()
                {
                    $('.search-result-list', self.el).prepend( (new PostView({ model: this })).render().el );
                });
                updateItemCount -= appendPosts.length;
            }, initial ? true : false]);

            initial -= 1; // decrement initial until 0 so we know when init is over and do not send
        },
        /*!
         * setup post list
         */
        setupColabStream: function(colabs)
        {
            var self = this,
                initial = colabs.count(); // used for breaking init. action, decrementing until 0
            // collaboratos list
            colabs.each(function()
            {
                var colab = this;
                colab._latestPost = 0;
                colab._viewModels = [];
                colab.on('read', function()
                {
                    // get posts for each collaborator
                    colab.get('Post').xfilter('*')
                        .on('read', function(){ self.readPostsHandle.call(this, initial, colab); })
                        .sync();

                    self.startAutoUpdate();
//                    clearInterval(updateInterval);
//                    updateInterval = setInterval(function()
//                    {
//                        if(!$('.search-result-list:visible', self.el).length)
//                        {
//                            clearInterval(updateInterval);
//                            return;
//                        }
//                        self.update();
//                    }, config.updateInterval*1000);

                }).sync();

            });
        },
        startAutoUpdate: function()
        {
            var self = this;
            clearInterval(updateInterval);
            updateInterval = setInterval(function()
            {
                if(!$('.search-result-list:visible', self.el).length)
                {
                    clearInterval(updateInterval);
                    return;
                }
                self.update();
            }, config.updateInterval*1000);

            return self;
        },
        render: function()
        {

        }
    });

    var colabView = null;
    $.extend( providers.colabs, { init: function(blogUrl)
    {
        colabView = new ColabView({ el: this.el, blogUrl: blogUrl });
        this.init = function(){ return colabView.startAutoUpdate(); }
    }});

    return providers;
});<commit_msg>NR-230 : Collaborators provider<commit_after>define( 'providers/colabs',
[ 'providers', 'jquery', 'gizmo/superdesk',

  config.guiJs('livedesk', 'models/blog'),
  config.guiJs('livedesk', 'models/collaborator'),

  'providers/colabs/adaptor',
  'tmpl!livedesk>providers/colabs',
  'tmpl!livedesk>providers/colabs/items' ],

function(providers, $, giz, Blog, Collaborator)
{
    var config = { updateInterval: 10 },
        colabsList = [],
        updateInterval = 0,
        intervalRunning = false,
        updateItemCount = 0;

    // single post item view
    var PostView = giz.View.extend
    ({
        init: function(opts)
        {
            this.model.on('update', this.render, this);
			this.model.on('read', this.render, this);
			this.model.on('delete', this.remove, this); // TODO should remove from ColabView?
        },
        render: function()
        {
            var self = this;
            $.tmpl( 'livedesk>providers/colabs/items', {Posts: this.model.feed('json')}, function(e, o)
            {
                self.setElement(o);
                // make draggable
                self.el.hasClass('draggable') && self.el.draggable
                ({
                    helper: 'clone',
                    appendTo: 'body',
                    zIndex: 2700,
                    start: function(){ $(this).data('post', providers.colabs.adaptor.universal(this)); }
                });
            });
            return self;
        },
        remove: function()
        {
            this.el.remove();
        }
    }),
    // main view
    ColabView = giz.View.extend
    ({
        namespace: 'livedesk',
        events:
        {
            //'.collaborators-header .feed-info .label': {'click': 'toggleHeader'},
            '.new-results': {'update': 'showNewResults'}
        },

        toggleHeader: function()
        {
            var colabId = $(this).attr('data-colab-id'),
                posts = $(this).parents('.collaborators-header')
                            .nextAll('.search-result-list').find('li[data-colab-id='+colabId+']');

            if($(this).data('is-off'))
            {
                posts.show();
                $(this).addClass('label-info').data('is-off', false);
            }
            else
            {
                posts.hide();
                $(this).removeClass('label-info').data('is-off', true);
            }
        },
        /*!
         * @param e event
         * @param count
         * @param callback
         * @param wether to do update auto. or add a click-to-show button
         */
        showNewResults: function(e, count, callback, auto)
        {
            var self = $('.new-results', this.el),
                cb = function()
                {
                    self.addClass('hide');
                    callback.apply(this);
                };
            auto ? cb() : self.removeClass('hide').text( count+" "+_('new items! Update') ).one('click.livedesk', cb);
        },

        init: function()
        {
            $('.search-result-list', this.el).html('');

            $(this.el).on('click', '.collaborators-header .feed-info .label', this.toggleHeader);

            var blog = giz.Auth(new Blog(this.blogUrl)), // autheticated blog model
                self = this;

            self.el.html('
'+_('Loading collaborators...')+'
');

            self.colabsList = [];

            blog.on('read', function()
            {
                var collaborators = this.get('Collaborator');
                collaborators.on('read', function()
                {
                    self.colabsList = this;
                    self.setupHeader.call(self, this);
                    self.setupColabStream.call(self, this);
                });
                collaborators.xfilter('Person.Id', 'Person.FullName', 'Person.EMail', 'Post').sync();
            });
            blog.sync();
        },

        update: function()
        {
            this.colabsList.each(function()
            {
                // get post list and sync it with the server
                this.get('Post').xfilter('*').sync({data: {'startEx.cId': this._latestPost}});
            });
        },

        /*!
         * display list header
         */
        setupHeader: function(colabs)
        {
            $(this.el).tmpl('livedesk>providers/colabs', {Colabs: colabs.feed('json', true)});
        },
        /*!
         * initial - initial count of collaborators
         */
        readPostsHandle: function(initial, colab)
        {
            // list of new posts to append
            var appendPosts = [],
                self = this;
            this.each(function()
            {
                if( $.inArray( this.get('Id'), colab._viewModels ) === -1 )
                {
                    appendPosts.push(this);
                    colab._viewModels.push(this.get('Id'));
                }
                var pCId = parseInt(this.get('CId'));
                if(!isNaN(pCId)) colab._latestPost = Math.max(colab._latestPost, pCId);
            });
            updateItemCount += appendPosts.length;

            appendPosts.length && $('.new-results', self.el).trigger('update.livedesk', [updateItemCount, function()
            {
                $(appendPosts).each(function()
                {
                    $('.search-result-list', self.el).prepend( (new PostView({ model: this })).render().el );
                });
                updateItemCount -= appendPosts.length;
            }, initial ? true : false]);

            initial -= 1; // decrement initial until 0 so we know when init is over and do not send
        },
        /*!
         * setup post list
         */
        setupColabStream: function(colabs)
        {
            var self = this,
                initial = colabs.count(); // used for breaking init. action, decrementing until 0
            // collaboratos list
            colabs.each(function()
            {
                var colab = this;
                colab._latestPost = 0;
                colab._viewModels = [];
                colab.on('read', function()
                {
                    // get posts for each collaborator
                    colab.get('Post').xfilter('*')
                        .on('read', function(){ self.readPostsHandle.call(this, initial, colab); })
                        .sync();
                    // start the auto update timers
                    self.startAutoUpdate();
                }).sync();

            });
        },
        startAutoUpdate: function()
        {
            var self = this;
            clearInterval(updateInterval);
            updateInterval = setInterval(function()
            {
                if(!$('.search-result-list:visible', self.el).length)
                {
                    clearInterval(updateInterval);
                    return;
                }
                self.update();
            }, config.updateInterval*1000);

            return self;
        },
        render: function()
        {
            console.log('render colabs')
        }
    });

    var colabView = null;
    $.extend( providers.colabs, { init: function(blogUrl)
    {
        colabView = new ColabView({ el: this.el, blogUrl: blogUrl });
        this.init = function()
        {
            return colabView.startAutoUpdate();
        };
    }});

    return providers;
});<|endoftext|>


<commit_before>var trackNumber = 0;

function nextTrack() {
 trackNumber = trackNumber + 1;
 updateStuff();
}

function previousTrack() {
 trackNumber = trackNumber - 1;
 updateStuff();
}

function checkMusic() {

}

function updateStuff() {
 document.getElementById('trackNum').innerHTML = trackNumber;
}
<commit_msg>Update tRemix.js<commit_after>var trackNumber = 0;

function nextTrack() {
 trackNumber = Number(trackNumber + 1);
 updateStuff();
}

function previousTrack() {
 trackNumber = Number(trackNumber - 1);
 updateStuff();
}

function checkMusic() {

}

function updateStuff() {
 document.getElementById('trackNum').innerHTML = trackNumber;
}
<|endoftext|>


<commit_before>import React, { Fragment } from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'

const width = '##WIDTH##'
const height = '##HEIGHT##'
const viewBox = '##VIEWBOX##'

const sizes = '##SIZES##'

const getDimensions = size => {
  if (size && typeof size.width === 'number' && typeof size.height === 'number') {
    return size
  }
  return size && sizes[size]
    ? sizes[size]
    : { width, height }
}

const getCss = (size, fillColor, fillColorRule) => {
  const dimensions = getDimensions(size)
  const fillRule = fillColor && fillColorRule ? `${fillColorRule}{ fill: ${fillColor}; }` : ''
  return css`
    width: ${dimensions.width}px;
    height: ${dimensions.height}px;
    ${fillRule}
  `
}

const Image = styled.svg`
  ${({noStyles, size, fillColor, fillColorRule}) => !noStyles
    ? getCss(size, fillColor, fillColorRule)
    : null
  }
`

const children = (
  <Fragment>
    ##SVG##
  </Fragment>
)

const defaultProps = {
  children,
  viewBox,
  fillColor: null,
  fillColorRule: '&&& path, &&& use, &&& g',
  sizes,
  size: null
}

const propTypes = {
  fillColor: PropTypes.string,
  fillColorRule: PropTypes.string,
  viewBox: PropTypes.string.isRequired,
  children: PropTypes.node.isRequired,
  size: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.shape({
      height: PropTypes.number.isRequired,
      width: PropTypes.number.isRequired
    })
  ]),
  sizes: (props, name, componentName) => {
    const prop = props[name]
    if (typeof prop !== 'object') { return }
    for (let key in prop) {
      if (!prop[key] || typeof prop[key].width !== 'number' || typeof prop[key].height !== 'number') {
        return new Error(
          'Invalid prop `' + name + '` supplied to' + ' `' + componentName + '`. Validation failed.'
        )
      }
    }
  }
}

export default Object.assign(Image, {
  getDimensions,
  getCss,
  defaultProps,
  propTypes,
  displayName: '##NAME##'
})
<commit_msg>use prop sizes bugfix<commit_after>import React, { Fragment } from 'react'
import PropTypes from 'prop-types'
import styled, { css } from 'styled-components'

const width = '##WIDTH##'
const height = '##HEIGHT##'
const viewBox = '##VIEWBOX##'

const sizes = '##SIZES##'

const getDimensions = (size, sizes) => {
  if (size && typeof size.width === 'number' && typeof size.height === 'number') {
    return size
  }
  return size && sizes[size]
    ? sizes[size]
    : { width, height }
}

const getCss = (size, sizes, fillColor, fillColorRule, noStyles) => {
  if (noStyles) { return '' }
  const dimensions = getDimensions(size, sizes)
  const fillRule = fillColor && fillColorRule ? `${fillColorRule}{ fill: ${fillColor}; }` : ''
  return css`
    width: ${dimensions.width}px;
    height: ${dimensions.height}px;
    ${fillRule}
  `
}

const propsToCss = ({
  size,
  sizes,
  fillColor,
  fillColorRule,
  noStyles
}) => getCss(size, sizes, fillColor, fillColorRule, noStyles)

const Image = styled.svg`${propsToCss}`

const children = (
  <Fragment>
    ##SVG##
  </Fragment>
)

const defaultProps = {
  children,
  viewBox,
  fillColor: null,
  fillColorRule: '&&& path, &&& use, &&& g',
  sizes,
  size: null
}

const propTypes = {
  fillColor: PropTypes.string,
  fillColorRule: PropTypes.string,
  viewBox: PropTypes.string.isRequired,
  children: PropTypes.node.isRequired,
  size: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.shape({
      height: PropTypes.number.isRequired,
      width: PropTypes.number.isRequired
    })
  ]),
  sizes: (props, name, componentName) => {
    const prop = props[name]
    if (typeof prop !== 'object') { return }
    for (let key in prop) {
      if (!prop[key] || typeof prop[key].width !== 'number' || typeof prop[key].height !== 'number') {
        return new Error(
          'Invalid prop `' + name + '` supplied to' + ' `' + componentName + '`. Validation failed.'
        )
      }
    }
  }
}

export default Object.assign(Image, {
  getDimensions,
  getCss,
  defaultProps,
  propTypes,
  displayName: '##NAME##'
})
<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";

var fs = require("fs");

function copyFileSync(srcFile, destFile) {
    var BUF_LENGTH = 64*1024;
    var buff = new Buffer(BUF_LENGTH);
    var fdr = fs.openSync(srcFile, 'r');
    var fdw = fs.openSync(destFile, 'w');
    var bytesRead = 1
    var pos = 0
    while (bytesRead > 0) {
        bytesRead = fs.readSync(fdr, buff, 0, BUF_LENGTH, pos);
        fs.writeSync(fdw,buff,0,bytesRead);
        pos += bytesRead;
      }
    fs.closeSync(fdr)
    fs.closeSync(fdw)
}

if (process.platform == "win32" || true) {
    console.log("installing bin/jsx for Windows");
    copyFileSync("bin/jsx-compiler.js", "bin/jsx");
}
// vim: set expandtab:
<commit_msg>remove testing stuff<commit_after>#!/usr/bin/env node
"use strict";

var fs = require("fs");

function copyFileSync(srcFile, destFile) {
    var BUF_LENGTH = 64*1024;
    var buff = new Buffer(BUF_LENGTH);
    var fdr = fs.openSync(srcFile, 'r');
    var fdw = fs.openSync(destFile, 'w');
    var bytesRead = 1
    var pos = 0
    while (bytesRead > 0) {
        bytesRead = fs.readSync(fdr, buff, 0, BUF_LENGTH, pos);
        fs.writeSync(fdw,buff,0,bytesRead);
        pos += bytesRead;
      }
    fs.closeSync(fdr)
    fs.closeSync(fdw)
}

if (process.platform == "win32") {
    console.log("installing bin/jsx for Windows");
    copyFileSync("bin/jsx-compiler.js", "bin/jsx");
}
// vim: set expandtab:
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import AddContractorComponent from './AddContractor.jsx';
import { addContractor } from '../../actions/contractor-info-actions.js';

const mapStateToProps = state => {
  return {
    error: state.contractors.error,
    isLoading: state.main.isLoading
  };
};

const mapDispatchToProps = dispatch => {
  return {
    onSubmit: (data, callback) => {
      dispatch(addContractor(data, callback));
    }
  };
};

class AddContractorContainer extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      contractor: {
        firstName: '',
        surname: '',
        agencySource: ''
      },
      projects: [
        {
          projectname: '',
          reportingmanagers: ['harry potter', 'luna luvgood'],
          hrpositions: ['professor', 'dark arts teacher'],
          ratetypes: ['Type A', 'Type B'],
          hourlyrate: '',
          paygrades: ['A', 'B'],
          refnos: ['1', '2', '3']
        }
      ],
      message: ''
    };
    this.handleTextInput = this.handleTextInput.bind(this);
    this.handleDropdownInput = this.handleDropdownInput.bind(this);
    this.handleDateInput = this.handleDateInput.bind(this);
    this.handleStatusInput = this.handleStatusInput.bind(this);
    this.handleCurrencyInput = this.handleCurrencyInput.bind(this);
    this.handleAdd = this.handleAdd.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.resetState = this.resetState.bind(this);
  }

  handleTextInput(event) {
    event.preventDefault();
    const { state } = this;
    const { contractor } = state;
    contractor[event.target.getAttribute('name')] = event.target.value;
    this.setState(Object.assign(state, { contractor }));
  }

  handleDropdownInput(event) {
    event.preventDefault();
  }

  handleDateInput(event) {
    event.preventDefault();
  }

  handleStatusInput(event) {
    event.preventDefault();
  }

  handleCurrencyInput(event) {
    event.preventDefault();
  }

  handleAdd(event) {
    event.preventDefault();
  }

  handleSubmit(event) {
    event.preventDefault();
    const { contractor } = this.state;
    this.props.onSubmit(contractor, this.resetState);
  }

  resetState() {
    const { props } = this;
    if (props.error) {
      this.setState({ message: props.error });
    } else {
      this.setState({
        contractor: {
          firstName: '',
          surname: '',
          agencySource: ''
        },
        projects: [
          {
            projectname: '',
            reportingmanagers: ['harry potter', 'luna luvgood'],
            hrpositions: ['professor', 'dark arts teacher'],
            ratetypes: ['Type A', 'Type B'],
            hourlyrate: '',
            paygrades: ['A', 'B'],
            refnos: ['1', '2', '3']
          }
        ],
        message: 'Contractor added successfully.'
      });
    }
  }

  render() {
    return <AddContractorComponent
      contractor={this.state.contractor}
      projects={this.state.projects}
      handleTextInput={this.handleTextInput}
      handleStatusInput={this.handleStatusInput}
      handleDropdownInput={this.handleDropdownInput}
      handleDateInput={this.handleDateInput}
      handleCurrencyInput={this.handleCurrencyInput}
      handleAdd={this.handleAdd}
      handleSubmit={this.handleSubmit}
      message={this.state.message}
    />;
  }
}

const AddContractor = connect(
  mapStateToProps,
  mapDispatchToProps
)(AddContractorContainer);

export default AddContractor;
<commit_msg>added cost centre to index.js<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import AddContractorComponent from './AddContractor.jsx';
import { addContractor } from '../../actions/contractor-info-actions.js';

const mapStateToProps = state => {
  return {
    error: state.contractors.error,
    isLoading: state.main.isLoading
  };
};

const mapDispatchToProps = dispatch => {
  return {
    onSubmit: (data, callback) => {
      dispatch(addContractor(data, callback));
    }
  };
};

class AddContractorContainer extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      contractor: {
        firstName: '',
        surname: '',
        agencySource: ''
      },
      projects: [
        {
          projectname: '',
          reportingmanagers: ['harry potter', 'luna luvgood'],
          costcentre: '',
          hrpositions: ['professor', 'dark arts teacher'],
          ratetypes: ['Type A', 'Type B'],
          hourlyrate: '',
          paygrades: ['A', 'B'],
          refnos: ['1', '2', '3']
        }
      ],
      message: ''
    };
    this.handleTextInput = this.handleTextInput.bind(this);
    this.handleDropdownInput = this.handleDropdownInput.bind(this);
    this.handleDateInput = this.handleDateInput.bind(this);
    this.handleStatusInput = this.handleStatusInput.bind(this);
    this.handleCurrencyInput = this.handleCurrencyInput.bind(this);
    this.handleAdd = this.handleAdd.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.resetState = this.resetState.bind(this);
  }

  handleTextInput(event) {
    event.preventDefault();
    const { state } = this;
    const { contractor } = state;
    contractor[event.target.getAttribute('name')] = event.target.value;
    this.setState(Object.assign(state, { contractor }));
  }

  handleDropdownInput(event) {
    event.preventDefault();
  }

  handleDateInput(event) {
    event.preventDefault();
  }

  handleStatusInput(event) {
    event.preventDefault();
  }

  handleCurrencyInput(event) {
    event.preventDefault();
  }

  handleAdd(event) {
    event.preventDefault();
  }

  handleSubmit(event) {
    event.preventDefault();
    const { contractor } = this.state;
    this.props.onSubmit(contractor, this.resetState);
  }

  resetState() {
    const { props } = this;
    if (props.error) {
      this.setState({ message: props.error });
    } else {
      this.setState({
        contractor: {
          firstName: '',
          surname: '',
          agencySource: ''
        },
        projects: [
          {
            projectname: '',
            reportingmanagers: ['harry potter', 'luna luvgood'],
            hrpositions: ['professor', 'dark arts teacher'],
            ratetypes: ['Type A', 'Type B'],
            hourlyrate: '',
            paygrades: ['A', 'B'],
            refnos: ['1', '2', '3']
          }
        ],
        message: 'Contractor added successfully.'
      });
    }
  }

  render() {
    return <AddContractorComponent
      contractor={this.state.contractor}
      projects={this.state.projects}
      handleTextInput={this.handleTextInput}
      handleStatusInput={this.handleStatusInput}
      handleDropdownInput={this.handleDropdownInput}
      handleDateInput={this.handleDateInput}
      handleCurrencyInput={this.handleCurrencyInput}
      handleAdd={this.handleAdd}
      handleSubmit={this.handleSubmit}
      message={this.state.message}
    />;
  }
}

const AddContractor = connect(
  mapStateToProps,
  mapDispatchToProps
)(AddContractorContainer);

export default AddContractor;
<|endoftext|>