<commit_before>var path = require('path');

module.exports = {
  name: 'fastboot',
  description: 'Runs a server to render your app using FastBoot.',

  availableOptions: [
    { name: 'build', type: Boolean, default: true },
    { name: 'environment', type: String, default: 'development', aliases: ['e',{'dev' : 'development'}, {'prod' : 'production'}] },
    { name: 'serve-assets', type: Boolean, default: false},
    { name: 'port', type: Number, default: 3000 },
    { name: 'output-path', type: String, default: 'fastboot-dist' }
  ],

  runCommand: function(appName, options) {
    var FastBootServer = require('../models/server');
    var RSVP = require('rsvp');
    var express = require('express');
    var outputPath = this.commandOptions.outputPath;

    var server = new FastBootServer({
      appFile: findAppFile(outputPath, appName),
      vendorFile: findVendorFile(outputPath),
      htmlFile: findHTMLFile(outputPath),
      ui: this.ui
    });

    var app = express();

    if (this.commandOptions.serveAssets) {
      app.get('/', server.middleware());
      app.use(express.static(outputPath));
    }

    app.get('/*', server.middleware());

    var ui = this.ui;

    var listener = app.listen(options.port, function() {
      var host = listener.address().address;
      var port = listener.address().port;

      ui.writeLine('Ember FastBoot running at http://' + host + ":" + port);
    });

    // Block forever
    return new RSVP.Promise(function() { });
  },

  triggerBuild: function(commandOptions) {
    var BuildTask = this.tasks.Build;
    var buildTask = new BuildTask({
      ui: this.ui,
      analytics: this.analytics,
      project: this.project
    });

    return buildTask.run(commandOptions);
  },

  run: function(options, args) {
    process.env.EMBER_CLI_FASTBOOT = true;

    this.commandOptions = options;

    var runCommand = function() {
      var appName = process.env.EMBER_CLI_FASTBOOT_APP_NAME || this.project.name();

      return this.runCommand(appName, options);
    }.bind(this);

    if (options.build) {
      return this.triggerBuild(options)
        .then(runCommand);
    }

    return runCommand();
  },
};

function findAppFile(outputPath, appName) {
  return findFile("app", path.join(outputPath, "assets", appName + "*.js"));
}

function findVendorFile(outputPath) {
  return findFile("vendor", path.join(outputPath, "assets", "vendor*.js"));
}

function findHTMLFile(outputPath) {
  var fs = require('fs');
  if (fs.existsSync('app/fastboot.html')) {
    return 'app/fastboot.html';
  }

  return findFile('html', path.join(outputPath, 'index*.html'));
}

function findFile(name, globPath) {
  var glob = require('glob');
  var files = glob.sync(globPath);

  assert("Found " + files.length + " " + name + " files (expected 1) when globbing '" + globPath + "'.", files.length === 1);

  return files[0];
}

function assert(message, condition) {
  var SilentError = require('ember-cli/lib/errors/silent');

  if (condition === false) {
    throw new SilentError(message);
  }
}
<commit_msg>remove fastboot.html, always use index.html<commit_after>var path = require('path');

module.exports = {
  name: 'fastboot',
  description: 'Runs a server to render your app using FastBoot.',

  availableOptions: [
    { name: 'build', type: Boolean, default: true },
    { name: 'environment', type: String, default: 'development', aliases: ['e',{'dev' : 'development'}, {'prod' : 'production'}] },
    { name: 'serve-assets', type: Boolean, default: false},
    { name: 'port', type: Number, default: 3000 },
    { name: 'output-path', type: String, default: 'fastboot-dist' }
  ],

  runCommand: function(appName, options) {
    var FastBootServer = require('../models/server');
    var RSVP = require('rsvp');
    var express = require('express');
    var outputPath = this.commandOptions.outputPath;

    var server = new FastBootServer({
      appFile: findAppFile(outputPath, appName),
      vendorFile: findVendorFile(outputPath),
      htmlFile: findHTMLFile(outputPath),
      ui: this.ui
    });

    var app = express();

    if (this.commandOptions.serveAssets) {
      app.get('/', server.middleware());
      app.use(express.static(outputPath));
    }

    app.get('/*', server.middleware());

    var ui = this.ui;

    var listener = app.listen(options.port, function() {
      var host = listener.address().address;
      var port = listener.address().port;

      ui.writeLine('Ember FastBoot running at http://' + host + ":" + port);
    });

    // Block forever
    return new RSVP.Promise(function() { });
  },

  triggerBuild: function(commandOptions) {
    var BuildTask = this.tasks.Build;
    var buildTask = new BuildTask({
      ui: this.ui,
      analytics: this.analytics,
      project: this.project
    });

    return buildTask.run(commandOptions);
  },

  run: function(options, args) {
    process.env.EMBER_CLI_FASTBOOT = true;

    this.commandOptions = options;

    var runCommand = function() {
      var appName = process.env.EMBER_CLI_FASTBOOT_APP_NAME || this.project.name();

      return this.runCommand(appName, options);
    }.bind(this);

    if (options.build) {
      return this.triggerBuild(options)
        .then(runCommand);
    }

    return runCommand();
  },
};

function findAppFile(outputPath, appName) {
  return findFile("app", path.join(outputPath, "assets", appName + "*.js"));
}

function findVendorFile(outputPath) {
  return findFile("vendor", path.join(outputPath, "assets", "vendor*.js"));
}

function findHTMLFile(outputPath) {
  return findFile('html', path.join(outputPath, 'index*.html'));
}

function findFile(name, globPath) {
  var glob = require('glob');
  var files = glob.sync(globPath);

  assert("Found " + files.length + " " + name + " files (expected 1) when globbing '" + globPath + "'.", files.length === 1);

  return files[0];
}

function assert(message, condition) {
  var SilentError = require('ember-cli/lib/errors/silent');

  if (condition === false) {
    throw new SilentError(message);
  }
}
<|endoftext|>


<commit_before>const AbstractHandler = require('./AbstractHandler');
const Constants = require('../../../../util/Constants');

class MessageDeleteHandler extends AbstractHandler {
  handle(packet) {
    const client = this.packetManager.client;
    const data = packet.d;
    const response = client.actions.MessageDelete.handle(data);
    if (response.message) client.emit(Constants.Events.MESSAGE_DELETE, response.message);
  }
}

module.exports = MessageDeleteHandler;
<commit_msg>actually fix that delete thing (#1507)<commit_after>const AbstractHandler = require('./AbstractHandler');

class MessageDeleteHandler extends AbstractHandler {
  handle(packet) {
    this.packetManager.client.actions.MessageDelete.handle(packet.d);
  }
}

module.exports = MessageDeleteHandler;
<|endoftext|>


<commit_before>'use strict';
var React = require('react');
var _ = require('underscore');
var moment = require('moment');
var globals = require('./globals');
var fetched = require('./fetched');
var form = require('../libs/bootstrap/form');
var modal = require('../libs/bootstrap/modal');
var panel = require('../libs/bootstrap/panel');
var parseAndLogError = require('./mixins').parseAndLogError;
var RestMixin = require('./rest').RestMixin;
var CuratorHistory = require('./curator_history');
var modesOfInheritance = require('./mapping/modes_of_inheritance.json');

var Form = form.Form;
var FormMixin = form.FormMixin;
var Input = form.Input;
var Alert = modal.Alert;
var ModalMixin = modal.ModalMixin;
var Panel = panel.Panel;

var CreateGeneDisease = React.createClass({
    mixins: [FormMixin, RestMixin, ModalMixin, CuratorHistory],

    contextTypes: {
        fetch: React.PropTypes.func,
        navigate: React.PropTypes.func
    },

    getInitialState: function() {
        return {
            gdm: {},
            adjectives: [],
            adjectiveDisabled: true
        };
    },

    // Handle value changes in modeInheritance dropdown selection
    handleChange: function(ref, e) {
        if (ref === 'hpo') {
            let selected = this.refs[ref].getValue();
            /******************************************************/
            /* If 'X-linked inheritance' is selected,             */
            /* enable adjective menu and set it a required field. */
            /* If 'Autosomal dominant inheritance' is selected,   */
            /* or 'Autosomal recessive inheritance is selected,   */
            /* enable adjective menu only & set it not required.  */
            /* Everything else, disable adjective menu.           */
            /******************************************************/
            if (selected.indexOf('X-linked inheritance') > -1) {
                this.handleAdjectives(false, modesOfInheritance['X-linked inheritance (HP:0001417)']);
            } else if (selected.indexOf('Autosomal dominant inheritance') > -1) {
                this.handleAdjectives(false, modesOfInheritance['Autosomal dominant inheritance (HP:0000006)']);
            } else if (selected.indexOf('Autosomal recessive inheritance') > -1) {
                this.handleAdjectives(false, modesOfInheritance['Autosomal recessive inheritance (HP:0000007)']);
            } else if (selected.indexOf('Mitochondrial inheritance') > -1) {
                this.handleAdjectives(false, modesOfInheritance['Mitochondrial inheritance (HP:0001427)']);
            } else if (selected.indexOf('Other') > -1) {
                this.handleAdjectives(false, modesOfInheritance['Other']);
            } else {
                this.handleAdjectives(true, []);
            }
        }
    },

    // Helper method for the 'handleChange' method to minimize repetitive code
    handleAdjectives: function(adjectiveDisabled, adjectives) {
        this.setState({
            adjectiveDisabled: adjectiveDisabled,
            adjectives: adjectives
        }, () => {this.refs.moiAdjective.setValue('none');});
    },

    // Form content validation
    validateForm: function() {
        // Start with default validation
        var valid = this.validateDefault();

        // Check if orphanetid
        if (valid) {
            valid = this.getFormValue('orphanetid').match(/^ORPHA[0-9]{1,6}$/i);
            if (!valid) {
                this.setFormErrors('orphanetid', 'Use Orphanet IDs (e.g. ORPHA15)');
            }
        }
        return valid;
    },

    editGdm: function() {
        this.context.navigate('/curation-central/?gdm=' + this.state.gdm.uuid);
    },

    // When the form is submitted...
    submitForm: function(e) {
        e.preventDefault(); e.stopPropagation(); // Don't run through HTML submit handler

        // Get values from form and validate them
        this.saveFormValue('hgncgene', this.refs.hgncgene.getValue().toUpperCase());
        this.saveFormValue('orphanetid', this.refs.orphanetid.getValue());
        this.saveFormValue('hpo', this.refs.hpo.getValue());
        let moiAdjectiveValue = this.refs.moiAdjective.getValue();
        if (moiAdjectiveValue && moiAdjectiveValue !== 'none') {
            this.saveFormValue('moiAdjective', moiAdjectiveValue);
        }
        if (this.validateForm()) {
            // Get the free-text values for the Orphanet ID and the Gene ID to check against the DB
            var orphaId = this.getFormValue('orphanetid').match(/^ORPHA([0-9]{1,6})$/i)[1];
            var geneId = this.getFormValue('hgncgene');
            var mode = this.getFormValue('hpo');
            let adjective = this.getFormValue('moiAdjective');

            // Get the disease and gene objects corresponding to the given Orphanet and Gene IDs in parallel.
            // If either error out, set the form error fields
            this.getRestDatas([
                '/diseases/' + orphaId,
                '/genes/' + geneId
            ], [
                function() { this.setFormErrors('orphanetid', 'Orphanet ID not found'); }.bind(this),
                function() { this.setFormErrors('hgncgene', 'HGNC gene symbol not found'); }.bind(this)
            ]).then(data => {
                // Load GDM if one with matching gene/disease/mode already exists
                return this.getRestData(
                    '/search/?type=gdm&disease.orphaNumber=' + orphaId + '&gene.symbol=' + geneId + '&modeInheritance=' + mode
                ).then(gdmSearch => {
                    if (gdmSearch.total === 0) {
                        // Matching GDM not found. Create a new GDM
                        let newGdm = {
                            gene: geneId,
                            disease: orphaId,
                            modeInheritance: mode
                        };
                        if (adjective && adjective.length) {
                            newGdm['modeInheritanceAdjective'] = adjective;
                        }

                        // Post the new GDM to the DB. Once promise returns, go to /curation-central page with the UUID
                        // of the new GDM in the query string.
                        return this.postRestData('/gdm/', newGdm).then(data => {
                            var newGdm = data['@graph'][0];

                            // Record history of adding a GDM
                            var meta = {
                                gdm: {
                                    operation: 'add',
                                    gene: newGdm.gene,
                                    disease: newGdm.disease
                                }
                            };
                            this.recordHistory('add', newGdm, meta);

                            // Navigate to Record Curation
                            var uuid = data['@graph'][0].uuid;
                            this.context.navigate('/curation-central/?gdm=' + uuid);
                        });
                    } else {
                        // Found matching GDM. See of the user wants to curate it.
                        this.setState({gdm: gdmSearch['@graph'][0]});
                        this.openAlert('confirm-edit-gdm');
                    }
                });
            }).catch(e => {
                // Some unexpected error happened
                parseAndLogError.bind(undefined, 'fetchedRequest');
            });
        }
    },

    render: function() {
        let adjectives = this.state.adjectives;
        let adjectiveDisabled = this.state.adjectiveDisabled;
        const moiKeys = Object.keys(modesOfInheritance);

        return (

{this.props.context.title}

                    <Panel panelClassName="panel-create-gene-disease">
                        <Form submitHandler={this.submitForm} formClassName="form-horizontal form-std">

                                <Input type="text" ref="hgncgene" label={<LabelHgncGene />} placeholder="e.g. DICER1"
                                    error={this.getFormError('hgncgene')} clearError={this.clrFormErrors.bind(null, 'hgncgene')}
                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" required />
                                <Input type="text" ref="orphanetid" label={<LabelOrphanetId />} placeholder="e.g. ORPHA15"
                                    error={this.getFormError('orphanetid')} clearError={this.clrFormErrors.bind(null, 'orphanetid')}
                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" required />
                                <Input type="select" ref="hpo" label="Mode of Inheritance" defaultValue="select" handleChange={this.handleChange}
                                    error={this.getFormError('hpo')} clearError={this.clrFormErrors.bind(null, 'hpo')}
                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="hpo" required>
                                    <option value="select" disabled="disabled">Select</option>
                                    <option value="" disabled="disabled"></option>
                                    {moiKeys.map(function(modeOfInheritance, i) {
                                        return <option key={i} value={modeOfInheritance}>{modeOfInheritance}</option>;
                                    })}
                                </Input>
                                <Input type="select" ref="moiAdjective" label="Select an adjective" defaultValue="none"
                                    error={this.getFormError('moiAdjective')} clearError={this.clrFormErrors.bind(null, 'moiAdjective')} inputDisabled={adjectiveDisabled}
                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="moiAdjective">
                                    <option value="none" disabled="disabled">Select</option>
                                    <option disabled="disabled"></option>
                                    {adjectives.map(function(adjective, i) {
                                        return <option key={i} value={adjective}>{adjective.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1]}</option>;
                                    })}
                                </Input>
                                <Input type="submit" inputClassName="btn-default pull-right" id="submit" />

                        </Form>
                        <Alert id="confirm-edit-gdm" content={<ConfirmEditGdm gdm={this.state.gdm} editGdm={this.editGdm} closeAlert={this.closeAlert} />} />
                    </Panel>

        );
    }
});

globals.curator_page.register(CreateGeneDisease, 'curator_page', 'create-gene-disease');

// HTML labels for inputs follow.
var LabelHgncGene = React.createClass({
    render: function() {
        return Enter HGNC gene symbol;
    }
});

var LabelOrphanetId = React.createClass({
    render: function() {
        return Enter Orphanet ID;
    }
});

var ConfirmEditGdm = React.createClass({
    propTypes: {
        gdm: React.PropTypes.object, // GDM object under consideration
        editGdm: React.PropTypes.func, // Function to call to edit the GDM
        closeAlert: React.PropTypes.func // Function to call to close the alert
    },

    // Called when any of the alert's buttons is clicked. Confirm is true if the 'Create' button was clicked;
    // false if the 'Cancel' button was clicked.
    handleClick: function(confirm, e) {
        if (confirm) {
            this.props.editGdm();
        }
        this.props.closeAlert('confirm-edit-gdm');
    },

    render: function() {
        var gdm = this.props.gdm;

        return (

A curation record already exists for {gdm.gene.symbol} — ORPHA{gdm.disease.orphaNumber} — {gdm.modeInheritance}. You may curate this existing record, or cancel to specify a different gene — disease — mode.

                    <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.handleClick.bind(null, false)} title="Cancel" />
                    <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.handleClick.bind(null, true)} title="Curate" />

        );
    }
});

// Display a history item for adding a PMID to a GDM
var GdmAddHistory = React.createClass({
    render: function() {
        var history = this.props.history;
        var gdm = history.primary;
        var gdmMeta = history.meta.gdm;
        var gdmHref = '/curation-central/?gdm=' + gdm.uuid;

        return (

                    {gdmMeta.gene.symbol}-{gdmMeta.disease.term}-
                    {gdm.modeInheritance.indexOf('(') > -1 ? gdm.modeInheritance.substring(0, gdm.modeInheritance.indexOf('(') - 1) : gdm.modeInheritance}

                 created
                ; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}

        );
    }
});

globals.history_views.register(GdmAddHistory, 'gdm', 'add');
<commit_msg>Removed 'disabled' attribute for 'none' value select option associated with MOI adjective<commit_after>'use strict';
var React = require('react');
var _ = require('underscore');
var moment = require('moment');
var globals = require('./globals');
var fetched = require('./fetched');
var form = require('../libs/bootstrap/form');
var modal = require('../libs/bootstrap/modal');
var panel = require('../libs/bootstrap/panel');
var parseAndLogError = require('./mixins').parseAndLogError;
var RestMixin = require('./rest').RestMixin;
var CuratorHistory = require('./curator_history');
var modesOfInheritance = require('./mapping/modes_of_inheritance.json');

var Form = form.Form;
var FormMixin = form.FormMixin;
var Input = form.Input;
var Alert = modal.Alert;
var ModalMixin = modal.ModalMixin;
var Panel = panel.Panel;

var CreateGeneDisease = React.createClass({
    mixins: [FormMixin, RestMixin, ModalMixin, CuratorHistory],

    contextTypes: {
        fetch: React.PropTypes.func,
        navigate: React.PropTypes.func
    },

    getInitialState: function() {
        return {
            gdm: {},
            adjectives: [],
            adjectiveDisabled: true
        };
    },

    // Handle value changes in modeInheritance dropdown selection
    handleChange: function(ref, e) {
        if (ref === 'hpo') {
            let selected = this.refs[ref].getValue();
            /******************************************************/
            /* If 'X-linked inheritance' is selected,             */
            /* enable adjective menu and set it a required field. */
            /* If 'Autosomal dominant inheritance' is selected,   */
            /* or 'Autosomal recessive inheritance is selected,   */
            /* enable adjective menu only & set it not required.  */
            /* Everything else, disable adjective menu.           */
            /******************************************************/
            if (selected.indexOf('X-linked inheritance') > -1) {
                this.handleAdjectives(false, modesOfInheritance['X-linked inheritance (HP:0001417)']);
            } else if (selected.indexOf('Autosomal dominant inheritance') > -1) {
                this.handleAdjectives(false, modesOfInheritance['Autosomal dominant inheritance (HP:0000006)']);
            } else if (selected.indexOf('Autosomal recessive inheritance') > -1) {
                this.handleAdjectives(false, modesOfInheritance['Autosomal recessive inheritance (HP:0000007)']);
            } else if (selected.indexOf('Mitochondrial inheritance') > -1) {
                this.handleAdjectives(false, modesOfInheritance['Mitochondrial inheritance (HP:0001427)']);
            } else if (selected.indexOf('Other') > -1) {
                this.handleAdjectives(false, modesOfInheritance['Other']);
            } else {
                this.handleAdjectives(true, []);
            }
        }
    },

    // Helper method for the 'handleChange' method to minimize repetitive code
    handleAdjectives: function(adjectiveDisabled, adjectives) {
        this.setState({
            adjectiveDisabled: adjectiveDisabled,
            adjectives: adjectives
        }, () => {this.refs.moiAdjective.setValue('none');});
    },

    // Form content validation
    validateForm: function() {
        // Start with default validation
        var valid = this.validateDefault();

        // Check if orphanetid
        if (valid) {
            valid = this.getFormValue('orphanetid').match(/^ORPHA[0-9]{1,6}$/i);
            if (!valid) {
                this.setFormErrors('orphanetid', 'Use Orphanet IDs (e.g. ORPHA15)');
            }
        }
        return valid;
    },

    editGdm: function() {
        this.context.navigate('/curation-central/?gdm=' + this.state.gdm.uuid);
    },

    // When the form is submitted...
    submitForm: function(e) {
        e.preventDefault(); e.stopPropagation(); // Don't run through HTML submit handler

        // Get values from form and validate them
        this.saveFormValue('hgncgene', this.refs.hgncgene.getValue().toUpperCase());
        this.saveFormValue('orphanetid', this.refs.orphanetid.getValue());
        this.saveFormValue('hpo', this.refs.hpo.getValue());
        let moiAdjectiveValue = this.refs.moiAdjective.getValue();
        if (moiAdjectiveValue && moiAdjectiveValue !== 'none') {
            this.saveFormValue('moiAdjective', moiAdjectiveValue);
        }
        if (this.validateForm()) {
            // Get the free-text values for the Orphanet ID and the Gene ID to check against the DB
            var orphaId = this.getFormValue('orphanetid').match(/^ORPHA([0-9]{1,6})$/i)[1];
            var geneId = this.getFormValue('hgncgene');
            var mode = this.getFormValue('hpo');
            let adjective = this.getFormValue('moiAdjective');

            // Get the disease and gene objects corresponding to the given Orphanet and Gene IDs in parallel.
            // If either error out, set the form error fields
            this.getRestDatas([
                '/diseases/' + orphaId,
                '/genes/' + geneId
            ], [
                function() { this.setFormErrors('orphanetid', 'Orphanet ID not found'); }.bind(this),
                function() { this.setFormErrors('hgncgene', 'HGNC gene symbol not found'); }.bind(this)
            ]).then(data => {
                // Load GDM if one with matching gene/disease/mode already exists
                return this.getRestData(
                    '/search/?type=gdm&disease.orphaNumber=' + orphaId + '&gene.symbol=' + geneId + '&modeInheritance=' + mode
                ).then(gdmSearch => {
                    if (gdmSearch.total === 0) {
                        // Matching GDM not found. Create a new GDM
                        let newGdm = {
                            gene: geneId,
                            disease: orphaId,
                            modeInheritance: mode
                        };
                        if (adjective && adjective.length) {
                            newGdm['modeInheritanceAdjective'] = adjective;
                        }

                        // Post the new GDM to the DB. Once promise returns, go to /curation-central page with the UUID
                        // of the new GDM in the query string.
                        return this.postRestData('/gdm/', newGdm).then(data => {
                            var newGdm = data['@graph'][0];

                            // Record history of adding a GDM
                            var meta = {
                                gdm: {
                                    operation: 'add',
                                    gene: newGdm.gene,
                                    disease: newGdm.disease
                                }
                            };
                            this.recordHistory('add', newGdm, meta);

                            // Navigate to Record Curation
                            var uuid = data['@graph'][0].uuid;
                            this.context.navigate('/curation-central/?gdm=' + uuid);
                        });
                    } else {
                        // Found matching GDM. See of the user wants to curate it.
                        this.setState({gdm: gdmSearch['@graph'][0]});
                        this.openAlert('confirm-edit-gdm');
                    }
                });
            }).catch(e => {
                // Some unexpected error happened
                parseAndLogError.bind(undefined, 'fetchedRequest');
            });
        }
    },

    render: function() {
        let adjectives = this.state.adjectives;
        let adjectiveDisabled = this.state.adjectiveDisabled;
        const moiKeys = Object.keys(modesOfInheritance);

        return (

{this.props.context.title}

                    <Panel panelClassName="panel-create-gene-disease">
                        <Form submitHandler={this.submitForm} formClassName="form-horizontal form-std">

                                <Input type="text" ref="hgncgene" label={<LabelHgncGene />} placeholder="e.g. DICER1"
                                    error={this.getFormError('hgncgene')} clearError={this.clrFormErrors.bind(null, 'hgncgene')}
                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" required />
                                <Input type="text" ref="orphanetid" label={<LabelOrphanetId />} placeholder="e.g. ORPHA15"
                                    error={this.getFormError('orphanetid')} clearError={this.clrFormErrors.bind(null, 'orphanetid')}
                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" required />
                                <Input type="select" ref="hpo" label="Mode of Inheritance" defaultValue="select" handleChange={this.handleChange}
                                    error={this.getFormError('hpo')} clearError={this.clrFormErrors.bind(null, 'hpo')}
                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="hpo" required>
                                    <option value="select" disabled="disabled">Select</option>
                                    <option value="" disabled="disabled"></option>
                                    {moiKeys.map(function(modeOfInheritance, i) {
                                        return <option key={i} value={modeOfInheritance}>{modeOfInheritance}</option>;
                                    })}
                                </Input>
                                <Input type="select" ref="moiAdjective" label="Select an adjective" defaultValue="none"
                                    error={this.getFormError('moiAdjective')} clearError={this.clrFormErrors.bind(null, 'moiAdjective')} inputDisabled={adjectiveDisabled}
                                    labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="moiAdjective">
                                    <option value="none">Select</option>
                                    <option disabled="disabled"></option>
                                    {adjectives.map(function(adjective, i) {
                                        return <option key={i} value={adjective}>{adjective.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1]}</option>;
                                    })}
                                </Input>
                                <Input type="submit" inputClassName="btn-default pull-right" id="submit" />

                        </Form>
                        <Alert id="confirm-edit-gdm" content={<ConfirmEditGdm gdm={this.state.gdm} editGdm={this.editGdm} closeAlert={this.closeAlert} />} />
                    </Panel>

        );
    }
});

globals.curator_page.register(CreateGeneDisease, 'curator_page', 'create-gene-disease');

// HTML labels for inputs follow.
var LabelHgncGene = React.createClass({
    render: function() {
        return Enter HGNC gene symbol;
    }
});

var LabelOrphanetId = React.createClass({
    render: function() {
        return Enter Orphanet ID;
    }
});

var ConfirmEditGdm = React.createClass({
    propTypes: {
        gdm: React.PropTypes.object, // GDM object under consideration
        editGdm: React.PropTypes.func, // Function to call to edit the GDM
        closeAlert: React.PropTypes.func // Function to call to close the alert
    },

    // Called when any of the alert's buttons is clicked. Confirm is true if the 'Create' button was clicked;
    // false if the 'Cancel' button was clicked.
    handleClick: function(confirm, e) {
        if (confirm) {
            this.props.editGdm();
        }
        this.props.closeAlert('confirm-edit-gdm');
    },

    render: function() {
        var gdm = this.props.gdm;

        return (

A curation record already exists for {gdm.gene.symbol} — ORPHA{gdm.disease.orphaNumber} — {gdm.modeInheritance}. You may curate this existing record, or cancel to specify a different gene — disease — mode.

                    <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.handleClick.bind(null, false)} title="Cancel" />
                    <Input type="button" inputClassName="btn-default btn-inline-spacer" clickHandler={this.handleClick.bind(null, true)} title="Curate" />

        );
    }
});

// Display a history item for adding a PMID to a GDM
var GdmAddHistory = React.createClass({
    render: function() {
        var history = this.props.history;
        var gdm = history.primary;
        var gdmMeta = history.meta.gdm;
        var gdmHref = '/curation-central/?gdm=' + gdm.uuid;

        return (

                    {gdmMeta.gene.symbol}-{gdmMeta.disease.term}-
                    {gdm.modeInheritance.indexOf('(') > -1 ? gdm.modeInheritance.substring(0, gdm.modeInheritance.indexOf('(') - 1) : gdm.modeInheritance}

                 created
                ; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}

        );
    }
});

globals.history_views.register(GdmAddHistory, 'gdm', 'add');
<|endoftext|>


<commit_before>var PICCOLO2D_BASEPATH = "rwt-resources/piccolo2djs/";

(function() {
	'use strict';
	rap.registerTypeHandler("eclipsesource.piccolo2djs", {

		factory : function(properties) {
			return new eclipsesource.piccolo2djs(properties);
		},
		destructor : "destroy",
		methods : ['showList','updateCalendarByDate'],
		properties : [ "size","dataJson","date","lineColor","isDefaulOpenToday"],
		events:[]

	});

	if (!window.eclipsesource) {
		window.eclipsesource = {};
	}

	eclipsesource.piccolo2djs = function(properties) {
		bindAll(this, [ "layout", "onReady", "onSend", "onRender","refreshSize","debounce","showListOrigin"]);
		this.parent = rap.getObject(properties.parent); //获取java端的一个图形容器。
		this.element = document.createElement("div");
		this.parent.append(this.element);
		this.parent.addListener("Resize", this.layout);
		this._date = new Date();
		this._currentDay = new Date();
		this._isDefaulOpenToday = false;
		this._lineColor = {};
		this._dataObj = {current:{},prev:{},next:{}};

		this._size = properties.size ? properties.size : {
			width : 300,
			height : 300
		};
		var area = this.parent.getClientArea();
		this._size = {width:area[2]||300,height:area[3]||300};
		this.element.style.width = '100%';//this._size.width+"px";
    this.element.style.height = '100%';//(this._size.height)+"px";
		// calendar chart container
		this.fishEyeContainer = document.createElement('div');
		this.fishEyeContainer.style.width = "100%";
		this.fishEyeContainer.style.height = "100%";
		this.element.appendChild(this.fishEyeContainer);
		//
		this.detailChartContainer = document.createElement('div');
		this.detailChartContainer.style.width = "100%";
		this.detailChartContainer.style.height = "100%";
		this.element.appendChild(this.detailChartContainer);

		this.refreshSize = this.debounce(this.refreshSizeOrigin,300);
		this.showListDebounce = this.debounce(this.showListOrigin,400);
		rap.on("render", this.onRender);
	};
	eclipsesource.piccolo2djs.prototype = {
		ready : false,
		onReady : function() {
			// TODO [tb] : on IE 7/8 the iframe and body has to be made
			// transparent explicitly
			this.ready = true;
			this.layout();
			console.log("piccolo2djs...onReady..");
		},

		onRender : function() {
      var _this = this;
			if (this.element.parentNode) {
				rap.off("render", this.onRender);
				console.log("piccolo2djs...onRender..");
				// Creates the graph inside the given container
				this.fishEyeCalendar = new FishEyeCalendar({
					year:this._date.getFullYear(),
					month:this._date.getMonth()+1,
					currentDay:this._currentDay,
					isDefaulOpenToday:this._isDefaulOpenToday,
					dataObj:this._dataObj,
					lineColor:this._lineColor,
					basePath:PICCOLO2D_BASEPATH,
					container:this.fishEyeContainer,
					detailContainer:this.detailChartContainer
				});
        /////////////////////
				// rap.on("send", this.onSend);
				this.ready = true;
				// this.layout();
			}
		},
		onSend : function() {
			// rap.getRemoteObject( this ).set( "model", "123456789"); //设置后端的值，还有其他两个方法:call(method,properties):调用后端的方法,notify(event,properties);
			// rap.getRemoteObject( this ).call( "handleCallRefreshData", "123456789"); //设置后端的值，还有其他两个方法:call(method,properties):调用后端的方法,notify(event,properties);
			// console.log("mxgraph...onSend..")
		},
		setDate:function(obj){
			this._date = new Date(obj.date.replace(/\-/g,'/'))
			this._currentDay = new Date(obj.currentDay.replace(/\-/g,'/')); //today date string.
			// console.log('setDate:',obj);
		},
		setLineColor:function(obj){
			this._lineColor = obj;
			// console.log('lineColor:',obj);
		},
		setDataJson:function(obj){
			this._dataObj = obj;
			// console.log('setDataJson:',obj);
		},
		setIsDefaulOpenToday:function(isOpen){
			this._isDefaulOpenToday = isOpen;
			// console.log('_isDefaulOpenToday:',isOpen);
		},
		showList:function(){  //update calendar call
			this.showListDebounce();
		},
		showListOrigin:function(){
			var _this = this;
			// this._dataObj = obj;
			setTimeout(function(){
				// console.log('showList:-----',_this._dataObj);
				_this.fishEyeCalendar && _this.fishEyeCalendar.updateCalendarByDateAndData(
					_this._date.getFullYear(),
					_this._date.getMonth()+1,
					_this._dataObj,
					_this._isDefaulOpenToday,
					_this._lineColor);
			},10);
		},
		setSize : function(size) {
			var _this = this;
			if (this.ready) {
				if(Math.abs(size.width-_this._size.width)<5 && Math.abs(size.height-_this._size.height)<5){ return; }
				console.log('async:size',size);
				async(this, function() { // Needed by IE for some reason
					_this.refreshSize(0,0,size.width,size.height);
				});
			} else {
				this._size = size;
			}
		},
		destroy : function() {
			// rap.off("send", this.onSend);
			(this.element && this.element.parentNode) ? this.element.parentNode.removeChild(this.element): null;
		},

		layout : function() {
			// console.log("piccolo2djs...layout..")
			if (this.ready) {
				var area = this.parent.getClientArea();
				if(Math.abs(area[2]-this._size.width)<5 && Math.abs(area[3]-this._size.height)<5){ return; }
				// console.log("this.parent.getClientArea():",area);
				this.refreshSize(area[0],area[1],area[2],area[3]);
			}
		},
		refreshSizeOrigin:function(left,top,width,height){
			console.log("piccolo2djs...refreshSize..");
			this._size = {width:width,height:height};
			this.element.style.left = left + "px";
			this.element.style.top = top + "px";
			this.element.style.width = width + "px";
			this.element.style.height = height + "px";

			this.fishEyeCalendar.refreshBySize(this._size);
		},
		debounce :function(func, wait, immediate) {
	    var timeout, args, context, timestamp, result;

	    var later = function() {
	      var last = now() - timestamp;

	      if (last < wait && last >= 0) {
	        timeout = setTimeout(later, wait - last);
	      } else {
	        timeout = null;
	        if (!immediate) {
	          result = func.apply(context, args);
	          if (!timeout) context = args = null;
	        }
	      }
	    };
	    return function() {
	      context = this;
	      args = arguments;
	      timestamp = now();
	      var callNow = immediate && !timeout;
	      if (!timeout) timeout = setTimeout(later, wait);
	      if (callNow) {
	        result = func.apply(context, args);
	        context = args = null;
	      }

	      return result;
	    };
	  }

	};

	var bind = function(context, method) {
		return function() {
			return method.apply(context, arguments);
		};
	};

	var bindAll = function(context, methodNames) {
		for (var i = 0; i < methodNames.length; i++) {
			var method = context[methodNames[i]];
			context[methodNames[i]] = bind(context, method);
		}
	};

	var async = function(context, func) {
		window.setTimeout(function() {
			func.apply(context);
		}, 0);
	};

	var now = Date.now || function() {
    return new Date().getTime();
  };

}());
<commit_msg>fixed a bug<commit_after>var PICCOLO2D_BASEPATH = "rwt-resources/piccolo2djs/";

(function() {
	'use strict';
	rap.registerTypeHandler("eclipsesource.piccolo2djs", {

		factory : function(properties) {
			return new eclipsesource.piccolo2djs(properties);
		},
		destructor : "destroy",
		methods : ['showList','updateCalendarByDate'],
		properties : [ "size","dataJson","date","lineColor","isDefaulOpenToday"],
		events:[]

	});

	if (!window.eclipsesource) {
		window.eclipsesource = {};
	}

	eclipsesource.piccolo2djs = function(properties) {
		bindAll(this, [ "layout", "onReady", "onSend", "onRender","refreshSize", "debounce","showListOrigin"]);
		this.parent = rap.getObject(properties.parent); //获取java端的一个图形容器。
		this.element = document.createElement("div");
		this.parent.append(this.element);
		this.parent.addListener("Resize", this.layout);
		this._date = new Date();
		this._currentDay = new Date();
		this._isDefaulOpenToday = false;
		this._lineColor = {};
		this._dataObj = {current:{},prev:{},next:{}};

		this._size = properties.size ? properties.size : {
			width : 300,
			height : 300
		};
		var area = this.parent.getClientArea();
		this._size = {width:area[2]||300,height:area[3]||300};
		this.element.style.width = '100%';//this._size.width+"px";
    this.element.style.height = '100%';//(this._size.height)+"px";
		// calendar chart container
		this.fishEyeContainer = document.createElement('div');
		this.fishEyeContainer.style.width = "100%";
		this.fishEyeContainer.style.height = "100%";
		this.element.appendChild(this.fishEyeContainer);
		//
		this.detailChartContainer = document.createElement('div');
		this.detailChartContainer.style.width = "100%";
		this.detailChartContainer.style.height = "100%";
		this.element.appendChild(this.detailChartContainer);

		this.refreshSize = this.debounce(this.refreshSizeOrigin,300);
		this.showListDebounce = this.debounce(this.showListOrigin,400);
		rap.on("render", this.onRender);
	};
	eclipsesource.piccolo2djs.prototype = {
		ready : false,
		onReady : function() {
			// TODO [tb] : on IE 7/8 the iframe and body has to be made
			// transparent explicitly
			this.ready = true;
			this.layout();
			console.log("piccolo2djs...onReady..");
		},

		onRender : function() {
      var _this = this;
			if (this.element.parentNode) {
				rap.off("render", this.onRender);
				console.log("piccolo2djs...onRender..");
				// Creates the graph inside the given container
				this.fishEyeCalendar = new FishEyeCalendar({
					year:this._date.getFullYear(),
					month:this._date.getMonth()+1,
					currentDay:this._currentDay,
					isDefaulOpenToday:this._isDefaulOpenToday,
					dataObj:this._dataObj,
					lineColor:this._lineColor,
					basePath:PICCOLO2D_BASEPATH,
					container:this.fishEyeContainer,
					detailContainer:this.detailChartContainer
				});
        /////////////////////
				// rap.on("send", this.onSend);
				this.ready = true;
				// this.layout();
			}
		},
		onSend : function() {
			// rap.getRemoteObject( this ).set( "model", "123456789"); //设置后端的值，还有其他两个方法:call(method,properties):调用后端的方法,notify(event,properties);
			// rap.getRemoteObject( this ).call( "handleCallRefreshData", "123456789"); //设置后端的值，还有其他两个方法:call(method,properties):调用后端的方法,notify(event,properties);
			// console.log("mxgraph...onSend..")
		},
		setDate:function(obj){
			this._date = new Date(obj.date.replace(/\-/g,'/'))
			this._currentDay = new Date(obj.currentDay.replace(/\-/g,'/')); //today date string.
			// console.log('setDate:',obj);
		},
		setLineColor:function(obj){
			this._lineColor = obj;
			// console.log('lineColor:',obj);
		},
		setDataJson:function(obj){
			this._dataObj = obj;
			// console.log('setDataJson:',obj);
		},
		setIsDefaulOpenToday:function(isOpen){
			this._isDefaulOpenToday = isOpen;
			// console.log('_isDefaulOpenToday:',isOpen);
		},
		showList:function(){  //update calendar call
			this.showListDebounce();
		},
		showListOrigin:function(){
			var _this = this;
			// this._dataObj = obj;
			setTimeout(function(){
				// console.log('showList:-----',_this._dataObj);
				_this.fishEyeCalendar && _this.fishEyeCalendar.updateCalendarByDateAndData(
					_this._date.getFullYear(),
					_this._date.getMonth()+1,
					_this._dataObj,
					_this._isDefaulOpenToday,
					_this._lineColor);
			},10);
		},
		setSize : function(size) {
			var _this = this;
			if (this.ready) {
				if(Math.abs(size.width-_this._size.width)<5 && Math.abs(size.height-_this._size.height)<5){ return; }
				console.log('async:size',size);
				async(this, function() { // Needed by IE for some reason
					_this.refreshSize(0,0,size.width,size.height);
				});
			} else {
				this._size = size;
			}
		},
		destroy : function() {
			// rap.off("send", this.onSend);
			(this.element && this.element.parentNode) ? this.element.parentNode.removeChild(this.element): null;
		},

		layout : function() {
			// console.log("piccolo2djs...layout..")
			if (this.ready) {
				var area = this.parent.getClientArea();
				if(Math.abs(area[2]-this._size.width)<5 && Math.abs(area[3]-this._size.height)<5){ return; }
				// console.log("this.parent.getClientArea():",area);
				this.refreshSize(area[0],area[1],area[2],area[3]);
			}
		},
		refreshSizeOrigin:function(left,top,width,height){
			console.log("piccolo2djs...refreshSize..");
			this._size = {width:width,height:height};
			this.element.style.left = left + "px";
			this.element.style.top = top + "px";
			this.element.style.width = width + "px";
			this.element.style.height = height + "px";

			this.fishEyeCalendar.refreshBySize({width:width,height:height});
		},
		debounce :function(func, wait, immediate) {
	    var timeout, args, context, timestamp, result;

	    var later = function() {
	      var last = now() - timestamp;

	      if (last < wait && last >= 0) {
	        timeout = setTimeout(later, wait - last);
	      } else {
	        timeout = null;
	        if (!immediate) {
	          result = func.apply(context, args);
	          if (!timeout) context = args = null;
	        }
	      }
	    };
	    return function() {
	      context = this;
	      args = arguments;
	      timestamp = now();
	      var callNow = immediate && !timeout;
	      if (!timeout) timeout = setTimeout(later, wait);
	      if (callNow) {
	        result = func.apply(context, args);
	        context = args = null;
	      }

	      return result;
	    };
	  }

	};

	var bind = function(context, method) {
		return function() {
			return method.apply(context, arguments);
		};
	};

	var bindAll = function(context, methodNames) {
		for (var i = 0; i < methodNames.length; i++) {
			var method = context[methodNames[i]];
			context[methodNames[i]] = bind(context, method);
		}
	};

	var async = function(context, func) {
		window.setTimeout(function() {
			func.apply(context);
		}, 0);
	};

	var now = Date.now || function() {
    return new Date().getTime();
  };

}());
<|endoftext|>


<commit_before>/**
 * Test Suite
 * PLEASE, DO NOT TOUCH IT
 *
 * @package     geena
 * @author      Rhinostone
 */
var TestSuite;

// Imports.
var fs = require('fs');
var helpers = require('helpers');
var inherits = require('inherits');

var TestSuite = function() {
    var self = this;

    this.root = __dirname;
    var d = _(__dirname).split(/\//);
    d.splice(d.length-1, 1);
    var geena = d.join('/');

    this.config = {
        root : this.root,
        geena : geena,
        target : this.root +'/workspace',
        nodeModules : this.root +'/node_modules'
    };

    var ignored = [
        /^\./ ,
        /node_modules/,
        /workspace/
    ];

    /**
     * Init
     * @constructor
     * */
    var init = function() {
        // load on startup
        loadScripts(self.root);
    };

    var loadScripts = function(path) {
        var files = fs.readdirSync(path);
        var file = '', filename = '';

        for (var f=0; f<files.length; ++f) {
            file = files[f].replace(/.js/, '');
            filename = path + '/' +files[f];

            var passed = true;
            for (var i in ignored) {
                if ( ignored[i].test(files[f]) ) {
                    passed = false
                }
            }

            if ( isDir(filename) &&
                !/node_modules/.test(filename.replace(self.root, '')) &&
                !/workspace/.test(filename.replace(self.root, '')) &&
                passed
            ) {
                //console.log('loading [ ' + filename +' ]\n');
                loadScripts(filename)
            } else if ( passed ) {
                console.log('suite is : ', files[f]);
                if (files[f] == '01-init_new_project.js') {
                    var Suite = require(filename);
                    if ( typeof(Suite) == 'function') {
                        Suite = inherits(Suite, self.Suite);
                        new Suite(self.config, exports)
                    }
                }
            }
        }
    }

    this.Suite = function(config, exports) {
        var self = this;

        this.hasFramework = function() {
             return self.hasWorkspace
        }
    }

    var isDir = function(path) {
        return fs.statSync(path).isDirectory()
    }

    init()
}()
<commit_msg>fixed last deploy errors and added more unit tests<commit_after>/**
 * Test Suite
 * PLEASE, DO NOT TOUCH IT
 *
 * @package     geena
 * @author      Rhinostone
 */
var TestSuite;

// Imports.
var fs = require('fs');
var helpers = require('helpers');
var inherits = require('inherits');

var TestSuite = function() {
    var self = this;

    this.root = __dirname;
    var d = _(__dirname).split(/\//);
    d.splice(d.length-1, 1);
    var geena = d.join('/');

    this.config = {
        root : this.root,
        geena : geena,
        target : this.root +'/workspace',
        nodeModules : this.root +'/node_modules'
    };

    var ignored = [
        /^\./ ,
        /node_modules/,
        /workspace/
    ];

    /**
     * Init
     * @constructor
     * */
    var init = function() {
        // load on startup
        loadScripts(self.root);
    };

    var loadScripts = function(path) {
        var files = fs.readdirSync(path);
        var file = '', filename = '';

        for (var f=0; f<files.length; ++f) {
            file = files[f].replace(/.js/, '');
            filename = path + '/' +files[f];

            var passed = true;
            for (var i in ignored) {
                if ( ignored[i].test(files[f]) ) {
                    passed = false
                }
            }

            if ( isDir(filename) &&
                !/node_modules/.test(filename.replace(self.root, '')) &&
                !/workspace/.test(filename.replace(self.root, '')) &&
                passed
            ) {
                //console.log('loading [ ' + filename +' ]\n');
                loadScripts(filename)
            } else if ( passed ) {
                //console.log('suite is : ', files[f]);
                //if (files[f] == '01-init_new_project.js') {
                    var Suite = require(filename);
                    if ( typeof(Suite) == 'function') {
                        Suite = inherits(Suite, self.Suite);
                        new Suite(self.config, exports)
                    }
                //}
            }
        }
    }

    this.Suite = function(config, exports) {
        var self = this;

        this.hasFramework = function() {
             return self.hasWorkspace
        }
    }

    var isDir = function(path) {
        return fs.statSync(path).isDirectory()
    }

    init()
}()
<|endoftext|>


<commit_before>require.config({

	paths : {
		"$" : "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min",
		"$ui" : "libs/jquery.ui",
		"$plugin" : "libs/plugins/amd/jquery-plugin",
		"wysihtml5" : "libs/wysihtml5",
		"text" : "libs/plugins/amd/text",
		"rosy" : "libs/rosy/src",
		"detailsShim" : "libs/details-shim"
	},

	waitSeconds : 15,

	shim : {
		"$" : {
			exports : "jQuery"
		},

		"$ui" : {
			exports: "$.ui",
			deps : ["$"]
		},

		"zynga/Scroller" : {
			exports : "Scroller",
			deps : ["zynga/Animate"]
		},

		"wysihtml5" : {
			exports : "wysihtml5"
		},

		"CFInstall" : {
			exports : "CFInstall"
		},

		"Handlebars" : {
			exports : "Handlebars"
		}
	}
});
<commit_msg>rename query export<commit_after>require.config({

	paths : {
		"$" : "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min",
		"$ui" : "libs/jquery.ui",
		"$plugin" : "libs/plugins/amd/jquery-plugin",
		"wysihtml5" : "libs/wysihtml5",
		"text" : "libs/plugins/amd/text",
		"rosy" : "libs/rosy/src",
		"detailsShim" : "libs/details-shim"
	},

	waitSeconds : 15,

	shim : {
		"$" : {
			exports : "$"
		},

		"$ui" : {
			exports: "$.ui",
			deps : ["$"]
		},

		"zynga/Scroller" : {
			exports : "Scroller",
			deps : ["zynga/Animate"]
		},

		"wysihtml5" : {
			exports : "wysihtml5"
		},

		"CFInstall" : {
			exports : "CFInstall"
		},

		"Handlebars" : {
			exports : "Handlebars"
		}
	}
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes, Animated, Easing, ART } from 'react-native';
const { Surface } = ART;

import Circle from './animated/Circle';

export default class Bubbles extends Component {
    static propTypes = {
        size: PropTypes.number,
        spaceBetween: PropTypes.number
    };

    state = {
        circles: [
            new Animated.Value(0),
            new Animated.Value(0),
            new Animated.Value(0)
        ]
    };

    componentDidMount() {
        this.state.circles.forEach((val, index) => {
            var timer = setTimeout(() => this.animate(index), index * 250);
            this.timers.push(timer);
        });
    }

    timers = [];

    componentWillUnmount() {
        this.timers.forEach((timer) => {
            clearTimeout(timer);
        });

        this.unmounted = true;
    }

    times = [0, 0, 0];

    animate(index) {
        Animated
            .sequence([
                Animated.timing(this.state.circles[index], {toValue: this.props.size, duration: 650}),
                Animated.timing(this.state.circles[index], {toValue: 0, duration: 650})
            ])
            .start(() => {
                if (!this.unmounted) {
                    this.animate(index);
                }
            });
    }

    static defaultProps = {
        spaceBetween: 6,
        size: 11
    };

    renderBubble(index) {
        const { size, spaceBetween } = this.props;
        const radius = this.state.circles[index];
        const offset = {
            x: size + index * (size * 2 + spaceBetween),
            y: size
        };

        return (<Circle
            fill="#000"
            radius={radius}
            {...offset}
        />);
    }

    render() {
        return (<Surface
            width={100}
            height={40}>
            {this.renderBubble(0)}
            {this.renderBubble(1)}
            {this.renderBubble(2)}
        </Surface>)
    }
}
<commit_msg>fix(Bubbles): Use scale instead of radius for animating Bubbles<commit_after>import React, { Component, PropTypes, Animated, Easing, ART } from 'react-native';
const { Surface } = ART;

import Circle from './animated/Circle';

export default class Bubbles extends Component {
  static propTypes = {
    size: PropTypes.number,
    spaceBetween: PropTypes.number
  };

  state = {
    circles: [
      new Animated.Value(0),
      new Animated.Value(0),
      new Animated.Value(0)
    ]
  };

  static defaultProps = {
    spaceBetween: 6,
    size: 11,
    color: '#000'
  };

  componentDidMount() {
    this.state.circles.forEach((val, index) => {
      var timer = setTimeout(() => this.animate(index), index * 300);
      this.timers.push(timer);
    });
  }

  componentWillUnmount() {
    this.timers.forEach((timer) => {
      clearTimeout(timer);
    });

    this.unmounted = true;
  }

  timers = [];

  animate(index) {
    Animated
      .sequence([
        Animated.timing(this.state.circles[index], {
          toValue: 1,
          duration: 600
        }),
        Animated.timing(this.state.circles[index], {
          toValue: 0,
          duration: 600
        })
      ])
      .start(() => {
        if (!this.unmounted) {
          this.animate(index);
        }
      });
  }

  renderBubble(index) {
    const { size, spaceBetween, color } = this.props;
    const scale = this.state.circles[index];
    const offset = {
      x: size + index * (size * 2 + spaceBetween),
      y: size
    };

    return (<Circle
      fill={color}
      radius={size}
      scale={scale}
      {...offset}
    />);
  }

  render() {
    const { size, spaceBetween } = this.props;
    const width = size * 6 + spaceBetween * 2;
    const height = size * 2;

    return (<Surface
      width={width}
      height={height}>
      {this.renderBubble(0)}
      {this.renderBubble(1)}
      {this.renderBubble(2)}
    </Surface>)
  }
}
<|endoftext|>


<commit_before>'use strict';

const t = require('babel-types');

// Helpers for constructing AST nodes
function PathExpression(path) {
	const iterPattern = /^(.*)\[(\d+)]$/;
	const paths = path.split('.').reduce((prev, key) => {
		const matches = key.match(iterPattern);
		if (matches) {
			const [, rest, index] = matches;
			return [...prev, t.stringLiteral(rest), t.identifier(`key${index}`)];
		}
		return [...prev, t.stringLiteral(key)];
	}, []);

	return paths;
}
function Get(path) {
	const paths = PathExpression(path);

	// precompile path expressions into
	//   context && context['prop'] && context['prop'][5] ...
	return t.callExpression(t.identifier('get'), [
		paths.reduce(
			(out, p) => t.logicalExpression('&&', out, t.memberExpression(out, p, true)),
			t.identifier('context')
		),
	]);
}
// take an array of string expressions
// and convert it to direct concatenation like this
// 	 a + b + c + d
function ConcatStringList(outputs) {
	let out = outputs[0];

	for (let i = 1; i < outputs.length; i += 1) {
		out = t.binaryExpression('+', out, outputs[i]);
	}

	return out;
}

const transforms = {
	StringLiteral(branch) {
		return t.stringLiteral(branch.value);
	},
	SimpleExpression(branch) {
		const path = branch.path;
		if (path === '@root') {
			return t.identifier('context');
		}
		if (path === '@key') {
			return t.identifier('key');
		}
		if (path === '@index') {
			return t.identifier('index');
		}
		if (path === '@first') {
			return t.binaryExpression('===', t.identifier('index'), t.numericLiteral(0));
		}
		if (path === '@last') {
			return t.binaryExpression('===', t.identifier('index'), t.binaryExpression(
				'-',
				t.identifier('length'),
				t.numericLiteral(1)
			));
		}

		return Get(path);
	},
	HelperExpression(branch) {
		return t.callExpression(t.identifier('helper'), [
			t.identifier('context'),
			t.identifier('helpers'),
			t.stringLiteral(branch.helperName),
			t.arrayExpression(compile(branch.args)),
		]);
	},
	OpenIf(branch, nextBranch) {
		let test = transforms[branch.test.tokenType](branch.test);
		if (branch.not) {
			test = t.unaryExpression('!', test, true);
		}

		let alternate = t.stringLiteral('');
		if (nextBranch && nextBranch.tokenType === 'Else') {
			alternate = ConcatStringList(compile(nextBranch.body));

			nextBranch.skipThis = true;
		}

		return t.conditionalExpression(test, ConcatStringList(compile(branch.body)), alternate);
	},
	OpenIter(branch) {
		const key = t.identifier(`key${branch.iterSuffix}`);
		const index = t.identifier(`index${branch.iterSuffix}`);
		const length = t.identifier(`length${branch.iterSuffix}`);

		const iter = t.callExpression(t.identifier('iter'), [
			Get(branch.subject.path),
			t.functionExpression(t.identifier('each'), [
				key,
				index,
				length,
			], t.blockStatement([
				t.variableDeclaration('var', [t.variableDeclarator(t.identifier('key'), key)]),
				t.variableDeclaration('var', [t.variableDeclarator(t.identifier('index'), index)]),
				t.variableDeclaration('var', [t.variableDeclarator(t.identifier('length'), length)]),
				t.returnStatement(ConcatStringList(compile(branch.body))),
			])),
		]);
		iter.name = branch.name;
		iter.cleanName = branch.cleanName;

		return iter;
	},
	Text(branch) {
		return t.stringLiteral(branch.value);
	},
	RawMustache(branch) {
		return transforms[branch.expression.tokenType](branch.expression, branch.raw);
	},
	EscapedMustache(branch) {
		return t.callExpression(
			t.memberExpression(t.identifier('helpers'), t.identifier('__escape')),
			[transforms.RawMustache(branch)]
		);
	},
};

/**
 * Transform a template syntax tree into a Babylon AST
 * @param {object[]} body
 * @returns {object[]}
 */
function compile(body) {
	const compiled = [];
	const len = body.length;
	for (let i = 0; i < len; i += 1) {
		const branch = body[i];
		if (!branch.skipThis) {
			compiled.push(transforms[branch.tokenType](branch, ...body.slice(i + 1)));
		}
	}

	return compiled;
}

const runtimeParams = [
	t.identifier('helpers'),
	t.identifier('context'),
	t.identifier('get'),
	t.identifier('iter'),
	t.identifier('helper'),
];

/**
 * Transform a template syntax tree into a Babylon AST
 * @param {object[]} parsed
 * @returns {object}
 */
function compiler(parsed) {
	const compiled = compile(parsed);

	return t.functionDeclaration(t.identifier('compiled'), runtimeParams, t.blockStatement([
		t.returnStatement(ConcatStringList(compiled)),
	]));
}

compiler.transforms = transforms;
compiler.runtimeParams = runtimeParams;

module.exports = compiler;
<commit_msg>Fix duplicate existence checks<commit_after>'use strict';

const t = require('babel-types');

// Helpers for constructing AST nodes
function PathExpression(path) {
	const iterPattern = /^(.*)\[(\d+)]$/;
	const paths = path.split('.').reduce((prev, key) => {
		const matches = key.match(iterPattern);
		if (matches) {
			const [, rest, index] = matches;
			return [...prev, t.stringLiteral(rest), t.identifier(`key${index}`)];
		}
		return [...prev, t.stringLiteral(key)];
	}, []);

	return paths;
}
function Get(path) {
	const paths = PathExpression(path);

	// precompile path expressions into
	//   context && context['prop'] && context['prop'][5] ...
	let last = t.identifier('context');
	return t.callExpression(t.identifier('get'), [
		paths.reduce(
			(out, p) => {
				last = t.memberExpression(last, p, true);
				return t.logicalExpression('&&', out, last);
			},
			last
		),
	]);
}
// take an array of string expressions
// and convert it to direct concatenation like this
// 	 a + b + c + d
function ConcatStringList(outputs) {
	let out = outputs[0];

	for (let i = 1; i < outputs.length; i += 1) {
		out = t.binaryExpression('+', out, outputs[i]);
	}

	return out;
}

const transforms = {
	StringLiteral(branch) {
		return t.stringLiteral(branch.value);
	},
	SimpleExpression(branch) {
		const path = branch.path;
		if (path === '@root') {
			return t.identifier('context');
		}
		if (path === '@key') {
			return t.identifier('key');
		}
		if (path === '@index') {
			return t.identifier('index');
		}
		if (path === '@first') {
			return t.binaryExpression('===', t.identifier('index'), t.numericLiteral(0));
		}
		if (path === '@last') {
			return t.binaryExpression('===', t.identifier('index'), t.binaryExpression(
				'-',
				t.identifier('length'),
				t.numericLiteral(1)
			));
		}

		return Get(path);
	},
	HelperExpression(branch) {
		return t.callExpression(t.identifier('helper'), [
			t.identifier('context'),
			t.identifier('helpers'),
			t.stringLiteral(branch.helperName),
			t.arrayExpression(compile(branch.args)),
		]);
	},
	OpenIf(branch, nextBranch) {
		let test = transforms[branch.test.tokenType](branch.test);
		if (branch.not) {
			test = t.unaryExpression('!', test, true);
		}

		let alternate = t.stringLiteral('');
		if (nextBranch && nextBranch.tokenType === 'Else') {
			alternate = ConcatStringList(compile(nextBranch.body));

			nextBranch.skipThis = true;
		}

		return t.conditionalExpression(test, ConcatStringList(compile(branch.body)), alternate);
	},
	OpenIter(branch) {
		const key = t.identifier(`key${branch.iterSuffix}`);
		const index = t.identifier(`index${branch.iterSuffix}`);
		const length = t.identifier(`length${branch.iterSuffix}`);

		const iter = t.callExpression(t.identifier('iter'), [
			Get(branch.subject.path),
			t.functionExpression(t.identifier('each'), [
				key,
				index,
				length,
			], t.blockStatement([
				t.variableDeclaration('var', [t.variableDeclarator(t.identifier('key'), key)]),
				t.variableDeclaration('var', [t.variableDeclarator(t.identifier('index'), index)]),
				t.variableDeclaration('var', [t.variableDeclarator(t.identifier('length'), length)]),
				t.returnStatement(ConcatStringList(compile(branch.body))),
			])),
		]);
		iter.name = branch.name;
		iter.cleanName = branch.cleanName;

		return iter;
	},
	Text(branch) {
		return t.stringLiteral(branch.value);
	},
	RawMustache(branch) {
		return transforms[branch.expression.tokenType](branch.expression, branch.raw);
	},
	EscapedMustache(branch) {
		return t.callExpression(
			t.memberExpression(t.identifier('helpers'), t.identifier('__escape')),
			[transforms.RawMustache(branch)]
		);
	},
};

/**
 * Transform a template syntax tree into a Babylon AST
 * @param {object[]} body
 * @returns {object[]}
 */
function compile(body) {
	const compiled = [];
	const len = body.length;
	for (let i = 0; i < len; i += 1) {
		const branch = body[i];
		if (!branch.skipThis) {
			compiled.push(transforms[branch.tokenType](branch, ...body.slice(i + 1)));
		}
	}

	return compiled;
}

const runtimeParams = [
	t.identifier('helpers'),
	t.identifier('context'),
	t.identifier('get'),
	t.identifier('iter'),
	t.identifier('helper'),
];

/**
 * Transform a template syntax tree into a Babylon AST
 * @param {object[]} parsed
 * @returns {object}
 */
function compiler(parsed) {
	const compiled = compile(parsed);

	return t.functionDeclaration(t.identifier('compiled'), runtimeParams, t.blockStatement([
		t.returnStatement(ConcatStringList(compiled)),
	]));
}

compiler.transforms = transforms;
compiler.runtimeParams = runtimeParams;

module.exports = compiler;
<|endoftext|>


<commit_before>'use strict';

/**
 * The base class for all Schema types
 *
 * @memberof HashBrown.Common.Entity.Resource
 */
class SchemaBase extends HashBrown.Entity.Resource.ResourceBase {
    set icon(name) { this.customIcon = name; }
    get icon() { return this.customIcon || super.icon; }

    static get type() { return null; }
    get type() { return this.constructor.type; }

    /**
     * Instantiates a resource
     *
     * @param {Object} params
     *
     * @return {HashBrown.Entity.Resource.SchemaBase} Instance
     */
    static new(params = {}) {
        checkParam(params, 'params', Object)

        params = params || {};

        if(!params.type) {
            return null;
        }

        if(params.type === 'field') {
            return new HashBrown.Entity.Resource.FieldSchema(params);
        } else if(params.type === 'content') {
            return new HashBrown.Entity.Resource.ContentSchema(params);
        }

        throw new Error(`Invalid schema type "${params.type}"`);
    }

    /**
     * Constructor
     *
     * @param {Object} params
     */
    constructor(params) {
        params = params || {};

        super(params);

        if(this.constructor === HashBrown.Entity.Resource.SchemaBase) {
            throw new Error('The HashBrown.Entity.Resource.SchemaBase constructor cannot be used directly');
        }
    }

    /**
     * Gets the human readable name
     *
     * @return {String} Name
     */
    getName() {
        return this.name || this.id;
    }

    /**
     * Gets a copy of every field in this object as a mutable object
     *
     * @returns {Object} object
     */
    getObject() {
        let object = super.getObject();

        object.type = this.type;

        return object;
    }

    /**
     * Structure
     */
    structure() {
        super.structure();

        this.def(String, 'name');
        this.def(String, 'customIcon');
        this.def(String, 'parentId');
        this.def(Object, 'config', {});
    }

    /**
     * Adopts values into this entity
     *
     * @param {Object} params
     */
    adopt(params = {}) {
        checkParam(params, 'params', Object);

        params = params || {};

        // Adopt old value names
        if(params.parentSchemaId) {
            if(!params.parentId) {
                params.parentId = params.parentSchemaId;
            }

            delete params.parentSchemaId;
        }

        if(params.icon) {
            params.customIcon = params.icon;
            delete params.icon;
        }

        // Remove type field, as this is indicated by the model
        delete params.type;

        super.adopt(params);
    }

    /**
     * Gets all children of this schema
     *
     * @return {Array} Children
     */
    async getChildren() {
        return await this.constructor.list(this.context, { parentId: this.id, customOnly: true });
    }

    /**
     * Merges two sets of schema data
     *
     * @param {HashBrown.Entity.Resource.SchemaBase} childSchema
     * @param {HashBrown.Entity.Resource.SchemaBase} parentSchema
     *
     * @returns {HashBrown.Entity.Resource.SchemaBase} Merged Schema
     */
    static merge(childSchema, parentSchema) {
        checkParam(childSchema, 'childSchema', HashBrown.Entity.Resource.SchemaBase, true);
        checkParam(parentSchema, 'parentSchema', HashBrown.Entity.Resource.SchemaBase, true);

        let mergedSchema = parentSchema;

        // Recursive merge
        function merge(parentValues, childValues) {
            for(let k in childValues) {
                if(typeof parentValues[k] === 'object' && typeof childValues[k] === 'object') {
                    merge(parentValues[k], childValues[k]);

                } else if(childValues[k]) {
                    parentValues[k] = childValues[k];

                }
            }
        }

        // Overwrite common values
        mergedSchema.id = childSchema.id;
        mergedSchema.name = childSchema.name;
        mergedSchema.parentId = childSchema.parentId;
        mergedSchema.icon = childSchema.icon || mergedSchema.icon;
        mergedSchema.isLocked = childSchema.isLocked || false;

        // Use most recent updated date for cache invalidation purposes
        if(parentSchema.updatedOn > childSchema.updatedOn) {
            mergedSchema.updatedOn = parentSchema.updatedOn;
        } else {
            mergedSchema.updatedOn = childSchema.updatedOn;
        }

        // Merge config
        if(!mergedSchema.config) { mergedSchema.config = {}; }
        if(!childSchema.config) { childSchema.config = {}; }

        merge(mergedSchema.config, childSchema.config);

        // Specific values for schema types
        switch(mergedSchema.type) {
            case 'field':
                mergedSchema.editorId = childSchema.editorId || mergedSchema.editorId;
                break;

            case 'content':
                // Merge tabs
                if(!mergedSchema.tabs) { mergedSchema.tabs = {}; }
                if(!childSchema.tabs) { childSchema.tabs = {}; }

                merge(mergedSchema.tabs, childSchema.tabs);

                // Set default tab id
                mergedSchema.defaultTabId = childSchema.defaultTabId || mergedSchema.defaultTabId;
                break;
        }

        return mergedSchema;
    }

    /**
     * Transforms a uischema.org definition to the HashBrown standard
     *
     * @param {String} key
     * @param {*} definition
     * @param {Object} i18n
     *
     * @return {Object} Definition
     */
    static getFieldFromUISchema(key, definition, i18n) {
        // First a sanity check
        if(!definition) { return null; }

        if(!i18n) {
            i18n = {};
        }

        if(definition.constructor === String) {
            definition = {
                '@type': definition
            };

        } else if(definition.constructor === Array) {
            definition = {
                '@type': 'ItemList',
                '@options': definition
            };

        } else if(definition.constructor === Object && !definition['@type']) {
            definition['@type'] = 'StructuredValue';

        }

        if(!definition['@type']) {
            throw new Error(`No @type field for definition ${JSON.stringify(definition)}`);
        }

        let isLocalized = definition['@config'] && definition['@config']['isLocalized'] === true;

        switch(definition['@type']) {
            case 'ItemList':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'array',
                    config: {
                        allowedSchemas: definition['@options']
                    }
                };

            case 'Number':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'number',
                };

            case 'StructuredValue':
                let struct = {};

                for(let key in definition) {
                    if(key[0] === '@') { continue; }

                    struct[key] = this.getFieldFromUISchema(definition[key], i18n[key]);
                }

                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'struct',
                    config: {
                        struct: struct
                    }
                };

            case 'Boolean':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'boolean'
                };

            case 'CreativeWork':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'contentReference'
                };

            case 'AudioObject':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'mediaReference',
                    config: {
                        allowedTypes: [ 'audio/*' ]
                    }
                };

            case 'VideoObject':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'mediaReference',
                    config: {
                        allowedTypes: [ 'video/*' ]
                    }
                };

            case 'DataDownload':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'mediaReference',
                    config: {
                        allowedTypes: [ 'application/*' ]
                    }
                };

            case 'ImageObject':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'mediaReference',
                    config: {
                        allowedTypes: [ 'image/*' ]
                    }
                };

            case 'MediaObject':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'mediaReference'
                };

            case 'Text':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'string'
                };

            case 'URL':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'url'
                };

            case 'MultiLineText':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'string',
                    config: {
                        isMultiLine: true
                    }
                };

            case 'RichText':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'richText'
                };

            case 'Enumeration':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'dropdown',
                    config: {
                        options: i18n['@options'] || {}
                    }
                };

            case 'Date':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'date',
                    config: {
                        isDateOnly: true
                    }
                };

            case 'DateTime':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'date'
                };

            default:
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: definition['@type']
                };
        }
    }
}

module.exports = SchemaBase;
<commit_msg>Fixed nested struct import from usichema<commit_after>'use strict';

/**
 * The base class for all Schema types
 *
 * @memberof HashBrown.Common.Entity.Resource
 */
class SchemaBase extends HashBrown.Entity.Resource.ResourceBase {
    set icon(name) { this.customIcon = name; }
    get icon() { return this.customIcon || super.icon; }

    static get type() { return null; }
    get type() { return this.constructor.type; }

    /**
     * Instantiates a resource
     *
     * @param {Object} params
     *
     * @return {HashBrown.Entity.Resource.SchemaBase} Instance
     */
    static new(params = {}) {
        checkParam(params, 'params', Object)

        params = params || {};

        if(!params.type) {
            return null;
        }

        if(params.type === 'field') {
            return new HashBrown.Entity.Resource.FieldSchema(params);
        } else if(params.type === 'content') {
            return new HashBrown.Entity.Resource.ContentSchema(params);
        }

        throw new Error(`Invalid schema type "${params.type}"`);
    }

    /**
     * Constructor
     *
     * @param {Object} params
     */
    constructor(params) {
        params = params || {};

        super(params);

        if(this.constructor === HashBrown.Entity.Resource.SchemaBase) {
            throw new Error('The HashBrown.Entity.Resource.SchemaBase constructor cannot be used directly');
        }
    }

    /**
     * Gets the human readable name
     *
     * @return {String} Name
     */
    getName() {
        return this.name || this.id;
    }

    /**
     * Gets a copy of every field in this object as a mutable object
     *
     * @returns {Object} object
     */
    getObject() {
        let object = super.getObject();

        object.type = this.type;

        return object;
    }

    /**
     * Structure
     */
    structure() {
        super.structure();

        this.def(String, 'name');
        this.def(String, 'customIcon');
        this.def(String, 'parentId');
        this.def(Object, 'config', {});
    }

    /**
     * Adopts values into this entity
     *
     * @param {Object} params
     */
    adopt(params = {}) {
        checkParam(params, 'params', Object);

        params = params || {};

        // Adopt old value names
        if(params.parentSchemaId) {
            if(!params.parentId) {
                params.parentId = params.parentSchemaId;
            }

            delete params.parentSchemaId;
        }

        if(params.icon) {
            params.customIcon = params.icon;
            delete params.icon;
        }

        // Remove type field, as this is indicated by the model
        delete params.type;

        super.adopt(params);
    }

    /**
     * Gets all children of this schema
     *
     * @return {Array} Children
     */
    async getChildren() {
        return await this.constructor.list(this.context, { parentId: this.id, customOnly: true });
    }

    /**
     * Merges two sets of schema data
     *
     * @param {HashBrown.Entity.Resource.SchemaBase} childSchema
     * @param {HashBrown.Entity.Resource.SchemaBase} parentSchema
     *
     * @returns {HashBrown.Entity.Resource.SchemaBase} Merged Schema
     */
    static merge(childSchema, parentSchema) {
        checkParam(childSchema, 'childSchema', HashBrown.Entity.Resource.SchemaBase, true);
        checkParam(parentSchema, 'parentSchema', HashBrown.Entity.Resource.SchemaBase, true);

        let mergedSchema = parentSchema;

        // Recursive merge
        function merge(parentValues, childValues) {
            for(let k in childValues) {
                if(typeof parentValues[k] === 'object' && typeof childValues[k] === 'object') {
                    merge(parentValues[k], childValues[k]);

                } else if(childValues[k]) {
                    parentValues[k] = childValues[k];

                }
            }
        }

        // Overwrite common values
        mergedSchema.id = childSchema.id;
        mergedSchema.name = childSchema.name;
        mergedSchema.parentId = childSchema.parentId;
        mergedSchema.icon = childSchema.icon || mergedSchema.icon;
        mergedSchema.isLocked = childSchema.isLocked || false;

        // Use most recent updated date for cache invalidation purposes
        if(parentSchema.updatedOn > childSchema.updatedOn) {
            mergedSchema.updatedOn = parentSchema.updatedOn;
        } else {
            mergedSchema.updatedOn = childSchema.updatedOn;
        }

        // Merge config
        if(!mergedSchema.config) { mergedSchema.config = {}; }
        if(!childSchema.config) { childSchema.config = {}; }

        merge(mergedSchema.config, childSchema.config);

        // Specific values for schema types
        switch(mergedSchema.type) {
            case 'field':
                mergedSchema.editorId = childSchema.editorId || mergedSchema.editorId;
                break;

            case 'content':
                // Merge tabs
                if(!mergedSchema.tabs) { mergedSchema.tabs = {}; }
                if(!childSchema.tabs) { childSchema.tabs = {}; }

                merge(mergedSchema.tabs, childSchema.tabs);

                // Set default tab id
                mergedSchema.defaultTabId = childSchema.defaultTabId || mergedSchema.defaultTabId;
                break;
        }

        return mergedSchema;
    }

    /**
     * Transforms a uischema.org definition to the HashBrown standard
     *
     * @param {String} key
     * @param {*} definition
     * @param {Object} i18n
     *
     * @return {Object} Definition
     */
    static getFieldFromUISchema(key, definition, i18n) {
        // First a sanity check
        if(!definition) { return null; }

        if(!i18n) {
            i18n = {};
        }

        if(definition.constructor === String) {
            definition = {
                '@type': definition
            };

        } else if(definition.constructor === Array) {
            definition = {
                '@type': 'ItemList',
                '@options': definition
            };

        } else if(definition.constructor === Object && !definition['@type']) {
            definition['@type'] = 'StructuredValue';

        }

        if(!definition['@type']) {
            throw new Error(`No @type field for definition ${JSON.stringify(definition)}`);
        }

        let isLocalized = definition['@config'] && definition['@config']['isLocalized'] === true;

        switch(definition['@type']) {
            case 'ItemList':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'array',
                    config: {
                        allowedSchemas: definition['@options']
                    }
                };

            case 'Number':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'number',
                };

            case 'StructuredValue':
                let struct = {};

                for(let key in definition) {
                    if(key[0] === '@') { continue; }

                    struct[key] = this.getFieldFromUISchema(key, definition[key], i18n[key]);
                }

                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'struct',
                    config: {
                        struct: struct
                    }
                };

            case 'Boolean':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'boolean'
                };

            case 'CreativeWork':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'contentReference'
                };

            case 'AudioObject':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'mediaReference',
                    config: {
                        allowedTypes: [ 'audio/*' ]
                    }
                };

            case 'VideoObject':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'mediaReference',
                    config: {
                        allowedTypes: [ 'video/*' ]
                    }
                };

            case 'DataDownload':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'mediaReference',
                    config: {
                        allowedTypes: [ 'application/*' ]
                    }
                };

            case 'ImageObject':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'mediaReference',
                    config: {
                        allowedTypes: [ 'image/*' ]
                    }
                };

            case 'MediaObject':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'mediaReference'
                };

            case 'Text':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'string'
                };

            case 'URL':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'url'
                };

            case 'MultiLineText':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'string',
                    config: {
                        isMultiLine: true
                    }
                };

            case 'RichText':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'richText'
                };

            case 'Enumeration':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'dropdown',
                    config: {
                        options: i18n['@options'] || {}
                    }
                };

            case 'Date':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'date',
                    config: {
                        isDateOnly: true
                    }
                };

            case 'DateTime':
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: 'date'
                };

            default:
                return {
                    label: i18n['@name'] || key,
                    isLocalized: isLocalized,
                    schemaId: definition['@type']
                };
        }
    }
}

module.exports = SchemaBase;
<|endoftext|>


<commit_before>var jsonBuffStream = require('json-multibuffer-stream')
var concat = require('concat-stream')
var buff = require('multibuffer')
var bops = require('bops')

module.exports.buffToJson = function(test, common) {
  test('buff <-> json', function(t) {
    var test = {'hello': 'world', 'foo': {'bar': '[baz]', 'pizza': [1,2,3]}}
    var columns = Object.keys(test)

    var encoded = jsonBuffStream.encode(test)
    var decoded = jsonBuffStream.decode(columns, encoded)

    t.equal(JSON.stringify(test), JSON.stringify(decoded), 'encoded/decoded matches')
    t.end()
  })

}

module.exports.putJson = function(test, common) {
  test('.put json', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put({"foo": "bar"}, function(err) {
        if (err) throw err
        var cat = dat.createReadStream()

        cat.pipe(concat(function(data) {
          t.equal(data.length, 1)
          t.equal(data[0].foo, "bar")
          done()
        }))
      })
    })
  })
}

module.exports.multiplePutJson = function(test, common) {
  test('.put same json multiple times (random id generation)', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put({"foo": "bar"}, function(err) {
        if (err) throw err
        dat.put({"foo": "bar"}, function(err) {
          if (err) throw err
          var cat = dat.createReadStream()

          cat.pipe(concat(function(data) {
            t.equal(data.length, 2)
            t.equal(data[0].foo, "bar")
            t.equal(data[1].foo, "bar")
            done()
          }))
        })
      })
    })
  })
}

module.exports.putBuff = function(test, common) {
  test('.put buff', function(t) {
    common.getDat(t, function(dat, done) {
      var row = buff.pack([bops.from('bar')])

      dat.put(row, {columns: ['foo']}, function(err) {
        if (err) throw err
        var cat = dat.createReadStream()

        cat.pipe(concat(function(data) {
          t.equal(data.length, 1)
          t.equal(data[0].foo, "bar")
          done()
        }))
      })
    })
  })
}

module.exports.all = function (test, common) {
  module.exports.buffToJson(test, common)
  module.exports.putJson(test, common)
  module.exports.multiplePutJson(test, common)
  module.exports.putBuff(test, common)
}<commit_msg>test that schema version increments when schema changes<commit_after>var jsonBuffStream = require('json-multibuffer-stream')
var concat = require('concat-stream')
var buff = require('multibuffer')
var bops = require('bops')

module.exports.buffToJson = function(test, common) {
  test('buff <-> json', function(t) {
    var test = {'hello': 'world', 'foo': {'bar': '[baz]', 'pizza': [1,2,3]}}
    var columns = Object.keys(test)

    var encoded = jsonBuffStream.encode(test)
    var decoded = jsonBuffStream.decode(columns, encoded)

    t.equal(JSON.stringify(test), JSON.stringify(decoded), 'encoded/decoded matches')
    t.end()
  })

}

module.exports.putJson = function(test, common) {
  test('.put json', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put({"foo": "bar"}, function(err) {
        if (err) throw err
        var cat = dat.createReadStream()

        cat.pipe(concat(function(data) {
          t.equal(data.length, 1)
          t.equal(data[0].foo, "bar")
          done()
        }))
      })
    })
  })
}

module.exports.multiplePutJson = function(test, common) {
  test('.put same json multiple times (random id generation)', function(t) {
    common.getDat(t, function(dat, done) {
      dat.put({"foo": "bar"}, function(err) {
        if (err) throw err
        dat.put({"foo": "bar"}, function(err) {
          if (err) throw err
          var cat = dat.createReadStream()

          cat.pipe(concat(function(data) {
            t.equal(data.length, 2)
            t.equal(data[0].foo, "bar")
            t.equal(data[1].foo, "bar")
            done()
          }))
        })
      })
    })
  })
}

module.exports.putBuff = function(test, common) {
  test('.put buff', function(t) {
    common.getDat(t, function(dat, done) {
      var row = buff.pack([bops.from('bar')])

      dat.put(row, {columns: ['foo']}, function(err) {
        if (err) throw err
        var cat = dat.createReadStream()

        cat.pipe(concat(function(data) {
          t.equal(data.length, 1)
          t.equal(data[0].foo, "bar")
          done()
        }))
      })
    })
  })
}

module.exports.schemaVersion = function(test, common) {
  test('schema version should increment when schema changes', function(t) {
    common.getDat(t, function(dat, done) {
      t.equal(dat.meta.json.schemaVersion, 0, 'schemaVersion 0')
      dat.put({"foo": "bar"}, function(err) {
        if (err) throw err
        t.equal(dat.meta.json.schemaVersion, 1, 'schemaVersion 1')
        dat.put({"foo": "bar", "taco": "pizza"}, function(err) {
          if (err) throw err
          var cat = dat.schemas.createReadStream()
          t.equal(dat.meta.json.schemaVersion, 2, 'schemaVersion 2')

          cat.pipe(concat(function(data) {
            t.equal(data.length, 2, '2 schema versions')
            t.equal(data[0].version, 2, 'latest version is 2')
            t.equal(data[1].version, 1, 'older version is 1')
            done()
          }))
        })
      })
    })
  })
}

module.exports.all = function (test, common) {
  module.exports.buffToJson(test, common)
  module.exports.putJson(test, common)
  module.exports.multiplePutJson(test, common)
  module.exports.putBuff(test, common)
  module.exports.schemaVersion(test, common)
}<|endoftext|>


<commit_before>define(function (require) {
	var test = require('intern!object'),
		assert = require('intern/chai!assert'),
		//Query = require('../query').Query,
		parseQuery = require('../parser').parseQuery,
		Transpiler = require('../transpiler').Transpiler,
		JSON = require('intern/dojo/json');
	test({
		name: 'rql/test/transpiling',
		testTranspiling: function () {
			var transpiler = new Transpiler();
			transpiler.use({name:"use",args:["core/numeric-arithmetic-operators"]},{callback:function(){
				//var def = transpiler.process("define(depth,(string,number),(),(tokenize(/),count()))");
				var def = transpiler.process("define(add2,(any*,number),(number),add(2,?))");
				var fn = def.body;
				console.warn(fn.toString())
			}});
		}
	});
});
<commit_msg>added async callback<commit_after>define(function (require) {
	var registerSuite = require('intern!object'),
		assert = require('intern/chai!assert'),
		//Query = require('../query').Query,
		parseQuery = require('../parser').parseQuery,
		Transpiler = require('../transpiler').Transpiler,
		JSON = require('intern/dojo/json');
	registerSuite({
		name: 'rql/test/transpiling',
		"use(core/numeric-arithmetic-operators),define(add2,(number,number),(number,number),(add(?),add(?))),add2(2,3)": function () {
			var dfd = this.async(1000);
			var transpiler = new Transpiler();
			var ready = dfd.callback(function (error, fn) {
		          if (error) {
		            throw error;
		          }
		          assert.equal(fn(1),6,'Addition operator should add numbers together');
			});
			//var def = transpiler.process("define(depth,(string,number),(),(tokenize(/),count()))");
			transpiler.process("use(core/numeric-arithmetic-operators),define(add2,(number,number),(number,number),(add(?),add(?))),add2(2,3)",function(err,fn){
				ready(err,fn);
			});
			return dfd;
		}
	});
});
<|endoftext|>