<commit_before>import m from 'mithril';
import _ from 'underscore';
import postgrest from 'mithril-postgrest';
import h from '../h';
import models from '../models';
import adminInputAction from './admin-input-action';
import adminRadioAction from './admin-radio-action';
import adminExternalAction from './admin-external-action';

const adminProjectDetail = {
    controller(args) {
        let bankl;
        const loadBank = () => {
            const model = models.projectAccount,
                project_id = args.item.project_id,
                opts = model.getRowOptions(h.idVM.id(project_id).parameters()),
                project = m.prop({});

            bankl = postgrest.loaderWithToken(opts);

            if (project_id) {
                bankl.load().then(_.compose(project, _.first));
            }

            return project;
        };
        let l;
        const loadUser = () => {
            const model = models.userDetail,
                user_id = args.item.user_id,
                opts = model.getRowOptions(h.idVM.id(user_id).parameters()),
                user = m.prop({});

            l = postgrest.loaderWithToken(opts);

            if (user_id) {
                l.load().then(_.compose(user, _.first));
            }

            return user;
        };

        return {
            user: loadUser(),
            bankAccount: loadBank(),
            actions: {
                refund: {
                    updateKey: 'id',
                    callToAction: 'Reembolso direto',
                    innerLabel: 'Tem certeza que deseja reembolsar esse apoio?',
                    outerLabel: 'Reembolsar Apoio',
                    model: models.contributionDetail
                },
                remove: {
                    property: 'state',
                    updateKey: 'id',
                    callToAction: 'Apagar',
                    innerLabel: 'Tem certeza que deseja apagar esse apoio?',
                    outerLabel: 'Apagar Apoio',
                    forceValue: 'deleted',
                    successMessage: 'Apoio removido com sucesso!',
                    errorMessage: 'O apoio não foi removido!',
                    model: models.contributionDetail
                }
            },
            l
        };
    },
    view(ctrl, args) {
        const actions = ctrl.actions,
            item = args.item,
            user = ctrl.user(),
            bankAccount = ctrl.bankAccount(),
            userAddress = user.address || {},
            addOptions = (builder, id) => _.extend({}, builder, {
                requestOptions: {
                    url: (`/admin/contributions/${id}/gateway_refund`),
                    method: 'PUT'
                }
            });

        return m('#admin-contribution-detail-box', [
            m('.divider.u-margintop-20.u-marginbottom-20'),
            m('.w-row.u-marginbottom-30', [
                (ctrl.l()) ? h.loader :
                m.component(adminExternalAction, {
                    data: addOptions(actions.refund, item.id),
                    item
                }),
                m.component(adminInputAction, {
                    data: actions.remove,
                    item
                })
            ]),
            m('.w-row.card.card-terciary.u-radius', [
                m('.w-col.w-col-4', [
                    m('.fontsize-smaller.fontweight-semibold.lineheight-tighter.u-marginbottom-20',
                        'Detalhes do projeto'
                    ),
                    m('.fontsize-smallest.fontweight-semibold.u-marginbottom-20',
                        `catarse.me/${item.permalink}`
                    ),
                    m('.fontsize-smallest.lineheight-looser.u-marginbottom-20', [
                        m('span.fontweight-semibold',
                            'Meta:'
                        ),
                        ` R$ ${h.formatNumber(item.goal, 2, 3)}\ `,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Alcançado:'
                        ),
                        ` R$ ${h.formatNumber(item.pledged, 2, 3)}\ `,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Taxa do MP:'
                        ),
                        ' R$ 341\ ',
                        m('br'),
                        m('span.fontweight-semibold',
                            'Taxa do Catarse:'
                        ),
                        ' R$ 1.055'
                    ]),
                    m('.fontsize-smallest.lineheight-looser', [
                        m('span.fontweight-semibold',
                            'Início: '
                        ),
                        h.momentify(item.project_online_date, 'DD/MM/YYYY, HH:mm'),
                        m('br'),
                        m('span.fontweight-semibold',
                            'Término: '
                        ),
                        h.momentify(item.project_expires_at, 'DD/MM/YYYY, HH:mm'),
                        m('br'),
                        // m('span.fontweight-semibold',
                            // 'Prazo de entrega:'
                        // ),
                        // ' 30/11/2015\ ',
                        // m('br'),
                        m('span.fontweight-semibold',
                            'Últ. atualização: '
                        ),
                        h.momentify(item.updated_at, 'DD/MM/YYYY, HH:mm'),
                        m('br'),
                        m('span.fontweight-semibold',
                            'Novidades: '
                        ),
                        item.posts_count,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Últ. novidade: '
                        ),
                        h.momentify(item.last_post, 'DD/MM/YYYY, HH:mm')
                    ])
                ]),
                m('.w-col.w-col-4', [
                    m('.fontsize-smaller.fontweight-semibold.lineheight-tighter.u-marginbottom-20',
                        'Dados bancários'
                    ),
                    m('.fontsize-smallest.lineheight-looser.u-marginbottom-20', [
                        m('span.fontweight-semibold',
                            'Valor do repasse:'
                        ),
                        m.trust(' '),
                        'R$ 15050',
                        m('br'),
                        m('span.fontweight-semibold',
                            'Data do repasse:'
                        ),
                        m.trust(' '),
                        '20/01/2015'
                    ]),
                    m('.fontsize-smallest.lineheight-looser', [
                        m('span.fontweight-semibold',
                            'Banco: '
                        ),
                        bankAccount.bank_name,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Agencia: '
                        ),
                        `${bankAccount.agency}-${bankAccount.agency_digit}`,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Conta: '
                        ),
                        `${bankAccount.account}-${bankAccount.account_digit}`,
                        m('br'),
                        bankAccount.account_type,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Nome: '
                        ),
                        bankAccount.owner_name,
                        m('br'),
                        m('span.fontweight-semibold',
                            'CPF: '
                        ),
                        bankAccount.owner_document
                    ])
                ]),
                m('.w-col.w-col-4', [
                    m('.fontsize-smaller.fontweight-semibold.lineheight-tighter.u-marginbottom-20',
                        'Detalhes do realizador'
                    ),
                    m('.fontsize-smallest.lineheight-looser.u-marginbottom-20', [
                        m('span.fontweight-semibold',
                            'Nome: '
                        ),
                        user.name,
                        m('br'),
                        m('span.fontweight-semibold',
                            'CPF: '
                        ),
                        user.owner_document,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Inscrição estadual: '
                        ),
                        user.state_inscription,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Email: '
                        ),
                        user.email,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Endereço: '
                        ),
                        m.trust(' '),
                        ` ${userAddress.address_street}, ${userAddress.address_number} ${userAddress.address_complement} - ${userAddress.address_city} - ${userAddress.address_state} ${userAddress.address_zip_code}`,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Telefone:'
                        ),
                        userAddress.phone_number
                    ]),
                    m('.fontsize-smallest.lineheight-looser', [
                        `${user.total_published_projects} projetos criados `,
                        m('br'),
                        m.trust(' '),
                        m('br')
                    ])
                ])
            ])
        ]);
    }
};

export default adminProjectDetail;
<commit_msg>Add switch owner id action<commit_after>import m from 'mithril';
import _ from 'underscore';
import postgrest from 'mithril-postgrest';
import h from '../h';
import models from '../models';
import adminInputAction from './admin-input-action';
import adminRadioAction from './admin-radio-action';
import adminExternalAction from './admin-external-action';
import projectVM from '../vms/project-vm';

const adminProjectDetail = {
    controller(args) {
        let bankl;
        const project_id = args.item.project_id;
        const loadBank = () => {
            const model = models.projectAccount,
                opts = model.getRowOptions(h.idVM.id(project_id).parameters()),
                project = m.prop({});

            bankl = postgrest.loaderWithToken(opts);

            if (project_id) {
                bankl.load().then(_.compose(project, _.first));
            }

            return project;
        };
        let l;
        const loadUser = () => {
            const model = models.userDetail,
                user_id = args.item.user_id,
                opts = model.getRowOptions(h.idVM.id(user_id).parameters()),
                user = m.prop({});

            l = postgrest.loaderWithToken(opts);

            if (user_id) {
                l.load().then(_.compose(user, _.first));
            }

            return user;
        };

        const changeUserAction = {
            toggler: h.toggleProp(false, true),
            submit: (event) => {
                event.preventDefault();
                changeUserAction.complete(false);
                projectVM
                    .updateProject(project_id, {user_id: changeUserAction.newValue()})
                    .then(() => {
                        changeUserAction.complete(true);
                        changeUserAction.success(true);
                        changeUserAction.error(false);
                    })
                    .catch(() => {
                        changeUserAction.complete(true);
                        changeUserAction.success(true);
                        changeUserAction.error(true);
                    });
                return false;
            },
            complete: m.prop(false),
            error: m.prop(false),
            success: m.prop(false),
            newValue: m.prop('')
        };

        const actionUnload = action => () => {
            action.complete(false);
            action.error(false);
            action.success(false);
            action.newValue('');
        };

        return {
            user: loadUser(),
            bankAccount: loadBank(),
            actions: {
                changeUserAction
            },
            actionUnload
        };
    },
    view(ctrl, args) {
        const actions = ctrl.actions,
            item = args.item,
            user = ctrl.user(),
            bankAccount = ctrl.bankAccount(),
            userAddress = user.address || {};

        return m('#admin-contribution-detail-box', [
            m('.divider.u-margintop-20.u-marginbottom-20'),
            m('.w-row.u-marginbottom-30', [
                m('.w-col.w-col-2', [
                    m('button.btn.btn-small.btn-terciary', {
                        onclick: ctrl.actions.changeUserAction.toggler.toggle
                    }, 'Trocar realizador'), (ctrl.actions.changeUserAction.toggler()) ?
                    m('.dropdown-list.card.u-radius.dropdown-list-medium.zindex-10',{
                        config: ctrl.actionUnload(ctrl.actions.changeUserAction)
                    },[
                        m('form.w-form', {
                            onsubmit: ctrl.actions.changeUserAction.submit
                        }, (!ctrl.actions.changeUserAction.complete()) ? [
                            m('label', 'Id do novo realizador:'),
                            m(`input.w-input.text-field[type="tel"][placeholder="ex: 239049"]`, {
                                onchange: m.withAttr('value', ctrl.actions.changeUserAction.newValue),
                                value: ctrl.actions.changeUserAction.newValue()
                            }),
                            m('input.w-button.btn.btn-small[type="submit"][value="Transferir"]')
                        ] : (!ctrl.actions.changeUserAction.error()) ? [
                            m('.w-form-done[style="display:block;"]', [
                                m('p', 'Usuário transferido com sucesso')
                            ])
                        ] : [
                            m('.w-form-error[style="display:block;"]', [
                                m('p', 'Houve um problema na requisição. Verifique se o usuário que vai receber o projeto possui dados válidos.')
                            ])
                        ])
                    ]) : ''
                ]),
            ]),
            m('.w-row.card.card-terciary.u-radius', [
                m('.w-col.w-col-4', [
                    m('.fontsize-smaller.fontweight-semibold.lineheight-tighter.u-marginbottom-20',
                        'Detalhes do projeto'
                    ),
                    m('.fontsize-smallest.fontweight-semibold.u-marginbottom-20',
                        `catarse.me/${item.permalink}`
                    ),
                    m('.fontsize-smallest.lineheight-looser.u-marginbottom-20', [
                        m('span.fontweight-semibold',
                            'Meta:'
                        ),
                        ` R$ ${h.formatNumber(item.goal, 2, 3)}\ `,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Alcançado:'
                        ),
                        ` R$ ${h.formatNumber(item.pledged, 2, 3)}\ `,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Taxa do MP:'
                        ),
                        ' R$ 341\ ',
                        m('br'),
                        m('span.fontweight-semibold',
                            'Taxa do Catarse:'
                        ),
                        ' R$ 1.055'
                    ]),
                    m('.fontsize-smallest.lineheight-looser', [
                        m('span.fontweight-semibold',
                            'Início: '
                        ),
                        h.momentify(item.project_online_date, 'DD/MM/YYYY, HH:mm'),
                        m('br'),
                        m('span.fontweight-semibold',
                            'Término: '
                        ),
                        h.momentify(item.project_expires_at, 'DD/MM/YYYY, HH:mm'),
                        m('br'),
                        // m('span.fontweight-semibold',
                            // 'Prazo de entrega:'
                        // ),
                        // ' 30/11/2015\ ',
                        // m('br'),
                        m('span.fontweight-semibold',
                            'Últ. atualização: '
                        ),
                        h.momentify(item.updated_at, 'DD/MM/YYYY, HH:mm'),
                        m('br'),
                        m('span.fontweight-semibold',
                            'Novidades: '
                        ),
                        item.posts_count,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Últ. novidade: '
                        ),
                        h.momentify(item.last_post, 'DD/MM/YYYY, HH:mm')
                    ])
                ]),
                m('.w-col.w-col-4', [
                    m('.fontsize-smaller.fontweight-semibold.lineheight-tighter.u-marginbottom-20',
                        'Dados bancários'
                    ),
                    m('.fontsize-smallest.lineheight-looser.u-marginbottom-20', [
                        m('span.fontweight-semibold',
                            'Valor do repasse:'
                        ),
                        m.trust(' '),
                        'R$ 15050',
                        m('br'),
                        m('span.fontweight-semibold',
                            'Data do repasse:'
                        ),
                        m.trust(' '),
                        '20/01/2015'
                    ]),
                    m('.fontsize-smallest.lineheight-looser', [
                        m('span.fontweight-semibold',
                            'Banco: '
                        ),
                        bankAccount.bank_name,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Agencia: '
                        ),
                        `${bankAccount.agency}-${bankAccount.agency_digit}`,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Conta: '
                        ),
                        `${bankAccount.account}-${bankAccount.account_digit}`,
                        m('br'),
                        bankAccount.account_type,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Nome: '
                        ),
                        bankAccount.owner_name,
                        m('br'),
                        m('span.fontweight-semibold',
                            'CPF: '
                        ),
                        bankAccount.owner_document
                    ])
                ]),
                m('.w-col.w-col-4', [
                    m('.fontsize-smaller.fontweight-semibold.lineheight-tighter.u-marginbottom-20',
                        'Detalhes do realizador'
                    ),
                    m('.fontsize-smallest.lineheight-looser.u-marginbottom-20', [
                        m('span.fontweight-semibold',
                            'Nome: '
                        ),
                        user.name,
                        m('br'),
                        m('span.fontweight-semibold',
                            'CPF: '
                        ),
                        user.owner_document,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Inscrição estadual: '
                        ),
                        user.state_inscription,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Email: '
                        ),
                        user.email,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Endereço: '
                        ),
                        m.trust(' '),
                        ` ${userAddress.address_street}, ${userAddress.address_number} ${userAddress.address_complement} - ${userAddress.address_city} - ${userAddress.address_state} ${userAddress.address_zip_code}`,
                        m('br'),
                        m('span.fontweight-semibold',
                            'Telefone:'
                        ),
                        userAddress.phone_number
                    ]),
                    m('.fontsize-smallest.lineheight-looser', [
                        `${user.total_published_projects} projetos criados `,
                        m('br'),
                        m.trust(' '),
                        m('br')
                    ])
                ])
            ])
        ]);
    }
};

export default adminProjectDetail;
<|endoftext|>


<commit_before>var os = require('os');
var cp = require('child_process');
var fs = require('fs');
var path = require('path');
var fse = require('fs-extra2');
var getWhistlePath = require('../lib/util/common').getWhistlePath;

var CMD_SUFFIX = process.platform === 'win32' ? '.cmd' : '';
var WHISTLE_PLUGIN_RE = /^((?:@[\w-]+\/)?whistle\.[a-z\d_-]+)(?:\@([\w.^~*-]*))?$/;
var PLUGIN_PATH = path.join(getWhistlePath(), 'plugins');
var CUSTOM_PLUGIN_PATH = path.join(getWhistlePath(), 'custom_plugins');
var PACKAGE_JSON = '{"repository":"https://github.com/avwo/whistle","license":"MIT"}';
var LICENSE = 'Copyright (c) 2019 avwo';
var RESP_URL = 'https://github.com/avwo/whistle';
var REMOTE_URL_RE = /^\s*((?:git[+@]|github:|https?:\/\/)[^\s]+[/\\]whistle\.[a-z\d_-]+(?:\.git)?)\s*$/i;

function getInstallPath(name, dir) {
  return path.join(dir || CUSTOM_PLUGIN_PATH, name);
}

function getPlugins(argv, isInstall) {
  return argv.filter(function(name) {
    if (WHISTLE_PLUGIN_RE.test(name)) {
      return true;
    }
    return isInstall && REMOTE_URL_RE.test(name);
  });
}

function removeDir(installPath) {
  if (fs.existsSync(installPath))  {
    fse.removeSync(installPath);
  }
}

function removeOldPlugin(name) {
  removeDir(path.join(PLUGIN_PATH, 'node_modules', name));
  removeDir(path.join(PLUGIN_PATH, 'node_modules', getTempName(name)));
}

function getTempName(name) {
  if (name.indexOf('/') === -1) {
    return '.' + name;
  }
  name = name.split('/');
  var lastIndex = name.length - 1;
  name[lastIndex] = '.' + name[lastIndex];
  return name.join('/');
}

function getInstallDir(argv) {
  argv = argv.slice();
  var result = { argv: argv };
  for (var i = 0, len = argv.length; i < len; i++) {
    var option = argv[i];
    if (option && option.indexOf('--dir=') === 0) {
      var dir = option.substring(option.indexOf('=') + 1);
      result.dir = dir && path.resolve(dir);
      argv.splice(i, 1);
      return result;
    }
  }
  return result;
}

function getPluginNameFormDeps(deps) {
  var keys = Object.keys(deps);
  for (var i = 0, len = keys.length; i < len; i++) {
    if (WHISTLE_PLUGIN_RE.test(keys[i])) {
      return RegExp.$1;
    }
  }
}

function getPkgName(name) {
  if (/[/\\](whistle\.[a-z\d_-]+)(?:\.git)?$/.test(name)) {
    return RegExp.$1;
  }
  return name;
}

function install(cmd, name, argv, ver, pluginsCache, callback) {
  var result = getInstallDir(argv.slice());
  var isPkg = WHISTLE_PLUGIN_RE.test(name);
  var pkgName = isPkg ? name : getPkgName(name);
  var installPath = getInstallPath(getTempName(pkgName), result.dir);
  argv = result.argv;
  fse.ensureDirSync(installPath);
  fse.emptyDirSync(installPath);
  var pkgJson = PACKAGE_JSON;
  if (ver) {
    pkgJson = pkgJson.replace(',', ',"dependencies":{"' + name + '":"' + ver + '"},');
  }
  fs.writeFileSync(path.join(installPath, 'package.json'), pkgJson);
  fs.writeFileSync(path.join(installPath, 'LICENSE'), LICENSE);
  fs.writeFileSync(path.join(installPath, 'README.md'), RESP_URL);
  argv.unshift('install', name);
  pluginsCache[pkgName] = 1;
  cp.spawn(cmd, argv, {
    stdio: 'inherit',
    cwd: installPath
  }).once('exit', function(code) {
    if (code) {
      removeDir(installPath);
      callback();
    } else {
      if (!isPkg) {
        var deps = fse.readJsonSync(path.join(installPath, 'package.json')).dependencies;
        name = deps && getPluginNameFormDeps(deps);
      }
      if (!name) {
        try {
          removeDir(installPath);
        } catch (e) {}
        return callback();
      }
      var realPath = getInstallPath(name, result.dir);
      removeDir(realPath);
      try {
        fs.renameSync(installPath, realPath);
      } catch (e) {
        fse.ensureDirSync(realPath);
        fse.copySync(installPath, realPath);
        try {
          removeDir(installPath);
        } catch (e) {}
      }
      var pkgPath = path.join(realPath, 'node_modules', name, 'package.json');
      try {
        if (fs.statSync(pkgPath).mtime.getFullYear() < 2010) {
          var now = new Date();
          fs.utimesSync(pkgPath, now, now);
        }
      } catch (e) {}
      callback(pkgPath);
    }
  });
}

function readJson(pkgPath) {
  try {
    return fse.readJsonSync(pkgPath);
  } catch (e) {
    try {
      return fse.readJsonSync(pkgPath);
    } catch (e) {}
  }
}

function installPlugins(cmd, plugins, argv, pluginsCache, deep) {
  deep = deep || 0;
  var count = 0;
  var peerPlugins = [];
  var callback = function(pkgPath) {
    if (pkgPath) {
      var pkg = readJson(pkgPath) || {};
      var list = pkg.whistleConfig && (pkg.whistleConfig.peerPluginList || pkg.whistleConfig.peerPlugins);
      if (Array.isArray(list) && list.length < 16) {
        list.forEach(function(name) {
          name = typeof name === 'string' ? name.trim() : null;
          if (name && (WHISTLE_PLUGIN_RE.test(name) || REMOTE_URL_RE.test(name))) {
            name = RegExp.$1;
            if (peerPlugins.indexOf(name) === -1) {
              peerPlugins.push(name);
            }
          }
        });
      }
    }
    if (--count <= 0 && deep < 16) {
      peerPlugins = peerPlugins.filter(function(name) {
        return !pluginsCache[name];
      });
      peerPlugins.length && installPlugins(cmd, peerPlugins, argv, pluginsCache, ++deep);
    }
  };
  plugins.forEach(function(name) {
    var isPkg = WHISTLE_PLUGIN_RE.test(name);
    if (isPkg || REMOTE_URL_RE.test(name)) {
      ++count;
      name = RegExp.$1;
      var ver = RegExp.$2;
      isPkg && removeOldPlugin(name);
      install(cmd, name, argv, ver, pluginsCache, callback);
    }
  });
}

exports.getWhistlePath = getWhistlePath;

exports.install = function(cmd, argv) {
  var plugins = getPlugins(argv, true);
  if (!plugins.length) {
    return;
  }
  argv = argv.filter(function(name) {
    return plugins.indexOf(name) === -1;
  });

  cmd += CMD_SUFFIX;
  argv.push('--no-package-lock');
  installPlugins(cmd, plugins, argv, {});
};

exports.uninstall = function(plugins) {
  var result = getInstallDir(plugins);
  plugins = result.argv;
  getPlugins(plugins).forEach(function(name) {
    if (WHISTLE_PLUGIN_RE.test(name)) {
      name = RegExp.$1;
      !result.dir && removeOldPlugin(name);
      removeDir(getInstallPath(name, result.dir));
    }
  });
};

exports.run = function(cmd, argv) {
  var newPath = [];
  fse.ensureDirSync(CUSTOM_PLUGIN_PATH);
  fs.readdirSync(CUSTOM_PLUGIN_PATH).forEach(function(name) {
    if (!name.indexOf('whistle.')) {
      newPath.push(path.join(CUSTOM_PLUGIN_PATH, name, 'node_modules/.bin'));
    } else if (name[0] === '@') {
      try {
        fs.readdirSync(path.join(CUSTOM_PLUGIN_PATH, name)).forEach(function(modName) {
          newPath.push(path.join(CUSTOM_PLUGIN_PATH, name, modName, 'node_modules/.bin'));
        });
      } catch (e) {}
    }
  });
  process.env.PATH && newPath.push(process.env.PATH);
  newPath = newPath.join(os.platform() === 'win32' ? ';' : ':');
  process.env.PATH = newPath;
  cp.spawn(cmd + CMD_SUFFIX, argv, {
    stdio: 'inherit',
    env: process.env
  });
};
<commit_msg>refactor: refine code<commit_after>var os = require('os');
var cp = require('child_process');
var fs = require('fs');
var path = require('path');
var fse = require('fs-extra2');
var getWhistlePath = require('../lib/util/common').getWhistlePath;

var CMD_SUFFIX = process.platform === 'win32' ? '.cmd' : '';
var WHISTLE_PLUGIN_RE = /^((?:@[\w-]+\/)?whistle\.[a-z\d_-]+)(?:\@([\w.^~*-]*))?$/;
var PLUGIN_PATH = path.join(getWhistlePath(), 'plugins');
var CUSTOM_PLUGIN_PATH = path.join(getWhistlePath(), 'custom_plugins');
var PACKAGE_JSON = '{"repository":"https://github.com/avwo/whistle","license":"MIT"}';
var LICENSE = 'Copyright (c) 2019 avwo';
var RESP_URL = 'https://github.com/avwo/whistle';
var REMOTE_URL_RE = /^\s*((?:git[+@]|github:|https?:\/\/)[^\s]+\/whistle\.[a-z\d_-]+(?:\.git)?)\s*$/i;

function getInstallPath(name, dir) {
  return path.join(dir || CUSTOM_PLUGIN_PATH, name);
}

function getPlugins(argv, isInstall) {
  return argv.filter(function(name) {
    if (WHISTLE_PLUGIN_RE.test(name)) {
      return true;
    }
    return isInstall && REMOTE_URL_RE.test(name);
  });
}

function removeDir(installPath) {
  if (fs.existsSync(installPath))  {
    fse.removeSync(installPath);
  }
}

function removeOldPlugin(name) {
  removeDir(path.join(PLUGIN_PATH, 'node_modules', name));
  removeDir(path.join(PLUGIN_PATH, 'node_modules', getTempName(name)));
}

function getTempName(name) {
  if (name.indexOf('/') === -1) {
    return '.' + name;
  }
  name = name.split('/');
  var lastIndex = name.length - 1;
  name[lastIndex] = '.' + name[lastIndex];
  return name.join('/');
}

function getInstallDir(argv) {
  argv = argv.slice();
  var result = { argv: argv };
  for (var i = 0, len = argv.length; i < len; i++) {
    var option = argv[i];
    if (option && option.indexOf('--dir=') === 0) {
      var dir = option.substring(option.indexOf('=') + 1);
      result.dir = dir && path.resolve(dir);
      argv.splice(i, 1);
      return result;
    }
  }
  return result;
}

function getPluginNameFormDeps(deps) {
  var keys = Object.keys(deps);
  for (var i = 0, len = keys.length; i < len; i++) {
    if (WHISTLE_PLUGIN_RE.test(keys[i])) {
      return RegExp.$1;
    }
  }
}

function getPkgName(name) {
  if (/[/\\](whistle\.[a-z\d_-]+)(?:\.git)?$/.test(name)) {
    return RegExp.$1;
  }
  return name;
}

function install(cmd, name, argv, ver, pluginsCache, callback) {
  var result = getInstallDir(argv.slice());
  var isPkg = WHISTLE_PLUGIN_RE.test(name);
  var pkgName = isPkg ? name : getPkgName(name);
  var installPath = getInstallPath(getTempName(pkgName), result.dir);
  argv = result.argv;
  fse.ensureDirSync(installPath);
  fse.emptyDirSync(installPath);
  var pkgJson = PACKAGE_JSON;
  if (ver) {
    pkgJson = pkgJson.replace(',', ',"dependencies":{"' + name + '":"' + ver + '"},');
  }
  fs.writeFileSync(path.join(installPath, 'package.json'), pkgJson);
  fs.writeFileSync(path.join(installPath, 'LICENSE'), LICENSE);
  fs.writeFileSync(path.join(installPath, 'README.md'), RESP_URL);
  argv.unshift('install', name);
  pluginsCache[pkgName] = 1;
  cp.spawn(cmd, argv, {
    stdio: 'inherit',
    cwd: installPath
  }).once('exit', function(code) {
    if (code) {
      removeDir(installPath);
      callback();
    } else {
      if (!isPkg) {
        var deps = fse.readJsonSync(path.join(installPath, 'package.json')).dependencies;
        name = deps && getPluginNameFormDeps(deps);
      }
      if (!name) {
        try {
          removeDir(installPath);
        } catch (e) {}
        return callback();
      }
      var realPath = getInstallPath(name, result.dir);
      removeDir(realPath);
      try {
        fs.renameSync(installPath, realPath);
      } catch (e) {
        fse.ensureDirSync(realPath);
        fse.copySync(installPath, realPath);
        try {
          removeDir(installPath);
        } catch (e) {}
      }
      var pkgPath = path.join(realPath, 'node_modules', name, 'package.json');
      try {
        if (fs.statSync(pkgPath).mtime.getFullYear() < 2010) {
          var now = new Date();
          fs.utimesSync(pkgPath, now, now);
        }
      } catch (e) {}
      callback(pkgPath);
    }
  });
}

function readJson(pkgPath) {
  try {
    return fse.readJsonSync(pkgPath);
  } catch (e) {
    try {
      return fse.readJsonSync(pkgPath);
    } catch (e) {}
  }
}

function installPlugins(cmd, plugins, argv, pluginsCache, deep) {
  deep = deep || 0;
  var count = 0;
  var peerPlugins = [];
  var callback = function(pkgPath) {
    if (pkgPath) {
      var pkg = readJson(pkgPath) || {};
      var list = pkg.whistleConfig && (pkg.whistleConfig.peerPluginList || pkg.whistleConfig.peerPlugins);
      if (Array.isArray(list) && list.length < 16) {
        list.forEach(function(name) {
          name = typeof name === 'string' ? name.trim() : null;
          if (name && (WHISTLE_PLUGIN_RE.test(name) || REMOTE_URL_RE.test(name))) {
            name = RegExp.$1;
            if (peerPlugins.indexOf(name) === -1) {
              peerPlugins.push(name);
            }
          }
        });
      }
    }
    if (--count <= 0 && deep < 16) {
      peerPlugins = peerPlugins.filter(function(name) {
        return !pluginsCache[name];
      });
      peerPlugins.length && installPlugins(cmd, peerPlugins, argv, pluginsCache, ++deep);
    }
  };
  plugins.forEach(function(name) {
    var isPkg = WHISTLE_PLUGIN_RE.test(name);
    if (isPkg || REMOTE_URL_RE.test(name)) {
      ++count;
      name = RegExp.$1;
      var ver = RegExp.$2;
      isPkg && removeOldPlugin(name);
      install(cmd, name, argv, ver, pluginsCache, callback);
    }
  });
}

exports.getWhistlePath = getWhistlePath;

exports.install = function(cmd, argv) {
  var plugins = getPlugins(argv, true);
  if (!plugins.length) {
    return;
  }
  argv = argv.filter(function(name) {
    return plugins.indexOf(name) === -1;
  });

  cmd += CMD_SUFFIX;
  argv.push('--no-package-lock');
  installPlugins(cmd, plugins, argv, {});
};

exports.uninstall = function(plugins) {
  var result = getInstallDir(plugins);
  plugins = result.argv;
  getPlugins(plugins).forEach(function(name) {
    if (WHISTLE_PLUGIN_RE.test(name)) {
      name = RegExp.$1;
      !result.dir && removeOldPlugin(name);
      removeDir(getInstallPath(name, result.dir));
    }
  });
};

exports.run = function(cmd, argv) {
  var newPath = [];
  fse.ensureDirSync(CUSTOM_PLUGIN_PATH);
  fs.readdirSync(CUSTOM_PLUGIN_PATH).forEach(function(name) {
    if (!name.indexOf('whistle.')) {
      newPath.push(path.join(CUSTOM_PLUGIN_PATH, name, 'node_modules/.bin'));
    } else if (name[0] === '@') {
      try {
        fs.readdirSync(path.join(CUSTOM_PLUGIN_PATH, name)).forEach(function(modName) {
          newPath.push(path.join(CUSTOM_PLUGIN_PATH, name, modName, 'node_modules/.bin'));
        });
      } catch (e) {}
    }
  });
  process.env.PATH && newPath.push(process.env.PATH);
  newPath = newPath.join(os.platform() === 'win32' ? ';' : ':');
  process.env.PATH = newPath;
  cp.spawn(cmd + CMD_SUFFIX, argv, {
    stdio: 'inherit',
    env: process.env
  });
};
<|endoftext|>


<commit_before>/**
 * [IL]
 * Library Import
 */
import React, { PropTypes } from 'react';

/**
 * [IS]
 * Style Import
 */
import Styles from './Styles/main.scss';
import Palette from 'theme/Palette';

/**
 * [IA]
 * Assets Import
 */
import Arrow from 'components/Assets/Arrow.js';

function Common(props) {
    const { breadcrumbs } = props;

    const arrow = (

            <Arrow color={ Palette.midGray }/>

    );

    const items = breadcrumbs.map((item) => {
        return (

                { item.title }

        );
    })
    .reduce((row, item, i, arr) => {
        row.push(item);
        if (i < arr.length - 1) {
            row.push(arrow);
        }

        return row;
    }, []);

    console.log(items.props);

    return (

                { items }

    );
}

/**
 * [CPT]
 * Component prop types
 */
Common.propTypes = {
    breadcrumbs: PropTypes.array.isRequired
};

/**
 * [IE]
 * Export
 */
export default Common;
<commit_msg>code clearing<commit_after>/**
 * [IL]
 * Library Import
 */
import React, { PropTypes } from 'react';

/**
 * [IS]
 * Style Import
 */
import Styles from './Styles/main.scss';
import Palette from 'theme/Palette';

/**
 * [IA]
 * Assets Import
 */
import Arrow from 'components/Assets/Arrow.js';

function Common(props) {
    const { breadcrumbs } = props;

    const arrow = (

            <Arrow color={ Palette.midGray }/>

    );

    const items = breadcrumbs.map((item) => {
        return (

                { item.title }

        );
    })
    .reduce((row, item, i, arr) => {
        row.push(item);
        if (i < arr.length - 1) {
            row.push(arrow);
        }

        return row;
    }, []);

    return (

                { items }

    );
}

/**
 * [CPT]
 * Component prop types
 */
Common.propTypes = {
    breadcrumbs: PropTypes.array.isRequired
};

/**
 * [IE]
 * Export
 */
export default Common;
<|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 UtilsNew from "../../../core/utilsNew.js";
import "./variant-interpreter-browser-rd.js";
import "./variant-interpreter-browser-cancer.js";
import "./variant-interpreter-browser-cnv.js";
import "./variant-interpreter-browser-rearrangement.js";
import "../../visualization/genome-browser.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
            }
        };
    }

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

        this._config = this.getDefaultConfig();
    }

    update(changedProperties) {
        if (changedProperties.has("clinicalAnalysis")) {
            this.clinicalAnalysisObserver();
        }
        if (changedProperties.has("clinicalAnalysisId")) {
            this.clinicalAnalysisIdObserver();
        }
        super.update(changedProperties);
    }

    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];
                })
                .catch(response => {
                    console.error("An error occurred fetching clinicalAnalysis: ", response);
                });
        }
    }

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

    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}"
                                    .cellbaseClient="${this.cellbaseClient}"
                                    .settings="${this.settings.browsers["RD"]}"
                                    @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 Small Variants",
                        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}"
                                        .cellbaseClient="${this.cellbaseClient}"
                                        .settings="${this.settings.browsers["CANCER_SNV"]}"
                                        @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}">
                                    </variant-interpreter-browser-cancer>

                            `;
                        }
                    });

                    // Add CNV Variant browser
                    if (this.settings.browsers["CANCER_CNV"]) {
                        items.push({
                            id: "somatic-cnv-variant-browser",
                            name: "Somatic CNV Variants",
                            active: false,
                            render: (clinicalAnalysis, active, opencgaSession) => html`

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

                            `,
                        });
                    }

                    // Check for adding rearrangements variant browser
                    if (this.settings.browsers["REARRANGEMENT"]) {
                        items.push({
                            id: "cancer-somatic-rearrangement-variant-browser",
                            name: "Somatic Rearrangement Variants",
                            render: (clinicalAnalysis, active, opencgaSession) => html`

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

                            `,
                        });
                    }

                    // Check for adding germline browser
                    if (this._germlineSample) {
                        items.push({
                            id: "cancer-germline-variant-browser",
                            name: "Germline Small Variants",
                            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}"
                                            .cellbaseClient="${this.cellbaseClient}"
                                            .settings="${this._config}"
                                            @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}"
                                            @samplechange="${this.onSampleChange}">
                                        </variant-interpreter-browser-rd>

                                `;
                            },
                        });
                        items.push({
                            id: "rearrangement-germline-variant-browser",
                            name: "Germline Rearrangement Variants",
                            render: (clinicalAnalysis, active, opencgaSession) => html`

                                    <tool-header
                                        title="Germline Rearrangement Variant Browser - ${this._germlineSample?.id}"
                                        class="bg-white">
                                    </tool-header>
                                    <variant-interpreter-browser-rearrangement
                                        .opencgaSession="${opencgaSession}"
                                        .clinicalAnalysis="${clinicalAnalysis}"
                                        .somatic="${false}"
                                        .cellbaseClient="${this.cellbaseClient}"
                                        .settings="${this.settings.browsers["REARRANGEMENT"]}"
                                        @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}">
                                    </variant-interpreter-browser-rearrangement>

                            `,
                        });
                    }
                }
            }

            // Append genome browser
            items.push({
                id: "genome-browser",
                name: "Genome Browser (Experimental)",
                render: (clinicalAnalysis, active, opencgaSession) => html`
                    <genome-browser
                        .opencgaSession="${opencgaSession}"
                        .region="${clinicalAnalysis.interpretation.primaryFindings[0]}"
                        .active="${active}"
                        .config="${{
                            cellBaseClient: this.cellbaseClient,
                        }}"
                        .tracks="${[
                            {
                                type: "gene-overview",
                                overview: true,
                                config: {},
                            },
                            {
                                type: "sequence",
                                config: {},
                            },
                            {
                                type: "gene",
                                config: {},
                            },
                            {
                                type: "opencga-variant",
                                config: {
                                    title: "Variants",
                                    query: {
                                        sample: clinicalAnalysis.proband.samples.map(s => s.id).join(","),
                                    },
                                    height: 120,
                                },
                            },
                            {
                                type: "opencga-alignment",
                                config: {
                                    title: `Alignments - ${clinicalAnalysis.proband.samples[0].id}`,
                                    sample: clinicalAnalysis.proband.samples[0].id,
                                },
                            },
                        ]}">
                    </genome-browser>
                `,
            });
        }

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

}

customElements.define("variant-interpreter-browser", VariantInterpreterBrowser);
<commit_msg>wc: display an alignments track for each sample of the proband #TASK-731<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 "./variant-interpreter-browser-rd.js";
import "./variant-interpreter-browser-cancer.js";
import "./variant-interpreter-browser-cnv.js";
import "./variant-interpreter-browser-rearrangement.js";
import "../../visualization/genome-browser.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
            }
        };
    }

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

        this._config = this.getDefaultConfig();
    }

    update(changedProperties) {
        if (changedProperties.has("clinicalAnalysis")) {
            this.clinicalAnalysisObserver();
        }
        if (changedProperties.has("clinicalAnalysisId")) {
            this.clinicalAnalysisIdObserver();
        }
        super.update(changedProperties);
    }

    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];
                })
                .catch(response => {
                    console.error("An error occurred fetching clinicalAnalysis: ", response);
                });
        }
    }

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

    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}"
                                    .cellbaseClient="${this.cellbaseClient}"
                                    .settings="${this.settings.browsers["RD"]}"
                                    @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 Small Variants",
                        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}"
                                        .cellbaseClient="${this.cellbaseClient}"
                                        .settings="${this.settings.browsers["CANCER_SNV"]}"
                                        @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}">
                                    </variant-interpreter-browser-cancer>

                            `;
                        }
                    });

                    // Add CNV Variant browser
                    if (this.settings.browsers["CANCER_CNV"]) {
                        items.push({
                            id: "somatic-cnv-variant-browser",
                            name: "Somatic CNV Variants",
                            active: false,
                            render: (clinicalAnalysis, active, opencgaSession) => html`

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

                            `,
                        });
                    }

                    // Check for adding rearrangements variant browser
                    if (this.settings.browsers["REARRANGEMENT"]) {
                        items.push({
                            id: "cancer-somatic-rearrangement-variant-browser",
                            name: "Somatic Rearrangement Variants",
                            render: (clinicalAnalysis, active, opencgaSession) => html`

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

                            `,
                        });
                    }

                    // Check for adding germline browser
                    if (this._germlineSample) {
                        items.push({
                            id: "cancer-germline-variant-browser",
                            name: "Germline Small Variants",
                            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}"
                                            .cellbaseClient="${this.cellbaseClient}"
                                            .settings="${this._config}"
                                            @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}"
                                            @samplechange="${this.onSampleChange}">
                                        </variant-interpreter-browser-rd>

                                `;
                            },
                        });
                        items.push({
                            id: "rearrangement-germline-variant-browser",
                            name: "Germline Rearrangement Variants",
                            render: (clinicalAnalysis, active, opencgaSession) => html`

                                    <tool-header
                                        title="Germline Rearrangement Variant Browser - ${this._germlineSample?.id}"
                                        class="bg-white">
                                    </tool-header>
                                    <variant-interpreter-browser-rearrangement
                                        .opencgaSession="${opencgaSession}"
                                        .clinicalAnalysis="${clinicalAnalysis}"
                                        .somatic="${false}"
                                        .cellbaseClient="${this.cellbaseClient}"
                                        .settings="${this.settings.browsers["REARRANGEMENT"]}"
                                        @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}">
                                    </variant-interpreter-browser-rearrangement>

                            `,
                        });
                    }
                }
            }

            // Append genome browser
            items.push({
                id: "genome-browser",
                name: "Genome Browser (Beta)",
                render: (clinicalAnalysis, active, opencgaSession) => html`
                    <genome-browser
                        .opencgaSession="${opencgaSession}"
                        .region="${clinicalAnalysis.interpretation.primaryFindings[0]}"
                        .active="${active}"
                        .config="${{
                            cellBaseClient: this.cellbaseClient,
                        }}"
                        .tracks="${[
                            {
                                type: "gene-overview",
                                overview: true,
                                config: {},
                            },
                            {
                                type: "sequence",
                                config: {},
                            },
                            {
                                type: "gene",
                                config: {},
                            },
                            {
                                type: "opencga-variant",
                                config: {
                                    title: "Variants",
                                    query: {
                                        sample: clinicalAnalysis.proband.samples.map(s => s.id).join(","),
                                    },
                                    height: 120,
                                },
                            },
                            ...(clinicalAnalysis.proband?.samples || []).map(sample => ({
                                type: "opencga-alignment",
                                config: {
                                    title: `Alignments - ${sample.id}`,
                                    sample: sample.id,
                                },
                            })),
                        ]}">
                    </genome-browser>
                `,
            });
        }

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

}

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


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import { Link } from 'react-router-dom';

import Graph from 'react-graph-vis';

import { Loader } from '~/client/core';

import * as actions from '../actions';
import { testActions } from '../actionTypes';

const graphOptions = {
  width: '100%',
  height: '100%',
  layout: {
    hierarchical: false,
  },
  edges: {
    smooth: true,
    color: '#000000',
  },
  physics: {
    stabilization: true
  },
  autoResize: true,
};

const graphStyle = { width: '100%', height: '480px' };

const subStyle = {
  fontSize: '60%',
  color: 'gray',
};

class DetailPage extends React.Component {
  render = () => {
    const { loaderState: { data } } = this.props;
    const { name, total, cycle, origin, notice, source, nodes, edges } = data;

    return (

{name} {cycle} Contributions

{notice}

Data from {origin}

Donations from top contributors: {total}

        <Graph graph={{ nodes, edges }} style={graphStyle} options={graphOptions} />

    );
  }
}

DetailPage.propTypes = {
  loaderState: PropTypes.shape({
    data: PropTypes.shape({
      name: PropTypes.string.isRequired,
      total: PropTypes.string.isRequired,
      cycle: PropTypes.string.isRequired,
      origin: PropTypes.string.isRequired,
      notice: PropTypes.string.isRequired,
      source: PropTypes.string.isRequired,
      nodes: PropTypes.array.isRequired,
      edges: PropTypes.array.isRequired,
    }),
  }),
};

DetailPage.defaultProps = {
  loaderState: { data: null },
};

export default Loader({
  selector: (state) => state.pages.searchPage.detailData,
  loadAction: actions.loadDetailData,
  handleLoad: testActions.handleDetailLoad,
  clearOnBack: true,
})(DetailPage);
<commit_msg>- Added donor count to ux<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import { Link } from 'react-router-dom';

import Graph from 'react-graph-vis';

import { Loader } from '~/client/core';

import * as actions from '../actions';
import { testActions } from '../actionTypes';

const graphOptions = {
  width: '100%',
  height: '100%',
  layout: {
    hierarchical: false,
  },
  edges: {
    smooth: true,
    color: '#000000',
  },
  physics: {
    stabilization: true
  },
  autoResize: true,
};

const graphStyle = { width: '100%', height: '480px' };

const subStyle = {
  fontSize: '60%',
  color: 'gray',
};

class DetailPage extends React.Component {
  render = () => {
    const { loaderState: { data } } = this.props;
    const { name, total, cycle, origin, notice, source, nodes, edges } = data;

    return (

{name} {cycle} Contributions

{notice}

Data from {origin}

Donations from top {nodes.length - 1} contributors: {total}

        <Graph graph={{ nodes, edges }} style={graphStyle} options={graphOptions} />

    );
  }
}

DetailPage.propTypes = {
  loaderState: PropTypes.shape({
    data: PropTypes.shape({
      name: PropTypes.string.isRequired,
      total: PropTypes.string.isRequired,
      cycle: PropTypes.string.isRequired,
      origin: PropTypes.string.isRequired,
      notice: PropTypes.string.isRequired,
      source: PropTypes.string.isRequired,
      nodes: PropTypes.array.isRequired,
      edges: PropTypes.array.isRequired,
    }),
  }),
};

DetailPage.defaultProps = {
  loaderState: { data: null },
};

export default Loader({
  selector: (state) => state.pages.searchPage.detailData,
  loadAction: actions.loadDetailData,
  handleLoad: testActions.handleDetailLoad,
  clearOnBack: true,
})(DetailPage);
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "firebug/lib/object",
    "firebug/firebug",
    "firebug/lib/events",
    "firebug/chrome/menu",
    "firebug/lib/dom",
    "firebug/lib/locale",
    "firebug/lib/css",
],
function(Obj, Firebug, Events, Menu, Dom, Locale, Css) {

// ********************************************************************************************* //
// Constants

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

var MODE_JAVASCRIPT = "js";
var CONTEXT_MENU = "";
var TEXT_CHANGED = "";

try
{
    // Introduced in Firefox 8
    Cu["import"]("resource:///modules/source-editor.jsm");

    MODE_JAVASCRIPT = SourceEditor.MODES.JAVASCRIPT;
    CONTEXT_MENU = SourceEditor.EVENTS.CONTEXT_MENU;
    TEXT_CHANGED = SourceEditor.EVENTS.TEXT_CHANGED;
}
catch (err)
{
    if (FBTrace.DBG_ERRORS)
        FBTrace.sysout("commandEditor: EXCEPTION source-editors is not available!");
}

// ********************************************************************************************* //
// Command Editor

Firebug.CommandEditor = Obj.extend(Firebug.Module,
{
    dispatchName: "commandEditor",

    editor: null,

    initialize: function()
    {
        Firebug.Module.initialize.apply(this, arguments);

        if (this.editor)
            return;

        if (typeof(SourceEditor) != "undefined")
            this.editor = new SourceEditor();
        else
            this.editor = new TextEditor();

        var config =
        {
            mode: MODE_JAVASCRIPT,
            showLineNumbers: false,
            theme: "chrome://firebug/skin/orion-firebug.css"
        };

        // Custom shortcuts for Orion editor
        config.keys = [{
            action: "firebug-cmdEditor-execute",
            code: KeyEvent.DOM_VK_RETURN,
            accel: true,
            callback: this.onExecute.bind(this),
        },{
            action: "firebug-cmdEditor-escape",
            code: KeyEvent.DOM_VK_ESCAPE,
            callback: this.onEscape.bind(this),
        }];

        // Initialize Orion editor.
        this.parent = document.getElementById("fbCommandEditor");
        this.editor.init(this.parent, config, this.onEditorLoad.bind(this));

        if (FBTrace.DBG_COMMANDEDITOR)
            FBTrace.sysout("commandEditor: SourceEditor initialized");
    },

    shutdown: function()
    {
        if (!this.editor)
            return;

        try
        {
            this.editor.removeEventListener("keypress", this.onKeyPress);
        }
        catch (err)
        {
        }

        this.editor.removeEventListener(CONTEXT_MENU, this.onContextMenu);
        this.editor.removeEventListener(TEXT_CHANGED, this.onTextChanged);

        this.editor.destroy();
        this.editor = null;
    },

    /**
     * The load event handler for the source editor. This method does post-load
     * editor initialization.
     */
    onEditorLoad: function()
    {
        try
        {
            // This event is not supported in Fx11, so catch the exception
            // which is thrown.
            this.editor.addEventListener("keypress", this.onKeyPress);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERROR)
                FBTrace.sysout("commandEditor.onEditorLoad; EXCEPTION " + err, err);
        }

        // xxxHonza: Context menu support is going to change in SourceEditor
        this.editor.addEventListener(CONTEXT_MENU, this.onContextMenu);
        this.editor.addEventListener(TEXT_CHANGED, this.onTextChanged);

        this.editor.setCaretOffset(this.editor.getCharCount());

        Firebug.chrome.applyTextSize(Firebug.textSize);

        if (FBTrace.DBG_COMMANDEDITOR)
            FBTrace.sysout("commandEditor.onEditorLoad; SourceEditor loaded");
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Keyboard shortcuts

    onKeyPress: function(event)
    {
        Firebug.CommandLine.update(Firebug.currentContext);

        switch (event.keyCode)
        {
            case KeyEvent.DOM_VK_RETURN:
                if (Events.isControl(event))
                    this.onExecute();
            break;

            case KeyEvent.DOM_VK_ESCAPE:
                this.onEscape();
                event.preventDefault();
            break;
        }
    },

    onExecute: function()
    {
        var context = Firebug.currentContext, text;
        Firebug.CommandLine.update(context);
    	if(this.isCollapse === true)
			Firebug.CommandLine.enter(context);
		else
			Firebug.CommandLine.enter(context, this.getSelection());
        return true;
    },

    onEscape: function()
    {
        var context = Firebug.currentContext;
        Firebug.CommandLine.update(context);
        Firebug.CommandLine.cancel(context);
        return true;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Other Events

    onTextChanged: function(event)
    {
        // Ignore changes that are triggered by Firebug's restore logic.
        if (Firebug.CommandEditor.ignoreChanges)
            return;

        Firebug.CommandLine.onCommandLineInput(event);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Contex Menu

    onContextMenu: function(event)
    {
        var popup = document.getElementById("fbCommandEditorPopup");
        Dom.eraseNode(popup);

        var browserWindow = Firebug.chrome.window;
        var commandDispatcher = browserWindow.document.commandDispatcher;

        var items = Firebug.CommandEditor.getContextMenuItems();
        for (var i=0; i<items.length; i++)
            Menu.createMenuItem(popup, items[i]);

        if (!popup.childNodes.length)
            return;

        popup.openPopupAtScreen(event.screenX, event.screenY, true);
    },

    getContextMenuItems: function()
    {
        var items = [];
        items.push({label: Locale.$STR("Cut"), commandID: "cmd_cut"});
        items.push({label: Locale.$STR("Copy"), commandID: "cmd_copy"});
        items.push({label: Locale.$STR("Paste"), commandID: "cmd_paste"});
        items.push({label: Locale.$STR("Delete"), commandID: "cmd_delete"});
        items.push("-");
        items.push({label: Locale.$STR("SelectAll"), commandID: "cmd_selectAll"});
        return items;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Public API

    setText: function(text)
    {
        try
        {
            // When manually setting the text, ignore the TEXT_CHANGED event.
            this.ignoreChanges = true;

            if (this.editor)
                this.editor.setText(text);
        }
        catch (err)
        {
            // No exception is really expected, we just need the finally clause.
        }
        finally
        {
            this.ignoreChanges = false;
        }
    },

    getText: function()
    {
        if (this.editor)
            return this.editor.getText();
    },

    setSelectionRange: function(start, end)
    {
        if (this.editor)
            this.editor.setSelection(start, end);
    },

    select: function()
    {
        // TODO xxxHonza
    },

	getSelection: function()
	{
		var selection;
		if(this.editor){
			selection = this.editor.getSelection();
			return this.getText().substring(selection.start, selection.end);
		}
	},
	isCollapse: function(){
		var selection, ret = true;
		if(this.editor){
			selection = this.editor.getSelection();
			ret = (selection.start === selection.end);
		}
		return ret;
	},

    hasFocus: function()
    {
        try
        {
            if (this.editor)
                return this.editor.hasFocus();
        }
        catch (e)
        {
        }
    },

    fontSizeAdjust: function(adjust)
    {
        if (!this.editor || !this.editor._view)
            return;

        if (typeof(SourceEditor) != "undefined")
        {
            var doc = this.editor._view._frame.contentDocument;

            // See issue 5488
            //doc.body.style.fontSizeAdjust = adjust;
        }
        else
        {
            this.editor.textBox.style.fontSizeAdjust = adjust;
        }
    }
});

// ********************************************************************************************* //
// Getters/setters

Firebug.CommandEditor.__defineGetter__("value", function()
{
    return this.getText();
});

Firebug.CommandEditor.__defineSetter__("value", function(val)
{
    this.setText(val);
});

// ********************************************************************************************* //
// Text Editor

/**
 * A simple <textbox> element is used in environments where the Orion SourceEditor is not
 * available (such as SeaMonkey)
 */
function TextEditor() {}
TextEditor.prototype =
{
    init: function(editorElement, config, callback)
    {
        var commandEditorBox = editorElement.parentNode;

        this.textBox = commandEditorBox.ownerDocument.createElement("textbox");
        this.textBox.setAttribute("id", "fbCommandEditor");
        this.textBox.setAttribute("multiline", "true");
        this.textBox.setAttribute("flex", "1");
        this.textBox.setAttribute("newlines", "pasteintact");
        this.textBox.setAttribute("label", "CommandEditor");

        commandEditorBox.replaceChild(this.textBox, editorElement);

        // The original source editor is also loaded asynchronously.
        setTimeout(callback);
    },

    destroy: function()
    {
    },

    addEventListener: function(type, callback)
    {
        if (!type)
            return;

        Events.addEventListener(this.textBox, type, callback, true);
    },

    removeEventListener: function(type, callback)
    {
        if (!type)
            return;

        Events.removeEventListener(this.textBox, type, callback, true);
    },

    setCaretOffset: function(offset)
    {
    },

    getCharCount: function()
    {
        return this.textBox.value ? this.textBox.value.length : 0;
    },

    setText: function(text)
    {
        this.textBox.value = text;
    },

    getText: function()
    {
        return this.textBox.value;
    },

    setSelection: function(start, end)
    {
        this.textBox.setSelection(start, end);
    },

    hasFocus: function()
    {
        return this.textBox.getAttribute("focused") == "true";
    }
}

// ********************************************************************************************* //
// Registration

Firebug.registerModule(Firebug.CommandEditor);

return Firebug.CommandEditor;

// ********************************************************************************************* //
});
<commit_msg>corrected coding style<commit_after>/* See license.txt for terms of usage */

define([
    "firebug/lib/object",
    "firebug/firebug",
    "firebug/lib/events",
    "firebug/chrome/menu",
    "firebug/lib/dom",
    "firebug/lib/locale",
    "firebug/lib/css",
],
function(Obj, Firebug, Events, Menu, Dom, Locale, Css) {

// ********************************************************************************************* //
// Constants

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

var MODE_JAVASCRIPT = "js";
var CONTEXT_MENU = "";
var TEXT_CHANGED = "";

try
{
    // Introduced in Firefox 8
    Cu["import"]("resource:///modules/source-editor.jsm");

    MODE_JAVASCRIPT = SourceEditor.MODES.JAVASCRIPT;
    CONTEXT_MENU = SourceEditor.EVENTS.CONTEXT_MENU;
    TEXT_CHANGED = SourceEditor.EVENTS.TEXT_CHANGED;
}
catch (err)
{
    if (FBTrace.DBG_ERRORS)
        FBTrace.sysout("commandEditor: EXCEPTION source-editors is not available!");
}

// ********************************************************************************************* //
// Command Editor

Firebug.CommandEditor = Obj.extend(Firebug.Module,
{
    dispatchName: "commandEditor",

    editor: null,

    initialize: function()
    {
        Firebug.Module.initialize.apply(this, arguments);

        if (this.editor)
            return;

        if (typeof(SourceEditor) != "undefined")
            this.editor = new SourceEditor();
        else
            this.editor = new TextEditor();

        var config =
        {
            mode: MODE_JAVASCRIPT,
            showLineNumbers: false,
            theme: "chrome://firebug/skin/orion-firebug.css"
        };

        // Custom shortcuts for Orion editor
        config.keys = [{
            action: "firebug-cmdEditor-execute",
            code: KeyEvent.DOM_VK_RETURN,
            accel: true,
            callback: this.onExecute.bind(this),
        },{
            action: "firebug-cmdEditor-escape",
            code: KeyEvent.DOM_VK_ESCAPE,
            callback: this.onEscape.bind(this),
        }];

        // Initialize Orion editor.
        this.parent = document.getElementById("fbCommandEditor");
        this.editor.init(this.parent, config, this.onEditorLoad.bind(this));

        if (FBTrace.DBG_COMMANDEDITOR)
            FBTrace.sysout("commandEditor: SourceEditor initialized");
    },

    shutdown: function()
    {
        if (!this.editor)
            return;

        try
        {
            this.editor.removeEventListener("keypress", this.onKeyPress);
        }
        catch (err)
        {
        }

        this.editor.removeEventListener(CONTEXT_MENU, this.onContextMenu);
        this.editor.removeEventListener(TEXT_CHANGED, this.onTextChanged);

        this.editor.destroy();
        this.editor = null;
    },

    /**
     * The load event handler for the source editor. This method does post-load
     * editor initialization.
     */
    onEditorLoad: function()
    {
        try
        {
            // This event is not supported in Fx11, so catch the exception
            // which is thrown.
            this.editor.addEventListener("keypress", this.onKeyPress);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERROR)
                FBTrace.sysout("commandEditor.onEditorLoad; EXCEPTION " + err, err);
        }

        // xxxHonza: Context menu support is going to change in SourceEditor
        this.editor.addEventListener(CONTEXT_MENU, this.onContextMenu);
        this.editor.addEventListener(TEXT_CHANGED, this.onTextChanged);

        this.editor.setCaretOffset(this.editor.getCharCount());

        Firebug.chrome.applyTextSize(Firebug.textSize);

        if (FBTrace.DBG_COMMANDEDITOR)
            FBTrace.sysout("commandEditor.onEditorLoad; SourceEditor loaded");
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Keyboard shortcuts

    onKeyPress: function(event)
    {
        Firebug.CommandLine.update(Firebug.currentContext);

        switch (event.keyCode)
        {
            case KeyEvent.DOM_VK_RETURN:
                if (Events.isControl(event))
                    this.onExecute();
            break;

            case KeyEvent.DOM_VK_ESCAPE:
                this.onEscape();
                event.preventDefault();
            break;
        }
    },

    onExecute: function()
    {
        var context = Firebug.currentContext;
        Firebug.CommandLine.update(context);
        if (this.isCollapsed())
            Firebug.CommandLine.enter(context);
        else
            Firebug.CommandLine.enter(context, this.getSelection());
        return true;
    },

    onEscape: function()
    {
        var context = Firebug.currentContext;
        Firebug.CommandLine.update(context);
        Firebug.CommandLine.cancel(context);
        return true;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Other Events

    onTextChanged: function(event)
    {
        // Ignore changes that are triggered by Firebug's restore logic.
        if (Firebug.CommandEditor.ignoreChanges)
            return;

        Firebug.CommandLine.onCommandLineInput(event);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Contex Menu

    onContextMenu: function(event)
    {
        var popup = document.getElementById("fbCommandEditorPopup");
        Dom.eraseNode(popup);

        var browserWindow = Firebug.chrome.window;
        var commandDispatcher = browserWindow.document.commandDispatcher;

        var items = Firebug.CommandEditor.getContextMenuItems();
        for (var i=0; i<items.length; i++)
            Menu.createMenuItem(popup, items[i]);

        if (!popup.childNodes.length)
            return;

        popup.openPopupAtScreen(event.screenX, event.screenY, true);
    },

    getContextMenuItems: function()
    {
        var items = [];
        items.push({label: Locale.$STR("Cut"), commandID: "cmd_cut"});
        items.push({label: Locale.$STR("Copy"), commandID: "cmd_copy"});
        items.push({label: Locale.$STR("Paste"), commandID: "cmd_paste"});
        items.push({label: Locale.$STR("Delete"), commandID: "cmd_delete"});
        items.push("-");
        items.push({label: Locale.$STR("SelectAll"), commandID: "cmd_selectAll"});
        return items;
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Public API

    setText: function(text)
    {
        try
        {
            // When manually setting the text, ignore the TEXT_CHANGED event.
            this.ignoreChanges = true;

            if (this.editor)
                this.editor.setText(text);
        }
        catch (err)
        {
            // No exception is really expected, we just need the finally clause.
        }
        finally
        {
            this.ignoreChanges = false;
        }
    },

    getText: function()
    {
        if (this.editor)
            return this.editor.getText();
    },

    setSelectionRange: function(start, end)
    {
        if (this.editor)
            this.editor.setSelection(start, end);
    },

    select: function()
    {
        // TODO xxxHonza
    },

    getSelection: function()
    {
        var selection;
        if (this.editor)
        {
            selection = this.editor.getSelection();
            return this.getText().substring(selection.start, selection.end);
        }
    },

    isCollapsed: function(){
        var selection;
        if (this.editor)
        {
            selection = this.editor.getSelection();
            return selection.start === selection.end;
        }
        return true;
    },

    hasFocus: function()
    {
        try
        {
            if (this.editor)
                return this.editor.hasFocus();
        }
        catch (e)
        {
        }
    },

    fontSizeAdjust: function(adjust)
    {
        if (!this.editor || !this.editor._view)
            return;

        if (typeof(SourceEditor) != "undefined")
        {
            var doc = this.editor._view._frame.contentDocument;

            // See issue 5488
            //doc.body.style.fontSizeAdjust = adjust;
        }
        else
        {
            this.editor.textBox.style.fontSizeAdjust = adjust;
        }
    }
});

// ********************************************************************************************* //
// Getters/setters

Firebug.CommandEditor.__defineGetter__("value", function()
{
    return this.getText();
});

Firebug.CommandEditor.__defineSetter__("value", function(val)
{
    this.setText(val);
});

// ********************************************************************************************* //
// Text Editor

/**
 * A simple <textbox> element is used in environments where the Orion SourceEditor is not
 * available (such as SeaMonkey)
 */
function TextEditor() {}
TextEditor.prototype =
{
    init: function(editorElement, config, callback)
    {
        var commandEditorBox = editorElement.parentNode;

        this.textBox = commandEditorBox.ownerDocument.createElement("textbox");
        this.textBox.setAttribute("id", "fbCommandEditor");
        this.textBox.setAttribute("multiline", "true");
        this.textBox.setAttribute("flex", "1");
        this.textBox.setAttribute("newlines", "pasteintact");
        this.textBox.setAttribute("label", "CommandEditor");

        commandEditorBox.replaceChild(this.textBox, editorElement);

        // The original source editor is also loaded asynchronously.
        setTimeout(callback);
    },

    destroy: function()
    {
    },

    addEventListener: function(type, callback)
    {
        if (!type)
            return;

        Events.addEventListener(this.textBox, type, callback, true);
    },

    removeEventListener: function(type, callback)
    {
        if (!type)
            return;

        Events.removeEventListener(this.textBox, type, callback, true);
    },

    setCaretOffset: function(offset)
    {
    },

    getCharCount: function()
    {
        return this.textBox.value ? this.textBox.value.length : 0;
    },

    setText: function(text)
    {
        this.textBox.value = text;
    },

    getText: function()
    {
        return this.textBox.value;
    },

    setSelection: function(start, end)
    {
        this.textBox.setSelection(start, end);
    },

    hasFocus: function()
    {
        return this.textBox.getAttribute("focused") == "true";
    }
}

// ********************************************************************************************* //
// Registration

Firebug.registerModule(Firebug.CommandEditor);

return Firebug.CommandEditor;

// ********************************************************************************************* //
});
<|endoftext|>