<commit_before>var BOSH_SERVICE = 'http://localhost:5280/http-bind/';
var show_log = false;

Strophe.addNamespace('C2SPUBSUB', 'http://prosody.im/streams/c2s');
Strophe.addNamespace('S2SPUBSUB', 'http://prosody.im/streams/s2s');
Strophe.addNamespace('PUBSUB', 'http://jabber.org/protocol/pubsub');
Strophe.addNamespace('CAPS', 'http://jabber.org/protocol/caps');

var localJID = null;
var connection   = null;

var pubsubHost = '%PUBSUBHOST%';

function log(msg) {
    var entry = $('

').append(document.createTextNode(msg));
    $('#log').append(entry);
}

function rawInput(data) {
    log('RECV: ' + data);
}

function rawOutput(data) {
    log('SENT: ' + data);
}

function _cbNewS2S(e) {
    var items, entry, retract, id, jid;
    items = e.getElementsByTagName('item');
    for (i = 0; i < items.length; i++) {
        id = items[i].attributes['id'].value;
        jid = items[i].getElementsByTagName('session')[0].attributes['jid'].value;

        entry = $('
' + jid + '
');
        if (e.getElementsByTagName('encrypted')[0]) {
            entry.append('');
        }
        if (e.getElementsByTagName('compressed')[0]) {
            entry.append('');
        }

        if (items[i].getElementsByTagName('out')[0]) {
            entry.appendTo('#s2sout');
        } else {
            entry.appendTo('#s2sin');
        }
    }
    retract = e.getElementsByTagName('retract')[0];
    if (retract) {
        id = retract.attributes['id'].value;
        $('#' + id).remove();
    }
    return true;
}

function _cbNewC2S(e) {
    var items, entry, retract, id, jid;
    items = e.getElementsByTagName('item');
    for (i = 0; i < items.length; i++) {
        id = items[i].attributes['id'].value;
        jid = items[i].getElementsByTagName('session')[0].attributes['jid'].value;
        entry = $('
' + jid + '
');
        if (e.getElementsByTagName('encrypted')[0]) {
            entry.append('');
        }
        if (e.getElementsByTagName('compressed')[0]) {
            entry.append('');
        }
        entry.appendTo('#c2s');
    }
    retract = e.getElementsByTagName('retract')[0];
    if (retract) {
        id = retract.attributes['id'].value;
        $('#' + id).remove();
    }
    return true;
}

function _cbPubSub(e) {
    var node = e.getElementsByTagName('items')[0].attributes['node'].value;
    if (node == Strophe.NS.C2SPUBSUB) {
        _cbNewC2S(e);
    } else if (node == Strophe.NS.S2SPUBSUB) {
        _cbNewS2S(e);
    }

    return true;
}

function onConnect(status) {
    if (status == Strophe.Status.CONNECTING) {
        log('Strophe is connecting.');
    } else if (status == Strophe.Status.CONNFAIL) {
        log('Strophe failed to connect.');
        showConnect();
    } else if (status == Strophe.Status.DISCONNECTING) {
        log('Strophe is disconnecting.');
    } else if (status == Strophe.Status.DISCONNECTED) {
        log('Strophe is disconnected.');
        showConnect();
    } else if (status == Strophe.Status.AUTHFAIL) {
        log('Authentication failed');
        if (connection) {
            connection.disconnect();
        }
    } else if (status == Strophe.Status.CONNECTED) {
        log('Strophe is connected.');
        showDisconnect();
	Adhoc.checkFeatures('#adhoc', connection.domain);
        connection.addHandler(_cbPubSub, Strophe.NS.PUBSUB + '#event', 'message');
        connection.send($iq({to: pubsubHost, type: 'set', id: connection.getUniqueId()}).c('pubsub', {xmlns: Strophe.NS.PUBSUB})
                .c('subscribe', {node: Strophe.NS.C2SPUBSUB, jid: connection.jid}));
        connection.send($iq({to: pubsubHost, type: 'set', id: connection.getUniqueId()}).c('pubsub', {xmlns: Strophe.NS.PUBSUB})
                .c('subscribe', {node: Strophe.NS.S2SPUBSUB, jid: connection.jid}));
        connection.sendIQ($iq({to: pubsubHost, type: 'get', id: connection.getUniqueId()}).c('pubsub', {xmlns: Strophe.NS.PUBSUB})
                .c('items', {node: Strophe.NS.S2SPUBSUB}), _cbNewS2S);
        connection.sendIQ($iq({to: pubsubHost, type: 'get', id: connection.getUniqueId()}).c('pubsub', {xmlns: Strophe.NS.PUBSUB})
                .c('items', {node: Strophe.NS.C2SPUBSUB}), _cbNewC2S);

    }
}

function showConnect() {
    var jid = $('#jid');
    var pass = $('#pass');
    var button = $('#connect').get(0);

    button.value = 'connect';
    pass.show();
    jid.show();
    $('#menu').hide();
    $('#adhoc').hide();
    $('#s2sList').hide();
    $('#c2sList').hide();
    $('#cred label').show();
    $('#cred br').show();
    $('#s2sin').empty();
    $('#s2sout').empty();
    $('#c2s').empty();
}

function showDisconnect() {
    var jid = $('#jid');
    var pass = $('#pass');
    var button = $('#connect').get(0);

    button.value = 'disconnect';
    pass.hide();
    jid.hide();
    $('#menu').show();
    $('#adhoc').show();
    $('#cred label').hide();
    $('#cred br').hide();
}

$(document).ready(function () {
    connection = new Strophe.Connection(BOSH_SERVICE);
    if (show_log) {
        $('#log_container').show();
        connection.rawInput = rawInput;
        connection.rawOutput = rawOutput;
    }

    $("#log_toggle").click(function () {
        $("#log").toggle();
    });

    $('#cred').bind('submit', function (event) {
        var button = $('#connect').get(0);
        var jid = $('#jid');
        var pass = $('#pass');
        localJID = jid.get(0).value;

        if (button.value == 'connect') {
            $('#log').empty();
            connection.connect(localJID,
               pass.get(0).value,
               onConnect);
        } else {
            connection.disconnect();
        }
        event.preventDefault();
    });

    $('#adhocMenu').click(function () {
	$('#s2sList').slideUp();
	$('#c2sList').slideUp();
	$('#adhoc').slideDown();
        event.preventDefault();
    });

    $('#serverMenu').click(function () {
	$('#adhoc').slideUp();
	$('#c2sList').slideUp();
	$('#s2sList').slideDown();
        event.preventDefault();
    });

    $('#clientMenu').click(function () {
	$('#adhoc').slideUp();
	$('#s2sList').slideUp();
	$('#c2sList').slideDown();
        event.preventDefault();
    });

});

window.onunload = window.onbeforeunload = function() {
    if (connection) {
        connection.disconnect();
    }
}
<commit_msg>mod_admin_web: Specify only directory as bosh service, so it (normally) doesn't need changing (Thanks Zash)<commit_after>var BOSH_SERVICE = '/http-bind/';
var show_log = false;

Strophe.addNamespace('C2SPUBSUB', 'http://prosody.im/streams/c2s');
Strophe.addNamespace('S2SPUBSUB', 'http://prosody.im/streams/s2s');
Strophe.addNamespace('PUBSUB', 'http://jabber.org/protocol/pubsub');
Strophe.addNamespace('CAPS', 'http://jabber.org/protocol/caps');

var localJID = null;
var connection   = null;

var pubsubHost = '%PUBSUBHOST%';

function log(msg) {
    var entry = $('

').append(document.createTextNode(msg));
    $('#log').append(entry);
}

function rawInput(data) {
    log('RECV: ' + data);
}

function rawOutput(data) {
    log('SENT: ' + data);
}

function _cbNewS2S(e) {
    var items, entry, retract, id, jid;
    items = e.getElementsByTagName('item');
    for (i = 0; i < items.length; i++) {
        id = items[i].attributes['id'].value;
        jid = items[i].getElementsByTagName('session')[0].attributes['jid'].value;

        entry = $('
' + jid + '
');
        if (e.getElementsByTagName('encrypted')[0]) {
            entry.append('');
        }
        if (e.getElementsByTagName('compressed')[0]) {
            entry.append('');
        }

        if (items[i].getElementsByTagName('out')[0]) {
            entry.appendTo('#s2sout');
        } else {
            entry.appendTo('#s2sin');
        }
    }
    retract = e.getElementsByTagName('retract')[0];
    if (retract) {
        id = retract.attributes['id'].value;
        $('#' + id).remove();
    }
    return true;
}

function _cbNewC2S(e) {
    var items, entry, retract, id, jid;
    items = e.getElementsByTagName('item');
    for (i = 0; i < items.length; i++) {
        id = items[i].attributes['id'].value;
        jid = items[i].getElementsByTagName('session')[0].attributes['jid'].value;
        entry = $('
' + jid + '
');
        if (e.getElementsByTagName('encrypted')[0]) {
            entry.append('');
        }
        if (e.getElementsByTagName('compressed')[0]) {
            entry.append('');
        }
        entry.appendTo('#c2s');
    }
    retract = e.getElementsByTagName('retract')[0];
    if (retract) {
        id = retract.attributes['id'].value;
        $('#' + id).remove();
    }
    return true;
}

function _cbPubSub(e) {
    var node = e.getElementsByTagName('items')[0].attributes['node'].value;
    if (node == Strophe.NS.C2SPUBSUB) {
        _cbNewC2S(e);
    } else if (node == Strophe.NS.S2SPUBSUB) {
        _cbNewS2S(e);
    }

    return true;
}

function onConnect(status) {
    if (status == Strophe.Status.CONNECTING) {
        log('Strophe is connecting.');
    } else if (status == Strophe.Status.CONNFAIL) {
        log('Strophe failed to connect.');
        showConnect();
    } else if (status == Strophe.Status.DISCONNECTING) {
        log('Strophe is disconnecting.');
    } else if (status == Strophe.Status.DISCONNECTED) {
        log('Strophe is disconnected.');
        showConnect();
    } else if (status == Strophe.Status.AUTHFAIL) {
        log('Authentication failed');
        if (connection) {
            connection.disconnect();
        }
    } else if (status == Strophe.Status.CONNECTED) {
        log('Strophe is connected.');
        showDisconnect();
	Adhoc.checkFeatures('#adhoc', connection.domain);
        connection.addHandler(_cbPubSub, Strophe.NS.PUBSUB + '#event', 'message');
        connection.send($iq({to: pubsubHost, type: 'set', id: connection.getUniqueId()}).c('pubsub', {xmlns: Strophe.NS.PUBSUB})
                .c('subscribe', {node: Strophe.NS.C2SPUBSUB, jid: connection.jid}));
        connection.send($iq({to: pubsubHost, type: 'set', id: connection.getUniqueId()}).c('pubsub', {xmlns: Strophe.NS.PUBSUB})
                .c('subscribe', {node: Strophe.NS.S2SPUBSUB, jid: connection.jid}));
        connection.sendIQ($iq({to: pubsubHost, type: 'get', id: connection.getUniqueId()}).c('pubsub', {xmlns: Strophe.NS.PUBSUB})
                .c('items', {node: Strophe.NS.S2SPUBSUB}), _cbNewS2S);
        connection.sendIQ($iq({to: pubsubHost, type: 'get', id: connection.getUniqueId()}).c('pubsub', {xmlns: Strophe.NS.PUBSUB})
                .c('items', {node: Strophe.NS.C2SPUBSUB}), _cbNewC2S);

    }
}

function showConnect() {
    var jid = $('#jid');
    var pass = $('#pass');
    var button = $('#connect').get(0);

    button.value = 'connect';
    pass.show();
    jid.show();
    $('#menu').hide();
    $('#adhoc').hide();
    $('#s2sList').hide();
    $('#c2sList').hide();
    $('#cred label').show();
    $('#cred br').show();
    $('#s2sin').empty();
    $('#s2sout').empty();
    $('#c2s').empty();
}

function showDisconnect() {
    var jid = $('#jid');
    var pass = $('#pass');
    var button = $('#connect').get(0);

    button.value = 'disconnect';
    pass.hide();
    jid.hide();
    $('#menu').show();
    $('#adhoc').show();
    $('#cred label').hide();
    $('#cred br').hide();
}

$(document).ready(function () {
    connection = new Strophe.Connection(BOSH_SERVICE);
    if (show_log) {
        $('#log_container').show();
        connection.rawInput = rawInput;
        connection.rawOutput = rawOutput;
    }

    $("#log_toggle").click(function () {
        $("#log").toggle();
    });

    $('#cred').bind('submit', function (event) {
        var button = $('#connect').get(0);
        var jid = $('#jid');
        var pass = $('#pass');
        localJID = jid.get(0).value;

        if (button.value == 'connect') {
            $('#log').empty();
            connection.connect(localJID,
               pass.get(0).value,
               onConnect);
        } else {
            connection.disconnect();
        }
        event.preventDefault();
    });

    $('#adhocMenu').click(function () {
	$('#s2sList').slideUp();
	$('#c2sList').slideUp();
	$('#adhoc').slideDown();
        event.preventDefault();
    });

    $('#serverMenu').click(function () {
	$('#adhoc').slideUp();
	$('#c2sList').slideUp();
	$('#s2sList').slideDown();
        event.preventDefault();
    });

    $('#clientMenu').click(function () {
	$('#adhoc').slideUp();
	$('#s2sList').slideUp();
	$('#c2sList').slideDown();
        event.preventDefault();
    });

});

window.onunload = window.onbeforeunload = function() {
    if (connection) {
        connection.disconnect();
    }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of the React source tree.
 */

const scriptTypes = ["text/jsx", "text/babel"];

let headEl;
let inlineScriptCount = 0;

/**
 * Actually transform the code.
 */
function transformCode(transformFn, script) {
  let source;
  if (script.url != null) {
    source = script.url;
  } else {
    source = "Inline Babel script";
    inlineScriptCount++;
    if (inlineScriptCount > 1) {
      source += " (" + inlineScriptCount + ")";
    }
  }

  return transformFn(script.content, {
    filename: source,
    ...buildBabelOptions(script),
  }).code;
}

/**
 * Builds the Babel options for transforming the specified script, using some
 * sensible default presets and plugins if none were explicitly provided.
 */
function buildBabelOptions(script) {
  return {
    presets: script.presets || ["react", "es2015"],
    plugins: script.plugins || [
      "proposal-class-properties",
      "proposal-object-rest-spread",
      "transform-flow-strip-types",
    ],
    sourceMaps: "inline",
  };
}

/**
 * Appends a script element at the end of the <head> with the content of code,
 * after transforming it.
 */
function run(transformFn, script) {
  const scriptEl = document.createElement("script");
  scriptEl.text = transformCode(transformFn, script);
  headEl.appendChild(scriptEl);
}

/**
 * Load script from the provided url and pass the content to the callback.
 */
function load(url, successCallback, errorCallback) {
  const xhr = new XMLHttpRequest();

  // async, however scripts will be executed in the order they are in the
  // DOM to mirror normal script loading.
  xhr.open("GET", url, true);
  if ("overrideMimeType" in xhr) {
    xhr.overrideMimeType("text/plain");
  }
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === 0 || xhr.status === 200) {
        successCallback(xhr.responseText);
      } else {
        errorCallback();
        throw new Error("Could not load " + url);
      }
    }
  };
  return xhr.send(null);
}

/**
 * Converts a comma-separated data attribute string into an array of values. If
 * the string is empty, returns an empty array. If the string is not defined,
 * returns null.
 */
function getPluginsOrPresetsFromScript(script, attributeName) {
  const rawValue = script.getAttribute(attributeName);
  if (rawValue === "") {
    // Empty string means to not load ANY presets or plugins
    return [];
  }
  if (!rawValue) {
    // Any other falsy value (null, undefined) means we're not overriding this
    // setting, and should use the default.
    return null;
  }
  return rawValue.split(",").map(item => item.trim());
}

/**
 * Loop over provided script tags and get the content, via innerHTML if an
 * inline script, or by using XHR. Transforms are applied if needed. The scripts
 * are executed in the order they are found on the page.
 */
function loadScripts(transformFn, scripts) {
  const result = [];
  const count = scripts.length;

  function check() {
    let script, i;

    for (i = 0; i < count; i++) {
      script = result[i];

      if (script.loaded && !script.executed) {
        script.executed = true;
        run(transformFn, script);
      } else if (!script.loaded && !script.error && !script.async) {
        break;
      }
    }
  }

  scripts.forEach((script, i) => {
    const scriptData = {
      // script.async is always true for non-JavaScript script tags
      async: script.hasAttribute("async"),
      error: false,
      executed: false,
      plugins: getPluginsOrPresetsFromScript(script, "data-plugins"),
      presets: getPluginsOrPresetsFromScript(script, "data-presets"),
    };

    if (script.src) {
      result[i] = {
        ...scriptData,
        content: null,
        loaded: false,
        url: script.src,
      };

      load(
        script.src,
        content => {
          result[i].loaded = true;
          result[i].content = content;
          check();
        },
        () => {
          result[i].error = true;
          check();
        },
      );
    } else {
      result[i] = {
        ...scriptData,
        content: script.innerHTML,
        loaded: true,
        url: script.getAttribute("data-module") || null,
      };
    }
  });

  check();
}

/**
 * Run script tags with type="text/jsx".
 * @param {Array} scriptTags specify script tags to run, run all in the <head> if not given
 */
export function runScripts(transformFn, scripts) {
  headEl = document.getElementsByTagName("head")[0];
  if (!scripts) {
    scripts = document.getElementsByTagName("script");
  }

  // Array.prototype.slice cannot be used on NodeList on IE8
  const jsxScripts = [];
  for (let i = 0; i < scripts.length; i++) {
    const script = scripts.item(i);
    // Support the old type="text/jsx;harmony=true"
    const type = script.type.split(";")[0];
    if (scriptTypes.indexOf(type) !== -1) {
      jsxScripts.push(script);
    }
  }

  if (jsxScripts.length === 0) {
    return;
  }

  console.warn(
    "You are using the in-browser Babel transformer. Be sure to precompile " +
      "your scripts for production - https://babeljs.io/docs/setup/",
  );

  loadScripts(transformFn, jsxScripts);
}
<commit_msg>fix: specify sourceFileName when generating inline sourcemaps (#10797)<commit_after>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of the React source tree.
 */

const scriptTypes = ["text/jsx", "text/babel"];

let headEl;
let inlineScriptCount = 0;

/**
 * Actually transform the code.
 */
function transformCode(transformFn, script) {
  let source;
  if (script.url != null) {
    source = script.url;
  } else {
    source = "Inline Babel script";
    inlineScriptCount++;
    if (inlineScriptCount > 1) {
      source += " (" + inlineScriptCount + ")";
    }
  }

  return transformFn(script.content, buildBabelOptions(script, source)).code;
}

/**
 * Builds the Babel options for transforming the specified script, using some
 * sensible default presets and plugins if none were explicitly provided.
 */
function buildBabelOptions(script, filename) {
  return {
    filename,
    presets: script.presets || ["react", "es2015"],
    plugins: script.plugins || [
      "proposal-class-properties",
      "proposal-object-rest-spread",
      "transform-flow-strip-types",
    ],
    sourceMaps: "inline",
    sourceFileName: filename,
  };
}

/**
 * Appends a script element at the end of the <head> with the content of code,
 * after transforming it.
 */
function run(transformFn, script) {
  const scriptEl = document.createElement("script");
  scriptEl.text = transformCode(transformFn, script);
  headEl.appendChild(scriptEl);
}

/**
 * Load script from the provided url and pass the content to the callback.
 */
function load(url, successCallback, errorCallback) {
  const xhr = new XMLHttpRequest();

  // async, however scripts will be executed in the order they are in the
  // DOM to mirror normal script loading.
  xhr.open("GET", url, true);
  if ("overrideMimeType" in xhr) {
    xhr.overrideMimeType("text/plain");
  }
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === 0 || xhr.status === 200) {
        successCallback(xhr.responseText);
      } else {
        errorCallback();
        throw new Error("Could not load " + url);
      }
    }
  };
  return xhr.send(null);
}

/**
 * Converts a comma-separated data attribute string into an array of values. If
 * the string is empty, returns an empty array. If the string is not defined,
 * returns null.
 */
function getPluginsOrPresetsFromScript(script, attributeName) {
  const rawValue = script.getAttribute(attributeName);
  if (rawValue === "") {
    // Empty string means to not load ANY presets or plugins
    return [];
  }
  if (!rawValue) {
    // Any other falsy value (null, undefined) means we're not overriding this
    // setting, and should use the default.
    return null;
  }
  return rawValue.split(",").map(item => item.trim());
}

/**
 * Loop over provided script tags and get the content, via innerHTML if an
 * inline script, or by using XHR. Transforms are applied if needed. The scripts
 * are executed in the order they are found on the page.
 */
function loadScripts(transformFn, scripts) {
  const result = [];
  const count = scripts.length;

  function check() {
    let script, i;

    for (i = 0; i < count; i++) {
      script = result[i];

      if (script.loaded && !script.executed) {
        script.executed = true;
        run(transformFn, script);
      } else if (!script.loaded && !script.error && !script.async) {
        break;
      }
    }
  }

  scripts.forEach((script, i) => {
    const scriptData = {
      // script.async is always true for non-JavaScript script tags
      async: script.hasAttribute("async"),
      error: false,
      executed: false,
      plugins: getPluginsOrPresetsFromScript(script, "data-plugins"),
      presets: getPluginsOrPresetsFromScript(script, "data-presets"),
    };

    if (script.src) {
      result[i] = {
        ...scriptData,
        content: null,
        loaded: false,
        url: script.src,
      };

      load(
        script.src,
        content => {
          result[i].loaded = true;
          result[i].content = content;
          check();
        },
        () => {
          result[i].error = true;
          check();
        },
      );
    } else {
      result[i] = {
        ...scriptData,
        content: script.innerHTML,
        loaded: true,
        url: script.getAttribute("data-module") || null,
      };
    }
  });

  check();
}

/**
 * Run script tags with type="text/jsx".
 * @param {Array} scriptTags specify script tags to run, run all in the <head> if not given
 */
export function runScripts(transformFn, scripts) {
  headEl = document.getElementsByTagName("head")[0];
  if (!scripts) {
    scripts = document.getElementsByTagName("script");
  }

  // Array.prototype.slice cannot be used on NodeList on IE8
  const jsxScripts = [];
  for (let i = 0; i < scripts.length; i++) {
    const script = scripts.item(i);
    // Support the old type="text/jsx;harmony=true"
    const type = script.type.split(";")[0];
    if (scriptTypes.indexOf(type) !== -1) {
      jsxScripts.push(script);
    }
  }

  if (jsxScripts.length === 0) {
    return;
  }

  console.warn(
    "You are using the in-browser Babel transformer. Be sure to precompile " +
      "your scripts for production - https://babeljs.io/docs/setup/",
  );

  loadScripts(transformFn, jsxScripts);
}
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import TextField from 'material-ui/TextField'

import { validateUsername } from 'web-utils'

class UsernameField extends React.Component {
  constructor (props) {
    super(props)
    this.username = null
    this.state = {
      username: null,
      error: null
    }
  }

  componentWillReceiveProps (nextProps) {
    console.log(nextProps)
    if (nextProps.usernameDuplicate) {
      this.setErrorMessage('Username is already taken.')
    }
  }

  hasValue () {
    return this.username.input &&
      this.username.input.value &&
      this.username.input.value.trim()
  }

  getValue () {
    if (this.hasValue) {
      return this.username.input.value.trim()
    }
    return null
  }

  setErrorMessage (message) {
    this.setState({
      error: message
    })
  }

  validate () {
    if (this.hasValue()) {
      const username = this.username.input.value.trim()
      const isValid = validateUsername(username)
      if (!isValid) {
        this.setErrorMessage('Username is invalid.')
      } else {
        this.setErrorMessage(null)
      }
      return isValid
    }
    return false
  }

  render () {
    const props = Object.assign({}, this.props)
    delete props['inputId']
    delete props['usernameDuplicate']

    return (
      <TextField
        id={this.props.inputId}
        ref={(input) => { this.username = input }}
        {...props}
        errorText={this.state.error} />
    )
  }
}

UsernameField.propTypes = {
  inputId: PropTypes.string.isRequired,
  usernameDuplicate: PropTypes.bool.isRequired
}

export default UsernameField
<commit_msg>Add more helpful error messages for username length.<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import TextField from 'material-ui/TextField'

import { validateUsername } from 'web-utils'

class UsernameField extends React.Component {
  constructor (props) {
    super(props)
    this.username = null
    this.state = {
      username: null,
      error: null
    }
  }

  componentWillReceiveProps (nextProps) {
    console.log(nextProps)
    if (nextProps.usernameDuplicate) {
      this.setErrorMessage('Username is already taken.')
    }
  }

  hasValue () {
    return this.username.input &&
      this.username.input.value &&
      this.username.input.value.trim()
  }

  getValue () {
    if (this.hasValue) {
      return this.username.input.value.trim()
    }
    return null
  }

  setErrorMessage (message) {
    this.setState({
      error: message
    })
  }

  validate () {
    if (this.hasValue()) {
      const username = this.username.input.value.trim()
      const isValid = validateUsername(username)
      if (!isValid) {
        if (username.length < 2) {
          this.setErrorMessage('Must be at least two characters.')
        } else {
          this.setErrorMessage('Username is invalid.')
        }
      } else {
        this.setErrorMessage(null)
      }
      return isValid
    }
    return false
  }

  render () {
    const props = Object.assign({}, this.props)
    delete props['inputId']
    delete props['usernameDuplicate']

    return (
      <TextField
        id={this.props.inputId}
        ref={(input) => { this.username = input }}
        {...props}
        errorText={this.state.error} />
    )
  }
}

UsernameField.propTypes = {
  inputId: PropTypes.string.isRequired,
  usernameDuplicate: PropTypes.bool.isRequired
}

export default UsernameField
<|endoftext|>


<commit_before>var clusterpost = require("clusterpost-lib");
var path = require('path');
var os = require('os');
var argv = require('minimist')(process.argv.slice(2));
var Converter=require("csvtojson").Converter;
var fs=require('fs');
var _=require('underscore');
var Promise = require('bluebird');
var csvtojson = require('csvtojson');

var help = function(){
    console.error("help: To execute the program you must provide a csv file with columns 'name,dwi,t1,mask,table,surface,surface_color,labelname,ignore_label,overlapping,loopcheck,create_tar'")
    console.error(process.argv[0], process.argv[1], "--csv <csvfilename>");
    console.error("--execution_server <default killdevil>");
    console.error("--queue <default fortnight>");
    console.error("--email <default None, to set the jobs email (for admin only users)>");
}

if(!argv["csv"]){
    help();
    process.exit(1);
}

var readCSV = function(filename){
    return new Promise(function(resolve, reject){
        var objarr = [];
        csvtojson()
        .fromFile(filename)
        .on('json', function(jsonObj){
            objarr.push(jsonObj);
        })
        .on('end', function(){
            resolve(objarr);
        })
        .on('error', function(err){
            reject(err);
        })
    });
}

var agentoptions = {
    rejectUnauthorized: false
}

clusterpost.setAgentOptions(agentoptions);

clusterpost.start(path.join(os.homedir(), '.civility.json'))
.then(function(){
    return clusterpost.getUser();
})
.then(function(res){

    return readCSV(argv["csv"])
    .then(function(civility_csv_arr){

        return Promise.map(civility_csv_arr, function(civility_params){
            var inputfiles = [];
            inputfiles.push(civility_params['dwi']);
            inputfiles.push(civility_params['t1']);
            inputfiles.push(civility_params['mask']);
            inputfiles.push(civility_params['table']);
            inputfiles.push(civility_params['surface']);
            if(civility_params['surface_color']){
                inputfiles.push(civility_params['surface_color']);
            }

            var job = {
                "type": "job",
                "name": civility_params['name'],
                "executable": "tractographyScriptAppv2.0.sh",
                "parameters": [
                    {
                        "flag": "--subject",
                        "name": civility_params['name']
                    },
                    {
                        "flag": "--dwi",
                        "name": path.basename(civility_params['dwi'])
                    },
                    {
                        "flag": "--t1",
                        "name": path.basename(civility_params['t1'])
                    },
                    {
                        "flag": "--mask",
                        "name": path.basename(civility_params['mask'])
                    },
                    {
                        "flag": "--table",
                        "name": path.basename(civility_params['table'])
                    },
                    {
                        "flag": "--surface",
                        "name": path.basename(civility_params['surface'])
                    },
                    {
                        "flag": "--label_name",
                        "name": civility_params['labelname']
                    },
                    {
                        "flag": "--bedpostxParam",
                        "name": '-n 2'
                    },
                    {
                        "flag": "--probtrackParam",
                        "name": '-P 3000 --steplength=0.75 --sampvox=0.5'
                    }
                ],
                "inputs": [
                    {
                        "name": path.basename(civility_params['dwi'])
                    },
                    {
                        "name": path.basename(civility_params['t1'])
                    },
                    {
                        "name": path.basename(civility_params['mask'])
                    },
                    {
                        "name": path.basename(civility_params['table'])
                    },
                    {
                        "name": path.basename(civility_params['surface'])
                    }
                ],
                "outputs": [
                    {
                        "type": "file",
                        "name": "stdout.out"
                    },
                    {
                        "type": "file",
                        "name": "stderr.err"
                    }
                ],
                "jobparameters" : [
                    {
                        flag: "-n",
                        name: "1"
                    },
                    {
                        flag:"-R",
                        name: "span[hosts=1]"
                    },
                    {
                        flag: "-M",
                        name: "10"
                    },
                    {
                        flag: "-q",
                        name:  argv["queue"]? argv["queue"] : "fortnight"
                    }
                ],
                "userEmail": argv["email"]? argv["email"] : res.email
            };

            if(civility_params['surface_color']){
                job.parameters.push({
                    "flag": "--extra_surface",
                    "name": path.basename(civility_params['surface_color'])
                })
            }

            if(civility_params['ignore_label']){
                job.parameters.push({
                    "flag": "--ignore_label",
                    "name": civility_params['ignore_label']
                })
            }

            if(civility_params['overlapping']){
                job.parameters.push({
                    "flag": "--overlapping",
                    "name": civility_params['overlapping'].toUpperCase() == "TRUE"? "true": "false"
                });
            }

            if(civility_params['loopcheck']){
                job.parameters.push({
                    "flag": "--loopcheck",
                    "name": civility_params['loopcheck'].toUpperCase() == "TRUE"? "true": "false"
                })
            }else{
                job.parameters.push({
                    "flag": "--loopcheck",
                    "name": "true"
                })
            }

            if(civility_params['create_tar'].toUpperCase() == "TRUE"){
                job.outputs.push({
                        "type": "tar.gz",
                        "name": "./"
                });
            }

            job.executionserver = argv["executionserver"]? argv["executionserver"] : "killdevil";
            return clusterpost.createAndSubmitJob(job, inputfiles);
        }, {concurrency: 1});
    });
})
.then(function(){
    process.exit(0);
})
.catch(console.error)
<commit_msg>STYLE: Print when a job is being submitted<commit_after>var clusterpost = require("clusterpost-lib");
var path = require('path');
var os = require('os');
var argv = require('minimist')(process.argv.slice(2));
var Converter=require("csvtojson").Converter;
var fs=require('fs');
var _=require('underscore');
var Promise = require('bluebird');
var csvtojson = require('csvtojson');

var help = function(){
    console.error("help: To execute the program you must provide a csv file with columns 'name,dwi,t1,mask,table,surface,surface_color,labelname,ignore_label,overlapping,loopcheck,create_tar'")
    console.error(process.argv[0], process.argv[1], "--csv <csvfilename>");
    console.error("--execution_server <default killdevil>");
    console.error("--queue <default fortnight>");
    console.error("--email <default None, to set the jobs email (for admin only users)>");
}

if(!argv["csv"]){
    help();
    process.exit(1);
}

var readCSV = function(filename){
    return new Promise(function(resolve, reject){
        var objarr = [];
        csvtojson()
        .fromFile(filename)
        .on('json', function(jsonObj){
            objarr.push(jsonObj);
        })
        .on('end', function(){
            resolve(objarr);
        })
        .on('error', function(err){
            reject(err);
        })
    });
}

var agentoptions = {
    rejectUnauthorized: false
}

clusterpost.setAgentOptions(agentoptions);

clusterpost.start(path.join(os.homedir(), '.civility.json'))
.then(function(){
    return clusterpost.getUser();
})
.then(function(res){

    return readCSV(argv["csv"])
    .then(function(civility_csv_arr){

        return Promise.map(civility_csv_arr, function(civility_params){
            var inputfiles = [];
            inputfiles.push(civility_params['dwi']);
            inputfiles.push(civility_params['t1']);
            inputfiles.push(civility_params['mask']);
            inputfiles.push(civility_params['table']);
            inputfiles.push(civility_params['surface']);
            if(civility_params['surface_color']){
                inputfiles.push(civility_params['surface_color']);
            }

            var job = {
                "type": "job",
                "name": civility_params['name'],
                "executable": "tractographyScriptAppv2.0.sh",
                "parameters": [
                    {
                        "flag": "--subject",
                        "name": civility_params['name']
                    },
                    {
                        "flag": "--dwi",
                        "name": path.basename(civility_params['dwi'])
                    },
                    {
                        "flag": "--t1",
                        "name": path.basename(civility_params['t1'])
                    },
                    {
                        "flag": "--mask",
                        "name": path.basename(civility_params['mask'])
                    },
                    {
                        "flag": "--table",
                        "name": path.basename(civility_params['table'])
                    },
                    {
                        "flag": "--surface",
                        "name": path.basename(civility_params['surface'])
                    },
                    {
                        "flag": "--label_name",
                        "name": civility_params['labelname']
                    },
                    {
                        "flag": "--bedpostxParam",
                        "name": '-n 2'
                    },
                    {
                        "flag": "--probtrackParam",
                        "name": '-P 3000 --steplength=0.75 --sampvox=0.5'
                    }
                ],
                "inputs": [
                    {
                        "name": path.basename(civility_params['dwi'])
                    },
                    {
                        "name": path.basename(civility_params['t1'])
                    },
                    {
                        "name": path.basename(civility_params['mask'])
                    },
                    {
                        "name": path.basename(civility_params['table'])
                    },
                    {
                        "name": path.basename(civility_params['surface'])
                    }
                ],
                "outputs": [
                    {
                        "type": "file",
                        "name": "stdout.out"
                    },
                    {
                        "type": "file",
                        "name": "stderr.err"
                    }
                ],
                "jobparameters" : [
                    {
                        flag: "-n",
                        name: "1"
                    },
                    {
                        flag:"-R",
                        name: "span[hosts=1]"
                    },
                    {
                        flag: "-M",
                        name: "10"
                    },
                    {
                        flag: "-q",
                        name:  argv["queue"]? argv["queue"] : "fortnight"
                    }
                ],
                "userEmail": argv["email"]? argv["email"] : res.email
            };

            if(civility_params['surface_color']){
                job.parameters.push({
                    "flag": "--extra_surface",
                    "name": path.basename(civility_params['surface_color'])
                })
            }

            if(civility_params['ignore_label']){
                job.parameters.push({
                    "flag": "--ignore_label",
                    "name": civility_params['ignore_label']
                })
            }

            if(civility_params['overlapping']){
                job.parameters.push({
                    "flag": "--overlapping",
                    "name": civility_params['overlapping'].toUpperCase() == "TRUE"? "true": "false"
                });
            }

            if(civility_params['loopcheck']){
                job.parameters.push({
                    "flag": "--loopcheck",
                    "name": civility_params['loopcheck'].toUpperCase() == "TRUE"? "true": "false"
                })
            }else{
                job.parameters.push({
                    "flag": "--loopcheck",
                    "name": "true"
                })
            }

            if(civility_params['create_tar'].toUpperCase() == "TRUE"){
                job.outputs.push({
                        "type": "tar.gz",
                        "name": "./"
                });
            }

            job.executionserver = argv["executionserver"]? argv["executionserver"] : "killdevil";

            console.log("Submitting job:" job);

            return clusterpost.createAndSubmitJob(job, inputfiles);
        }, {concurrency: 1});
    });
})
.then(function(){
    process.exit(0);
})
.catch(console.error)
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of the React source tree.
 */

const scriptTypes = ["text/jsx", "text/babel"];

let headEl;
let inlineScriptCount = 0;

/**
 * Actually transform the code.
 */
function transformCode(transformFn, script) {
  let source;
  if (script.url != null) {
    source = script.url;
  } else {
    source = "Inline Babel script";
    inlineScriptCount++;
    if (inlineScriptCount > 1) {
      source += " (" + inlineScriptCount + ")";
    }
  }

  return transformFn(script.content, buildBabelOptions(script, source)).code;
}

/**
 * Builds the Babel options for transforming the specified script, using some
 * sensible default presets and plugins if none were explicitly provided.
 */
function buildBabelOptions(script, filename) {
  return {
    filename,
    presets: script.presets || ["react", "es2015"],
    plugins: script.plugins || [
      "proposal-class-properties",
      "proposal-object-rest-spread",
      "transform-flow-strip-types",
    ],
    sourceMaps: "inline",
    sourceFileName: filename,
  };
}

/**
 * Appends a script element at the end of the <head> with the content of code,
 * after transforming it.
 */
function run(transformFn, script) {
  const scriptEl = document.createElement("script");
  if (typeof script.type !== "undefined") {
    scriptEl.setAttribute("type", script.type);
  }
  scriptEl.text = transformCode(transformFn, script);
  headEl.appendChild(scriptEl);
}

/**
 * Load script from the provided url and pass the content to the callback.
 */
function load(url, successCallback, errorCallback) {
  const xhr = new XMLHttpRequest();

  // async, however scripts will be executed in the order they are in the
  // DOM to mirror normal script loading.
  xhr.open("GET", url, true);
  if ("overrideMimeType" in xhr) {
    xhr.overrideMimeType("text/plain");
  }
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === 0 || xhr.status === 200) {
        successCallback(xhr.responseText);
      } else {
        errorCallback();
        throw new Error("Could not load " + url);
      }
    }
  };
  return xhr.send(null);
}

/**
 * Converts a comma-separated data attribute string into an array of values. If
 * the string is empty, returns an empty array. If the string is not defined,
 * returns null.
 */
function getPluginsOrPresetsFromScript(script, attributeName) {
  const rawValue = script.getAttribute(attributeName);
  if (rawValue === "") {
    // Empty string means to not load ANY presets or plugins
    return [];
  }
  if (!rawValue) {
    // Any other falsy value (null, undefined) means we're not overriding this
    // setting, and should use the default.
    return null;
  }
  return rawValue.split(",").map(item => item.trim());
}

/**
 * Loop over provided script tags and get the content, via innerHTML if an
 * inline script, or by using XHR. Transforms are applied if needed. The scripts
 * are executed in the order they are found on the page.
 */
function loadScripts(transformFn, scripts) {
  const result = [];
  const count = scripts.length;

  function check() {
    let script, i;

    for (i = 0; i < count; i++) {
      script = result[i];

      if (script.loaded && !script.executed) {
        script.executed = true;
        run(transformFn, script);
      } else if (!script.loaded && !script.error && !script.async) {
        break;
      }
    }
  }

  scripts.forEach((script, i) => {
    const scriptData = {
      // script.async is always true for non-JavaScript script tags
      async: script.hasAttribute("async"),
      type: script.getAttribute("data-type"),
      error: false,
      executed: false,
      plugins: getPluginsOrPresetsFromScript(script, "data-plugins"),
      presets: getPluginsOrPresetsFromScript(script, "data-presets"),
    };

    if (script.src) {
      result[i] = {
        ...scriptData,
        content: null,
        loaded: false,
        url: script.src,
      };

      load(
        script.src,
        content => {
          result[i].loaded = true;
          result[i].content = content;
          check();
        },
        () => {
          result[i].error = true;
          check();
        },
      );
    } else {
      result[i] = {
        ...scriptData,
        content: script.innerHTML,
        loaded: true,
        url: script.getAttribute("data-module") || null,
      };
    }
  });

  check();
}

/**
 * Run script tags with type="text/jsx".
 * @param {Array} scriptTags specify script tags to run, run all in the <head> if not given
 */
export function runScripts(transformFn, scripts) {
  headEl = document.getElementsByTagName("head")[0];
  if (!scripts) {
    scripts = document.getElementsByTagName("script");
  }

  // Array.prototype.slice cannot be used on NodeList on IE8
  const jsxScripts = [];
  for (let i = 0; i < scripts.length; i++) {
    const script = scripts.item(i);
    // Support the old type="text/jsx;harmony=true"
    const type = script.type.split(";")[0];
    if (scriptTypes.indexOf(type) !== -1) {
      jsxScripts.push(script);
    }
  }

  if (jsxScripts.length === 0) {
    return;
  }

  console.warn(
    "You are using the in-browser Babel transformer. Be sure to precompile " +
      "your scripts for production - https://babeljs.io/docs/setup/",
  );

  loadScripts(transformFn, jsxScripts);
}
<commit_msg>Fix standalone tag when data-type is not set. (#11624)<commit_after>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of the React source tree.
 */

const scriptTypes = ["text/jsx", "text/babel"];

let headEl;
let inlineScriptCount = 0;

/**
 * Actually transform the code.
 */
function transformCode(transformFn, script) {
  let source;
  if (script.url != null) {
    source = script.url;
  } else {
    source = "Inline Babel script";
    inlineScriptCount++;
    if (inlineScriptCount > 1) {
      source += " (" + inlineScriptCount + ")";
    }
  }

  return transformFn(script.content, buildBabelOptions(script, source)).code;
}

/**
 * Builds the Babel options for transforming the specified script, using some
 * sensible default presets and plugins if none were explicitly provided.
 */
function buildBabelOptions(script, filename) {
  return {
    filename,
    presets: script.presets || ["react", "es2015"],
    plugins: script.plugins || [
      "proposal-class-properties",
      "proposal-object-rest-spread",
      "transform-flow-strip-types",
    ],
    sourceMaps: "inline",
    sourceFileName: filename,
  };
}

/**
 * Appends a script element at the end of the <head> with the content of code,
 * after transforming it.
 */
function run(transformFn, script) {
  const scriptEl = document.createElement("script");
  if (script.type) {
    scriptEl.setAttribute("type", script.type);
  }
  scriptEl.text = transformCode(transformFn, script);
  headEl.appendChild(scriptEl);
}

/**
 * Load script from the provided url and pass the content to the callback.
 */
function load(url, successCallback, errorCallback) {
  const xhr = new XMLHttpRequest();

  // async, however scripts will be executed in the order they are in the
  // DOM to mirror normal script loading.
  xhr.open("GET", url, true);
  if ("overrideMimeType" in xhr) {
    xhr.overrideMimeType("text/plain");
  }
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === 0 || xhr.status === 200) {
        successCallback(xhr.responseText);
      } else {
        errorCallback();
        throw new Error("Could not load " + url);
      }
    }
  };
  return xhr.send(null);
}

/**
 * Converts a comma-separated data attribute string into an array of values. If
 * the string is empty, returns an empty array. If the string is not defined,
 * returns null.
 */
function getPluginsOrPresetsFromScript(script, attributeName) {
  const rawValue = script.getAttribute(attributeName);
  if (rawValue === "") {
    // Empty string means to not load ANY presets or plugins
    return [];
  }
  if (!rawValue) {
    // Any other falsy value (null, undefined) means we're not overriding this
    // setting, and should use the default.
    return null;
  }
  return rawValue.split(",").map(item => item.trim());
}

/**
 * Loop over provided script tags and get the content, via innerHTML if an
 * inline script, or by using XHR. Transforms are applied if needed. The scripts
 * are executed in the order they are found on the page.
 */
function loadScripts(transformFn, scripts) {
  const result = [];
  const count = scripts.length;

  function check() {
    let script, i;

    for (i = 0; i < count; i++) {
      script = result[i];

      if (script.loaded && !script.executed) {
        script.executed = true;
        run(transformFn, script);
      } else if (!script.loaded && !script.error && !script.async) {
        break;
      }
    }
  }

  scripts.forEach((script, i) => {
    const scriptData = {
      // script.async is always true for non-JavaScript script tags
      async: script.hasAttribute("async"),
      type: script.getAttribute("data-type"),
      error: false,
      executed: false,
      plugins: getPluginsOrPresetsFromScript(script, "data-plugins"),
      presets: getPluginsOrPresetsFromScript(script, "data-presets"),
    };

    if (script.src) {
      result[i] = {
        ...scriptData,
        content: null,
        loaded: false,
        url: script.src,
      };

      load(
        script.src,
        content => {
          result[i].loaded = true;
          result[i].content = content;
          check();
        },
        () => {
          result[i].error = true;
          check();
        },
      );
    } else {
      result[i] = {
        ...scriptData,
        content: script.innerHTML,
        loaded: true,
        url: script.getAttribute("data-module") || null,
      };
    }
  });

  check();
}

/**
 * Run script tags with type="text/jsx".
 * @param {Array} scriptTags specify script tags to run, run all in the <head> if not given
 */
export function runScripts(transformFn, scripts) {
  headEl = document.getElementsByTagName("head")[0];
  if (!scripts) {
    scripts = document.getElementsByTagName("script");
  }

  // Array.prototype.slice cannot be used on NodeList on IE8
  const jsxScripts = [];
  for (let i = 0; i < scripts.length; i++) {
    const script = scripts.item(i);
    // Support the old type="text/jsx;harmony=true"
    const type = script.type.split(";")[0];
    if (scriptTypes.indexOf(type) !== -1) {
      jsxScripts.push(script);
    }
  }

  if (jsxScripts.length === 0) {
    return;
  }

  console.warn(
    "You are using the in-browser Babel transformer. Be sure to precompile " +
      "your scripts for production - https://babeljs.io/docs/setup/",
  );

  loadScripts(transformFn, jsxScripts);
}
<|endoftext|>


<commit_before>define(["dojo/_base/declare", "ppwcode/contracts/_Mixin", "dojo/_base/lang", "dijit/registry", "dojo/dom-style", "dojo/dom-class", "dojo/has",
        "dijit/_WidgetBase", "../SemanticObject",
        "ppwcode/contracts/doh"], // MUDO REMOVE temp for testing invariants in the field
    function(declare, _ContractMixin, lang, registry, domStyle, domClass, has,
             _WidgetBase, SemanticObject,
             doh) {

      var editModes = [
        // editMode for when there is no target
        "NOTARGET",

        // editMode for viewing the data. No interaction allowed.
        "VIEW",

        // editMode for editing the data. Interaction allowed.
        "EDIT",

        // editMode while the SemanticObject is busy. No interaction allowed.
        "BUSY",

        // editMode representing unacceptable data (the object is not civilized,
        // or we have other means of knowing the data is unacceptable).
        // Interaction must be allowed to reset the object, or ammeliorate the data/
        // This means this is a sub-state of EDIT.
        "WILD",

        // editMode representing an error occured. We cannot proceed. The widget
        // and its object must be destroyed.
        "ERROR"];

      function setEditModeOnWidgets(domNode, editMode) {
        if (has("dojo-debug-messages")) {
          // make ERROR and WILD mode very clear in debug mode
          if (editMode === _EditableSemanticObjectDetail.prototype.NOTARGET) {
            domStyle.set(domNode, "backgroundColor", "gray");
          }
          else if (editMode === _EditableSemanticObjectDetail.prototype.ERROR) {
            domStyle.set(domNode, "backgroundColor", "red");
          }
          else if (editMode === _EditableSemanticObjectDetail.prototype.WILD) {
            domStyle.set(domNode, "backgroundColor", "yellow");
          }
          else {
            domStyle.set(domNode, "backgroundColor", "transparent");
          }
        }
        var innerWidgets = registry.findWidgets(domNode);
        var widgetState = null;
        switch (editMode) {
          case _EditableSemanticObjectDetail.prototype.NOTARGET:
            widgetState = { readOnly:false, disabled:true };
            break;
          case _EditableSemanticObjectDetail.prototype.EDIT:
            widgetState = { readOnly:false, disabled:false };
            break;
          case _EditableSemanticObjectDetail.prototype.BUSY:
            widgetState = { readOnly:false, disabled:true };
            break;
          case _EditableSemanticObjectDetail.prototype.ERROR:
            widgetState = { readOnly:false, disabled:true };
            break;
          default:
            widgetState = { readOnly:true, disabled:false };
        }
        innerWidgets.forEach(function (w) {
          if (!w.isInstanceOf(_EditableSemanticObjectDetail)) {
            w.set("readOnly", widgetState.readOnly);
            w.set("disabled", widgetState.disabled);
          }
        });
      }

      function setEditModeOnBlock(domNode, editMode) {
        if (editMode === _EditableSemanticObjectDetail.prototype.VIEW ||
            editMode === _EditableSemanticObjectDetail.prototype.EDIT ||
            editMode === _EditableSemanticObjectDetail.prototype.WILD) {
          domClass.replace(domNode,
            "editableSemanticObjectDetail_blockEnabled",
            "editableSemanticObjectDetail_blockDisabled editableSemanticObjectDetail_blockInvisible"
          );
        }
        else if (editMode === _EditableSemanticObjectDetail.prototype.BUSY ||
                 editMode === _EditableSemanticObjectDetail.prototype.ERROR) {
          domClass.replace(domNode,
            "editableSemanticObjectDetail_blockDisabled",
            "editableSemanticObjectDetail_blockEnabled editableSemanticObjectDetail_blockInvisible"
          );
        }
        else { // no target
          domClass.replace(domNode,
            "editableSemanticObjectDetail_blockInvisible",
            "editableSemanticObjectDetail_blockEnabled editableSemanticObjectDetail_blockDisabled"
          );
        }
      }

      var _EditableSemanticObjectDetail = declare([_WidgetBase, _ContractMixin], {
        // summary:
        //   Widget that represents a SemanticObject in detail, and that gives the opportunity
        //   to the user the view the details, edit the details, and create a new object.
        //   Abstract class to be extended for particular subtypes of SemanticObject.
        // description:
        //   What is common to all subtypes is that the widget:
        //   - has a `target` that is a SemanticObject; getTargetType() returns the top-most supported
        //     Constructor of supported targets. All targets must be instances of this type.
        //   - has an `editMode` (view, edit, busy, wild, error)
        //
        //   The representation should reflect the editMode in a clear visual way to the user.
        //   Even when the information shown is completely read-only, widgets should extend
        //   this class, to change the representation of the displayed information consistently
        //   with other information in different editModes, e.g., in "busy" mode.
        //   The available edit modes are defined in _EditableSemanticObjectDetail.prototype.editModes.
        //
        //   Instances can be wrapped around zero or more _EditableSemanticObjectDetails, recursively (no loops!).
        //   We take care of propagating `editMode`. Subclasses need to override
        //   getWrappedDetails to return the wrapped details. All instances need to be instances of this class.
        //   The default implementation returns an empty array.
        //   The target of a wrapped detail might be the same target as our target, but it might be
        //   another related object, of a different type. set("target", ...) will call _propagateTarget, which is
        //   chained, so that subclasses can add propagation of setting the target. Our implementation only sets our
        //   target.

        _c_invar: [
          function() {return this.get("editMode");},
          function() {return _EditableSemanticObjectDetail.prototype.editModes.indexOf(this.get("editMode")) >= 0;},
          function() {return this.getTargetType() != null;},
          // TODO getTargetType is a subtype of SemanticObject
          function() {return this.get("target") == null ||
                        (this.get("target").isInstanceOf && this.get("target").isInstanceOf(this.getTargetType()));},
          function() {return (this.get("editMode") === this.NOTARGET) === (this.get("target") === null);},
          function() {return this._wrappedDetails() != null;},
          function() {return lang.isArray(this._wrappedDetails());},
          {
            objectSelector: function() {
              return this._wrappedDetails();
            },
            invars: [
              function(wd) {
                return wd && wd != null &&
                  wd.isInstanceOf && wd.isInstanceOf(_EditableSemanticObjectDetail);
              },
              // wrapped details might contain other objects of other types as target,
              // but the editMode needs to be in sync
              function(wd) {
                return wd.get("editMode") === this.get("editMode");
              }
            ]
          }
        ],

        "-chains-": {
          _propagateTarget: "after",
          _localEditModeChange: "after"
        },

        // target: SemanticObject
        //    SemanticObject that is represented.
        //    Access in declarative template with  ... data-dojo-props="value: at('rel:', BINDING_PROPERTY_NAME)
        target: null,

        // editMode: String
        //    The edit mode is either
        editMode: editModes[0], // default value

        isInEditMode: function() {
          return this.editMode === this.EDIT || this.editMode === this.BUSY || this.editMode === this.WILD;
        },

        _wrappedDetails: function() {
          // summary:
          //   Array containing the wrapped details, a subclass wants the target and editMode propagated to.
          // tags:
          //   protected

          return []; // return Array
        },

        getTargetType: function() {
          // summary:
          //    The supported type of SemanticObjects. All targets must be an instance of this type.
          // description:
          //    Subclasses should overwrite to return the correct type.

          return SemanticObject;
        },

        _propagateTarget: function(/*SemanticObject*/ so) {
          // summary:
          //   Propagate the target as appropriate to wrapped details.
          //   Chained. Subtypes could add propagation to wrapped details.
          // tags:
          //   protected
          // description:
          //   Does nothing in _EditableSemanticObjectDetail

          this._c_NOP();
        },

        _setTargetAttr: function(so) {
          // summary:
          //    Sets the target of this instance. Chained. Subtypes could add propagation to wrapped details.
          this._c_pre(function() {return so == null || (so.isInstanceOf && so.isInstanceOf(this.getTargetType()));});

          if (so !== this.get("target")) {
            this._set("target", so);
          }
          this._propagateTarget(so);
          this.set("editMode", so ? this.VIEW : this.NOTARGET);

          doh.validateInvariants(this); // MUDO REMOVE
        },

        _setEditModeAttr: function(value) {
          // summary:
          //    Set the editMode, and propagate to the wrapped details.
          //    Also makes all innerWidgets read-only in editMode VIEW,
          //    disabled in editMode BUSY, and not-read-only and enabled
          //    in the other editModes.

          // Called during create by _WidgetBase with default value automatically
          this._c_pre(function() {return value != null});
          this._c_pre(function() {return _EditableSemanticObjectDetail.prototype.editModes.indexOf(value) >= 0});

          this._set("editMode", value);
          this._wrappedDetails().forEach(function(wd) {
            wd.set("editMode", value);
          });
          setEditModeOnBlock(this.get("domNode"), value);
          setEditModeOnWidgets(this.get("domNode"), value);
          this._localEditModeChange(value);
          doh.validateInvariants(this); // MUDO REMOVE
        },

        _localEditModeChange: function(/*String*/ editMode) {
          // summary:
          //   Make changes to representation to represent the
          //   new edit mode. Chained. Overwrite when needed.
          // tags:
          //   protected
          // description:
          //   Does nothing in _EditableSemanticObjectDetail

          this._c_NOP();
        }

      });

      // All supported editModes
      _EditableSemanticObjectDetail.prototype.editModes = editModes;
      editModes.forEach(function(em) {
        _EditableSemanticObjectDetail.prototype[em] = em;
      });

      return _EditableSemanticObjectDetail; // return _EditableSemanticObjectDetail

    });
<commit_msg>Debug style for "ok editMode" better now.<commit_after>define(["dojo/_base/declare", "ppwcode/contracts/_Mixin", "dojo/_base/lang", "dijit/registry", "dojo/dom-style", "dojo/dom-class", "dojo/has",
        "dijit/_WidgetBase", "../SemanticObject",
        "ppwcode/contracts/doh"], // MUDO REMOVE temp for testing invariants in the field
    function(declare, _ContractMixin, lang, registry, domStyle, domClass, has,
             _WidgetBase, SemanticObject,
             doh) {

      var editModes = [
        // editMode for when there is no target
        "NOTARGET",

        // editMode for viewing the data. No interaction allowed.
        "VIEW",

        // editMode for editing the data. Interaction allowed.
        "EDIT",

        // editMode while the SemanticObject is busy. No interaction allowed.
        "BUSY",

        // editMode representing unacceptable data (the object is not civilized,
        // or we have other means of knowing the data is unacceptable).
        // Interaction must be allowed to reset the object, or ammeliorate the data/
        // This means this is a sub-state of EDIT.
        "WILD",

        // editMode representing an error occured. We cannot proceed. The widget
        // and its object must be destroyed.
        "ERROR"];

      function setEditModeOnWidgets(domNode, editMode) {
        if (has("dojo-debug-messages")) {
          // make ERROR and WILD mode very clear in debug mode
          if (editMode === _EditableSemanticObjectDetail.prototype.NOTARGET) {
            domStyle.set(domNode, "backgroundColor", "gray");
          }
          else if (editMode === _EditableSemanticObjectDetail.prototype.ERROR) {
            domStyle.set(domNode, "backgroundColor", "red");
          }
          else if (editMode === _EditableSemanticObjectDetail.prototype.WILD) {
            domStyle.set(domNode, "backgroundColor", "yellow");
          }
          else {
            domStyle.set(domNode, "backgroundColor", "");
          }
        }
        var innerWidgets = registry.findWidgets(domNode);
        var widgetState = null;
        switch (editMode) {
          case _EditableSemanticObjectDetail.prototype.NOTARGET:
            widgetState = { readOnly:false, disabled:true };
            break;
          case _EditableSemanticObjectDetail.prototype.EDIT:
            widgetState = { readOnly:false, disabled:false };
            break;
          case _EditableSemanticObjectDetail.prototype.BUSY:
            widgetState = { readOnly:false, disabled:true };
            break;
          case _EditableSemanticObjectDetail.prototype.ERROR:
            widgetState = { readOnly:false, disabled:true };
            break;
          default:
            widgetState = { readOnly:true, disabled:false };
        }
        innerWidgets.forEach(function (w) {
          if (!w.isInstanceOf(_EditableSemanticObjectDetail)) {
            w.set("readOnly", widgetState.readOnly);
            w.set("disabled", widgetState.disabled);
          }
        });
      }

      function setEditModeOnBlock(domNode, editMode) {
        if (editMode === _EditableSemanticObjectDetail.prototype.VIEW ||
            editMode === _EditableSemanticObjectDetail.prototype.EDIT ||
            editMode === _EditableSemanticObjectDetail.prototype.WILD) {
          domClass.replace(domNode,
            "editableSemanticObjectDetail_blockEnabled",
            "editableSemanticObjectDetail_blockDisabled editableSemanticObjectDetail_blockInvisible"
          );
        }
        else if (editMode === _EditableSemanticObjectDetail.prototype.BUSY ||
                 editMode === _EditableSemanticObjectDetail.prototype.ERROR) {
          domClass.replace(domNode,
            "editableSemanticObjectDetail_blockDisabled",
            "editableSemanticObjectDetail_blockEnabled editableSemanticObjectDetail_blockInvisible"
          );
        }
        else { // no target
          domClass.replace(domNode,
            "editableSemanticObjectDetail_blockInvisible",
            "editableSemanticObjectDetail_blockEnabled editableSemanticObjectDetail_blockDisabled"
          );
        }
      }

      var _EditableSemanticObjectDetail = declare([_WidgetBase, _ContractMixin], {
        // summary:
        //   Widget that represents a SemanticObject in detail, and that gives the opportunity
        //   to the user the view the details, edit the details, and create a new object.
        //   Abstract class to be extended for particular subtypes of SemanticObject.
        // description:
        //   What is common to all subtypes is that the widget:
        //   - has a `target` that is a SemanticObject; getTargetType() returns the top-most supported
        //     Constructor of supported targets. All targets must be instances of this type.
        //   - has an `editMode` (view, edit, busy, wild, error)
        //
        //   The representation should reflect the editMode in a clear visual way to the user.
        //   Even when the information shown is completely read-only, widgets should extend
        //   this class, to change the representation of the displayed information consistently
        //   with other information in different editModes, e.g., in "busy" mode.
        //   The available edit modes are defined in _EditableSemanticObjectDetail.prototype.editModes.
        //
        //   Instances can be wrapped around zero or more _EditableSemanticObjectDetails, recursively (no loops!).
        //   We take care of propagating `editMode`. Subclasses need to override
        //   getWrappedDetails to return the wrapped details. All instances need to be instances of this class.
        //   The default implementation returns an empty array.
        //   The target of a wrapped detail might be the same target as our target, but it might be
        //   another related object, of a different type. set("target", ...) will call _propagateTarget, which is
        //   chained, so that subclasses can add propagation of setting the target. Our implementation only sets our
        //   target.

        _c_invar: [
          function() {return this.get("editMode");},
          function() {return _EditableSemanticObjectDetail.prototype.editModes.indexOf(this.get("editMode")) >= 0;},
          function() {return this.getTargetType() != null;},
          // TODO getTargetType is a subtype of SemanticObject
          function() {return this.get("target") == null ||
                        (this.get("target").isInstanceOf && this.get("target").isInstanceOf(this.getTargetType()));},
          function() {return (this.get("editMode") === this.NOTARGET) === (this.get("target") === null);},
          function() {return this._wrappedDetails() != null;},
          function() {return lang.isArray(this._wrappedDetails());},
          {
            objectSelector: function() {
              return this._wrappedDetails();
            },
            invars: [
              function(wd) {
                return wd && wd != null &&
                  wd.isInstanceOf && wd.isInstanceOf(_EditableSemanticObjectDetail);
              },
              // wrapped details might contain other objects of other types as target,
              // but the editMode needs to be in sync
              function(wd) {
                return wd.get("editMode") === this.get("editMode");
              }
            ]
          }
        ],

        "-chains-": {
          _propagateTarget: "after",
          _localEditModeChange: "after"
        },

        // target: SemanticObject
        //    SemanticObject that is represented.
        //    Access in declarative template with  ... data-dojo-props="value: at('rel:', BINDING_PROPERTY_NAME)
        target: null,

        // editMode: String
        //    The edit mode is either
        editMode: editModes[0], // default value

        isInEditMode: function() {
          return this.editMode === this.EDIT || this.editMode === this.BUSY || this.editMode === this.WILD;
        },

        _wrappedDetails: function() {
          // summary:
          //   Array containing the wrapped details, a subclass wants the target and editMode propagated to.
          // tags:
          //   protected

          return []; // return Array
        },

        getTargetType: function() {
          // summary:
          //    The supported type of SemanticObjects. All targets must be an instance of this type.
          // description:
          //    Subclasses should overwrite to return the correct type.

          return SemanticObject;
        },

        _propagateTarget: function(/*SemanticObject*/ so) {
          // summary:
          //   Propagate the target as appropriate to wrapped details.
          //   Chained. Subtypes could add propagation to wrapped details.
          // tags:
          //   protected
          // description:
          //   Does nothing in _EditableSemanticObjectDetail

          this._c_NOP();
        },

        _setTargetAttr: function(so) {
          // summary:
          //    Sets the target of this instance. Chained. Subtypes could add propagation to wrapped details.
          this._c_pre(function() {return so == null || (so.isInstanceOf && so.isInstanceOf(this.getTargetType()));});

          if (so !== this.get("target")) {
            this._set("target", so);
          }
          this._propagateTarget(so);
          this.set("editMode", so ? this.VIEW : this.NOTARGET);

          doh.validateInvariants(this); // MUDO REMOVE
        },

        _setEditModeAttr: function(value) {
          // summary:
          //    Set the editMode, and propagate to the wrapped details.
          //    Also makes all innerWidgets read-only in editMode VIEW,
          //    disabled in editMode BUSY, and not-read-only and enabled
          //    in the other editModes.

          // Called during create by _WidgetBase with default value automatically
          this._c_pre(function() {return value != null});
          this._c_pre(function() {return _EditableSemanticObjectDetail.prototype.editModes.indexOf(value) >= 0});

          this._set("editMode", value);
          this._wrappedDetails().forEach(function(wd) {
            wd.set("editMode", value);
          });
          setEditModeOnBlock(this.get("domNode"), value);
          setEditModeOnWidgets(this.get("domNode"), value);
          this._localEditModeChange(value);
          doh.validateInvariants(this); // MUDO REMOVE
        },

        _localEditModeChange: function(/*String*/ editMode) {
          // summary:
          //   Make changes to representation to represent the
          //   new edit mode. Chained. Overwrite when needed.
          // tags:
          //   protected
          // description:
          //   Does nothing in _EditableSemanticObjectDetail

          this._c_NOP();
        }

      });

      // All supported editModes
      _EditableSemanticObjectDetail.prototype.editModes = editModes;
      editModes.forEach(function(em) {
        _EditableSemanticObjectDetail.prototype[em] = em;
      });

      return _EditableSemanticObjectDetail; // return _EditableSemanticObjectDetail

    });
<|endoftext|>


<commit_before>/**
 * This widget provides visibility and color data controls for a VisualizationModel.
 * It emits an event anytime the value has changed, attaching data in the form
 * of a serialized query string.
 */
cinema.views.CompositeToolsWidget = Backbone.View.extend({
    initialize: function (settings) {
        this.model = settings.model;
        this.controlModel = settings.controlModel || new cinema.models.ControlModel({ info: this.model });
        this.viewpoint = settings.viewpoint || new cinema.models.ViewPointModel({ controlModel: this.controlModel });
        this.layers = settings.layers || new cinema.models.LayerModel(this.model.defaultLayers());
        this.toolbarSelector = settings.toolbarContainer || '.c-panel-toolbar';

        this.$('.c-control-panel-body').html(cinema.templates.compositeToolsWidget());

        this.listenTo(cinema.events, 'c:editpipelines', this.togglePipelineEditor);
        this.listenTo(cinema.events, 'c:editcontrols', this.toggleControlEditor);

        this.pipelineWidget = new cinema.views.PipelineWidget({
            el: this.$('.c-pipeline-content'),
            model: this.model,
            layers: this.layers
        });

        this.controlWidget = new cinema.views.ControlWidget({
            el: this.$('.c-control-content'),
            model: this.model,
            viewport: this.viewpoint,
            controlModel: this.controlModel,
            toolbarSelector: this.toolbarSelector,
            toolbarRootView: this,
            exclude: ['layer', 'field', 'filename']
        });
        this.render();
    },

    render: function () {
        this.$('.c-control-panel-body').html(cinema.templates.compositeToolsWidget());
        this.pipelineWidget.setElement(this.$('.c-pipeline-content')).render();
        this.controlWidget.setElement(this.$('.c-control-content')).render();
    },

    hideControlEditor: function () {
        var link = this.$('.c-control-edit'),
            state;
        if (link.attr('state') === 'on') {
            state = 'off';
            link.attr('state', state);
            link.fadeOut();
        }
        else {
            state = 'on';
            link.attr('state', state);
            link.fadeIn();
        }
    },

    togglePipelineEditor: function () {
        this.$('.c-pipeline-edit').fadeToggle();
    },

    toggleControlEditor: function () {
        this.$('.c-control-edit').fadeToggle();
    }

});
<commit_msg>fix incorrect merge conflict resolution<commit_after>/**
 * This widget provides visibility and color data controls for a VisualizationModel.
 * It emits an event anytime the value has changed, attaching data in the form
 * of a serialized query string.
 */
cinema.views.CompositeToolsWidget = Backbone.View.extend({
    initialize: function (settings) {
        this.model = settings.model;
        this.controlModel = settings.controlModel || new cinema.models.ControlModel({ info: this.model });
        this.viewpoint = settings.viewpoint || new cinema.models.ViewPointModel({ controlModel: this.controlModel });
        this.layers = settings.layers || new cinema.models.LayerModel(this.model.defaultLayers());
        this.toolbarSelector = settings.toolbarContainer || '.c-panel-toolbar';

        this.$('.c-control-panel-body').html(cinema.templates.compositeToolsWidget());

        this.listenTo(cinema.events, 'c:editpipelines', this.togglePipelineEditor);
        this.listenTo(cinema.events, 'c:editcontrols', this.toggleControlEditor);

        this.pipelineWidget = new cinema.views.PipelineWidget({
            el: this.$('.c-pipeline-content'),
            model: this.model,
            layers: this.layers
        });

        this.controlWidget = new cinema.views.ControlWidget({
            el: this.$('.c-control-content'),
            model: this.model,
            viewport: this.viewpoint,
            controlModel: this.controlModel,
            toolbarSelector: this.toolbarSelector,
            toolbarRootView: this,
            exclude: ['layer', 'field', 'filename']
        });
        this.render();
    },

    render: function () {
        this.$('.c-control-panel-body').html(cinema.templates.compositeToolsWidget());
        this.pipelineWidget.setElement(this.$('.c-pipeline-content')).render();
        this.controlWidget.setElement(this.$('.c-control-content')).render();
    },

    togglePipelineEditor: function () {
        this.$('.c-pipeline-edit').fadeToggle();
    },

    toggleControlEditor: function () {
        this.$('.c-control-edit').fadeToggle();
    }

});
<|endoftext|>


<commit_before>/* @flow */

import * as React from 'react';
import {
  TabRouter,
  StackActions,
  createNavigator,
  createNavigationContainer,
  NavigationActions,
} from 'react-navigation';
import SceneView from 'react-navigation/src/views/SceneView';

export type InjectedProps = {
  getLabelText: (props: { route: any }) => any,
  renderIcon: (props: {
    route: any,
    focused: boolean,
    tintColor: string,
  }) => React.Node,
  renderScene: (props: { route: any }) => ?React.Node,
  onIndexChange: (index: number) => any,
  onTabPress: (props: { route: any }) => mixed,
  navigation: any,
  descriptors: any,
  screenProps?: any,
};

export default function createTabNavigator(TabView: React.ComponentType<*>) {
  class NavigationView extends React.Component<*> {
    _renderScene = ({ route }) => {
      const { screenProps, descriptors } = this.props;
      const descriptor = descriptors[route.key];
      const TabComponent = descriptor.getComponent();
      return (
        <SceneView
          screenProps={screenProps}
          navigation={descriptor.navigation}
          component={TabComponent}
        />
      );
    };

    _renderIcon = ({ route, focused = true, tintColor }) => {
      const { descriptors } = this.props;
      const descriptor = descriptors[route.key];
      const options = descriptor.options;

      if (options.tabBarIcon) {
        return typeof options.tabBarIcon === 'function'
          ? options.tabBarIcon({ focused, tintColor })
          : options.tabBarIcon;
      }

      return null;
    };

    _getLabelText = ({ route }) => {
      const { descriptors } = this.props;
      const descriptor = descriptors[route.key];
      const options = descriptor.options;

      if (options.tabBarLabel) {
        return options.tabBarLabel;
      }

      if (typeof options.title === 'string') {
        return options.title;
      }

      return route.routeName;
    };

    _handleOnTabPress = ({ route }) => {
      const { descriptors } = this.props;
      const descriptor = descriptors[route.key];
      const { navigation, options } = descriptor;

      if (options.tabBarOnPress) {
        options.tabBarOnPress({
          navigation,
        });
      } else {
        const isFocused =
          this.props.navigation.state.index ===
          this.props.navigation.state.routes.indexOf(route);

        if (isFocused) {
          if (route.hasOwnProperty('index') && route.index > 0) {
            navigation.dispatch(StackActions.popToTop({ key: route.key }));
          } else {
            // TODO: do something to scroll to top
          }
        }
      }
    };

    _handleIndexChange = index => {
      const { navigation } = this.props;
      navigation.dispatch(NavigationActions.navigate({
        routeName: navigation.state.routes[index].routeName,
      }));
    };

    render() {
      const { descriptors, navigation, screenProps } = this.props;
      const { state } = navigation;
      const route = state.routes[state.index];
      const descriptor = descriptors[route.key];
      const options = {
        ...this.props.navigationConfig,
        ...descriptor.options,
      };

      return (
        <TabView
          {...options}
          getLabelText={this._getLabelText}
          renderIcon={this._renderIcon}
          renderScene={this._renderScene}
          onIndexChange={this._handleIndexChange}
          onTabPress={this._handleOnTabPress}
          navigation={navigation}
          descriptors={descriptors}
          screenProps={screenProps}
        />
      );
    }
  }

  return (routes: *, config: * = {}) => {
    const router = TabRouter(routes, config);
    const navigator = createNavigator(NavigationView, router, config);

    return createNavigationContainer(navigator);
  };
}
<commit_msg>fix: import SceneView from react-navigation default export<commit_after>/* @flow */

import * as React from 'react';
import {
  TabRouter,
  StackActions,
  SceneView,
  createNavigator,
  createNavigationContainer,
  NavigationActions,
} from 'react-navigation';

export type InjectedProps = {
  getLabelText: (props: { route: any }) => any,
  renderIcon: (props: {
    route: any,
    focused: boolean,
    tintColor: string,
  }) => React.Node,
  renderScene: (props: { route: any }) => ?React.Node,
  onIndexChange: (index: number) => any,
  onTabPress: (props: { route: any }) => mixed,
  navigation: any,
  descriptors: any,
  screenProps?: any,
};

export default function createTabNavigator(TabView: React.ComponentType<*>) {
  class NavigationView extends React.Component<*> {
    _renderScene = ({ route }) => {
      const { screenProps, descriptors } = this.props;
      const descriptor = descriptors[route.key];
      const TabComponent = descriptor.getComponent();
      return (
        <SceneView
          screenProps={screenProps}
          navigation={descriptor.navigation}
          component={TabComponent}
        />
      );
    };

    _renderIcon = ({ route, focused = true, tintColor }) => {
      const { descriptors } = this.props;
      const descriptor = descriptors[route.key];
      const options = descriptor.options;

      if (options.tabBarIcon) {
        return typeof options.tabBarIcon === 'function'
          ? options.tabBarIcon({ focused, tintColor })
          : options.tabBarIcon;
      }

      return null;
    };

    _getLabelText = ({ route }) => {
      const { descriptors } = this.props;
      const descriptor = descriptors[route.key];
      const options = descriptor.options;

      if (options.tabBarLabel) {
        return options.tabBarLabel;
      }

      if (typeof options.title === 'string') {
        return options.title;
      }

      return route.routeName;
    };

    _handleOnTabPress = ({ route }) => {
      const { descriptors } = this.props;
      const descriptor = descriptors[route.key];
      const { navigation, options } = descriptor;

      if (options.tabBarOnPress) {
        options.tabBarOnPress({
          navigation,
        });
      } else {
        const isFocused =
          this.props.navigation.state.index ===
          this.props.navigation.state.routes.indexOf(route);

        if (isFocused) {
          if (route.hasOwnProperty('index') && route.index > 0) {
            navigation.dispatch(StackActions.popToTop({ key: route.key }));
          } else {
            // TODO: do something to scroll to top
          }
        }
      }
    };

    _handleIndexChange = index => {
      const { navigation } = this.props;
      navigation.dispatch(NavigationActions.navigate({
        routeName: navigation.state.routes[index].routeName,
      }));
    };

    render() {
      const { descriptors, navigation, screenProps } = this.props;
      const { state } = navigation;
      const route = state.routes[state.index];
      const descriptor = descriptors[route.key];
      const options = {
        ...this.props.navigationConfig,
        ...descriptor.options,
      };

      return (
        <TabView
          {...options}
          getLabelText={this._getLabelText}
          renderIcon={this._renderIcon}
          renderScene={this._renderScene}
          onIndexChange={this._handleIndexChange}
          onTabPress={this._handleOnTabPress}
          navigation={navigation}
          descriptors={descriptors}
          screenProps={screenProps}
        />
      );
    }
  }

  return (routes: *, config: * = {}) => {
    const router = TabRouter(routes, config);
    const navigator = createNavigator(NavigationView, router, config);

    return createNavigationContainer(navigator);
  };
}
<|endoftext|>


<commit_before>exports.description = 'Displays general help info or info about a specific command.';

exports.usage = '[command]';

exports.options = {
    command: {
        noName: true,
        description: 'Get more information about a specific command.'
    }
};

exports.invoke = function (shell, options) {
    var cmdNames = [];

    // Populate cmdNames with all command module names and sort the array alphabetically.
    for (var key in shell.cmds)
        if (shell.cmds.hasOwnProperty(key))
            cmdNames.push(key);
    cmdNames.sort();

    shell.log();

    // If no command was passed in as an argument to the help command then display the generic help menu listing all available commands.
    if (!options.command) {

        // Calculate the length of the largest command name for formatting purposes.
        var maxLength = 0;
        for (var index = 0; index < cmdNames.length; index++) {
            var cmdName = cmdNames[index];
            maxLength = cmdName.length > maxLength ? cmdName.length : maxLength;
        }

        // Iterate over all command modules and add a line of text with the command name and description.
        var inverted = false;
        for (var index = 0; index < cmdNames.length; index++) {
            var cmdName = cmdNames[index],
                cmd = shell.cmds[cmdName],
                helpStr = cmdName;
            if (cmd.description) {
                helpStr += new Array((maxLength - cmdName.length) + 7).join(' ');
                helpStr += cmd.description;
            }

            // If the command is not hidden then add the line.
            // If there are 5 commands or less then type the lines character by character.
            // If there are more than 5 commands then do not type them out as it takes too long and the effect isn't worth the wait.
            if (!cmd.hidden) {
                var lineOptions = { dontType: cmdNames.length > 5, inverted: inverted };
                inverted = !inverted;
                shell.log(helpStr, lineOptions);
            }
        }
        shell.log();
    }
    // If a command was passed in as an argument to the help command then display more specific help information for the specified command.
    else {
        var cmd = shell.cmds[options.command];
        if (!cmd)
            shell.error(options.command + ' is not a valid command name.');
        else {

            // Display the command's description if it has one.
            if (cmd.description) {
                shell.log(cmd.description);
                shell.log();
            }

            // If a "usage key" is specified then display it.
            if (cmd.usage) {
                shell.log('Usage: "' + options.command + ' ' + cmd.usage + '"');
                shell.log();
            }

            // If the command defines options that it recognizes then iterate over those and display information about them.
            if (cmd.options) {
                var strs = [],
                    maxLength = 0;
                for (var key in cmd.options) {
                    var option = cmd.options[key];
                    if (!option.hidden) {
                        var optionStr = (key.length > 1 ? '--' : '-') + key;
                        if (option.aliases) {
                            option.aliases.forEach(function (alias) {
                                optionStr += ',' + (alias.length > 1 ? '--' : '-') + alias;
                            });
                        }
                        strs.push({ option: option, str: optionStr});
                        maxLength = optionStr.length > maxLength ? optionStr.length : maxLength;
                    }
                }
                if (strs.length > 0) {
                    shell.log('Options:');
                    shell.log();
                    for (var index in strs) {
                        var option = strs[index].option,
                            optionStr = strs[index].str;
                        if (option.description) {
                            optionStr += new Array((maxLength - optionStr.length) + 5).join(' ');
                            optionStr += option.description;
                        }
                        shell.log(optionStr, { dontType: true });
                    }
                    shell.log();
                }
            }
        }
    }
};<commit_msg>Reformatted help screen for specific command info.<commit_after>exports.description = 'Displays general help info or info about a specific command.';

exports.usage = '[command]';

exports.options = {
    command: {
        noName: true,
        description: 'Get more information about a specific command.'
    }
};

exports.invoke = function (shell, options) {
    var cmdNames = [];

    // Populate cmdNames with all command module names and sort the array alphabetically.
    for (var key in shell.cmds)
        if (shell.cmds.hasOwnProperty(key))
            cmdNames.push(key);
    cmdNames.sort();

    shell.log();

    // If no command was passed in as an argument to the help command then display the generic help menu listing all available commands.
    if (!options.command) {

        // Calculate the length of the largest command name for formatting purposes.
        var maxLength = 0;
        for (var index = 0; index < cmdNames.length; index++) {
            var cmdName = cmdNames[index];
            maxLength = cmdName.length > maxLength ? cmdName.length : maxLength;
        }

        // Iterate over all command modules and add a line of text with the command name and description.
        var inverted = false;
        for (var index = 0; index < cmdNames.length; index++) {
            var cmdName = cmdNames[index],
                cmd = shell.cmds[cmdName],
                helpStr = cmdName;
            if (cmd.description) {
                helpStr += new Array((maxLength - cmdName.length) + 7).join(' ');
                helpStr += cmd.description;
            }

            // If the command is not hidden then add the line.
            // If there are 5 commands or less then type the lines character by character.
            // If there are more than 5 commands then do not type them out as it takes too long and the effect isn't worth the wait.
            if (!cmd.hidden) {
                var lineOptions = { dontType: cmdNames.length > 5, inverted: inverted };
                inverted = !inverted;
                shell.log(helpStr, lineOptions);
            }
        }
        shell.log();
    }
    // If a command was passed in as an argument to the help command then display more specific help information for the specified command.
    else {
        var cmd = shell.cmds[options.command];
        if (!cmd)
            shell.error(options.command + ' is not a valid command name.');
        else {

            var firstLine = options.command;
            // If a "usage key" is specified then display it.
            if (cmd.usage)
                firstLine += ' ' + cmd.usage;
            shell.log(firstLine, { bold: true });
            shell.log();

            // Display the command's description if it has one.
            if (cmd.description) {
                shell.log(cmd.description);
                shell.log();
            }

            // If the command defines options that it recognizes then iterate over those and display information about them.
            if (cmd.options) {
                var strs = [],
                    maxLength = 0;
                for (var key in cmd.options) {
                    var option = cmd.options[key];
                    if (!option.hidden) {
                        var optionStr = (key.length > 1 ? '--' : '-') + key;
                        if (option.aliases) {
                            option.aliases.forEach(function (alias) {
                                optionStr += ',' + (alias.length > 1 ? '--' : '-') + alias;
                            });
                        }
                        strs.push({ option: option, str: optionStr});
                        maxLength = optionStr.length > maxLength ? optionStr.length : maxLength;
                    }
                }
                if (strs.length > 0) {
                    shell.log('Options:');
                    shell.log();
                    for (var index in strs) {
                        var option = strs[index].option,
                            optionStr = strs[index].str;
                        if (option.description) {
                            optionStr += new Array((maxLength - optionStr.length) + 5).join(' ');
                            optionStr += option.description;
                        }
                        shell.log(optionStr, { dontType: true });
                    }
                    shell.log();
                }
            }
        }
    }
};<|endoftext|>