<commit_before>$(function(){
  $(document).foundation();

  $('body').on('click', '.settings-link', function() {
    $('.rails-db-settings').toggle();
  });

  $('body').on('click', '.column-selection input, .column-name', function() {
    table_name = $('h2')[0].innerHTML;
    if($(this).hasClass('column-name')){
      column_name = $(this)[0].innerHTML.replace(/\s+/, '').replace(/\s+/, '');
      if($(this).prev().prop('checked') == false){
        $(this).prev().prop('checked', true)
        remove_column_from_cookie(table_name, column_name);
      } else {
        $(this).prev().prop('checked', false)
        write_column_to_cookie(table_name, column_name);
      }
    } else {
      column_name = $(this).prop('name');
      if($(this).prop('checked') == false){
        write_column_to_cookie(table_name, column_name);
      } else {
        remove_column_from_cookie(table_name, column_name);
      }
    }
    $('th.column_' + column_name).toggle();
    $('td.column_' + column_name).toggle();
  });

});

function write_column_to_cookie(table_name, column_name) {
  column_names = get_column_names_from_cookie(table_name);
  $.cookie(table_name, column_names += ', ' + column_name);
};

function remove_column_from_cookie(table_name, column_name) {
  column_names = get_column_names_from_cookie(table_name);
  $.cookie(table_name, column_names.replace(', ' + column_name, ''));
};

function get_column_names_from_cookie(table_name) {
  if($.cookie(table_name) == undefined) {
    return '';
  } else {
    return $.cookie(table_name);
  }
};

<commit_msg>Refactored JavaScript which shows and hides columns<commit_after>$(function(){
  $(document).foundation();

  $('body').on('click', '.settings-link', function() {
    $('.rails-db-settings').toggle();
  });

  $('body').on('click', '.column-name input', function() {
    table_name = $('h2')[0].innerHTML;
    column_name = $(this).prop('name');
    if($(this).prop('checked') == false){
      write_column_to_cookie(table_name, column_name);
    } else {
      remove_column_from_cookie(table_name, column_name);
    }
    $('th.column_' + column_name).toggle();
    $('td.column_' + column_name).toggle();
  });

});

function write_column_to_cookie(table_name, column_name) {
  column_names = get_column_names_from_cookie(table_name);
  $.cookie(table_name, column_names += ', ' + column_name);
};

function remove_column_from_cookie(table_name, column_name) {
  column_names = get_column_names_from_cookie(table_name);
  $.cookie(table_name, column_names.replace(', ' + column_name, ''));
};

function get_column_names_from_cookie(table_name) {
  if($.cookie(table_name) == undefined) {
    return '';
  } else {
    return $.cookie(table_name);
  }
};

<|endoftext|>


<commit_before>const devDependencies = [];
const dependencies = [];

module.exports.add = (names) => {
  dependencies.push(...names);
};

module.exports.addDev = (names) => {
  devDependencies.push(...names);
};

module.exports.get = () => dependencies;
module.exports.getDev = () => devDependencies;

module.exports.has = (name) => dependencies.includes(name) || devDependencies.includes(name);
<commit_msg>refactor: deprecate old file<commit_after><|endoftext|>


<commit_before>(function() {
  window.shared || (window.shared = {});
  var dom = window.shared.ReactHelpers.dom;
  var createEl = window.shared.ReactHelpers.createEl;

  var NoteCard = window.shared.NoteCard;
  var PropTypes = window.shared.PropTypes;
  var FeedHelpers = window.shared.FeedHelpers;
  var moment = window.moment;

  var styles = {
    noItems: {
      margin: 10
    },
    badge: {
      display: 'inline-block',
      background: '#eee',
      outline: '3px solid #eee',
      width: '10em',
      textAlign: 'center',
      marginLeft: 10,
      marginRight: 10
    }
  };

  /*
  Renders the list of notes.
  */
  var NotesList = window.shared.NotesList = React.createClass({
    displayName: 'NotesList',

    propTypes: {
      feed: PropTypes.feed.isRequired,
      educatorsIndex: React.PropTypes.object.isRequired,
      eventNoteTypesIndex: React.PropTypes.object.isRequired,
      onSaveNote: React.PropTypes.func.isRequired
    },

    render: function() {
      var mergedNotes = FeedHelpers.mergedNotes(this.props.feed);
      return dom.div({ className: 'NotesList' },
        (mergedNotes.length === 0) ? dom.div({ style: styles.noItems }, 'No notes') : mergedNotes.map(function(mergedNote) {
        switch (mergedNote.type) {
          case 'event_notes': return this.renderEventNote(mergedNote);
          case 'deprecated_interventions': return this.renderDeprecatedIntervention(mergedNote);
        }
      }, this));
    },

    renderEventNoteTypeBadge: function(eventNoteTypeId) {
      var eventNoteType = this.props.eventNoteTypesIndex[eventNoteTypeId];
      if (eventNoteType === undefined) return null;
      return dom.span({ style: styles.badge }, eventNoteType.name);
    },

    renderEventNote: function(eventNote) {
      return createEl(NoteCard, {
        key: ['event_note', eventNote.id].join(),
        eventNoteId: eventNote.id,
        eventNoteTypeId: eventNote.event_note_type_id,
        noteMoment: moment.utc(eventNote.recorded_at),
        badge: this.renderEventNoteTypeBadge(eventNote.event_note_type_id),
        educatorId: eventNote.educator_id,
        text: eventNote.text,
        attachmentUrls: eventNote.attachment_urls,
        educatorsIndex: this.props.educatorsIndex,
        onSave: this.props.onSaveNote
      });
    },

    // TODO(kr) support custom intervention type
    // This assumes that the `end_date` field is not accurate enough to be worth splitting
    // this out into two note entries.
    renderDeprecatedIntervention: function(deprecatedIntervention) {
      return createEl(NoteCard, {
        key: ['deprecated_intervention', deprecatedIntervention.id].join(),
        noteMoment: moment.utc(deprecatedIntervention.start_date_timestamp),
        badge: dom.span({ style: styles.badge }, 'Old intervention'),
        educatorId: deprecatedIntervention.educator_id,
        text: _.compact([deprecatedIntervention.name, deprecatedIntervention.comment, deprecatedIntervention.goal]).join('\n'),
        educatorsIndex: this.props.educatorsIndex,
        attachmentUrls: []  // deprecated interventions have no attachments
      });
    },

  });
})();
<commit_msg>Pass in default value for attached Urls ([])<commit_after>(function() {
  window.shared || (window.shared = {});
  var dom = window.shared.ReactHelpers.dom;
  var createEl = window.shared.ReactHelpers.createEl;

  var NoteCard = window.shared.NoteCard;
  var PropTypes = window.shared.PropTypes;
  var FeedHelpers = window.shared.FeedHelpers;
  var moment = window.moment;

  var styles = {
    noItems: {
      margin: 10
    },
    badge: {
      display: 'inline-block',
      background: '#eee',
      outline: '3px solid #eee',
      width: '10em',
      textAlign: 'center',
      marginLeft: 10,
      marginRight: 10
    }
  };

  /*
  Renders the list of notes.
  */
  var NotesList = window.shared.NotesList = React.createClass({
    displayName: 'NotesList',

    propTypes: {
      feed: PropTypes.feed.isRequired,
      educatorsIndex: React.PropTypes.object.isRequired,
      eventNoteTypesIndex: React.PropTypes.object.isRequired,
      onSaveNote: React.PropTypes.func.isRequired
    },

    render: function() {
      var mergedNotes = FeedHelpers.mergedNotes(this.props.feed);
      return dom.div({ className: 'NotesList' },
        (mergedNotes.length === 0) ? dom.div({ style: styles.noItems }, 'No notes') : mergedNotes.map(function(mergedNote) {
        switch (mergedNote.type) {
          case 'event_notes': return this.renderEventNote(mergedNote);
          case 'deprecated_interventions': return this.renderDeprecatedIntervention(mergedNote);
        }
      }, this));
    },

    renderEventNoteTypeBadge: function(eventNoteTypeId) {
      var eventNoteType = this.props.eventNoteTypesIndex[eventNoteTypeId];
      if (eventNoteType === undefined) return null;
      return dom.span({ style: styles.badge }, eventNoteType.name);
    },

    renderEventNote: function(eventNote) {
      return createEl(NoteCard, {
        key: ['event_note', eventNote.id].join(),
        eventNoteId: eventNote.id,
        eventNoteTypeId: eventNote.event_note_type_id,
        noteMoment: moment.utc(eventNote.recorded_at),
        badge: this.renderEventNoteTypeBadge(eventNote.event_note_type_id),
        educatorId: eventNote.educator_id,
        text: eventNote.text,
        attachmentUrls: eventNote.attachment_urls || [],
        educatorsIndex: this.props.educatorsIndex,
        onSave: this.props.onSaveNote
      });
    },

    // TODO(kr) support custom intervention type
    // This assumes that the `end_date` field is not accurate enough to be worth splitting
    // this out into two note entries.
    renderDeprecatedIntervention: function(deprecatedIntervention) {
      return createEl(NoteCard, {
        key: ['deprecated_intervention', deprecatedIntervention.id].join(),
        noteMoment: moment.utc(deprecatedIntervention.start_date_timestamp),
        badge: dom.span({ style: styles.badge }, 'Old intervention'),
        educatorId: deprecatedIntervention.educator_id,
        text: _.compact([deprecatedIntervention.name, deprecatedIntervention.comment, deprecatedIntervention.goal]).join('\n'),
        educatorsIndex: this.props.educatorsIndex,
        attachmentUrls: []  // deprecated interventions have no attachments
      });
    },

  });
})();
<|endoftext|>


<commit_before>var yo = require('yo-yo')

// -------------- styling ----------------------
var csjs = require('csjs-inject')
var styleGuide = require('./style-guide')
var styles = styleGuide()

var css = csjs`
  .settingsTabView {
    padding: 2%;
    display: flex;
  }
  .info extends ${styles.infoTextBox} {
    margin-bottom: 2em;
  }
  .crow {
    margin-top: 1em;
    display: flex;
  }
  .select extends ${styles.dropdown} {
    float: left;
    max-width: 90%;
  }
  .button extends ${styles.button} {
    background-color: #C6CFF7;
    width: 100%;
    align-self: center;
    text-align: -webkit-center;
  }
  .col1 extends ${styles.titleL} {
    float: left;
    align-self: center;
  }
  .checkboxText {
    margin-left: 3px;
  }
  .compilationWarning extends ${styles.warningTextBox} {
    margin-top: 1em;
    margin-left: 0.5em;
  }
}
`
module.exports = SettingsTab

function SettingsTab (container, appAPI, appEvents, opts) {
  if (typeof container === 'string') container = document.querySelector(container)
  if (!container) throw new Error('no container given')

  var warnCompilationSlow = yo`<div id="warnCompilationSlow" class="${css.compilationWarning}"></div>`

  appEvents.compiler.register('compilationDuration', function tabHighlighting (speed) {
    warnCompilationSlow.style.visibility = 'hidden'
    var settingsView = document.querySelector('#header #menu .settingsView')
    settingsView.style.color = ''
    if (speed > 1000) {
      warnCompilationSlow.className = css.compilationWarning
      warnCompilationSlow.style.visibility = 'visible'
      warnCompilationSlow.innerHTML = `Last compilation took ${speed}ms. We suggest to turn off autocompilation.`
      settingsView.style.color = '#FF8B8B'
    }
  })

  var el = yo`

Your current Solidity version is

        <select class="${css.select}" id="versionSelector"></select>

<input class="${css.col1}" id="editorWrap" type="checkbox">

        Text Wrap

<input class="${css.col1}" id="optimize" type="checkbox">

        Enable Optimization

<input class="${css.col1}" id="autoCompile" type="checkbox" checked>

        Auto Compile

Compile

      ${warnCompilationSlow}

  `
  container.appendChild(el)
}
<commit_msg>Refactor tabHighlighting function<commit_after>var yo = require('yo-yo')

// -------------- styling ----------------------
var csjs = require('csjs-inject')
var styleGuide = require('./style-guide')
var styles = styleGuide()

var css = csjs`
  .settingsTabView {
    padding: 2%;
    display: flex;
  }
  .info extends ${styles.infoTextBox} {
    margin-bottom: 2em;
  }
  .crow {
    margin-top: 1em;
    display: flex;
  }
  .select extends ${styles.dropdown} {
    float: left;
    max-width: 90%;
  }
  .button extends ${styles.button} {
    background-color: #C6CFF7;
    width: 100%;
    align-self: center;
    text-align: -webkit-center;
  }
  .col1 extends ${styles.titleL} {
    float: left;
    align-self: center;
  }
  .checkboxText {
    margin-left: 3px;
  }
  .compilationWarning extends ${styles.warningTextBox} {
    margin-top: 1em;
    margin-left: 0.5em;
  }
}
`
module.exports = SettingsTab

function SettingsTab (container, appAPI, appEvents, opts) {
  if (typeof container === 'string') container = document.querySelector(container)
  if (!container) throw new Error('no container given')

  var warnCompilationSlow = yo`<div id="warnCompilationSlow"></div>`

  appEvents.compiler.register('compilationDuration', function tabHighlighting (speed) {
    var settingsView = document.querySelector('#header #menu .settingsView')
    if (speed > 1000) {
      warnCompilationSlow.className = css.compilationWarning
      warnCompilationSlow.innerHTML = `Last compilation took ${speed}ms. We suggest to turn off autocompilation.`
      warnCompilationSlow.style.visibility = 'visible'
      settingsView.style.color = '#FF8B8B'
    }
  })

  var el = yo`

Your current Solidity version is

        <select class="${css.select}" id="versionSelector"></select>

<input class="${css.col1}" id="editorWrap" type="checkbox">

        Text Wrap

<input class="${css.col1}" id="optimize" type="checkbox">

        Enable Optimization

<input class="${css.col1}" id="autoCompile" type="checkbox" checked>

        Auto Compile

Compile

      ${warnCompilationSlow}

  `
  container.appendChild(el)
}
<|endoftext|>


<commit_before>/*
 * The MIT License
 *
 * Copyright 2013 RBC1B.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
if (!roms) {
    var roms = {};
};

if (!roms.common) {
    roms.common = {};
};

roms.common.validatorPhoneNumber = function(value, element) {
    if (this.optional(element)) {
        return true;
    } else {
        try {
            var phone = cleanPhone(value);
            var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
            var number = phoneUtil.parseAndKeepRawInput(phone, "GB");
            return phoneUtil.isValidNumber(number);
        } catch (exception) {
            return false;
        }
    }
};

roms.common.validatorMobilePhoneNumber = function(value, element) {
    if (this.optional(element)) {
        return true;
    } else {
        try {
            var phone = cleanPhone(value);
            var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
            var number = phoneUtil.parseAndKeepRawInput(phone, "GB");
            return phoneUtil.getNumberType(number) == 1;
        } catch (exception) {
            return false;
        }
    }
};

roms.common.validatorErrorPlacement = function(error, element) {
    var $container = element.closest(".error-container");
    if ($container.length > 0) {
        error.appendTo($container);
    } else {
        element.after(error);
    }
};

/**
 * Match a person to a given forename and surname (exact match).
 * This assumes we have the person-link-search-form and person-link-modal elements on the page
 * @param forename person's first name
 * @param surname person's last name
 * @param $personId jquery element linking to the input use to store the matched person id
 * @param populateFunction callback to populate the page with the selected person
 */
roms.common.matchLinkedPerson = function (forename, surname, $personId, populateFunction) {
    if(!forename || !surname) {
        // clear any linked name
        $personId.data("full-name", "");
        populateFunction(null, forename, surname, $personId);
        return;
    }

    var existingPersonName = $personId.data("full-name");
    if (existingPersonName == forename + " " + surname) {
        // no change in value
        return;
    }
    var existingPersonId = $personId.val();

    $.ajax({
        url: roms.common.relativePath + '/persons/search',
        contentType: "application/json",
        dataType: 'json',
        data:  {
            forename: forename,
            surname: surname,
            checkVolunteer: false
        },
        success: function(data) {
            // no match, and no person linked. We don't show anything
            if ((!data || data.length === 0) && !existingPersonId) {
                return;
            }

            templateData = {};
            templateData.existingPersonId = existingPersonId;
            templateData.existingPersonName = existingPersonName;

            if (data) {
                templateData.matchedPersons = true;
                templateData.results = data;
            }

            var template = $("#person-link-search-form").html();
            var html = Mustache.to_html(template, templateData);

            $("#person-link-modal .modal-body").html(html)
            var modalElement = $("#person-link-modal")

            modalElement.modal('show')

            // if they select the person id, set it to the hidden volunteer person id field
            $("a.matched-person").on("click", function(event){
                populateFunction($(this).data("person-id"), forename, surname, $personId);
                modalElement.modal('hide')
            });
        }
    });

    $personId.data("full-name", forename + " " + surname);
}

/**
 * Extensions to datatables to fit in with bootstrap styling
 * See http://www.datatables.net/media/blog/bootstrap_2/DT_bootstrap.js
 * @param $table table element
 * @param additional dataTable options to set
 */
roms.common.datatables = function($table, options) {
    $.extend( true, $.fn.dataTable.defaults, {
        "sDom": "<'row'<'col-md-2 pull-right'l><'col-md-3 col-md-offset-7'f>>rt<'row'<'col-md-6'i><'col-md-6'p>>",
        "sPaginationType": "bootstrap",
        "oLanguage": {
            "sLengthMenu": "_MENU_ records per page"
        }
    } );

    $.extend( $.fn.dataTableExt.oStdClasses, {
        "sWrapper": "dataTables_wrapper form-inline"
    } );

    /* API method to get paging information */
    $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
    {
        return {
            "iStart":         oSettings._iDisplayStart,
            "iEnd":           oSettings.fnDisplayEnd(),
            "iLength":        oSettings._iDisplayLength,
            "iTotal":         oSettings.fnRecordsTotal(),
            "iFilteredTotal": oSettings.fnRecordsDisplay(),
            "iPage":          oSettings._iDisplayLength === -1 ?
            0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
            "iTotalPages":    oSettings._iDisplayLength === -1 ?
            0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
        };
    };

    /* Bootstrap style pagination control */
    $.extend( $.fn.dataTableExt.oPagination, {
        "bootstrap": {
            "fnInit": function( oSettings, nPaging, fnDraw ) {
                var oLang = oSettings.oLanguage.oPaginate;
                var fnClickHandler = function ( e ) {
                    e.preventDefault();
                    if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
                        fnDraw( oSettings );
                    }
                };

                $(nPaging).append(
                    '
'+
                    '
← '+oLang.sPrevious+'
'+
                    '
'+oLang.sNext+' →
'+
                    '
'
                    );
                var els = $('a', nPaging);
                $(els[0]).bind( 'click.DT', {
                    action: "previous"
                }, fnClickHandler );
                $(els[1]).bind( 'click.DT', {
                    action: "next"
                }, fnClickHandler );
            },

            "fnUpdate": function ( oSettings, fnDraw ) {
                var iListLength = 5;
                var oPaging = oSettings.oInstance.fnPagingInfo();
                var an = oSettings.aanFeatures.p;
                var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);

                if ( oPaging.iTotalPages < iListLength) {
                    iStart = 1;
                    iEnd = oPaging.iTotalPages;
                }
                else if ( oPaging.iPage <= iHalf ) {
                    iStart = 1;
                    iEnd = iListLength;
                } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
                    iStart = oPaging.iTotalPages - iListLength + 1;
                    iEnd = oPaging.iTotalPages;
                } else {
                    iStart = oPaging.iPage - iHalf + 1;
                    iEnd = iStart + iListLength - 1;
                }

                for ( i=0, ien=an.length ; i<ien ; i++ ) {
                    // Remove the middle elements
                    $('li:gt(0)', an[i]).filter(':not(:last)').remove();

                    // Add the new list items and their event handlers
                    for ( j=iStart ; j<=iEnd ; j++ ) {
                        sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
                        $('
'+j+'
')
                        .insertBefore( $('li:last', an[i])[0] )
                        .bind('click', function (e) {
                            e.preventDefault();
                            oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
                            fnDraw( oSettings );
                        } );
                    }

                    // Add / remove disabled classes from the static elements
                    if ( oPaging.iPage === 0 ) {
                        $('li:first', an[i]).addClass('disabled');
                    } else {
                        $('li:first', an[i]).removeClass('disabled');
                    }

                    if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
                        $('li:last', an[i]).addClass('disabled');
                    } else {
                        $('li:last', an[i]).removeClass('disabled');
                    }
                }
                //If all data fits into one page, hide the pagination and "Showing ? of ? Entries"
                if (oPaging.iTotalPages <= 1) {
                    $('.dataTables_paginate').hide();
                    $('.dataTables_info').hide();
                } else {
                    $('.dataTables_paginate').show();
                    $('.dataTables_info').show();
                }
                //If the number of rows are 5 or less, hide "... records per page" and Search box
                if (oPaging.iTotal <= 5) {
                    $('.dataTables_length').hide();
                    $('.dataTables_filter').hide();
                }
        }
    } });

    /*
     * TableTools Bootstrap compatibility
     * Required TableTools 2.1+
     */
    if ( $.fn.DataTable.TableTools ) {
        // Set the classes that TableTools uses to something suitable for Bootstrap
        $.extend( true, $.fn.DataTable.TableTools.classes, {
            "container": "DTTT btn-group",
            "buttons": {
                "normal": "btn",
                "disabled": "disabled"
            },
            "collection": {
                "container": "DTTT_dropdown dropdown-menu",
                "buttons": {
                    "normal": "",
                    "disabled": "disabled"
                }
            },
            "print": {
                "info": "DTTT_print_info modal"
            },
            "select": {
                "row": "active"
            }
        } );

        // Have the collection use a bootstrap compatible dropdown
        $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
            "collection": {
                "container": "ul",
                "button": "li",
                "liner": "a"
            }
        } );
    }

    // create the table
    $table.dataTable(options);

}

roms.common.persistentTabs = function() {
    if (location.hash.substr(0,2) == "#!") {
        $("a[href='#" + location.hash.substr(2) + "']").tab("show");
    }

    $("a[data-toggle='tab']").on("shown", function (e) {
        var hash = $(e.target).attr("href");
        if (hash.substr(0,1) == "#") {
            location.replace("#!" + hash.substr(1));
        }
    });
}

roms.common.validation = {};
$(document).ready(function() {
    // store the relative path, used for all the ajax calls
    // we trim the trailing slash to allow uris that include it look absolute
    roms.common.relativePath = $("#relative-path").data("relative-path").replace(/\/$/, '');

    // remote validation method for kingdom hall typeahead lookups
    roms.common.validation.kingdomHall = function($nameInput, $idInput) {
        return {
            // check for an exact match. Populate the kingdom hall id
            url: roms.common.relativePath + "/kingdom-halls/search",
            contentType: "application/json",
            dataType: "json",
            data: {
                name: function() {
                    return $nameInput.val();
                }
            },
            dataFilter: function(rawData) {
                var data = JSON.parse(rawData)
                if (data && data[0].name == $nameInput.val()) {
                    $idInput.val(data[0].id);
                    return true;
                }
             // no match - clear the stored id
                $idInput.val(null);
                return false;
            }
        };
    }

    roms.common.validation.congregation = function($nameInput, $idInput) {
        return {
            // check for an exact match. Populate the congregation id
            url: roms.common.relativePath + "/congregations/search",
            contentType: "application/json",
            dataType: "json",
            data: {
                name: function() {
                    return $nameInput.val();
                }
            },
            dataFilter: function(rawData) {
                var data = JSON.parse(rawData)
                if (data && data[0].name == $nameInput.val()) {
                    $idInput.val(data[0].id);
                    return true;
                }
                // no match - clear the stored id
                $idInput.val(null);
                return false;
            }
        };
    }

    roms.common.validation.user = function($nameInput, $idInput) {
        return {
            // check for an exact match. Populate the user id
            url: roms.common.relativePath + "/users/search",
            contentType: "application/json",
            dataType: "json",
            data: {
                name: function() {
                    return $nameInput.val();
                }
            },
            dataFilter: function(rawData) {
                var data = JSON.parse(rawData)
                if (data && data[0].userName == $nameInput.val()) {
                    $idInput.val(data[0].personId);
                    return true;
                }
                // no match - clear the stored id
                $idInput.val(null);
                return false;
            }
        };
    }

});

// validation configuration

<commit_msg>[#64343772] Further amendments to common.js<commit_after>/*
 * The MIT License
 *
 * Copyright 2013 RBC1B.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
if (!roms) {
    var roms = {};
};

if (!roms.common) {
    roms.common = {};
};

roms.common.validatorPhoneNumber = function(value, element) {
    if (this.optional(element)) {
        return true;
    } else {
        try {
            var phone = cleanPhone(value);
            var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
            var number = phoneUtil.parseAndKeepRawInput(phone, "GB");
            return phoneUtil.isValidNumber(number);
        } catch (exception) {
            return false;
        }
    }
};

roms.common.validatorMobilePhoneNumber = function(value, element) {
    if (this.optional(element)) {
        return true;
    } else {
        try {
            var phone = cleanPhone(value);
            var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
            var number = phoneUtil.parseAndKeepRawInput(phone, "GB");
            return phoneUtil.getNumberType(number) == 1;
        } catch (exception) {
            return false;
        }
    }
};

roms.common.validatorErrorPlacement = function(error, element) {
    var $container = element.closest(".error-container");
    if ($container.length > 0) {
        error.appendTo($container);
    } else {
        element.after(error);
    }
};

/**
 * Match a person to a given forename and surname (exact match).
 * This assumes we have the person-link-search-form and person-link-modal elements on the page
 * @param forename person's first name
 * @param surname person's last name
 * @param $personId jquery element linking to the input use to store the matched person id
 * @param populateFunction callback to populate the page with the selected person
 */
roms.common.matchLinkedPerson = function (forename, surname, $personId, populateFunction) {
    if(!forename || !surname) {
        // clear any linked name
        $personId.data("full-name", "");
        populateFunction(null, forename, surname, $personId);
        return;
    }

    var existingPersonName = $personId.data("full-name");
    if (existingPersonName == forename + " " + surname) {
        // no change in value
        return;
    }
    var existingPersonId = $personId.val();

    $.ajax({
        url: roms.common.relativePath + '/persons/search',
        contentType: "application/json",
        dataType: 'json',
        data:  {
            forename: forename,
            surname: surname,
            checkVolunteer: false
        },
        success: function(data) {
            // no match, and no person linked. We don't show anything
            if ((!data || data.length === 0) && !existingPersonId) {
                return;
            }

            templateData = {};
            templateData.existingPersonId = existingPersonId;
            templateData.existingPersonName = existingPersonName;

            if (data) {
                templateData.matchedPersons = true;
                templateData.results = data;
            }

            var template = $("#person-link-search-form").html();
            var html = Mustache.to_html(template, templateData);

            $("#person-link-modal .modal-body").html(html)
            var modalElement = $("#person-link-modal")

            modalElement.modal('show')

            // if they select the person id, set it to the hidden volunteer person id field
            $("a.matched-person").on("click", function(event){
                populateFunction($(this).data("person-id"), forename, surname, $personId);
                modalElement.modal('hide')
            });
        }
    });

    $personId.data("full-name", forename + " " + surname);
}

/**
 * Extensions to datatables to fit in with bootstrap styling
 * See http://www.datatables.net/media/blog/bootstrap_2/DT_bootstrap.js
 * @param $table table element
 * @param additional dataTable options to set
 */
roms.common.datatables = function($table, options) {
    $.extend( true, $.fn.dataTable.defaults, {
        "sDom": "<'row'<'col-md-2 pull-right'l><'col-md-3 col-md-offset-7'f>>rt<'row'<'col-md-6'i><'col-md-6'p>>",
        "sPaginationType": "bootstrap",
        "oLanguage": {
            "sLengthMenu": "_MENU_ records per page"
        }
    } );

    $.extend( $.fn.dataTableExt.oStdClasses, {
        "sWrapper": "dataTables_wrapper form-inline"
    } );

    /* API method to get paging information */
    $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
    {
        return {
            "iStart":         oSettings._iDisplayStart,
            "iEnd":           oSettings.fnDisplayEnd(),
            "iLength":        oSettings._iDisplayLength,
            "iTotal":         oSettings.fnRecordsTotal(),
            "iFilteredTotal": oSettings.fnRecordsDisplay(),
            "iPage":          oSettings._iDisplayLength === -1 ?
            0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
            "iTotalPages":    oSettings._iDisplayLength === -1 ?
            0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
        };
    };

    /* Bootstrap style pagination control */
    $.extend( $.fn.dataTableExt.oPagination, {
        "bootstrap": {
            "fnInit": function( oSettings, nPaging, fnDraw ) {
                var oLang = oSettings.oLanguage.oPaginate;
                var fnClickHandler = function ( e ) {
                    e.preventDefault();
                    if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
                        fnDraw( oSettings );
                    }
                };
                //var oPaging = oSettings.oInstance.fnPagingInfo();
                //Search box and "... records per page" hide themselves if total records are 5 or less.
                //This will not be influenced by filtering.
                //if (oPaging.iTotal <= 5)    {
                //   $('.dataTables_filter').hide();
                //    $('.dataTables_length').hide();
                //} else  {
                //    $('.dataTables_filter').show();
                //    $('.dataTables_length').show();
                //}
                //alert(oPaging.iTotal);

                $(nPaging).append(
                    '
'+
                    '
← '+oLang.sPrevious+'
'+
                    '
'+oLang.sNext+' →
'+
                    '
'
                    );
                var els = $('a', nPaging);
                $(els[0]).bind( 'click.DT', {
                    action: "previous"
                }, fnClickHandler );
                $(els[1]).bind( 'click.DT', {
                    action: "next"
                }, fnClickHandler );
            },

            "fnUpdate": function ( oSettings, fnDraw ) {
                var iListLength = 5;
                var oPaging = oSettings.oInstance.fnPagingInfo();
                var an = oSettings.aanFeatures.p;
                var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);

                if ( oPaging.iTotalPages < iListLength) {
                    iStart = 1;
                    iEnd = oPaging.iTotalPages;
                }
                else if ( oPaging.iPage <= iHalf ) {
                    iStart = 1;
                    iEnd = iListLength;
                } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
                    iStart = oPaging.iTotalPages - iListLength + 1;
                    iEnd = oPaging.iTotalPages;
                } else {
                    iStart = oPaging.iPage - iHalf + 1;
                    iEnd = iStart + iListLength - 1;
                }

                for ( i=0, ien=an.length ; i<ien ; i++ ) {
                    // Remove the middle elements
                    $('li:gt(0)', an[i]).filter(':not(:last)').remove();

                    // Add the new list items and their event handlers
                    for ( j=iStart ; j<=iEnd ; j++ ) {
                        sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
                        $('
'+j+'
')
                        .insertBefore( $('li:last', an[i])[0] )
                        .bind('click', function (e) {
                            e.preventDefault();
                            oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
                            fnDraw( oSettings );
                        } );
                    }

                    // Add / remove disabled classes from the static elements
                    if ( oPaging.iPage === 0 ) {
                        $('li:first', an[i]).addClass('disabled');
                    } else {
                        $('li:first', an[i]).removeClass('disabled');
                    }

                    if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
                        $('li:last', an[i]).addClass('disabled');
                    } else {
                        $('li:last', an[i]).removeClass('disabled');
                    }
                }
                //If all data fits into one page, hide the pagination and "Showing ? of ? Entries"
                if (oPaging.iTotalPages <= 1) {
                    $('.dataTables_paginate').hide();
                    $('.dataTables_info').hide();
                } else {
                   $('.dataTables_paginate').show();
                   $('.dataTables_info').show();
                }
                if (oPaging.iTotal <= 5)    {
                    $('.dataTables_filter').hide();
                    $('.dataTables_length').hide();
                } else  {
                    $('.dataTables_filter').show();
                    $('.dataTables_length').show();
                }
        }
    } });

    /*
     * TableTools Bootstrap compatibility
     * Required TableTools 2.1+
     */
    if ( $.fn.DataTable.TableTools ) {
        // Set the classes that TableTools uses to something suitable for Bootstrap
        $.extend( true, $.fn.DataTable.TableTools.classes, {
            "container": "DTTT btn-group",
            "buttons": {
                "normal": "btn",
                "disabled": "disabled"
            },
            "collection": {
                "container": "DTTT_dropdown dropdown-menu",
                "buttons": {
                    "normal": "",
                    "disabled": "disabled"
                }
            },
            "print": {
                "info": "DTTT_print_info modal"
            },
            "select": {
                "row": "active"
            }
        } );

        // Have the collection use a bootstrap compatible dropdown
        $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
            "collection": {
                "container": "ul",
                "button": "li",
                "liner": "a"
            }
        } );
    }

    // create the table
    $table.dataTable(options);
}

roms.common.persistentTabs = function() {
    if (location.hash.substr(0,2) == "#!") {
        $("a[href='#" + location.hash.substr(2) + "']").tab("show");
    }

    $("a[data-toggle='tab']").on("shown", function (e) {
        var hash = $(e.target).attr("href");
        if (hash.substr(0,1) == "#") {
            location.replace("#!" + hash.substr(1));
        }
    });
}

roms.common.validation = {};
$(document).ready(function() {
    // store the relative path, used for all the ajax calls
    // we trim the trailing slash to allow uris that include it look absolute
    roms.common.relativePath = $("#relative-path").data("relative-path").replace(/\/$/, '');

    // remote validation method for kingdom hall typeahead lookups
    roms.common.validation.kingdomHall = function($nameInput, $idInput) {
        return {
            // check for an exact match. Populate the kingdom hall id
            url: roms.common.relativePath + "/kingdom-halls/search",
            contentType: "application/json",
            dataType: "json",
            data: {
                name: function() {
                    return $nameInput.val();
                }
            },
            dataFilter: function(rawData) {
                var data = JSON.parse(rawData)
                if (data && data[0].name == $nameInput.val()) {
                    $idInput.val(data[0].id);
                    return true;
                }
             // no match - clear the stored id
                $idInput.val(null);
                return false;
            }
        };
    }

    roms.common.validation.congregation = function($nameInput, $idInput) {
        return {
            // check for an exact match. Populate the congregation id
            url: roms.common.relativePath + "/congregations/search",
            contentType: "application/json",
            dataType: "json",
            data: {
                name: function() {
                    return $nameInput.val();
                }
            },
            dataFilter: function(rawData) {
                var data = JSON.parse(rawData)
                if (data && data[0].name == $nameInput.val()) {
                    $idInput.val(data[0].id);
                    return true;
                }
                // no match - clear the stored id
                $idInput.val(null);
                return false;
            }
        };
    }

    roms.common.validation.user = function($nameInput, $idInput) {
        return {
            // check for an exact match. Populate the user id
            url: roms.common.relativePath + "/users/search",
            contentType: "application/json",
            dataType: "json",
            data: {
                name: function() {
                    return $nameInput.val();
                }
            },
            dataFilter: function(rawData) {
                var data = JSON.parse(rawData)
                if (data && data[0].userName == $nameInput.val()) {
                    $idInput.val(data[0].personId);
                    return true;
                }
                // no match - clear the stored id
                $idInput.val(null);
                return false;
            }
        };
    }

});

// validation configuration

<|endoftext|>


<commit_before>var NotAsync = {} ;
var asyncExit = /^async[\t ]+(return|throw)/ ;
var asyncFunction = /^async[\t ]+function/ ;
var atomOrPropertyOrLabel = /^\s*[:;]/ ;
var asyncAtEndOfLine = /^async[\t ]*\n/ ;

/* Return the object holding the parser's 'State'. This is different between acorn ('this')
 * and babylon ('this.state')
 */
function state(p) {
	if (p.state && p.state.constructor.name==='State') // Probably babylon
		return p.state ;
	return p ; // Probably acorn
}

/* Create a new parser derived from the specified parser, so that in the
 * event of an error we can back out and try again */
function subParse(parser, pos, extensions) {
	var p = new parser.constructor(parser.options, parser.input.substring(pos), 0);
	if (extensions)
		for (var k in extensions)
			p[k] = extensions[k] ;

	p.inFunction = state(parser).inFunction ;
	p.inAsyncFunction = state(parser).inAsyncFunction ;
	p.inGenerator = state(parser).inGenerator ;
	p.inModule = state(parser).inModule ;
	p.nextToken();
	return p;
}

function asyncAwaitPlugin (parser,options){
	var es7check = function(){} ;

	parser.extend("initialContext",function(base){
		return function(){
			if (this.options.ecmaVersion < 7) {
				es7check = function(node) {
					parser.raise(node.start,"async/await keywords only available when ecmaVersion>=7") ;
				} ;
			}
			return base.apply(this,arguments);
		}
	}) ;

	parser.extend("parseStatement",function(base){
		return function (declaration, topLevel) {
			var st = state(this) ;
			if (st.type.label==='name') {
				if (asyncFunction.test(st.input.slice(st.start))) {
					var wasAsync = st.inAsyncFunction ;
					try {
						st.inAsyncFunction = true ;
						this.next() ;
						var r = this.parseStatement(declaration, topLevel) ;
						r.async = true ;
						return r ;
					} finally {
						st.inAsyncFunction = wasAsync ;
					}
				} else if ((typeof options==="object" && options.asyncExits) && asyncExit.test(st.input.slice(st.start))) {
					// NON-STANDARD EXTENSION iff. options.asyncExits is set, the
					// extensions 'async return <expr>?' and 'async throw <expr>?'
					// are enabled. In each case they are the standard ESTree nodes
					// with the flag 'async:true'
					this.next() ;
					var r = this.parseStatement(declaration, topLevel) ;
					r.async = true ;
					return r ;
				}
			}
			return base.apply(this,arguments);
		}
	}) ;

	parser.extend("parseExprAtom",function(base){
		return function(refShorthandDefaultPos){
			var st = state(this) ;
			var start = st.start ;
			var rhs,r = base.apply(this,arguments);
			if (r.type==='Identifier') {
				if (r.name==='async' && !asyncAtEndOfLine.test(st.input.slice(start))) {
					// Is this really an async function?
					var isAsync = st.inAsyncFunction ;
					try {
						st.inAsyncFunction = true ;
						var pp = this ;
						var inBody = false ;

						var parseHooks = {
							parseFunctionBody:function(){
								try {
									var wasInBody = inBody ;
									inBody = true ;
									return pp.parseFunctionBody.apply(this,arguments) ;
								} finally {
									inBody = wasInBody ;
								}
							},
							raise:function(){
								try {
									return pp.raise.apply(this,arguments) ;
								} catch(ex) {
									throw inBody?ex:NotAsync ;
								}
							}
						} ;

						rhs = subParse(this,st.start,parseHooks).parseExpression() ;
						if (rhs.type==='SequenceExpression')
							rhs = rhs.expressions[0] ;
						if (rhs.type==='FunctionExpression' || rhs.type==='FunctionDeclaration' || rhs.type==='ArrowFunctionExpression') {
							rhs.async = true ;
							st.pos = rhs.end ;
							this.next();
							es7check(rhs) ;
							return rhs ;
						}
					} catch (ex) {
						if (ex!==NotAsync)
							throw ex ;
					}
					finally {
						st.inAsyncFunction = isAsync ;
					}
				}
				else if (r.name==='await') {
					var n = this.startNode() ;
					if (st.inAsyncFunction) {
						rhs = this.parseExprSubscripts() ;
						n.operator = 'await' ;
						n.argument = rhs ;
						n = this.finishNodeAt(n,'AwaitExpression', rhs.end, rhs.loc) ;
						es7check(n) ;
						return n ;
					} else
						// NON-STANDARD EXTENSION iff. options.awaitAnywhere is true,
						// an 'AwaitExpression' is allowed anywhere the token 'await'
						// could not be an identifier with the name 'await'.

						// Look-ahead to see if this is really a property or label called async or await
						if (st.input.slice(r.end).match(atomOrPropertyOrLabel))
							return r ; // This is a valid property name or label

						if (typeof options==="object" && options.awaitAnywhere) {
							var start = st.start ;
							rhs = subParse(this,st.start-4).parseExprSubscripts() ;
							if (rhs.end<=start) {
								rhs = subParse(this,st.start).parseExprSubscripts() ;
								n.operator = 'await' ;
								n.argument = rhs ;
								n = this.finishNodeAt(n,'AwaitExpression', rhs.end, rhs.loc) ;
								st.pos = rhs.end ;
								this.next();
								es7check(n) ;
								return n ;
							}
						}
				}
			}
			return r ;
		}
	}) ;

	parser.extend("parsePropertyName",function(base){
		return function (prop) {
			var st = state(this) ;
			var key = base.apply(this,arguments) ;
			if (key.type === "Identifier" && key.name === "async") {
				// Look-ahead to see if this is really a property or label called async or await
				if (!st.input.slice(key.end).match(atomOrPropertyOrLabel)){
					es7check(prop) ;
					prop.async = true ;
					key = base.apply(this,arguments) ;
					if (key.type==='Identifier') {
						if (key.name==='constructor')
							this.raise(key.start,"'constructor()' cannot be be async") ;
						else if (key.name==='set')
							this.raise(key.start,"'set <member>(value)' cannot be be async") ;
					}
				}
			}
			return key;
		};
	}) ;
}

module.exports = function(acorn) {
	acorn.plugins.asyncawait = asyncAwaitPlugin ;
}
<commit_msg>Don't truncate input when sub-parsing, to keep locations correct. This (however) breaks Babylon. TBC<commit_after>var NotAsync = {} ;
var asyncExit = /^async[\t ]+(return|throw)/ ;
var asyncFunction = /^async[\t ]+function/ ;
var atomOrPropertyOrLabel = /^\s*[:;]/ ;
var asyncAtEndOfLine = /^async[\t ]*\n/ ;

/* Return the object holding the parser's 'State'. This is different between acorn ('this')
 * and babylon ('this.state')
 */
function state(p) {
	if (p.state && p.state.constructor.name==='State') // Probably babylon
		return p.state ;
	return p ; // Probably acorn
}

/* Create a new parser derived from the specified parser, so that in the
 * event of an error we can back out and try again */
function subParse(parser, pos, extensions) {
	// NB: The Babylon constructor does NOT expect 'pos' as an argument, and so
	// the input needs truncation at the start position, however at present
	// this doesn't work nicely as all the node location/start/end values
	// are therefore offset. Consequently, this plug-in is NOT currently working
	// with the (undocumented) Babylon plug-in interface.
	var p = new parser.constructor(parser.options, parser.input, pos);
	if (extensions)
		for (var k in extensions)
			p[k] = extensions[k] ;

	var src = state(parser) ;
	var dest = state(p) ;
	['inFunction','inAsyncFunction','inAsync','inGenerator','inModule'].forEach(function(k){
		if (k in src)
			dest[k] = src[k] ;
	}) ;
	p.nextToken();
	return p;
}

function asyncAwaitPlugin (parser,options){
	var es7check = function(){} ;

	parser.extend("initialContext",function(base){
		return function(){
			if (this.options.ecmaVersion < 7) {
				es7check = function(node) {
					parser.raise(node.start,"async/await keywords only available when ecmaVersion>=7") ;
				} ;
			}
			return base.apply(this,arguments);
		}
	}) ;

	parser.extend("parseStatement",function(base){
		return function (declaration, topLevel) {
			var st = state(this) ;
			if (st.type.label==='name') {
				if (asyncFunction.test(st.input.slice(st.start))) {
					var wasAsync = st.inAsyncFunction ;
					try {
						st.inAsyncFunction = true ;
						this.next() ;
						var r = this.parseStatement(declaration, topLevel) ;
						r.async = true ;
						return r ;
					} finally {
						st.inAsyncFunction = wasAsync ;
					}
				} else if ((typeof options==="object" && options.asyncExits) && asyncExit.test(st.input.slice(st.start))) {
					// NON-STANDARD EXTENSION iff. options.asyncExits is set, the
					// extensions 'async return <expr>?' and 'async throw <expr>?'
					// are enabled. In each case they are the standard ESTree nodes
					// with the flag 'async:true'
					this.next() ;
					var r = this.parseStatement(declaration, topLevel) ;
					r.async = true ;
					return r ;
				}
			}
			return base.apply(this,arguments);
		}
	}) ;

	parser.extend("parseExprAtom",function(base){
		return function(refShorthandDefaultPos){
			var st = state(this) ;
			var start = st.start ;
			var rhs,r = base.apply(this,arguments);
			if (r.type==='Identifier') {
				if (r.name==='async' && !asyncAtEndOfLine.test(st.input.slice(start))) {
					// Is this really an async function?
					var isAsync = st.inAsyncFunction ;
					try {
						st.inAsyncFunction = true ;
						var pp = this ;
						var inBody = false ;

						var parseHooks = {
							parseFunctionBody:function(){
								try {
									var wasInBody = inBody ;
									inBody = true ;
									return pp.parseFunctionBody.apply(this,arguments) ;
								} finally {
									inBody = wasInBody ;
								}
							},
							raise:function(){
								try {
									return pp.raise.apply(this,arguments) ;
								} catch(ex) {
									throw inBody?ex:NotAsync ;
								}
							}
						} ;

						start = st.start ;
						rhs = subParse(this,start,parseHooks).parseExpression() ;
						if (rhs.type==='SequenceExpression')
							rhs = rhs.expressions[0] ;
						if (rhs.type==='FunctionExpression' || rhs.type==='FunctionDeclaration' || rhs.type==='ArrowFunctionExpression') {
							rhs.async = true ;
							st.pos = rhs.end; //+start ;
							this.next();
							es7check(rhs) ;
							return rhs ;
						}
					} catch (ex) {
						if (ex!==NotAsync)
							throw ex ;
					}
					finally {
						st.inAsyncFunction = isAsync ;
					}
				}
				else if (r.name==='await') {
					var n = this.startNode() ;
					if (st.inAsyncFunction) {
						rhs = this.parseExprSubscripts() ;
						n.operator = 'await' ;
						n.argument = rhs ;
						n = this.finishNodeAt(n,'AwaitExpression', rhs.end, rhs.loc) ;
						es7check(n) ;
						return n ;
					} else
						// NON-STANDARD EXTENSION iff. options.awaitAnywhere is true,
						// an 'AwaitExpression' is allowed anywhere the token 'await'
						// could not be an identifier with the name 'await'.

						// Look-ahead to see if this is really a property or label called async or await
						if (st.input.slice(r.end).match(atomOrPropertyOrLabel))
							return r ; // This is a valid property name or label

						if (typeof options==="object" && options.awaitAnywhere) {
							start = st.start ;
							rhs = subParse(this,start-4).parseExprSubscripts() ;
							if (rhs.end<=start) {
								rhs = subParse(this,start).parseExprSubscripts() ;
								n.operator = 'await' ;
								n.argument = rhs ;
								n = this.finishNodeAt(n,'AwaitExpression', rhs.end, rhs.loc) ;
								st.pos = rhs.end;//+start ;
								this.next();
								es7check(n) ;
								return n ;
							}
						}
				}
			}
			return r ;
		}
	}) ;

	parser.extend("parsePropertyName",function(base){
		return function (prop) {
			var st = state(this) ;
			var key = base.apply(this,arguments) ;
			if (key.type === "Identifier" && key.name === "async") {
				// Look-ahead to see if this is really a property or label called async or await
				if (!st.input.slice(key.end).match(atomOrPropertyOrLabel)){
					es7check(prop) ;
					prop.async = true ;
					key = base.apply(this,arguments) ;
					if (key.type==='Identifier') {
						if (key.name==='constructor')
							this.raise(key.start,"'constructor()' cannot be be async") ;
						else if (key.name==='set')
							this.raise(key.start,"'set <member>(value)' cannot be be async") ;
					}
				}
			}
			return key;
		};
	}) ;
}

module.exports = function(acorn) {
	acorn.plugins.asyncawait = asyncAwaitPlugin ;
}
<|endoftext|>


<commit_before>import React from "react";
import { Provider } from "react-redux";
import renderer from "react-test-renderer";
import getStore from "../../store";
import { loadMediaFiles } from "../../actionCreators";

import PlaylistShade from "./PlaylistShade";

const media = {
  addEventListener: jest.fn(),
  loadFromUrl: jest.fn(),
  setVolume: jest.fn(),
  setBalance: jest.fn(),
  _analyser: null
};

describe("PlaylistShade", () => {
  let store;
  beforeEach(() => {
    store = getStore(media);
  });

  it("renders to snapshot", () => {
    store.dispatch(
      loadMediaFiles([{ url: "http://example.com", defaultName: "Some Name" }])
    );
    const tree = renderer
      .create(
        <Provider store={store}>
          <PlaylistShade />
        </Provider>
      )
      .toJSON();
    expect(tree).toMatchSnapshot();
  });
});
<commit_msg>Fix tests<commit_after>import React from "react";
import { Provider } from "react-redux";
import renderer from "react-test-renderer";
import Emitter from "../../emitter";
import getStore from "../../store";
import { loadMediaFiles } from "../../actionCreators";

import PlaylistShade from "./PlaylistShade";

const media = {
  addEventListener: jest.fn(),
  loadFromUrl: jest.fn(),
  setVolume: jest.fn(),
  setBalance: jest.fn(),
  _analyser: null
};

describe("PlaylistShade", () => {
  let store;
  beforeEach(() => {
    store = getStore(media, new Emitter());
  });

  it("renders to snapshot", () => {
    store.dispatch(
      loadMediaFiles([{ url: "http://example.com", defaultName: "Some Name" }])
    );
    const tree = renderer
      .create(
        <Provider store={store}>
          <PlaylistShade />
        </Provider>
      )
      .toJSON();
    expect(tree).toMatchSnapshot();
  });
});
<|endoftext|>


<commit_before>'use strict'
var $ = require('jquery')
var yo = require('yo-yo')
var helper = require('../../lib/helper.js')
var txExecution = require('../execution/txExecution')
var txFormat = require('../execution/txFormat')
var txHelper = require('../execution/txHelper')
var modalDialogCustom = require('../ui/modal-dialog-custom')
var executionContext = require('../../execution-context')
const copy = require('clipboard-copy')

// -------------- styling ----------------------
var csjs = require('csjs-inject')
var remix = require('ethereum-remix')
var styleGuide = remix.ui.styleGuide
var styles = styleGuide()

var css = csjs`
  .runTabView {
    padding: 2%;
    display: flex;
    flex-direction: column;
  }
  .settings {
    ${styles.displayBox}
    margin-bottom: 2%;
    padding: 10px 15px 15px 15px;
  }
  .crow {
    margin-top: .5em;
    display: flex;
  }
  .col1 {
    ${styles.titleL}
    width: 30%;
    float: left;
    align-self: center;
  }
  .col1_1 {
    ${styles.titleM}
    font-size: 12px;
    width: 25%;
    min-width: 75px;
    float: left;
    align-self: center;
  }
  .col2 {
    ${styles.inputField}
  }
  .select {
    ${styles.dropdown}
    text-align: center;
    font-weight: normal;
    min-width: 150px;
  }
  .copyaddress {
    color: ${styles.colors.blue};
    margin-left: 0.5em;
    margin-top: 0.7em;
    cursor: pointer;
  }
  .copyaddress:hover {
    color: ${styles.colors.grey};
  }
  .instanceContainer {
    ${styles.displayBox}
    display: flex;
    flex-direction: column;
    background-color: ${styles.colors.transparent};
    margin-top: 2%;
    border: none;
  }
  .pendingTxsContainer  {
    ${styles.displayBox}
    display: flex;
    flex-direction: column;
    background-color: ${styles.colors.transparent};
    margin-top: 2%;
    border: none;
    padding-bottom: 0;
  }
  .container {
    ${styles.displayBox}
    margin-top: 2%;
  }
  .contractNames {
    ${styles.dropdown}
  }
  .subcontainer {
    display: flex;
    flex-direction: row;
    align-items: baseline;
  }
  .buttons {
    display: flex;
    cursor: pointer;
    justify-content: center;
    flex-direction: column;
    text-align: center;
    font-size: 12px;
  }
  .button {
    display: flex;
    align-items: center;
    margin-top: 2%;
  }
  .atAddress {
    ${styles.button}
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    background-color: ${styles.colors.lightGreen};
    border-color: ${styles.colors.lightGreen};
  }
  .create {
    ${styles.button}
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    background-color: ${styles.colors.lightRed};
    border-color: ${styles.colors.lightRed};
  }
  .input {
    ${styles.inputField}
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    padding-left: 10px;
  }
  .noInstancesText {
    ${styles.displayBox}
    text-align: center;
    color: ${styles.colors.lightGrey};
    font-style: italic;
  }
  .pendingTxsText {
    ${styles.displayBox}
    text-align: center;
    color: ${styles.colors.lightGrey};
    font-style: italic;
  }
  .item {
    margin-right: 1em;
    display: flex;
    align-items: center;
  }
  .transact {
    color: ${styles.colors.lightRed};
    margin-right: .3em;
  }
  .payable {
    color: ${styles.colors.red};
    margin-right: .3em;
  }
  .call {
    color: ${styles.colors.lightBlue};
    margin-right: .3em;
  }
  .pendingContainer {
    display: flex;
    align-items: baseline;
  }
  .pending {
    height: 25px;
    text-align: center;
    padding-left: 10px;
    border-radius: 3px;
    margin-left: 5px;
  }
  .icon {
    font-size: 12px;
    color: ${styles.colors.orange};
    margin-left: 10%;
  }
`

module.exports = runTab

var instanceContainer = yo`<div class="${css.instanceContainer}"></div>`
var noInstancesText = yo`<div class="${css.noInstancesText}">No Contract Instances.</div>`

var pendingTxsText = yo`<div class="${css.pendingTxsText}"></div>`
var pendingTxsContainer = yo`<div class="${css.pendingTxsContainer}">${pendingTxsText}</div>`

function runTab (container, appAPI, appEvents, opts) {
  var el = yo`

    ${settings(appAPI, appEvents)}
    ${contractDropdown(appAPI, appEvents, instanceContainer)}
    ${pendingTxsContainer}
    ${instanceContainer}

  `
  container.appendChild(el)

  // PENDING transactions
  function updatePendingTxs (container, appAPI) {
    var pendingCount = Object.keys(appAPI.udapp().pendingTransactions()).length
    pendingTxsText.innerText = pendingCount + ' pending transactions'
  }

  // DROPDOWN
  var selectExEnv = el.querySelector('#selectExEnvOptions')
  selectExEnv.addEventListener('change', function (event) {
    if (!executionContext.executionContextChange(selectExEnv.options[selectExEnv.selectedIndex].value)) {
      selectExEnv.value = executionContext.getProvider()
    }
    fillAccountsList(appAPI, el)
    instanceContainer.innerHTML = '' // clear the instances list
    noInstancesText.style.display = 'block'
    instanceContainer.appendChild(noInstancesText)
  })
  selectExEnv.value = executionContext.getProvider()
  fillAccountsList(appAPI, el)
  setInterval(() => {
    updateAccountBalances(container, appAPI)
    updatePendingTxs(container, appAPI)
  }, 500)
}

function fillAccountsList (appAPI, container) {
  var $txOrigin = $(container.querySelector('#txorigin'))
  $txOrigin.empty()
  appAPI.udapp().getAccounts((err, accounts) => {
    if (err) { console.log(err) }
    if (accounts && accounts[0]) {
      for (var a in accounts) { $txOrigin.append($('<option />').val(accounts[a]).text(accounts[a])) }
      $txOrigin.val(accounts[0])
    } else {
      $txOrigin.val('unknown')
    }
  })
}

function updateAccountBalances (container, appAPI) {
  var accounts = $(container.querySelector('#txorigin')).children('option')
  accounts.each(function (index, value) {
    (function (acc) {
      appAPI.getBalance(accounts[acc].value, function (err, res) {
        if (!err) {
          accounts[acc].innerText = helper.shortenAddress(accounts[acc].value, res)
        }
      })
    })(index)
  })
}

/* ------------------------------------------------
    section CONTRACT DROPDOWN and BUTTONS
------------------------------------------------ */

function contractDropdown (appAPI, appEvents, instanceContainer) {
  instanceContainer.appendChild(noInstancesText)

  appEvents.compiler.register('compilationFinished', function (success, data, source) {
    getContractNames(success, data)
  })

  var atAddressButtonInput = yo`<input class="${css.input} ataddressinput" placeholder="Enter contract's address - i.e. 0x60606..." title="atAddress" />`
  var createButtonInput = yo`<input class="${css.input}" placeholder="" title="create" />`
  var selectContractNames = yo`<select class="${css.contractNames}" disabled></select>`
  var el = yo`

        ${selectContractNames}

At Address

          ${atAddressButtonInput}

Create

          ${createButtonInput}

  `

  function setInputParamsPlaceHolder () {
    createButtonInput.value = ''
    if (appAPI.getContracts() && selectContractNames.selectedIndex >= 0 && selectContractNames.children.length > 0) {
      var contract = appAPI.getContracts()[selectContractNames.children[selectContractNames.selectedIndex].innerHTML]
      var ctrabi = txHelper.getConstructorInterface(contract.interface)
      if (ctrabi.inputs.length) {
        createButtonInput.setAttribute('placeholder', txHelper.inputParametersDeclarationToString(ctrabi.inputs))
        createButtonInput.removeAttribute('disabled')
        return
      }
    }
    createButtonInput.setAttribute('placeholder', '')
    createButtonInput.setAttribute('disabled', true)
  }

  selectContractNames.addEventListener('change', setInputParamsPlaceHolder)

  // ADD BUTTONS AT ADDRESS AND CREATE
  function createInstance () {
    var contractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)
    var contracts = appAPI.getContracts()
    var contractName = contractNames.children[contractNames.selectedIndex].innerHTML
    var contract = appAPI.getContracts()[contractName]

    var constructor = txHelper.getConstructorInterface(contract.interface)
    var args = createButtonInput.value
    txFormat.buildData(contract, contracts, true, constructor, args, appAPI.udapp(), (error, data) => {
      if (!error) {
        appAPI.logMessage(`creation of ${contractName} pending...`)
        txExecution.createContract(data, appAPI.udapp(), (error, txResult) => {
          if (!error) {
            var isVM = executionContext.isVM()
            if (isVM) {
              var vmError = txExecution.checkVMError(txResult)
              if (vmError.error) {
                modalDialogCustom.alert(vmError.message)
                return
              }
            }
            noInstancesText.style.display = 'none'
            var address = isVM ? txResult.result.createdAddress : txResult.result.contractAddress
            instanceContainer.appendChild(appAPI.udapp().renderInstance(contract, address, selectContractNames.value))
          } else {
            modalDialogCustom.alert(error)
          }
        })
      } else {
        modalDialogCustom.alert(error)
      }
    })
  }

  function loadFromAddress (appAPI) {
    noInstancesText.style.display = 'none'
    var contractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)
    var contract = appAPI.getContracts()[contractNames.children[contractNames.selectedIndex].innerHTML]
    var address = atAddressButtonInput.value
    instanceContainer.appendChild(appAPI.udapp().renderInstance(contract, address, selectContractNames.value))
  }

  // GET NAMES OF ALL THE CONTRACTS
  function getContractNames (success, data) {
    var contractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)
    contractNames.innerHTML = ''
    if (success) {
      selectContractNames.removeAttribute('disabled')
      for (var name in data.contracts) {
        contractNames.appendChild(yo`<option>${name}</option>`)
      }
    } else {
      selectContractNames.setAttribute('disabled', true)
    }
    setInputParamsPlaceHolder()
  }

  return el
}

/* ------------------------------------------------
    section SETTINGS: Environment, Account, Gas, Value
------------------------------------------------ */
function settings (appAPI, appEvents) {
  // COPY ADDRESS
  function copyAddress () {
    copy(document.querySelector('#runTabView #txorigin').value)
  }

  // SETTINGS HTML
  var el = yo`

          Environment

        <select id="selectExEnvOptions" class="${css.select}">
          <option id="vm-mode"
            title="Execution environment does not connect to any node, everything is local and in memory only."
            value="vm"
            checked name="executionContext">
            JavaScript VM
          </option>
          <option id="injected-mode"
            title="Execution environment has been provided by Mist or similar provider."
            value="injected"
            checked name="executionContext">
            Injected Web3
          </option>
          <option id="web3-mode"
            title="Execution environment connects to node at localhost (or via IPC if available), transactions will be sent to the network and can cause loss of money or worse!
            If this page is served via https and you access your node via http, it might not work. In this case, try cloning the repository and serving it via http."
            value="web3"
            name="executionContext">
            Web3 Provider
          </option>
        </select>

Account

        <select name="txorigin" class="${css.select}" id="txorigin"></select>

Gas limit

        <input type="number" class="${css.col2}" id="gasLimit" value="3000000">

Gas Price

        <input type="number" class="${css.col2}" id="gasPrice" value="0">

Value

        <input type="text" class="${css.col2}" id="value" value="0" title="(e.g. .7 ether ...)">

  `

  // EVENTS
  appEvents.udapp.register('transactionExecuted', (error, to, data, lookupOnly, txResult) => {
    if (error) return
    if (!lookupOnly) el.querySelector('#value').value = '0'
  })

  return el
}
<commit_msg>improve logging<commit_after>'use strict'
var $ = require('jquery')
var yo = require('yo-yo')
var helper = require('../../lib/helper.js')
var txExecution = require('../execution/txExecution')
var txFormat = require('../execution/txFormat')
var txHelper = require('../execution/txHelper')
var modalDialogCustom = require('../ui/modal-dialog-custom')
var executionContext = require('../../execution-context')
const copy = require('clipboard-copy')

// -------------- styling ----------------------
var csjs = require('csjs-inject')
var remix = require('ethereum-remix')
var styleGuide = remix.ui.styleGuide
var styles = styleGuide()

var css = csjs`
  .runTabView {
    padding: 2%;
    display: flex;
    flex-direction: column;
  }
  .settings {
    ${styles.displayBox}
    margin-bottom: 2%;
    padding: 10px 15px 15px 15px;
  }
  .crow {
    margin-top: .5em;
    display: flex;
  }
  .col1 {
    ${styles.titleL}
    width: 30%;
    float: left;
    align-self: center;
  }
  .col1_1 {
    ${styles.titleM}
    font-size: 12px;
    width: 25%;
    min-width: 75px;
    float: left;
    align-self: center;
  }
  .col2 {
    ${styles.inputField}
  }
  .select {
    ${styles.dropdown}
    text-align: center;
    font-weight: normal;
    min-width: 150px;
  }
  .copyaddress {
    color: ${styles.colors.blue};
    margin-left: 0.5em;
    margin-top: 0.7em;
    cursor: pointer;
  }
  .copyaddress:hover {
    color: ${styles.colors.grey};
  }
  .instanceContainer {
    ${styles.displayBox}
    display: flex;
    flex-direction: column;
    background-color: ${styles.colors.transparent};
    margin-top: 2%;
    border: none;
  }
  .pendingTxsContainer  {
    ${styles.displayBox}
    display: flex;
    flex-direction: column;
    background-color: ${styles.colors.transparent};
    margin-top: 2%;
    border: none;
    padding-bottom: 0;
  }
  .container {
    ${styles.displayBox}
    margin-top: 2%;
  }
  .contractNames {
    ${styles.dropdown}
  }
  .subcontainer {
    display: flex;
    flex-direction: row;
    align-items: baseline;
  }
  .buttons {
    display: flex;
    cursor: pointer;
    justify-content: center;
    flex-direction: column;
    text-align: center;
    font-size: 12px;
  }
  .button {
    display: flex;
    align-items: center;
    margin-top: 2%;
  }
  .atAddress {
    ${styles.button}
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    background-color: ${styles.colors.lightGreen};
    border-color: ${styles.colors.lightGreen};
  }
  .create {
    ${styles.button}
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    background-color: ${styles.colors.lightRed};
    border-color: ${styles.colors.lightRed};
  }
  .input {
    ${styles.inputField}
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    padding-left: 10px;
  }
  .noInstancesText {
    ${styles.displayBox}
    text-align: center;
    color: ${styles.colors.lightGrey};
    font-style: italic;
  }
  .pendingTxsText {
    ${styles.displayBox}
    text-align: center;
    color: ${styles.colors.lightGrey};
    font-style: italic;
  }
  .item {
    margin-right: 1em;
    display: flex;
    align-items: center;
  }
  .transact {
    color: ${styles.colors.lightRed};
    margin-right: .3em;
  }
  .payable {
    color: ${styles.colors.red};
    margin-right: .3em;
  }
  .call {
    color: ${styles.colors.lightBlue};
    margin-right: .3em;
  }
  .pendingContainer {
    display: flex;
    align-items: baseline;
  }
  .pending {
    height: 25px;
    text-align: center;
    padding-left: 10px;
    border-radius: 3px;
    margin-left: 5px;
  }
  .icon {
    font-size: 12px;
    color: ${styles.colors.orange};
    margin-left: 10%;
  }
`

module.exports = runTab

var instanceContainer = yo`<div class="${css.instanceContainer}"></div>`
var noInstancesText = yo`<div class="${css.noInstancesText}">No Contract Instances.</div>`

var pendingTxsText = yo`<div class="${css.pendingTxsText}"></div>`
var pendingTxsContainer = yo`<div class="${css.pendingTxsContainer}">${pendingTxsText}</div>`

function runTab (container, appAPI, appEvents, opts) {
  var el = yo`

    ${settings(appAPI, appEvents)}
    ${contractDropdown(appAPI, appEvents, instanceContainer)}
    ${pendingTxsContainer}
    ${instanceContainer}

  `
  container.appendChild(el)

  // PENDING transactions
  function updatePendingTxs (container, appAPI) {
    var pendingCount = Object.keys(appAPI.udapp().pendingTransactions()).length
    pendingTxsText.innerText = pendingCount + ' pending transactions'
  }

  // DROPDOWN
  var selectExEnv = el.querySelector('#selectExEnvOptions')
  selectExEnv.addEventListener('change', function (event) {
    if (!executionContext.executionContextChange(selectExEnv.options[selectExEnv.selectedIndex].value)) {
      selectExEnv.value = executionContext.getProvider()
    }
    fillAccountsList(appAPI, el)
    instanceContainer.innerHTML = '' // clear the instances list
    noInstancesText.style.display = 'block'
    instanceContainer.appendChild(noInstancesText)
  })
  selectExEnv.value = executionContext.getProvider()
  fillAccountsList(appAPI, el)
  setInterval(() => {
    updateAccountBalances(container, appAPI)
    updatePendingTxs(container, appAPI)
  }, 500)
}

function fillAccountsList (appAPI, container) {
  var $txOrigin = $(container.querySelector('#txorigin'))
  $txOrigin.empty()
  appAPI.udapp().getAccounts((err, accounts) => {
    if (err) { console.log(err) }
    if (accounts && accounts[0]) {
      for (var a in accounts) { $txOrigin.append($('<option />').val(accounts[a]).text(accounts[a])) }
      $txOrigin.val(accounts[0])
    } else {
      $txOrigin.val('unknown')
    }
  })
}

function updateAccountBalances (container, appAPI) {
  var accounts = $(container.querySelector('#txorigin')).children('option')
  accounts.each(function (index, value) {
    (function (acc) {
      appAPI.getBalance(accounts[acc].value, function (err, res) {
        if (!err) {
          accounts[acc].innerText = helper.shortenAddress(accounts[acc].value, res)
        }
      })
    })(index)
  })
}

/* ------------------------------------------------
    section CONTRACT DROPDOWN and BUTTONS
------------------------------------------------ */

function contractDropdown (appAPI, appEvents, instanceContainer) {
  instanceContainer.appendChild(noInstancesText)

  appEvents.compiler.register('compilationFinished', function (success, data, source) {
    getContractNames(success, data)
  })

  var atAddressButtonInput = yo`<input class="${css.input} ataddressinput" placeholder="Enter contract's address - i.e. 0x60606..." title="atAddress" />`
  var createButtonInput = yo`<input class="${css.input}" placeholder="" title="create" />`
  var selectContractNames = yo`<select class="${css.contractNames}" disabled></select>`
  var el = yo`

        ${selectContractNames}

At Address

          ${atAddressButtonInput}

Create

          ${createButtonInput}

  `

  function setInputParamsPlaceHolder () {
    createButtonInput.value = ''
    if (appAPI.getContracts() && selectContractNames.selectedIndex >= 0 && selectContractNames.children.length > 0) {
      var contract = appAPI.getContracts()[selectContractNames.children[selectContractNames.selectedIndex].innerHTML]
      var ctrabi = txHelper.getConstructorInterface(contract.interface)
      if (ctrabi.inputs.length) {
        createButtonInput.setAttribute('placeholder', txHelper.inputParametersDeclarationToString(ctrabi.inputs))
        createButtonInput.removeAttribute('disabled')
        return
      }
    }
    createButtonInput.setAttribute('placeholder', '')
    createButtonInput.setAttribute('disabled', true)
  }

  selectContractNames.addEventListener('change', setInputParamsPlaceHolder)

  // ADD BUTTONS AT ADDRESS AND CREATE
  function createInstance () {
    var contractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)
    var contracts = appAPI.getContracts()
    var contractName = contractNames.children[contractNames.selectedIndex].innerHTML
    var contract = appAPI.getContracts()[contractName]

    var constructor = txHelper.getConstructorInterface(contract.interface)
    var args = createButtonInput.value
    txFormat.buildData(contract, contracts, true, constructor, args, appAPI.udapp(), (error, data) => {
      if (!error) {
        appAPI.logMessage(`creation of ${contractName} pending...`)
        txExecution.createContract(data, appAPI.udapp(), (error, txResult) => {
          if (!error) {
            var isVM = executionContext.isVM()
            if (isVM) {
              var vmError = txExecution.checkVMError(txResult)
              if (vmError.error) {
                modalDialogCustom.alert(vmError.message)
                return
              }
            }
            noInstancesText.style.display = 'none'
            var address = isVM ? txResult.result.createdAddress : txResult.result.contractAddress
            instanceContainer.appendChild(appAPI.udapp().renderInstance(contract, address, selectContractNames.value))
          } else {
            appAPI.logMessage(`creation of ${contractName} errored: ` + error)
          }
        })
      } else {
        appAPI.logMessage(`creation of ${contractName} errored: ` + error)
      }
    })
  }

  function loadFromAddress (appAPI) {
    noInstancesText.style.display = 'none'
    var contractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)
    var contract = appAPI.getContracts()[contractNames.children[contractNames.selectedIndex].innerHTML]
    var address = atAddressButtonInput.value
    instanceContainer.appendChild(appAPI.udapp().renderInstance(contract, address, selectContractNames.value))
  }

  // GET NAMES OF ALL THE CONTRACTS
  function getContractNames (success, data) {
    var contractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)
    contractNames.innerHTML = ''
    if (success) {
      selectContractNames.removeAttribute('disabled')
      for (var name in data.contracts) {
        contractNames.appendChild(yo`<option>${name}</option>`)
      }
    } else {
      selectContractNames.setAttribute('disabled', true)
    }
    setInputParamsPlaceHolder()
  }

  return el
}

/* ------------------------------------------------
    section SETTINGS: Environment, Account, Gas, Value
------------------------------------------------ */
function settings (appAPI, appEvents) {
  // COPY ADDRESS
  function copyAddress () {
    copy(document.querySelector('#runTabView #txorigin').value)
  }

  // SETTINGS HTML
  var el = yo`

          Environment

        <select id="selectExEnvOptions" class="${css.select}">
          <option id="vm-mode"
            title="Execution environment does not connect to any node, everything is local and in memory only."
            value="vm"
            checked name="executionContext">
            JavaScript VM
          </option>
          <option id="injected-mode"
            title="Execution environment has been provided by Mist or similar provider."
            value="injected"
            checked name="executionContext">
            Injected Web3
          </option>
          <option id="web3-mode"
            title="Execution environment connects to node at localhost (or via IPC if available), transactions will be sent to the network and can cause loss of money or worse!
            If this page is served via https and you access your node via http, it might not work. In this case, try cloning the repository and serving it via http."
            value="web3"
            name="executionContext">
            Web3 Provider
          </option>
        </select>

Account

        <select name="txorigin" class="${css.select}" id="txorigin"></select>

Gas limit

        <input type="number" class="${css.col2}" id="gasLimit" value="3000000">

Gas Price

        <input type="number" class="${css.col2}" id="gasPrice" value="0">

Value

        <input type="text" class="${css.col2}" id="value" value="0" title="(e.g. .7 ether ...)">

  `

  // EVENTS
  appEvents.udapp.register('transactionExecuted', (error, to, data, lookupOnly, txResult) => {
    if (error) return
    if (!lookupOnly) el.querySelector('#value').value = '0'
  })

  return el
}
<|endoftext|>


<commit_before>console.log('Load background for mastoandon');

function getBrowser() {
  try {
    return browser;
  } catch (err) {
    return chrome;
  }
}

function tabsQuery(query) {
  return new Promise(function (resolv, reject) {
    try {
      let querying = getBrowser().tabs.query(query);
      if (!querying) {
        getBrowser().tabs.query(query, resolv);
        return;
      }
      querying.then(resolv).catch(reject);
    } catch (err) {
      try {
        getBrowser().tabs.query(query, resolv);
      } catch (err) {
        reject('browser.tabs.query unsupported!');
      }
    }
  });
}

function tabsExecuteScript(tabId, code) {
  return new Promise(function (resolv, reject) {
    try {
      let executing = getBrowser().tabs.executeScript(tabId, code);
      if (!executing) {
        getBrowser().tabs.executeScript(tabId, code, resolv);
        return;
      }
      executing.then(resolv).catch(reject);
    } catch (err) {
      try {
        getBrowser().tabs.executeScript(tabId, code, resolv);
      } catch (err) {
        reject('browser.tabs.executeScript unsupported!');
      }
    }
  });
}

function pageActionGetTitle(query) {
  return new Promise(function (resolv, reject) {
    try {
      let executing = getBrowser().pageAction.getTitle(query);
      if (!executing) {
        getBrowser().pageAction.getTitle(query, resolv);
        return;
      }
      executing.then(resolv).catch(reject);
    } catch (err) {
      try {
        getBrowser().pageAction.getTitle(query, resolv);
      } catch (err) {
        reject('browser.pageAction.getTitle unsupported!');
      }
    }
  });
}

function storageLocalGet(query) {
  return new Promise(function (resolv, reject) {
    try {
      let executing = getBrowser().storage.local.get(query);
      if (!executing) {
        getBrowser().storage.local.get(query, resolv);
        return;
      }
      executing.then(resolv).catch(reject);
    } catch (err) {
      try {
        getBrowser().storage.local.get(query, resolv);
      } catch (err) {
        reject('browser.storage.local.get unsupported!');
      }
    }
  });
}

function storageLocalSet(query) {
  return new Promise(function (resolv, reject) {
    try {
      let executing = getBrowser().storage.local.set(query);
      if (!executing) {
        getBrowser().storage.local.set(query, resolv);
        return;
      }
      executing.then(resolv).catch(reject);
    } catch (err) {
      try {
        getBrowser().storage.local.set(query, resolv);
      } catch (err) {
        reject('browser.storage.local.set unsupported!');
      }
    }
  });
}

function pageActionHandler(event) {
  chrome.tabs.create({
    "url": "/view/config.html"
  });
}

if (chrome.pageAction && chrome.pageAction.onClicked) {
  chrome.pageAction.onClicked.addListener(pageActionHandler);
} else {
  console.warn('chrome.pageAction.onClicked unsupported!');
}
if (chrome.browserAction && chrome.browserAction.onClicked) {
  chrome.browserAction.onClicked.addListener(pageActionHandler);
} else {
  console.warn('chrome.browserAction.onClicked unsupported!');
}

let config = getFromStorage();

function returnResponse(message, sender, sendResponse) {
  // console.log(JSON.stringify(message, null, 1));
  if (!message.popup) {
    return;
  }
  syncStorage(message);
  let responseMessage = 'Connecting...';
  sendResponse({
    message: responseMessage,
    config: config
  });
}

chrome.runtime.onMessage.addListener(returnResponse);

async function syncStorage(message) {
  if (message.config) {
    await setIntoStorage(message.config);
  }
  config = await getFromStorage();
}

async function getFromStorage() {
  try {
    await storageLocalGet('mstdn');
  } catch (err) {
    await storageLocalSet({
      'mstdn': {}
    });
  }
  let _results = await storageLocalGet('mstdn');
  if (_results.mstdn) {
    _results = _results.mstdn;
  }
  return _results;
}

async function setIntoStorage(data) {
  await storageLocalSet({
    'mstdn': data
  });
}

function initializePageAction(tab) {
  if (chrome.pageAction && chrome.pageAction.setIcon && chrome.pageAction.setTitle) {
    chrome.pageAction.setIcon({
      tabId: tab.id,
      path: "icons/mastoandon-32.png"
    });
    chrome.pageAction.setTitle({
      tabId: tab.id,
      title: getBrowser().i18n.getMessage('extensionName')
    });
  } else {
    console.warn('chrome.pageAction.setIcon unsupported!')
  }
  if (chrome.pageAction) {
    chrome.pageAction.show(tab.id);
  }
}

function initializePageActions() {
  tabsQuery({}).then((tabs) => {
    console.log('# of tabs ' + tabs.length);
    for (let tab of tabs) {
      initializePageAction(tab);
    }
  }).catch(console.warn);
}

initializePageActions();
chrome.tabs.onUpdated.addListener((id, changeInfo, tab) => {
  console.log('onUpdated ' + id);
  initializePageAction(tab);
});

function initialize() {}

initialize();<commit_msg>Modify sync of local storage.<commit_after>console.log('Load background for mastoandon');

function getBrowser() {
  try {
    return browser;
  } catch (err) {
    return chrome;
  }
}

function tabsQuery(query) {
  return new Promise(function (resolv, reject) {
    try {
      let querying = getBrowser().tabs.query(query);
      if (!querying) {
        getBrowser().tabs.query(query, resolv);
        return;
      }
      querying.then(resolv).catch(reject);
    } catch (err) {
      try {
        getBrowser().tabs.query(query, resolv);
      } catch (err) {
        reject('browser.tabs.query unsupported!');
      }
    }
  });
}

function tabsExecuteScript(tabId, code) {
  return new Promise(function (resolv, reject) {
    try {
      let executing = getBrowser().tabs.executeScript(tabId, code);
      if (!executing) {
        getBrowser().tabs.executeScript(tabId, code, resolv);
        return;
      }
      executing.then(resolv).catch(reject);
    } catch (err) {
      try {
        getBrowser().tabs.executeScript(tabId, code, resolv);
      } catch (err) {
        reject('browser.tabs.executeScript unsupported!');
      }
    }
  });
}

function pageActionGetTitle(query) {
  return new Promise(function (resolv, reject) {
    try {
      let executing = getBrowser().pageAction.getTitle(query);
      if (!executing) {
        getBrowser().pageAction.getTitle(query, resolv);
        return;
      }
      executing.then(resolv).catch(reject);
    } catch (err) {
      try {
        getBrowser().pageAction.getTitle(query, resolv);
      } catch (err) {
        reject('browser.pageAction.getTitle unsupported!');
      }
    }
  });
}

function storageLocalGet(query) {
  return new Promise(function (resolv, reject) {
    try {
      let executing = getBrowser().storage.local.get(query);
      if (!executing) {
        getBrowser().storage.local.get(query, resolv);
        return;
      }
      executing.then(resolv).catch(reject);
    } catch (err) {
      try {
        getBrowser().storage.local.get(query, resolv);
      } catch (err) {
        reject('browser.storage.local.get unsupported!');
      }
    }
  });
}

function storageLocalSet(query) {
  return new Promise(function (resolv, reject) {
    try {
      let executing = getBrowser().storage.local.set(query);
      if (!executing) {
        getBrowser().storage.local.set(query, resolv);
        return;
      }
      executing.then(resolv).catch(reject);
    } catch (err) {
      try {
        getBrowser().storage.local.set(query, resolv);
      } catch (err) {
        reject('browser.storage.local.set unsupported!');
      }
    }
  });
}

function pageActionHandler(event) {
  chrome.tabs.create({
    "url": "/view/config.html"
  });
}

if (chrome.pageAction && chrome.pageAction.onClicked) {
  chrome.pageAction.onClicked.addListener(pageActionHandler);
} else {
  console.warn('chrome.pageAction.onClicked unsupported!');
}
if (chrome.browserAction && chrome.browserAction.onClicked) {
  chrome.browserAction.onClicked.addListener(pageActionHandler);
} else {
  console.warn('chrome.browserAction.onClicked unsupported!');
}

let config = {};

function returnResponse(message, sender, sendResponse) {
  // console.log(JSON.stringify(message, null, 1));
  if (!message.popup) {
    return;
  }
  syncStorage(message);
  let responseMessage = 'Sync storage complete.';
  sendResponse({
    message: responseMessage,
    config: config
  });
}

chrome.runtime.onMessage.addListener(returnResponse);

async function syncStorage(message) {
  if (message && message.config) {
    message.config.status = true;
    await setIntoStorage(message.config);
  }
  config = await getFromStorage();
  console.log('Sync storage complete: ' + JSON.stringify(config, null, 1));
  if (!config.status) {
    setTimeout(syncStorage, 3000);
  }
}

syncStorage();

async function getFromStorage() {
  try {
    await storageLocalGet('mstdn');
  } catch (err) {
    await storageLocalSet({
      'mstdn': {
        'status': true
      }
    });
  }
  let _results = await storageLocalGet('mstdn');
  if (_results.mstdn) {
    _results = _results.mstdn;
  }
  return _results;
}

async function setIntoStorage(data) {
  await storageLocalSet({
    'mstdn': data
  });
}

function initializePageAction(tab) {
  if (chrome.pageAction && chrome.pageAction.setIcon && chrome.pageAction.setTitle) {
    chrome.pageAction.setIcon({
      tabId: tab.id,
      path: "icons/mastoandon-32.png"
    });
    chrome.pageAction.setTitle({
      tabId: tab.id,
      title: getBrowser().i18n.getMessage('extensionName')
    });
  } else {
    console.warn('chrome.pageAction.setIcon unsupported!')
  }
  if (chrome.pageAction) {
    chrome.pageAction.show(tab.id);
  }
}

function initializePageActions() {
  tabsQuery({}).then((tabs) => {
    console.log('# of tabs ' + tabs.length);
    for (let tab of tabs) {
      initializePageAction(tab);
    }
  }).catch(console.warn);
}

initializePageActions();
chrome.tabs.onUpdated.addListener((id, changeInfo, tab) => {
  console.log('onUpdated ' + id);
  initializePageAction(tab);
});

function initialize() {}

initialize();<|endoftext|>


<commit_before>define('Sloth', function(){

	//some private vars
	var slice = Array.prototype.slice,
		win = window,
		scr = win.screen,
		undef,
		delegate = win.setTimout,
		branches = [],
		Branch = function(element, threshold, callback){
			this.element = element;
			this.threshold = threshold;
			this.callback = function(){
				callback(element);
			};
		},
		execute = function(event){
			var i = branches.length-1,
				branch;
			console.time('call')
			while(branch = branches[i--]){
				if(branch.isVisible()) {
					console.log(branch);
					delegate(branch.callback,0);
					branches.splice(i, 1);
				}
			}
			console.timeEnd('call')
		};

	Branch.prototype.isVisible = function(){
		return (win.scrollY + scr.availHeight >= this.element.offsetTop - this.threshold);
	};

	var setup = function(){
		win.addEventListener('scroll', execute);

		if(win.scrollY == 0 ) execute();
		setup = undef;
	};

	//return Sloth function
	return function(params){
		if(params) {
			var elements = params.on,
				threshold = params.threshold !== undef ? params.threshold : 100,
				callback = params.callback;

			if(!elements) throw 'No elements passed';
			if(!callback) throw 'No callback passed';

			if(elements instanceof NodeList){
				var i = elements.length;

				while(i--) {
					branches.push(new Branch(elements[i], threshold, callback))
				}
			}else {
				branches.push(new Branch(elements, threshold, callback))
			}

			setup && setup();
		} else{
			throw 'Gimme some data';
		}

	}
});

//Sloth({
// 	on: [], required
//  threshold: 100, default: 100
//  callback: function(){}, required
//
// })<commit_msg>Cleaning up, support for adding more callbacks later on, using arrays<commit_after>define('Sloth', function(){
	//some private vars
	var slice = Array.prototype.slice,
		win = window,
		wTop,
		wBottom,
		undef,
		delegate = win.setTimeout,
		branches = [],
		Branch = function(element, threshold, callback){
			this.element = element;
			this.threshold = threshold;
			this.callback = function(){
				callback(element);
			};
		},
		execute = function(){
			var i = branches.length,
				branch;

			if(!i) {
				win.removeEventListener('scroll', execute);
			} else {
				wTop = win.scrollY;
				wBottom = wTop + win.innerHeight;

				while( i-- ){
					branch = branches[i];

					if (branch.isVisible()) {
						delegate( branch.callback, 0 );
						branches.splice(i, 1);
					}
				}

			}
		};

	Branch.prototype.isVisible = function(){
		var elem =  this.element,
			threshold = this.threshold,
			top = elem.offsetTop - threshold,
			bottom = top + elem.offsetHeight + threshold;

		return wBottom >= top && wTop <= bottom;
	};

	var setup = function(){
		execute();
		branches.length && win.addEventListener('scroll', execute);
	};

	//return Sloth function
	return function(params){
		if(params) {
			var elements = params.on,
				threshold = params.threshold !== undef ? params.threshold : 100,
				callback = params.callback,
				i;

			if(!elements) throw 'No elements passed';
			if(!callback) throw 'No callback passed';

			if(elements instanceof NodeList){
				elements = slice.call(elements);
				i = elements.length;

				while(i--) branches.push(new Branch(elements[i], threshold, callback));
			}else {
				branches.push(new Branch(elements, threshold, callback))
			}

			setup();
		} else{
			throw 'Gimme some data';
		}
	}
});<|endoftext|>