<commit_before>window.charts = window.charts || {};

charts.graphUrl; // /v1/users/... without query params
charts.dataPoints = [];

var getEventsFor = function (type, typeId, objectTags, actionTags, operation, period, shareToken, readToken) {
    return $.ajax({
        url: "/v1/" + type + "/" + typeId + "/events/" + objectTags + "/" + actionTags + "/" + operation + "/" + period + "/" + "type/json",
        data: {
            shareToken: shareToken,
            readToken: readToken
        },
        headers: {
            "Accept": "application/json",
            "Authorization": $.cookie("_eun")
        }
    });
};

var plotChart = function (events) {
    if (renderType === "barchart") {
        if (events === null || events.length == 0) {
            $(".no-data").show();
        } else {
            charts.plotBarChart("#chart", events, null, null);
            $('.detailsSection').show();
            $('.share-button-container').show();
        }
    }
};

charts.addComment = function () {
    var commentText = $("#commentText").val();

    var comment = {
        text: commentText,
        user: username,
        avatarUrl: avatarUrl
    };
    var graph = {
        graphUrl: charts.graphUrl,
        dataPointDate: charts.selectedDate,
        username: graphOwner,
        objectTags: objectTags,
        actionTags: actionTags,
        operation: operation,
        period: period,
        renderType: renderType,
        comment: comment
    };

    //disable further commenting until current one completes
    $('#commentAddButton').attr('disabled','disabled');
    $('#addText').hide();
    $('.sending_comment_loader').show();

    $.ajax({
        url: "/v1/comments",
        method: "POST",
        data: graph,
        headers: {
            "Accept": "application/json",
            "Authorization": $.cookie("_eun")
        }
    }).done(function (data) {
        //enable the add button
        $('#commentAddButton').removeAttr('disabled');
        $('#addText').show();
        $('.sending_comment_loader').hide();

        var displayedComment = {text: commentText, avatarUrl: graphOwnerAvatarUrl};
        var selectedDataPoint = _.find(charts.dataPoints, function (dataPoint) {
            return dataPoint.dataPointDate === charts.selectedDate;
        });
        if (_.isEmpty(selectedDataPoint)) {
            var newDataPoint = {
                dataPointDate: charts.selectedDate,
                avatars: [graphOwnerAvatarUrl],
                comments: [displayedComment]
            };
            charts.dataPoints.push(newDataPoint);
        } else {
            selectedDataPoint.comments.push(displayedComment);
        }
        $(".commentList").append("

" +
            "

" + comment.text + "
" +
            "

");
        $("#commentText").val("");
    });
};

$("#addCommentInput").keyup(function (e) {
    if (e.keyCode == 13) {
        charts.addComment();
    }
});

var handleAddComment = function () {
    if (isUserLoggedIn) {
        $("#addCommentInput").show();
    }
    else {
        window.localStorage.selectedDate = charts.selectedDate;
        $("#loginModal").modal({show: true});
    }
};

var handleShareGraph = function () {
    var unregisteredUserOnStreamsPage = function () {
        return !isUserLoggedIn && (window.location.pathname.search("streams") !== -1);
    };

    if (isUserLoggedIn) {
        $.ajax({
            url: "/v1/graph/share?graphUrl=" + window.location.pathname,
            success: function (data) {
                $("#shareModal").modal({show: true});
                $("#loadingDiv").hide();
                var link = window.location.origin + data.graphShareUrl;
                var graphShareLink = " "+link+" ";
                $("#graphShareHyperLink").html(graphShareLink);
                $("#graphShareLink").html(link);
                $("#shareModal").modal({show: true});
            },
            error: function () {
                alert("some problem. Please try again later.");
            }
        });
    } else if (unregisteredUserOnStreamsPage()) {
        $("#loginModal").modal({show: true});
    } else {
        $.ajax({
            url: "/v1/graph/share?graphUrl=" + window.location.pathname,
            success: function (data) {
                $("#shareModal").modal({show: true});
                $("#loadingDiv").hide();
                var link = window.location.origin + data.graphShareUrl;
                var graphShareLink = ""+link+"";
                $("#graphShareHyperLink").html(graphShareLink);
                $("#graphShareLink").html(link);
            },
            error: function () {
                alert("some problem. Please try again later.");
            }
        });
    }
};

var showChartTitle = function () {
    $("#chartTitle").html(chartTitle);
    if (isUserLoggedIn) {
        $("#avatar").html("").addClass('avatar');
    }
    if (isUserLoggedIn || (!isUserLoggedIn && !(_.isEmpty(shareToken)))) {
        $.when(getEventsFor("users", graphOwner, objectTags, actionTags, operation, period, shareToken, readToken))
            .done(plotChart)
            .fail();
    } else {
        $.when(getEventsFor("streams", streamId, objectTags, actionTags, operation, period, shareToken, readToken))
            .done(plotChart)
            .fail();
    }
};

var submitShare = function () {
    var emailId = $("#emailId").val();
    var graphShareUrl = $("#graphShareLink").html();

    $.ajax({
        url: "/v1/share_graph",
        method: "POST",
        data: { graphShareUrl: graphShareUrl, toEmailId: emailId },
        success: function () {
            $(".shareEmailNoticeMessage").html("Graph link emailed successfully");
        },
        error: function () {
            alert("some problem. Please try again later.");
        }
    });
};

charts.showComments = function () {
    var commentsDiv = $(".commentList");
    commentsDiv.empty();

    charts.dataPoints
        .filter(function (dataPoint) {
            return dataPoint.dataPointDate === charts.selectedDate;
        })
        .forEach(function (dataPoint) {
            dataPoint.comments.forEach(function (comment) {
                commentsDiv.append("

" +
                    "
" + comment.text + "

");
            });
        });
};

var displayCommentsSummary = function () {
    for (var i = 6; i >= 0; i--) {
        var currentDataPointDate = moment.utc().subtract(i, 'days').format("YYYY-MM-DD"); // "2014-11-14"
        var currentDataPoint = _.findWhere(charts.dataPoints, {"dataPointDate": currentDataPointDate});
        if (!_.isEmpty(currentDataPoint)) {
            var latest3Avatars = currentDataPoint.avatars.slice(0, 3);
            latest3Avatars.forEach(function (avatarUrl, j) {
                $("#group" + i + "-avatar" + j).css({'background-image': 'url(' + avatarUrl + ')'});
            });
            if (currentDataPoint.comments.length > 3) {
                $("#group" + i + "-commentCount").addClass("count").html(currentDataPoint.comments.length);
            }
        }
    }
};

$(document).ready(function () {
    showChartTitle();
    $.ajax({
        url: "/v1/comments",
        method: "GET",
        data: {
            username: graphOwner,
            objectTags: objectTags,
            actionTags: actionTags,
            operation: operation,
            period: period,
            renderType: renderType
        },
        headers: {
            "Accept": "application/json",
            "Authorization": $.cookie("_eun")
        }
    }).done(function (comments) {
        charts.dataPoints = comments;
        displayCommentsSummary();
    });
    $("#shareSubmit").click(submitShare);

    var cw = $('.avatar_group').width();
    var ch = $(window).width() * (cw / 100);
    $('.avatar_group').css({'height': ch+'px'});

    setTimeout(function(){
        charts.showComments();
        if(isUserLoggedIn){
        if(window.localStorage.selectedDate) {
            delete window.localStorage.selectedDate;
        }
    }
    }, 3000)
});
<commit_msg>dont allow blank commenting<commit_after>window.charts = window.charts || {};

charts.graphUrl; // /v1/users/... without query params
charts.dataPoints = [];

var getEventsFor = function (type, typeId, objectTags, actionTags, operation, period, shareToken, readToken) {
    return $.ajax({
        url: "/v1/" + type + "/" + typeId + "/events/" + objectTags + "/" + actionTags + "/" + operation + "/" + period + "/" + "type/json",
        data: {
            shareToken: shareToken,
            readToken: readToken
        },
        headers: {
            "Accept": "application/json",
            "Authorization": $.cookie("_eun")
        }
    });
};

var plotChart = function (events) {
    if (renderType === "barchart") {
        if (events === null || events.length == 0) {
            $(".no-data").show();
        } else {
            charts.plotBarChart("#chart", events, null, null);
            $('.detailsSection').show();
            $('.share-button-container').show();
        }
    }
};

charts.addComment = function () {
    var commentText = $("#commentText").val();

    if("" == commentText.trim()) return;

    var comment = {
        text: commentText,
        user: username,
        avatarUrl: avatarUrl
    };
    var graph = {
        graphUrl: charts.graphUrl,
        dataPointDate: charts.selectedDate,
        username: graphOwner,
        objectTags: objectTags,
        actionTags: actionTags,
        operation: operation,
        period: period,
        renderType: renderType,
        comment: comment
    };

    //disable further commenting until current one completes
    $('#commentAddButton').attr('disabled','disabled');
    $('#addText').hide();
    $('.sending_comment_loader').show();

    $.ajax({
        url: "/v1/comments",
        method: "POST",
        data: graph,
        headers: {
            "Accept": "application/json",
            "Authorization": $.cookie("_eun")
        }
    }).done(function (data) {
        //enable the add button
        $('#commentAddButton').removeAttr('disabled');
        $('#addText').show();
        $('.sending_comment_loader').hide();

        var displayedComment = {text: commentText, avatarUrl: graphOwnerAvatarUrl};
        var selectedDataPoint = _.find(charts.dataPoints, function (dataPoint) {
            return dataPoint.dataPointDate === charts.selectedDate;
        });
        if (_.isEmpty(selectedDataPoint)) {
            var newDataPoint = {
                dataPointDate: charts.selectedDate,
                avatars: [graphOwnerAvatarUrl],
                comments: [displayedComment]
            };
            charts.dataPoints.push(newDataPoint);
        } else {
            selectedDataPoint.comments.push(displayedComment);
        }
        $(".commentList").append("

" +
            "

" + comment.text + "
" +
            "

");
        $("#commentText").val("");
    });
};

$("#addCommentInput").keyup(function (e) {
    if (e.keyCode == 13) {
        charts.addComment();
    }
});

var handleAddComment = function () {
    if (isUserLoggedIn) {
        $("#addCommentInput").show();
    }
    else {
        window.localStorage.selectedDate = charts.selectedDate;
        $("#loginModal").modal({show: true});
    }
};

var handleShareGraph = function () {
    var unregisteredUserOnStreamsPage = function () {
        return !isUserLoggedIn && (window.location.pathname.search("streams") !== -1);
    };

    if (isUserLoggedIn) {
        $.ajax({
            url: "/v1/graph/share?graphUrl=" + window.location.pathname,
            success: function (data) {
                $("#shareModal").modal({show: true});
                $("#loadingDiv").hide();
                var link = window.location.origin + data.graphShareUrl;
                var graphShareLink = " "+link+" ";
                $("#graphShareHyperLink").html(graphShareLink);
                $("#graphShareLink").html(link);
                $("#shareModal").modal({show: true});
            },
            error: function () {
                alert("some problem. Please try again later.");
            }
        });
    } else if (unregisteredUserOnStreamsPage()) {
        $("#loginModal").modal({show: true});
    } else {
        $.ajax({
            url: "/v1/graph/share?graphUrl=" + window.location.pathname,
            success: function (data) {
                $("#shareModal").modal({show: true});
                $("#loadingDiv").hide();
                var link = window.location.origin + data.graphShareUrl;
                var graphShareLink = ""+link+"";
                $("#graphShareHyperLink").html(graphShareLink);
                $("#graphShareLink").html(link);
            },
            error: function () {
                alert("some problem. Please try again later.");
            }
        });
    }
};

var showChartTitle = function () {
    $("#chartTitle").html(chartTitle);
    if (isUserLoggedIn) {
        $("#avatar").html("").addClass('avatar');
    }
    if (isUserLoggedIn || (!isUserLoggedIn && !(_.isEmpty(shareToken)))) {
        $.when(getEventsFor("users", graphOwner, objectTags, actionTags, operation, period, shareToken, readToken))
            .done(plotChart)
            .fail();
    } else {
        $.when(getEventsFor("streams", streamId, objectTags, actionTags, operation, period, shareToken, readToken))
            .done(plotChart)
            .fail();
    }
};

var submitShare = function () {
    var emailId = $("#emailId").val();
    var graphShareUrl = $("#graphShareLink").html();

    $.ajax({
        url: "/v1/share_graph",
        method: "POST",
        data: { graphShareUrl: graphShareUrl, toEmailId: emailId },
        success: function () {
            $(".shareEmailNoticeMessage").html("Graph link emailed successfully");
        },
        error: function () {
            alert("some problem. Please try again later.");
        }
    });
};

charts.showComments = function () {
    var commentsDiv = $(".commentList");
    commentsDiv.empty();

    charts.dataPoints
        .filter(function (dataPoint) {
            return dataPoint.dataPointDate === charts.selectedDate;
        })
        .forEach(function (dataPoint) {
            dataPoint.comments.forEach(function (comment) {
                commentsDiv.append("

" +
                    "
" + comment.text + "

");
            });
        });
};

var displayCommentsSummary = function () {
    for (var i = 6; i >= 0; i--) {
        var currentDataPointDate = moment.utc().subtract(i, 'days').format("YYYY-MM-DD"); // "2014-11-14"
        var currentDataPoint = _.findWhere(charts.dataPoints, {"dataPointDate": currentDataPointDate});
        if (!_.isEmpty(currentDataPoint)) {
            var latest3Avatars = currentDataPoint.avatars.slice(0, 3);
            latest3Avatars.forEach(function (avatarUrl, j) {
                $("#group" + i + "-avatar" + j).css({'background-image': 'url(' + avatarUrl + ')'});
            });
            if (currentDataPoint.comments.length > 3) {
                $("#group" + i + "-commentCount").addClass("count").html(currentDataPoint.comments.length);
            }
        }
    }
};

$(document).ready(function () {
    showChartTitle();
    $.ajax({
        url: "/v1/comments",
        method: "GET",
        data: {
            username: graphOwner,
            objectTags: objectTags,
            actionTags: actionTags,
            operation: operation,
            period: period,
            renderType: renderType
        },
        headers: {
            "Accept": "application/json",
            "Authorization": $.cookie("_eun")
        }
    }).done(function (comments) {
        charts.dataPoints = comments;
        displayCommentsSummary();
    });
    $("#shareSubmit").click(submitShare);

    var cw = $('.avatar_group').width();
    var ch = $(window).width() * (cw / 100);
    $('.avatar_group').css({'height': ch+'px'});

    setTimeout(function(){
        charts.showComments();
        if(isUserLoggedIn){
        if(window.localStorage.selectedDate) {
            delete window.localStorage.selectedDate;
        }
    }
    }, 3000)
});
<|endoftext|>


<commit_before>import React from "react";
import { FormGroup, Label, Input } from "helpers/reactstrap";
import { Query } from "react-apollo";
import gql from "graphql-tag";

export default ({ updateArgs, args, client }) => {
  console.log(args);
  return (
    <FormGroup className="macro-macroAction">
      Macro
      <Input
        type="select"
        value={args.macroId || "nothing"}
        onChange={e => updateArgs("macroId", e.target.value)}
      >
        <option disabled value="nothing">
          Pick a macro
        </option>
        <Query
          query={gql`
            query Macros {
              macros {
                id
                name
              }
            }
          `}
        >
          {({ loading, data }) => {
            if (loading) return null;
            return data.macros.map(m => (
              <option key={m.id} value={m.id}>
                {m.name}
              </option>
            ));
          }}
        </Query>
      </Input>
    </FormGroup>
  );
};
<commit_msg>fix(Macros): Fixes the display of macro options on the trigger macros macro. Closes #2396<commit_after>import React from "react";
import { FormGroup, Label, Input } from "helpers/reactstrap";
import { Query } from "react-apollo";
import gql from "graphql-tag";

export default ({ updateArgs, args, client }) => {
  console.log(args);
  return (
    <FormGroup className="macro-macroAction">
      Macro
      <Query
        query={gql`
          query Macros {
            macros {
              id
              name
            }
          }
        `}
      >
        {({ loading, data }) => {
          if (loading) return null;
          return (
            <Input
              type="select"
              value={args.macroId || "nothing"}
              onChange={e => updateArgs("macroId", e.target.value)}
            >
              <option disabled value="nothing">
                Pick a macro
              </option>

              {data.macros.map(m => (
                <option key={m.id} value={m.id}>
                  {m.name}
                </option>
              ))}
            </Input>
          );
        }}
      </Query>
    </FormGroup>
  );
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
// Actions
import { showModal, getUsers, deleteUser } from '../../actions/driver';
// Components
import Driver from '../../components/drivers/Driver';
import DriverModal from '../../components/drivers/DriverModal';
import { Button } from 'react-bootstrap';
import FontAwesome from 'react-fontawesome';

class DriverContainer extends Component {
  componentWillMount(){
    this.props.getUsers();
  }

  show = (event, driver = {}) => {this.props.showModal(driver);}
  destroy = id => {this.props.deleteUser(id)}

  render(){
    const drivers = this.props.drivers.map((driver, index) => <Driver driver={driver} key={index} onEdit={this.show} onDestroy={this.destroy}/>)
    return (

Drivers

        <Button className="create-route-btn" onClick={this.show} >
          Create Driver <FontAwesome name="plus"/>
        </Button>

{drivers}

        {this.props.showDriverModal && <DriverModal /> /* re render the route so that it updates*/}

    )
  }
}

function mapStateToProps(state, ownProps){
  return {
    drivers: state.drivers.drivers,
    showDriverModal: state.drivers.showModal
  }
}

export default connect(mapStateToProps, { showModal, getUsers, deleteUser })(DriverContainer);
<commit_msg>show error when empyty<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
// Actions
import { showModal, getUsers, deleteUser } from '../../actions/driver';
// Components
import Driver from '../../components/drivers/Driver';
import DriverModal from '../../components/drivers/DriverModal';
import { Button } from 'react-bootstrap';
import FontAwesome from 'react-fontawesome';

class DriverContainer extends Component {
  componentWillMount(){
    this.props.getUsers();
  }

  show = (event, driver = {}) => {this.props.showModal(driver);}
  destroy = id => {this.props.deleteUser(id)}

  render(){
    const drivers = this.props.drivers.map((driver, index) => <Driver driver={driver} key={index} onEdit={this.show} onDestroy={this.destroy}/>)
    return (

Drivers

        {drivers.length ?
        <Button className="create-route-btn" onClick={this.show} >
          Create Driver <FontAwesome name="plus"/>
        </Button>
        :
You Cannot Edit Drivers
}

{drivers}

        {this.props.showDriverModal && <DriverModal /> /* re render the route so that it updates*/}

    )
  }
}

function mapStateToProps(state, ownProps){
  return {
    drivers: state.drivers.drivers,
    showDriverModal: state.drivers.showModal
  }
}

export default connect(mapStateToProps, { showModal, getUsers, deleteUser })(DriverContainer);
<|endoftext|>


<commit_before>Template.courseSidebarSection.helpers({
    'editMode': function () {
        return Session.get('editMode');
    },
    'lessons': function () {
        // Get lesson IDs array
        var lessonIDs = this.lessonIDs;

        // Get lessons from database
        var lessons = Lessons.find({_id: {$in: lessonIDs}});

        return lessons;
    }
});

//Template.section.events({
//    'click .add-lesson': function (event, template) {
//        // get the value of the input field
//        var lessonTitle = template.find('.lesson-title').value;
//
//        // Make sure the lesson title contains one or more characters
//        // and add lesson to section
//        if (lessonTitle.length) {
//            // set up a demonstration lesson with title
//            var newLesson = {"title": lessonTitle};
//
//            // get the template data for use in this funciton
//            // TODO: Re-write this to interact with database
//            var courseData = template.data;
//
//            // add the example lesson to the lessons object
//            courseData.lessons.push(newLesson);
//
//            // Set the reactive variable to include the new lesson
//            // sections is defined in the resource-sidebar.js
//            sections.set(courseData);
//
//            // Reset the template field
//           $('.lesson-name').val('');
//        }
//    }
//});
//Template.courseSidebarSection.events({
//    'click .add-lesson': function (event, template) {
//        // get the value of the input field
//        var lessonTitle = template.find('.lesson-title').value;
//
//        // Make sure the lesson title contains one or more characters
//        // and add lesson to section
//        if (lessonTitle.length) {
//            // set up a demonstration lesson with title
//            var newLesson = {"title": lessonTitle};
//
//            // get the template data for use in this funciton
//            // TODO: Re-write this to interact with database
//            var courseData = template.data;
//
//            // add the example lesson to the lessons object
//            courseData.lessons.push(newLesson);
//
//            // Set the reactive variable to include the new lesson
//            // sections is defined in the resource-sidebar.js
//            sections.set(courseData);
//
//            // Reset the template field
//           $('.lesson-name').val('');
//        }
//    }
//});
<commit_msg>Cleanup unused code.<commit_after>Template.courseSidebarSection.helpers({
    'editMode': function () {
        return Session.get('editMode');
    },
    'lessons': function () {
        // Get lesson IDs array
        var lessonIDs = this.lessonIDs;

        // Get lessons from database
        var lessons = Lessons.find({_id: {$in: lessonIDs}});

        return lessons;
    }
});
<|endoftext|>


<commit_before>Template.initiativeShow.helpers({
  comments: function(){
    return this.comments.sort(function(a, b) {
      if(a && b && a.createdAt && b.createdAt) {
        return b.createdAt - a.createdAt;
      } else {
        return 1;
      }
    });
  }
});

Template.initiativeShow.events({
  'click .votes': function(e, tpl){
    // TODO: restrict votes to 1 pr initiative
    var initiative = this;
    addOrRemoveVote(initiative);
  }
});

Template.initiativeShow.onRendered(function(){
    $('body').addClass('show-initiative');
});

Template.initiativeShow.onDestroyed(function(){
    $('body.show-initiative').removeClass('show-initiative');
});

Template.initiativeCommenter.events({
  'submit .commenter-form': function (event, template) {
    event.preventDefault();

    // Grab input, and current user.
    var input = template.find('input[name="comment"]');
    Meteor.call("addComment", Meteor.userId(), this._id, input.value);
    input.value = "";
    sAlert.info('Thank you for your comment');
  }
});<commit_msg>Fix null sorting issue.<commit_after>Template.initiativeShow.helpers({
  comments: function(){
    if(this && this.comments) {
      return this.comments.sort(function(a, b) {
        if(a && b && a.createdAt && b.createdAt) {
          return b.createdAt - a.createdAt;
        } else {
          return 1;
        }
      });
    }
  }
});

Template.initiativeShow.events({
  'click .votes': function(e, tpl){
    // TODO: restrict votes to 1 pr initiative
    var initiative = this;
    addOrRemoveVote(initiative);
  }
});

Template.initiativeShow.onRendered(function(){
    $('body').addClass('show-initiative');
});

Template.initiativeShow.onDestroyed(function(){
    $('body.show-initiative').removeClass('show-initiative');
});

Template.initiativeCommenter.events({
  'submit .commenter-form': function (event, template) {
    event.preventDefault();

    // Grab input, and current user.
    var input = template.find('input[name="comment"]');
    Meteor.call("addComment", Meteor.userId(), this._id, input.value);
    input.value = "";
    sAlert.info('Thank you for your comment');
  }
});<|endoftext|>


<commit_before>function cc_m2_c2a(){
	jQuery('[name="postcode"]').each(function(index,elem){
		if(jQuery(elem).data('cc_attach') != '1' && jQuery(elem).closest('form').find('[name="street[0]"]').length == 1){
			jQuery(elem).data('cc_attach','1');
			var form = jQuery(elem).closest('form');

			var custom_id = '';
			if(c2a_config.advanced.search_elem_id !== null){
				custom_id = ' id="'+ c2a_config.advanced.search_elem_id +'"'
			}

			// null fix for m2_1.1.16
			if (c2a_config.texts.search_label == null) c2a_config.texts.search_label = '';

			var tmp_html = '

' +
							c2a_config.texts.search_label+'';
			if(c2a_config.advanced.hide_fields){
				tmp_html += '
'+c2a_config.texts.manual_entry_toggle+'
';
			}
			tmp_html += '

<input class="cc_search_input input-text" type="text"/>

';

			if (!c2a_config.advanced.use_first_line || c2a_config.advanced.hide_fields) {
				form.find('[name="street[0]"]').closest('.field-row').before( tmp_html );
			} else {
				form.find('[name="street[0]"]').addClass('cc_search_input');
			}
			if (c2a_config.advanced.lock_country_to_dropdown) {
				if (c2a_config.advanced.use_first_line) {
					form.find('.cc_search_input').closest('fieldset').before(form.find('[name="country_id"]').closest('div.field'));
				} else {
					form.find('.cc_search_input').closest('div.field').before(form.find('[name="country_id"]').closest('div.field'));
				}
			}

			var dom = {
				search:		form.find('.cc_search_input'),
				company:	form.find('[name="company"]'),
				line_1:		form.find('[name="street[0]"]'),
				line_2:		form.find('[name="street[1]"]'),
				postcode:	form.find('[name="postcode"]'),
				town:		form.find('[name="city"]'),
				county:		{
							input:	form.find('[name="region"]'),
							list:	form.find('[name="region_id"]')
				},
				country:	form.find('[name="country_id"]')
			};
			cc_holder.attach({
				search:		dom.search[0],
				company:	dom.company[0],
				line_1:		dom.line_1[0],
				line_2:		dom.line_2[0],
				postcode:	dom.postcode[0],
				town:		dom.town[0],
				county:		{
					input:	dom.county.input,
					list:	dom.county.list
				},
				country:	dom.country[0]
			});
			form.find('.cc_hide_fields_action').on('click',function(){
				cc_hide_fields(dom, 'manual-show')
			});

			cc_hide_fields(dom,'init');
		}
	});
}
var cc_holder = null;

function cc_hide_fields(dom, action){
	var action = action || 'show';
	if(!c2a_config.advanced.hide_fields){
		return;
	}
	switch(action){
		case 'init':
			var elementsToHide = ['line_1', 'line_2', 'line_3', 'line_4', 'town', 'postcode', 'county'];
			// determine if we can hide by default
			var formEmpty = true;
			for(var i=0; i<elementsToHide.length - 1; i++){ // -1 is to skip County
				if(jQuery(dom[elementsToHide[i]]).length && jQuery(dom[elementsToHide[i]]).val() !== ''){
					formEmpty = false;
				}
			}
			if(!c2a_config.advanced.lock_country_to_dropdown){
				elementsToHide.push('country');
			}
			for(var i=0; i<elementsToHide.length; i++){
				if(jQuery(dom[elementsToHide[i]]).length){
					switch(elementsToHide[i]){
						case 'county':
							jQuery(dom[elementsToHide[i]].input).closest('.field').addClass('cc_hide');
							jQuery(dom[elementsToHide[i]].list).closest('.field').addClass('cc_hide');
							break;
						case 'line_1':
							jQuery(dom[elementsToHide[i]]).closest('fieldset.field').addClass('cc_hide');
							break;
						default:
							jQuery(dom[elementsToHide[i]]).closest('.field').addClass('cc_hide');
					}
				}
			}
			var form = jQuery(dom.country).closest('form');
			// store the checking loop in the DOM object
			form.data('cc_hidden',0);
			if(formEmpty){
				cc_hide_fields(dom, 'hide');
			} else {
				cc_hide_fields(dom, 'show');
			}
			setInterval(function(){cc_reveal_fields_on_error(dom);}, 250);
			break;
		case 'hide':
			var form = jQuery(dom.country).closest('form');
			form.find('.cc_hide').each(function(index, item){
				jQuery(item).addClass('cc_hidden');
			});
			form.find('.cc_hide_fields_action').removeClass('cc_slider_on');
			form.data('cc_hidden',1);
			break;
		case 'manual-show':
		case 'show':
			var form = jQuery(dom.country).closest('form');
			jQuery(dom.country).trigger('change');
			form.find('.cc_hide').each(function(index, item){
				jQuery(item).removeClass('cc_hidden');
			});
			form.find('.cc_hide_fields_action').hide(200);
			form.data('cc_hidden',0);
			if(action == 'manual-show'){
				jQuery(dom.country).trigger('change');
			}
			break;
		case 'toggle':
			var form = jQuery(dom.country).closest('form');
			if(form.data('cc_hidden') == 1){
				cc_hide_fields(dom, 'show');
			} else {
				cc_hide_fields(dom, 'hide');
			}
			break;
	}
}

function cc_reveal_fields_on_error(dom){
	var form = jQuery(dom.country).closest('form');
	var errors_present = false;
	form.find('.cc_hide').each(function(index, item){
		if(jQuery(item).hasClass('_error')){
			errors_present = true;
		}
	});
	if(errors_present){
		cc_hide_fields(dom, 'show');
		form.find('.cc_hide_fields_action').hide(); // prevent the user from hiding the fields again
	}
}
requirejs(['jquery'], function( $ ) {
	jQuery( document ).ready(function() {
		if(c2a_config.enabled && c2a_config.key != null){
			var config = {
				accessToken: c2a_config.key,
				onSetCounty: function(c2a, elements, county){
					return;
				},
				domMode: 'object',
				gfxMode: c2a_config.gfx_mode,
				style: {
					ambient: c2a_config.gfx_ambient,
					accent: c2a_config.gfx_accent
				},
				showLogo: false,
				texts: c2a_config.texts,
				onResultSelected: function(c2a, elements, address){
					switch(address.country_name) {
						case 'Jersey':
							jQuery(elements.country).val('JE')
							break;
						case 'Guernsey':
							jQuery(elements.country).val('GG')
							break;
						case 'Isle of Man':
							jQuery(elements.country).val('IM')
							break;
						default:
							jQuery(elements.country).val(address.country.iso_3166_1_alpha_2);
					}
					jQuery(elements.country).trigger('change');

					var county = {
						preferred: address.province,
						code: address.province_code,
						name: address.province_name
					};

					if(elements.county.list.length == 1){
						c2a.setCounty(elements.county.list[0], county);
					}
					if(elements.county.input.length == 1){
						c2a.setCounty(elements.county.input[0], county);
					}
					jQuery(elements.county.input).trigger('change');
					jQuery(elements.county.list).trigger('change');

					jQuery(elements.company).trigger('change');
					jQuery(elements.line_1).trigger('change');
					jQuery(elements.line_2).trigger('change');
					jQuery(elements.postcode).trigger('change');
					jQuery(elements.town).trigger('change');

					cc_hide_fields(elements,'show');
				},
				onError: function(){
					if(typeof this.activeDom.postcode !== 'undefined'){
						cc_hide_fields(this.activeDom,'show');
					} else {
						c2a_config.advanced.hide_fields = false;
					}
				},
				transliterate: c2a_config.advanced.transliterate,
				debug: c2a_config.advanced.debug,
				cssPath: false,
				tag: 'Magento 2'
			};
			if(typeof c2a_config.enabled_countries !== 'undefined'){
				config.countryMatchWith = 'iso_2';
				config.enabledCountries = c2a_config.enabled_countries;
			}
			if(c2a_config.advanced.lock_country_to_dropdown){
				config.countrySelector = false;
				config.onSearchFocus = function(c2a, dom){
					var currentCountry = dom.country.options[dom.country.selectedIndex].value;
					if(currentCountry !== ''){
						var countryCode = getCountryCode(c2a, currentCountry, 'iso_2');
						c2a.selectCountry(countryCode);
					}
				};
			}

			cc_holder = new clickToAddress(config);
			setInterval(cc_m2_c2a,200);
		}

		if(c2a_config.enabled && c2a_config.key == null){
			console.warn('ClickToAddress: Incorrect token format supplied');
		}
	});
});
<commit_msg>misc improvements<commit_after>function cc_m2_c2a(){
	jQuery('[name="postcode"]').each(function(index,elem){
		if(jQuery(elem).data('cc_attach') != '1' && jQuery(elem).closest('form').find('[name="street[0]"]').length == 1){
			jQuery(elem).data('cc_attach','1');
			var form = jQuery(elem).closest('form');

			var custom_id = '';
			if(c2a_config.advanced.search_elem_id !== null){
				custom_id = ' id="'+ c2a_config.advanced.search_elem_id +'"'
			}

			// null fix for m2_1.1.16
			if (c2a_config.texts.search_label == null) c2a_config.texts.search_label = '';

			if (c2a_config.advanced.hide_fields) {
				//  if hide fields is enabled, always add our own search input
				var tmp_html = `

								${c2a_config.texts.search_label}

									${c2a_config.texts.manual_entry_toggle}

<input class="cc_search_input input-text" type="text"/>

				`
				form.find('[name="street[0]"]').closest('.field-row').before( tmp_html );
			} else if (!c2a_config.advanced.hide_fields && !c2a_config.advanced.use_first_line) {
				var tmp_html = `

								${c2a_config.texts.search_label}

<input class="cc_search_input input-text" type="text"/>

				`
				form.find('[name="street[0]"]').closest('.field-row').before( tmp_html );
			} else if (!c2a_config.advanced.hide_fields && c2a_config.advanced.use_first_line) {
				var tmp_html = `

								${c2a_config.texts.search_label}

				`
				form.find('[name="street[0]"]').closest('.field-row').before( tmp_html );
				form.find('[name="street[0]"]').addClass('cc_search_input');
			}

			if (c2a_config.advanced.lock_country_to_dropdown) {
				form.find('[name="country_id"]').closest('div.field').wrap('

');
				if (c2a_config.advanced.use_first_line) {
					form.find('.cc_search_input').closest('div.field-row').prev('div.field-row').before(form.find('[name="country_id"]').closest('div.field-row'));
				} else {
					form.find('.cc_search_input').closest('div.field-row').before(form.find('[name="country_id"]').closest('div.field-row'));
				}
			}

			var dom = {
				search:		form.find('.cc_search_input'),
				company:	form.find('[name="company"]'),
				line_1:		form.find('[name="street[0]"]'),
				line_2:		form.find('[name="street[1]"]'),
				postcode:	form.find('[name="postcode"]'),
				town:		form.find('[name="city"]'),
				county:		{
							input:	form.find('[name="region"]'),
							list:	form.find('[name="region_id"]')
				},
				country:	form.find('[name="country_id"]')
			};
			cc_holder.attach({
				search:		dom.search[0],
				company:	dom.company[0],
				line_1:		dom.line_1[0],
				line_2:		dom.line_2[0],
				postcode:	dom.postcode[0],
				town:		dom.town[0],
				county:		{
					input:	dom.county.input,
					list:	dom.county.list
				},
				country:	dom.country[0]
			});
			form.find('.cc_hide_fields_action').on('click',function(){
				cc_hide_fields(dom, 'manual-show')
			});

			cc_hide_fields(dom,'init');
		}
	});
}
var cc_holder = null;

function cc_hide_fields(dom, action){
	var action = action || 'show';
	if(!c2a_config.advanced.hide_fields){
		return;
	}
	switch(action){
		case 'init':
			var elementsToHide = ['line_1', 'line_2', 'line_3', 'line_4', 'town', 'postcode', 'county'];
			// determine if we can hide by default
			var formEmpty = true;
			for(var i=0; i<elementsToHide.length - 1; i++){ // -1 is to skip County
				if(jQuery(dom[elementsToHide[i]]).length && jQuery(dom[elementsToHide[i]]).val() !== ''){
					formEmpty = false;
				}
			}
			if(!c2a_config.advanced.lock_country_to_dropdown){
				elementsToHide.push('country');
			}
			for(var i=0; i<elementsToHide.length; i++){
				if(jQuery(dom[elementsToHide[i]]).length){
					switch(elementsToHide[i]){
						case 'county':
							jQuery(dom[elementsToHide[i]].input).closest('.field').addClass('cc_hide');
							jQuery(dom[elementsToHide[i]].list).closest('.field').addClass('cc_hide');
							break;
						case 'line_1':
							jQuery(dom[elementsToHide[i]]).closest('fieldset.field').addClass('cc_hide');
							break;
						default:
							jQuery(dom[elementsToHide[i]]).closest('.field').addClass('cc_hide');
					}
				}
			}
			var form = jQuery(dom.country).closest('form');
			// store the checking loop in the DOM object
			form.data('cc_hidden',0);
			if(formEmpty){
				cc_hide_fields(dom, 'hide');
			} else {
				cc_hide_fields(dom, 'show');
			}
			setInterval(function(){cc_reveal_fields_on_error(dom);}, 250);
			break;
		case 'hide':
			var form = jQuery(dom.country).closest('form');
			form.find('.cc_hide').each(function(index, item){
				jQuery(item).addClass('cc_hidden');
			});
			form.find('.cc_hide_fields_action').removeClass('cc_slider_on');
			form.data('cc_hidden',1);
			break;
		case 'manual-show':
		case 'show':
			var form = jQuery(dom.country).closest('form');
			jQuery(dom.country).trigger('change');
			form.find('.cc_hide').each(function(index, item){
				jQuery(item).removeClass('cc_hidden');
			});
			form.find('.cc_hide_fields_action').hide(200);
			form.data('cc_hidden',0);
			if(action == 'manual-show'){
				jQuery(dom.country).trigger('change');
			}
			break;
		case 'toggle':
			var form = jQuery(dom.country).closest('form');
			if(form.data('cc_hidden') == 1){
				cc_hide_fields(dom, 'show');
			} else {
				cc_hide_fields(dom, 'hide');
			}
			break;
	}
}

function cc_reveal_fields_on_error(dom){
	var form = jQuery(dom.country).closest('form');
	var errors_present = false;
	form.find('.cc_hide').each(function(index, item){
		if(jQuery(item).hasClass('_error')){
			errors_present = true;
		}
	});
	if(errors_present){
		cc_hide_fields(dom, 'show');
		form.find('.cc_hide_fields_action').hide(); // prevent the user from hiding the fields again
	}
}
requirejs(['jquery'], function( $ ) {
	jQuery( document ).ready(function() {
		if(c2a_config.enabled && c2a_config.key != null){
			var config = {
				accessToken: c2a_config.key,
				onSetCounty: function(c2a, elements, county){
					return;
				},
				domMode: 'object',
				gfxMode: c2a_config.gfx_mode,
				style: {
					ambient: c2a_config.gfx_ambient,
					accent: c2a_config.gfx_accent
				},
				showLogo: false,
				texts: c2a_config.texts,
				onResultSelected: function(c2a, elements, address){
					switch(address.country_name) {
						case 'Jersey':
							jQuery(elements.country).val('JE')
							break;
						case 'Guernsey':
							jQuery(elements.country).val('GG')
							break;
						case 'Isle of Man':
							jQuery(elements.country).val('IM')
							break;
						default:
							jQuery(elements.country).val(address.country.iso_3166_1_alpha_2);
					}
					jQuery(elements.country).trigger('change');

					var county = {
						preferred: address.province,
						code: address.province_code,
						name: address.province_name
					};

					if(elements.county.list.length == 1){
						c2a.setCounty(elements.county.list[0], county);
					}
					if(elements.county.input.length == 2){
						c2a.setCounty(elements.county.input[1], county);
					}
					jQuery(elements.county.input).trigger('change');
					jQuery(elements.county.list).trigger('change');

					jQuery(elements.company).trigger('change');
					jQuery(elements.line_1).trigger('change');
					jQuery(elements.line_2).trigger('change');
					jQuery(elements.postcode).trigger('change');
					jQuery(elements.town).trigger('change');

					cc_hide_fields(elements,'show');
				},
				onError: function(){
					if(typeof this.activeDom.postcode !== 'undefined'){
						cc_hide_fields(this.activeDom,'show');
					} else {
						c2a_config.advanced.hide_fields = false;
					}
				},
				transliterate: c2a_config.advanced.transliterate,
				debug: c2a_config.advanced.debug,
				cssPath: false,
				tag: 'Magento 2'
			};
			if(typeof c2a_config.enabled_countries !== 'undefined'){
				config.countryMatchWith = 'iso_2';
				config.enabledCountries = c2a_config.enabled_countries;
			}
			if(c2a_config.advanced.lock_country_to_dropdown){
				config.countrySelector = false;
				config.onSearchFocus = function(c2a, dom){
					var currentCountry = dom.country.options[dom.country.selectedIndex].value;
					if(currentCountry !== ''){
						var countryCode = getCountryCode(c2a, currentCountry, 'iso_2');
						c2a.selectCountry(countryCode);
					}
				};
			}

			cc_holder = new clickToAddress(config);
			setInterval(cc_m2_c2a,200);
		}

		if(c2a_config.enabled && c2a_config.key == null){
			console.warn('ClickToAddress: Incorrect token format supplied');
		}
	});
});
<|endoftext|>


<commit_before>import * as toolsUtils from './tools/utils';

export Arwes from './Arwes';
export Words from './Words';
export Heading from './Heading';
export Paragraph from './Paragraph';
export Link from './Link';
export Blockquote from './Blockquote';
export List from './List';
export Content from './Content';
export Frame from './Frame';
export Button from './Button';
export Line from './Line';
export Loading from './Loading';
export Image from './Image';
export Code from './Code';
export Table from './Table';
export Project from './Project';
export Header from './Header';
export Footer from './Footer';
export Grid, { Row, Col } from './Grid';
export Animation from './Animation';
export Appear from './Appear';
export Highlight from './Highlight';
export Puffs from './Puffs';
export Logo from './Logo';

export ThemeProvider from './ThemeProvider';
export withStyles from './tools/withStyles';
export createTheme from './tools/createTheme';

export createLoader from './tools/createLoader';
export createResponsive from './tools/createResponsive';

export const utils = toolsUtils;
<commit_msg>feat(arwes): remove deprecated export modules<commit_after><|endoftext|>


<commit_before>$(function(){
    // Redirect users that don't support filereader
    if(!$('html').hasClass('filereader')){
        document.location.href = window.simple_upload_url;
        return false;
    }

    // prevents browser default drag/drop
    $(document).bind('drop dragover', function (e) {
        e.preventDefault();
    });

    $('#fileupload').fileupload({
        dataType: 'html',
        sequentialUploads: true,
        dropZone: $('.drop-zone'),
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        previewMinWidth:150,
        previewMaxWidth:150,
        previewMinHeight:150,
        previewMaxHeight:150,

        add: function (e, data) {
            var $this = $(this);
            var that = $this.data('blueimp-fileupload') || $this.data('fileupload')
            var li = $($('#upload-list-item').html()).addClass('upload-uploading')
            var options = that.options;

            $('#upload-list').append(li);
            data.context = li;

            data.process(function () {
                return $this.fileupload('process', data);
            }).always(function () {
                data.context.removeClass('processing');
                data.context.find('.left').each(function(index, elm){
                    $(elm).append(data.files[index].name);
                });
                data.context.find('.preview .thumb').each(function (index, elm) {
                    $(elm).addClass('hasthumb')
                    $(elm).append(data.files[index].preview);
                });
            }).done(function () {
                data.context.find('.start').prop('disabled', false);
                if ((that._trigger('added', e, data) !== false) &&
                        (options.autoUpload || data.autoUpload) &&
                        data.autoUpload !== false) {
                    data.submit();
                }
            }).fail(function () {
                if (data.files.error) {
                    data.context.each(function (index) {
                        var error = data.files[index].error;
                        if (error) {
                            $(this).find('.error').text(error);
                        }
                    });
                }
            });

        },

        progress: function (e, data) {
            if (e.isDefaultPrevented()) {
                return false;
            }

            var progress = Math.floor(data.loaded / data.total * 100);
            data.context.each(function () {
                $(this).find('.progress').addClass('active').attr('aria-valuenow', progress).find('.bar').css(
                    'width',
                    progress + '%'
                ).html(progress + '%');
            });
        },

        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#overall-progress').addClass('active').attr('aria-valuenow', progress).find('.bar').css(
                'width',
                progress + '%'
            ).html(progress + '%');

            if (progress >= 100){
                $('#overall-progress').removeClass('active').find('.bar').css('width','0%');
            }
        },

        done: function (e, data) {
            var itemElement = $(data.context);
            var response = $.parseJSON(data.result);

            console.log(e);
            console.log(data);

            if(response.success){
                itemElement.addClass('upload-success')

                $('.right', itemElement).append(response.form);

                // run tagit enhancement
                $('.tag_field input', itemElement).tagit(window.tagit_opts);

                // ajax-enhance forms added on done()
                $('#upload-list').on('submit', 'form', function(e){
                    var form = $(this);

                    e.preventDefault();

                    $.post(this.action, form.serialize(), function(data) {
                        if (data.success) {
                            itemElement.slideUp(function(){$(this).remove()});
                        }else{
                            console.log(data);
                            form.replaceWith(data.form);
                            // run tagit enhancement on new form
                            $('.tag_field input', form).tagit(window.tagit_opts);
                        }
                    });
                });

                $('#upload-list').on('click', '.delete', function(e){
                    var form = $(this);

                    e.preventDefault();

                    $.post(this.href, form.serialize(), function(data) {
                        if (data.success) {
                            itemElement.slideUp(function(){$(this).remove()});
                        }else{

                        }
                    });
                });

            } else {
                itemElement.addClass('upload-failure');
                $('.right .error_messages', itemElement).append(response.error_message);
            }

        },

        fail: function(e, data){
            var itemElement = $(data.context);
            itemElement.addClass('upload-failure');
        },

        always: function(e, data){
            var itemElement = $(data.context);
            itemElement.removeClass('upload-uploading').addClass('upload-complete');
        },
    });
});<commit_msg>Fixed delete button<commit_after>$(function(){
    // Redirect users that don't support filereader
    if(!$('html').hasClass('filereader')){
        document.location.href = window.simple_upload_url;
        return false;
    }

    // prevents browser default drag/drop
    $(document).bind('drop dragover', function (e) {
        e.preventDefault();
    });

    $('#fileupload').fileupload({
        dataType: 'html',
        sequentialUploads: true,
        dropZone: $('.drop-zone'),
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        previewMinWidth:150,
        previewMaxWidth:150,
        previewMinHeight:150,
        previewMaxHeight:150,

        add: function (e, data) {
            var $this = $(this);
            var that = $this.data('blueimp-fileupload') || $this.data('fileupload')
            var li = $($('#upload-list-item').html()).addClass('upload-uploading')
            var options = that.options;

            $('#upload-list').append(li);
            data.context = li;

            data.process(function () {
                return $this.fileupload('process', data);
            }).always(function () {
                data.context.removeClass('processing');
                data.context.find('.left').each(function(index, elm){
                    $(elm).append(data.files[index].name);
                });
                data.context.find('.preview .thumb').each(function (index, elm) {
                    $(elm).addClass('hasthumb')
                    $(elm).append(data.files[index].preview);
                });
            }).done(function () {
                data.context.find('.start').prop('disabled', false);
                if ((that._trigger('added', e, data) !== false) &&
                        (options.autoUpload || data.autoUpload) &&
                        data.autoUpload !== false) {
                    data.submit();
                }
            }).fail(function () {
                if (data.files.error) {
                    data.context.each(function (index) {
                        var error = data.files[index].error;
                        if (error) {
                            $(this).find('.error').text(error);
                        }
                    });
                }
            });

        },

        progress: function (e, data) {
            if (e.isDefaultPrevented()) {
                return false;
            }

            var progress = Math.floor(data.loaded / data.total * 100);
            data.context.each(function () {
                $(this).find('.progress').addClass('active').attr('aria-valuenow', progress).find('.bar').css(
                    'width',
                    progress + '%'
                ).html(progress + '%');
            });
        },

        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#overall-progress').addClass('active').attr('aria-valuenow', progress).find('.bar').css(
                'width',
                progress + '%'
            ).html(progress + '%');

            if (progress >= 100){
                $('#overall-progress').removeClass('active').find('.bar').css('width','0%');
            }
        },

        done: function (e, data) {
            var itemElement = $(data.context);
            var response = $.parseJSON(data.result);

            console.log(e);
            console.log(data);

            if(response.success){
                itemElement.addClass('upload-success')

                $('.right', itemElement).append(response.form);

                // run tagit enhancement
                $('.tag_field input', itemElement).tagit(window.tagit_opts);

                // ajax-enhance forms added on done()
                $('#upload-list').on('submit', 'form', function(e){
                    var form = $(this);

                    e.preventDefault();

                    $.post(this.action, form.serialize(), function(data) {
                        if (data.success) {
                            itemElement.slideUp(function(){$(this).remove()});
                        }else{
                            console.log(data);
                            form.replaceWith(data.form);
                            // run tagit enhancement on new form
                            $('.tag_field input', form).tagit(window.tagit_opts);
                        }
                    });
                });

                $('#upload-list').on('click', '.delete', function(e){
                    var form = $(this).closest('form');

                    e.preventDefault();

                    var CSRFToken = $('input[name="csrfmiddlewaretoken"]', form).val();

                    $.post(this.href, {csrfmiddlewaretoken: CSRFToken}, function(data) {
                        if (data.success) {
                            itemElement.slideUp(function(){$(this).remove()});
                        }else{

                        }
                    });
                });

            } else {
                itemElement.addClass('upload-failure');
                $('.right .error_messages', itemElement).append(response.error_message);
            }

        },

        fail: function(e, data){
            var itemElement = $(data.context);
            itemElement.addClass('upload-failure');
        },

        always: function(e, data){
            var itemElement = $(data.context);
            itemElement.removeClass('upload-uploading').addClass('upload-complete');
        },
    });
});<|endoftext|>


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

/**
 * @fileoverview Logic blocks for Blockly, modified for App Inventor
 * @author fraser@google.com (Neil Fraser)
 * @author andrew.f.mckinney@gmail.com (Andrew F. McKinney)
 * Due to the frequency of long strings, the 80-column wrap rule need not apply
 * to language files.
 */

if (!Blockly.Language) Blockly.Language = {};

Blockly.Language.logic_boolean = {
  // Boolean data type: true and false.
  category : Blockly.LANG_CATEGORY_LOGIC,
  init : function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendDummyInput().appendTitle(new Blockly.FieldDropdown(this.OPERATORS), 'BOOL');
    var thisBlock = this;
    this.setTooltip(function() {
      var op = thisBlock.getTitleValue('BOOL');
      return Blockly.Language.logic_boolean.TOOLTIPS[op];
    });
    this.appendCollapsedInput().appendTitle(Blockly.LANG_LOGIC_BOOLEAN_TRUE, 'COLLAPSED_TEXT');
  },
  helpUrl : function() {
    var op = thisBlock.getTitleValue('BOOL');
    return Blockly.Language.logic_boolean.HELPURLS[op];},
  onchange: Blockly.WarningHandler.checkErrors,
  typeblock: [{
    translatedName: Blockly.LANG_LOGIC_BOOLEAN_TRUE,
    dropDown: {
      titleName: 'BOOL',
      value: 'TRUE'
    }
  },{
    translatedName: Blockly.LANG_LOGIC_BOOLEAN_FALSE,
    dropDown: {
      titleName: 'BOOL',
      value: 'FALSE'
    }
  }],
  prepareCollapsedText: function(){
    var titleFromOperator = Blockly.FieldDropdown.lookupOperator(this.OPERATORS, this.getTitleValue('BOOL'));
    this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT');
  }
};

Blockly.Language.logic_boolean.OPERATORS = [
    [ Blockly.LANG_LOGIC_BOOLEAN_TRUE, 'TRUE' ],
    [ Blockly.LANG_LOGIC_BOOLEAN_FALSE, 'FALSE' ]];

Blockly.Language.logic_boolean.TOOLTIPS = {
  TRUE : Blockly.LANG_LOGIC_BOOLEAN_TOOLTIP_TRUE,
  FALSE : Blockly.LANG_LOGIC_BOOLEAN_TOOLTIP_FALSE
};

Blockly.Language.logic_boolean.HELPURLS = {
  TRUE : Blockly.LANG_LOGIC_BOOLEAN_TRUE_HELPURL,
  FALSE : Blockly.LANG_LOGIC_BOOLEAN_FALSE_HELPURL
};

Blockly.Language.logic_false = {
  // Boolean data type: true and false.
  category : Blockly.LANG_CATEGORY_LOGIC,
  init : function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendDummyInput().appendTitle(new Blockly.FieldDropdown(Blockly.Language.logic_boolean.OPERATORS), 'BOOL');
    this.setTitleValue('FALSE','BOOL');
    var thisBlock = this;
    this.setTooltip(function() {
      var op = thisBlock.getTitleValue('BOOL');
      return Blockly.Language.logic_boolean.TOOLTIPS[op];
    });
    this.appendCollapsedInput().appendTitle(Blockly.LANG_LOGIC_BOOLEAN_FALSE, 'COLLAPSED_TEXT');
  },
  helpUrl : function() {
    var op = this.getTitleValue('BOOL');
    return Blockly.Language.logic_boolean.HELPURLS[op];},
  onchange: Blockly.WarningHandler.checkErrors,
  prepareCollapsedText: function(){
    var titleFromOperator = Blockly.FieldDropdown.lookupOperator(
        Blockly.Language.logic_boolean.OPERATORS, this.getTitleValue('BOOL'));
    this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT');
  }
};

Blockly.Language.logic_negate = {
  // Negation.
  category : Blockly.LANG_CATEGORY_LOGIC,
  helpUrl : Blockly.LANG_LOGIC_NEGATE_HELPURL,
  init : function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendValueInput('BOOL').setCheck(Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.INPUT)).appendTitle('not');
    this.setTooltip(Blockly.LANG_LOGIC_NEGATE_TOOLTIP);
    this.appendCollapsedInput().appendTitle('not', 'COLLAPSED_TEXT');
  },
  onchange: Blockly.WarningHandler.checkErrors,
  typeblock: [{ translatedName:Blockly.LANG_LOGIC_NEGATE_INPUT_NOT }]
};

Blockly.Language.logic_compare = {
  // Comparison operator.
  category : Blockly.LANG_CATEGORY_LOGIC,
  helpUrl : function() {
      var mode = this.getTitleValue('OP');
      return Blockly.Language.logic_compare.HELPURLS[mode];
    },
  init : function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendValueInput('A');
    this.appendValueInput('B').appendTitle(new Blockly.FieldDropdown(this.OPERATORS), 'OP');
    this.setInputsInline(true);
    // Assign 'this' to a variable for use in the tooltip closure below.
    var thisBlock = this;
    this.setTooltip(function() {
      var mode = thisBlock.getTitleValue('OP');
      return Blockly.Language.logic_compare.TOOLTIPS[mode];
    });
    this.appendCollapsedInput().appendTitle(
        Blockly.FieldDropdown.lookupOperator(this.OPERATORS, this.getTitleValue('OP')), 'COLLAPSED_TEXT');
  },
  onchange: Blockly.WarningHandler.checkErrors,
  //TODO (user) compare has not been internationalized yet
  // Potential clash with Math =, so using 'logic equal' for now
  typeblock: [{ translatedName: 'logic equal' }],
  prepareCollapsedText: function(){
    var titleFromOperator = Blockly.FieldDropdown.lookupOperator(this.OPERATORS, this.getTitleValue('OP'));
    this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT');
  }
};

Blockly.Language.logic_compare.TOOLTIPS = {
  EQ: 'Tests whether two things are equal. \n' +
        'The things being compared can be any thing, not only numbers.',
  NEQ: 'Tests whether two things are not equal. \n' +
        'The things being compared can be any thing, not only numbers.'
};

Blockly.Language.logic_compare.HELPURLS = {
  EQ: Blockly.LANG_LOGIC_COMPARE_HELPURL_EQ,
  NEQ: Blockly.LANG_LOGIC_COMPARE_HELPURL_NEQ
};

Blockly.Language.logic_compare.OPERATORS =
  [['=', 'EQ'],
   ['\u2260', 'NEQ']];

Blockly.Language.logic_operation = {
  // Logical operations: 'and', 'or'.
  category: Blockly.LANG_CATEGORY_LOGIC,
  init: function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendValueInput('A').setCheck(Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.INPUT));
    this.appendValueInput('B').setCheck(Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(this.OPERATORS), 'OP');
    this.setInputsInline(true);
    // Assign 'this' to a variable for use in the tooltip closure below.
    var thisBlock = this;
    this.setTooltip(function() {
      var op = thisBlock.getTitleValue('OP');
      return Blockly.Language.logic_operation.TOOLTIPS[op];
    });
    this.appendCollapsedInput().appendTitle('and', 'COLLAPSED_TEXT');
  },
  helpUrl: function() {
      var op = thisBlock.getTitleValue('OP');
      return Blockly.Language.logic_operation.HELPURLS[op];
    },
  onchange: Blockly.WarningHandler.checkErrors,
  typeblock: [{
    translatedName: Blockly.LANG_LOGIC_OPERATION_AND,
    dropDown: {
      titleName: 'OP',
      value: 'AND'
    }
  },{
    translatedName: Blockly.LANG_LOGIC_OPERATION_OR,
    dropDown: {
      titleName: 'OP',
      value: 'OR'
    }
  }],
  prepareCollapsedText: function(){
    var titleFromOperator = Blockly.FieldDropdown.lookupOperator(this.OPERATORS, this.getTitleValue('OP'));
    this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT');
  }
};

Blockly.Language.logic_operation.OPERATORS =
    [[Blockly.LANG_LOGIC_OPERATION_AND, 'AND'],
     [Blockly.LANG_LOGIC_OPERATION_OR, 'OR']];

Blockly.Language.logic_operation.HELPURLS = {
  AND : Blockly.LANG_LOGIC_OPERATION_HELPURL_AND,
  OR : Blockly.LANG_LOGIC_OPERATION_HELPURL_OR
};
Blockly.Language.logic_operation.TOOLTIPS = {
  AND : Blockly.LANG_LOGIC_OPERATION_TOOLTIP_AND,
  OR : Blockly.LANG_LOGIC_OPERATION_TOOLTIP_OR
};

Blockly.Language.logic_or = {
  // Logical operations: 'and', 'or'.
  category: Blockly.LANG_CATEGORY_LOGIC,
  init: function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendValueInput('A').setCheck(Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.INPUT));
    this.appendValueInput('B').setCheck(Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(Blockly.Language.logic_operation.OPERATORS), 'OP');
    this.setTitleValue('OR','OP');
    this.setInputsInline(true);
    // Assign 'this' to a variable for use in the tooltip closure below.
    var thisBlock = this;
    this.setTooltip(function() {
      var op = thisBlock.getTitleValue('OP');
      return Blockly.Language.logic_operation.TOOLTIPS[op];
    });
    this.appendCollapsedInput().appendTitle('or', 'COLLAPSED_TEXT');
  },
  helpUrl: function() {
      var op = thisBlock.getTitleValue('OP');
      return Blockly.Language.logic_operation.HELPURLS[op];
    },
  onchange: Blockly.WarningHandler.checkErrors,
  prepareCollapsedText: function(){
    var titleFromOperator = Blockly.FieldDropdown.lookupOperator(
        Blockly.Language.logic_operation.OPERATORS, this.getTitleValue('OP'));
    this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT');
  }
};

<commit_msg>Fix Logic blocks so right-clicking give you the correct context menu.<commit_after>/**
 * Visual Blocks Language
 *
 * Copyright 2012 Massachusetts Institute of Technology. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Logic blocks for Blockly, modified for App Inventor
 * @author fraser@google.com (Neil Fraser)
 * @author andrew.f.mckinney@gmail.com (Andrew F. McKinney)
 * Due to the frequency of long strings, the 80-column wrap rule need not apply
 * to language files.
 */

if (!Blockly.Language) Blockly.Language = {};

Blockly.Language.logic_boolean = {
  // Boolean data type: true and false.
  category : Blockly.LANG_CATEGORY_LOGIC,
  init : function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendDummyInput().appendTitle(new Blockly.FieldDropdown(this.OPERATORS), 'BOOL');
    var thisBlock = this;
    this.setTooltip(function() {
      var op = thisBlock.getTitleValue('BOOL');
      return Blockly.Language.logic_boolean.TOOLTIPS[op];
    });
    this.appendCollapsedInput().appendTitle(Blockly.LANG_LOGIC_BOOLEAN_TRUE, 'COLLAPSED_TEXT');
  },
  helpUrl : function() {
    var op = this.getTitleValue('BOOL');
    return Blockly.Language.logic_boolean.HELPURLS[op];},
  onchange: Blockly.WarningHandler.checkErrors,
  typeblock: [{
    translatedName: Blockly.LANG_LOGIC_BOOLEAN_TRUE,
    dropDown: {
      titleName: 'BOOL',
      value: 'TRUE'
    }
  },{
    translatedName: Blockly.LANG_LOGIC_BOOLEAN_FALSE,
    dropDown: {
      titleName: 'BOOL',
      value: 'FALSE'
    }
  }],
  prepareCollapsedText: function(){
    var titleFromOperator = Blockly.FieldDropdown.lookupOperator(this.OPERATORS, this.getTitleValue('BOOL'));
    this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT');
  }
};

Blockly.Language.logic_boolean.OPERATORS = [
    [ Blockly.LANG_LOGIC_BOOLEAN_TRUE, 'TRUE' ],
    [ Blockly.LANG_LOGIC_BOOLEAN_FALSE, 'FALSE' ]];

Blockly.Language.logic_boolean.TOOLTIPS = {
  TRUE : Blockly.LANG_LOGIC_BOOLEAN_TOOLTIP_TRUE,
  FALSE : Blockly.LANG_LOGIC_BOOLEAN_TOOLTIP_FALSE
};

Blockly.Language.logic_boolean.HELPURLS = {
  TRUE : Blockly.LANG_LOGIC_BOOLEAN_TRUE_HELPURL,
  FALSE : Blockly.LANG_LOGIC_BOOLEAN_FALSE_HELPURL
};

Blockly.Language.logic_false = {
  // Boolean data type: true and false.
  category : Blockly.LANG_CATEGORY_LOGIC,
  init : function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendDummyInput().appendTitle(new Blockly.FieldDropdown(Blockly.Language.logic_boolean.OPERATORS), 'BOOL');
    this.setTitleValue('FALSE','BOOL');
    var thisBlock = this;
    this.setTooltip(function() {
      var op = thisBlock.getTitleValue('BOOL');
      return Blockly.Language.logic_boolean.TOOLTIPS[op];
    });
    this.appendCollapsedInput().appendTitle(Blockly.LANG_LOGIC_BOOLEAN_FALSE, 'COLLAPSED_TEXT');
  },
  helpUrl : function() {
    var op = this.getTitleValue('BOOL');
    return Blockly.Language.logic_boolean.HELPURLS[op];},
  onchange: Blockly.WarningHandler.checkErrors,
  prepareCollapsedText: function(){
    var titleFromOperator = Blockly.FieldDropdown.lookupOperator(
        Blockly.Language.logic_boolean.OPERATORS, this.getTitleValue('BOOL'));
    this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT');
  }
};

Blockly.Language.logic_negate = {
  // Negation.
  category : Blockly.LANG_CATEGORY_LOGIC,
  helpUrl : Blockly.LANG_LOGIC_NEGATE_HELPURL,
  init : function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendValueInput('BOOL').setCheck(Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.INPUT)).appendTitle('not');
    this.setTooltip(Blockly.LANG_LOGIC_NEGATE_TOOLTIP);
    this.appendCollapsedInput().appendTitle('not', 'COLLAPSED_TEXT');
  },
  onchange: Blockly.WarningHandler.checkErrors,
  typeblock: [{ translatedName:Blockly.LANG_LOGIC_NEGATE_INPUT_NOT }]
};

Blockly.Language.logic_compare = {
  // Comparison operator.
  category : Blockly.LANG_CATEGORY_LOGIC,
  helpUrl : function() {
      var mode = this.getTitleValue('OP');
      return Blockly.Language.logic_compare.HELPURLS[mode];
    },
  init : function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendValueInput('A');
    this.appendValueInput('B').appendTitle(new Blockly.FieldDropdown(this.OPERATORS), 'OP');
    this.setInputsInline(true);
    // Assign 'this' to a variable for use in the tooltip closure below.
    var thisBlock = this;
    this.setTooltip(function() {
      var mode = thisBlock.getTitleValue('OP');
      return Blockly.Language.logic_compare.TOOLTIPS[mode];
    });
    this.appendCollapsedInput().appendTitle(
        Blockly.FieldDropdown.lookupOperator(this.OPERATORS, this.getTitleValue('OP')), 'COLLAPSED_TEXT');
  },
  onchange: Blockly.WarningHandler.checkErrors,
  //TODO (user) compare has not been internationalized yet
  // Potential clash with Math =, so using 'logic equal' for now
  typeblock: [{ translatedName: 'logic equal' }],
  prepareCollapsedText: function(){
    var titleFromOperator = Blockly.FieldDropdown.lookupOperator(this.OPERATORS, this.getTitleValue('OP'));
    this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT');
  }
};

Blockly.Language.logic_compare.TOOLTIPS = {
  EQ: 'Tests whether two things are equal. \n' +
        'The things being compared can be any thing, not only numbers.',
  NEQ: 'Tests whether two things are not equal. \n' +
        'The things being compared can be any thing, not only numbers.'
};

Blockly.Language.logic_compare.HELPURLS = {
  EQ: Blockly.LANG_LOGIC_COMPARE_HELPURL_EQ,
  NEQ: Blockly.LANG_LOGIC_COMPARE_HELPURL_NEQ
};

Blockly.Language.logic_compare.OPERATORS =
  [['=', 'EQ'],
   ['\u2260', 'NEQ']];

Blockly.Language.logic_operation = {
  // Logical operations: 'and', 'or'.
  category: Blockly.LANG_CATEGORY_LOGIC,
  init: function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendValueInput('A').setCheck(Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.INPUT));
    this.appendValueInput('B').setCheck(Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(this.OPERATORS), 'OP');
    this.setInputsInline(true);
    // Assign 'this' to a variable for use in the tooltip closure below.
    var thisBlock = this;
    this.setTooltip(function() {
      var op = thisBlock.getTitleValue('OP');
      return Blockly.Language.logic_operation.TOOLTIPS[op];
    });
    this.appendCollapsedInput().appendTitle('and', 'COLLAPSED_TEXT');
  },
  helpUrl: function() {
      var op = this.getTitleValue('OP');
      return Blockly.Language.logic_operation.HELPURLS[op];
    },
  onchange: Blockly.WarningHandler.checkErrors,
  typeblock: [{
    translatedName: Blockly.LANG_LOGIC_OPERATION_AND,
    dropDown: {
      titleName: 'OP',
      value: 'AND'
    }
  },{
    translatedName: Blockly.LANG_LOGIC_OPERATION_OR,
    dropDown: {
      titleName: 'OP',
      value: 'OR'
    }
  }],
  prepareCollapsedText: function(){
    var titleFromOperator = Blockly.FieldDropdown.lookupOperator(this.OPERATORS, this.getTitleValue('OP'));
    this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT');
  }
};

Blockly.Language.logic_operation.OPERATORS =
    [[Blockly.LANG_LOGIC_OPERATION_AND, 'AND'],
     [Blockly.LANG_LOGIC_OPERATION_OR, 'OR']];

Blockly.Language.logic_operation.HELPURLS = {
  AND : Blockly.LANG_LOGIC_OPERATION_HELPURL_AND,
  OR : Blockly.LANG_LOGIC_OPERATION_HELPURL_OR
};
Blockly.Language.logic_operation.TOOLTIPS = {
  AND : Blockly.LANG_LOGIC_OPERATION_TOOLTIP_AND,
  OR : Blockly.LANG_LOGIC_OPERATION_TOOLTIP_OR
};

Blockly.Language.logic_or = {
  // Logical operations: 'and', 'or'.
  category: Blockly.LANG_CATEGORY_LOGIC,
  init: function() {
    this.setColour(Blockly.LOGIC_CATEGORY_HUE);
    this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT));
    this.appendValueInput('A').setCheck(Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.INPUT));
    this.appendValueInput('B').setCheck(Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(Blockly.Language.logic_operation.OPERATORS), 'OP');
    this.setTitleValue('OR','OP');
    this.setInputsInline(true);
    // Assign 'this' to a variable for use in the tooltip closure below.
    var thisBlock = this;
    this.setTooltip(function() {
      var op = thisBlock.getTitleValue('OP');
      return Blockly.Language.logic_operation.TOOLTIPS[op];
    });
    this.appendCollapsedInput().appendTitle('or', 'COLLAPSED_TEXT');
  },
  helpUrl: function() {
      var op = this.getTitleValue('OP');
      return Blockly.Language.logic_operation.HELPURLS[op];
    },
  onchange: Blockly.WarningHandler.checkErrors,
  prepareCollapsedText: function(){
    var titleFromOperator = Blockly.FieldDropdown.lookupOperator(
        Blockly.Language.logic_operation.OPERATORS, this.getTitleValue('OP'));
    this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT');
  }
};

<|endoftext|>


<commit_before>var L = require('leaflet');

module.exports = function mapClip() {
  var directive = {
    restrict: 'A',
    scope: {
      feature: '=mapClip',
      disableInteraction: '='
    },
    replace: true,
    template: '

',
    controller: MapClipController
  };

  return directive;
};

MapClipController.$inject = ['$scope', '$element', 'MapService', 'LocalStorageService'];

function MapClipController($scope, $element, MapService, LocalStorageService) {
  var zoomControl = L.control.zoom();
  var worldExtentControl = L.control.worldExtent();

  var map = null;
  var controlsOn = false;
  var layers = {};
  var observation = null;
  var marker = null;

  initialize();

  var mapListener = {
    onBaseLayerSelected: onBaseLayerSelected
  };
  MapService.addListener(mapListener);

  $scope.$on('$destroy', function() {
    MapService.removeListener(mapListener);
  });

  $scope.$watch('feature', function() {
    if (observation) {
      map.removeLayer(observation);
    }
    if (marker) {
      map.removeLayer(marker);
    }
    addObservation($scope.feature);

  }, true);

  function onBaseLayerSelected(baseLayer) {
    var layer = layers[baseLayer.name];
    if (layer) map.removeLayer(layer.layer);

    layer = createRasterLayer(baseLayer);
    layers[baseLayer.name] = {type: 'tile', layer: baseLayer, rasterLayer: layer};

    layer.addTo(map);
  }

  function createRasterLayer(layer) {
    var baseLayer = null;
    var options = {};
    if (layer.format === 'XYZ' || layer.format === 'TMS') {
      options = { tms: layer.format === 'TMS', maxZoom: 18 };
      baseLayer = new L.TileLayer(layer.url, options);
    } else if (layer.format === 'WMS') {
      options = {
        layers: layer.wms.layers,
        version: layer.wms.version,
        format: layer.wms.format,
        transparent: layer.wms.transparent
      };

      if (layer.wms.styles) options.styles = layer.wms.styles;
      baseLayer = new L.TileLayer.WMS(layer.url, options);
    }

    return baseLayer;
  }

  $scope.$watch('feature.style.iconUrl', function() {
    if (!$scope.feature.geometry || !$scope.feature.style || !$scope.feature.style.iconUrl) return;
    marker.setIcon(L.fixedWidthIcon({
      iconUrl: $scope.feature.style.iconUrl
    }));
  });

  function addObservation(feature) {
    if (!feature || !feature.geometry || !feature.geometry.coordinates.length) {
      const mapPosition = LocalStorageService.getMapPosition();
      map.setView(mapPosition.center, 1);
      return;
    }

    if (feature.geometry) {
      if(feature.geometry.type === 'Point'){
        observation = L.geoJson(feature, {
          pointToLayer: function (feature, latlng) {
            marker = L.fixedWidthMarker(latlng, {
              iconUrl: feature.style ? feature.style.iconUrl : ($scope.feature.style ? $scope.feature.style.iconUrl : '')
            });
            return marker;
          }
        });
        observation.addTo(map);
        map.setView(L.GeoJSON.coordsToLatLng(feature.geometry.coordinates), 15);
      } else {
        observation = L.geoJson(feature, {
          style: function(feature) {
            return feature.style;
          }
        });
        observation.addTo(map);

        var coordinates = feature.geometry.coordinates;
        if(feature.geometry.type === 'Polygon'){
          coordinates = coordinates[0];
        }
        map.fitBounds(L.latLngBounds(L.GeoJSON.coordsToLatLngs(coordinates)));
      }
    }
  }

  function initialize() {
    const mapPosition = LocalStorageService.getMapPosition();

    map = L.map($element[0], {
      center: mapPosition.center,
      zoom: 1,
      minZoom: 0,
      maxZoom: 18,
      zoomControl: false,
      trackResize: true,
      scrollWheelZoom: false,
      attributionControl: false
    });

    if ($scope.disableInteraction) {
      map.scrollWheelZoom.disable();
      map.dragging.disable();
      map.touchZoom.disable();
      map.doubleClickZoom.disable();
      map.boxZoom.disable();
      map.keyboard.disable();
    }

    map.on('mouseover', function() {
      if (!controlsOn && !$scope.disableInteraction) {
        controlsOn = true;
        map.addControl(zoomControl);
        map.addControl(worldExtentControl);
      }
    });

    map.on('mouseout', function() {
      if (controlsOn && !$scope.disableInteraction) {
        map.removeControl(zoomControl);
        map.removeControl(worldExtentControl);
        controlsOn = false;
      }
    });

  }
}
<commit_msg>Only set map clip icon for point types<commit_after>var L = require('leaflet');

module.exports = function mapClip() {
  var directive = {
    restrict: 'A',
    scope: {
      feature: '=mapClip',
      disableInteraction: '='
    },
    replace: true,
    template: '

',
    controller: MapClipController
  };

  return directive;
};

MapClipController.$inject = ['$scope', '$element', 'MapService', 'LocalStorageService'];

function MapClipController($scope, $element, MapService, LocalStorageService) {
  var zoomControl = L.control.zoom();
  var worldExtentControl = L.control.worldExtent();

  var map = null;
  var controlsOn = false;
  var layers = {};
  var observation = null;
  var marker = null;

  initialize();

  var mapListener = {
    onBaseLayerSelected: onBaseLayerSelected
  };
  MapService.addListener(mapListener);

  $scope.$on('$destroy', function() {
    MapService.removeListener(mapListener);
  });

  $scope.$watch('feature', function() {
    if (observation) {
      map.removeLayer(observation);
    }
    if (marker) {
      map.removeLayer(marker);
    }
    addObservation($scope.feature);

  }, true);

  function onBaseLayerSelected(baseLayer) {
    var layer = layers[baseLayer.name];
    if (layer) map.removeLayer(layer.layer);

    layer = createRasterLayer(baseLayer);
    layers[baseLayer.name] = {type: 'tile', layer: baseLayer, rasterLayer: layer};

    layer.addTo(map);
  }

  function createRasterLayer(layer) {
    var baseLayer = null;
    var options = {};
    if (layer.format === 'XYZ' || layer.format === 'TMS') {
      options = { tms: layer.format === 'TMS', maxZoom: 18 };
      baseLayer = new L.TileLayer(layer.url, options);
    } else if (layer.format === 'WMS') {
      options = {
        layers: layer.wms.layers,
        version: layer.wms.version,
        format: layer.wms.format,
        transparent: layer.wms.transparent
      };

      if (layer.wms.styles) options.styles = layer.wms.styles;
      baseLayer = new L.TileLayer.WMS(layer.url, options);
    }

    return baseLayer;
  }

  $scope.$watch('feature.style.iconUrl', function() {
    if (!$scope.feature.geometry || !$scope.feature.style || !$scope.feature.style.iconUrl) return;

    if (marker) {
      marker.setIcon(L.fixedWidthIcon({
        iconUrl: $scope.feature.style.iconUrl
      }));
    }
  });

  function addObservation(feature) {
    if (!feature || !feature.geometry || !feature.geometry.coordinates.length) {
      const mapPosition = LocalStorageService.getMapPosition();
      map.setView(mapPosition.center, 1);
      return;
    }

    if (feature.geometry) {
      if(feature.geometry.type === 'Point'){
        observation = L.geoJson(feature, {
          pointToLayer: function (feature, latlng) {
            marker = L.fixedWidthMarker(latlng, {
              iconUrl: feature.style ? feature.style.iconUrl : ($scope.feature.style ? $scope.feature.style.iconUrl : '')
            });
            return marker;
          }
        });
        observation.addTo(map);
        map.setView(L.GeoJSON.coordsToLatLng(feature.geometry.coordinates), 15);
      } else {
        observation = L.geoJson(feature, {
          style: function(feature) {
            return feature.style;
          }
        });
        observation.addTo(map);

        var coordinates = feature.geometry.coordinates;
        if(feature.geometry.type === 'Polygon'){
          coordinates = coordinates[0];
        }
        map.fitBounds(L.latLngBounds(L.GeoJSON.coordsToLatLngs(coordinates)));
      }
    }
  }

  function initialize() {
    const mapPosition = LocalStorageService.getMapPosition();

    map = L.map($element[0], {
      center: mapPosition.center,
      zoom: 1,
      minZoom: 0,
      maxZoom: 18,
      zoomControl: false,
      trackResize: true,
      scrollWheelZoom: false,
      attributionControl: false
    });

    if ($scope.disableInteraction) {
      map.scrollWheelZoom.disable();
      map.dragging.disable();
      map.touchZoom.disable();
      map.doubleClickZoom.disable();
      map.boxZoom.disable();
      map.keyboard.disable();
    }

    map.on('mouseover', function() {
      if (!controlsOn && !$scope.disableInteraction) {
        controlsOn = true;
        map.addControl(zoomControl);
        map.addControl(worldExtentControl);
      }
    });

    map.on('mouseout', function() {
      if (controlsOn && !$scope.disableInteraction) {
        map.removeControl(zoomControl);
        map.removeControl(worldExtentControl);
        controlsOn = false;
      }
    });

  }
}
<|endoftext|>


<commit_before>describe('gridstack engine', function() {
    'use strict';

    var e;
    var w;
    var engine;

    beforeEach(function() {
        w = window;
        e = w.GridStackUI.Engine;
        engine = new w.GridStackUI.Engine(12);
    });

    describe('test constructor', function() {
        it('should be setup properly', function() {
            expect(engine.width).toEqual(12);
            expect(engine.float).toEqual(false);
            expect(engine.height).toEqual(0);
            expect(engine.nodes).toEqual([]);
        });
    });

    describe('test _prepareNode', function() {
        it('should prepare a node', function() {
            expect(engine._prepareNode({}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({x: 10}, false)).toEqual(jasmine.objectContaining({x: 10, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({x: -10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({y: 10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 10, width: 1, height: 1}));
            expect(engine._prepareNode({y: -10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({width: 3}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 3, height: 1}));
            expect(engine._prepareNode({width: 100}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 12, height: 1}));
            expect(engine._prepareNode({width: 0}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({width: -190}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({height: 3}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 3}));
            expect(engine._prepareNode({height: 0}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({height: -10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({x: 4, width: 10}, false)).toEqual(jasmine.objectContaining({x: 2, y: 0, width: 10, height: 1}));
            expect(engine._prepareNode({x: 4, width: 10}, true)).toEqual(jasmine.objectContaining({x: 4, y: 0, width: 8, height: 1}));
        });
    });
});
<commit_msg>GridStackEngine testing<commit_after>describe('gridstack engine', function() {
    'use strict';

    var e;
    var w;

    beforeEach(function() {
        w = window;
        e = w.GridStackUI.Engine;
    });

    describe('test constructor', function() {
        var engine;

        beforeAll(function() {
            engine = new GridStackUI.Engine(12);
        })

        it('should be setup properly', function() {
            expect(engine.width).toEqual(12);
            expect(engine.float).toEqual(false);
            expect(engine.height).toEqual(0);
            expect(engine.nodes).toEqual([]);
        });
    });

    describe('test _prepareNode', function() {
        var engine;

        beforeAll(function() {
            engine = new GridStackUI.Engine(12);
        })

        it('should prepare a node', function() {
            expect(engine._prepareNode({}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({x: 10}, false)).toEqual(jasmine.objectContaining({x: 10, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({x: -10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({y: 10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 10, width: 1, height: 1}));
            expect(engine._prepareNode({y: -10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({width: 3}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 3, height: 1}));
            expect(engine._prepareNode({width: 100}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 12, height: 1}));
            expect(engine._prepareNode({width: 0}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({width: -190}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({height: 3}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 3}));
            expect(engine._prepareNode({height: 0}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({height: -10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, width: 1, height: 1}));
            expect(engine._prepareNode({x: 4, width: 10}, false)).toEqual(jasmine.objectContaining({x: 2, y: 0, width: 10, height: 1}));
            expect(engine._prepareNode({x: 4, width: 10}, true)).toEqual(jasmine.objectContaining({x: 4, y: 0, width: 8, height: 1}));
        });
    });

    describe('test isAreaEmpty', function() {
        var engine;

        beforeAll(function() {
            engine = new GridStackUI.Engine(12, null, true);
            engine.nodes = [
                engine._prepareNode({x: 3, y: 2, width: 3, height: 2})
            ];
        })

        it('should be true', function() {
            expect(engine.isAreaEmpty(0, 0, 3, 2)).toEqual(true);
            expect(engine.isAreaEmpty(3, 4, 3, 2)).toEqual(true);
        });

        it('should be false', function() {
            expect(engine.isAreaEmpty(1, 1, 3, 2)).toEqual(false);
            expect(engine.isAreaEmpty(2, 3, 3, 2)).toEqual(false);
        });
    });

    describe('test cleanNodes/getDirtyNodes', function() {
        var engine;

        beforeAll(function() {
            engine = new GridStackUI.Engine(12, null, true);
            engine.nodes = [
                engine._prepareNode({x: 0, y: 0, width: 1, height: 1, idx: 1, _dirty: true}),
                engine._prepareNode({x: 3, y: 2, width: 3, height: 2, idx: 2, _dirty: true}),
                engine._prepareNode({x: 3, y: 7, width: 3, height: 2, idx: 3})
            ];
        });

        beforeEach(function() {
            engine._updateCounter = 0;
        });

        it('should return all dirty nodes', function() {
            var nodes = engine.getDirtyNodes();

            expect(nodes.length).toEqual(2);
            expect(nodes[0].idx).toEqual(1);
            expect(nodes[1].idx).toEqual(2);
        });

        it('should\'n clean nodes if _updateCounter > 0', function() {
            engine._updateCounter = 1;
            engine.cleanNodes();

            expect(engine.getDirtyNodes().length).toBeGreaterThan(0);
        });

        it('should clean all dirty nodes', function() {
            engine.cleanNodes();

            expect(engine.getDirtyNodes().length).toEqual(0);
        });
    });

    describe('test _notify', function() {
        var engine;
        var spy;

        beforeEach(function() {
            spy = {
                callback: function () {}
            }
            spyOn(spy, 'callback');

            engine = new GridStackUI.Engine(12, spy.callback, true);

            engine.nodes = [
                engine._prepareNode({x: 0, y: 0, width: 1, height: 1, idx: 1, _dirty: true}),
                engine._prepareNode({x: 3, y: 2, width: 3, height: 2, idx: 2, _dirty: true}),
                engine._prepareNode({x: 3, y: 7, width: 3, height: 2, idx: 3})
            ];
        });

        it('should\'n be called if _updateCounter > 0', function() {
            engine._updateCounter = 1;
            engine._notify();

            expect(spy.callback).not.toHaveBeenCalled();
        });

        it('should by called with dirty nodes', function() {
            engine._notify();

            expect(spy.callback).toHaveBeenCalledWith([
                engine.nodes[0],
                engine.nodes[1]
            ]);
        });

        it('should by called with extra passed dirty nodes', function() {
            var n1 = {idx: -1},
                n2 = {idx: -2};

            engine._notify(n1, n2);

            expect(spy.callback).toHaveBeenCalledWith([
                n1,
                n2,
                engine.nodes[0],
                engine.nodes[1]
            ]);
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var lib     = require('../lib/express-api-template.js'),
    userLib = require('../users/lib.js');

module.exports = {

  login: {

    token: function(req, res) {
    // URI: /login/:token
      var data  = {},
          token = req.params.token;

      userLib.authenticate(token, function(err, user) {
        if (err) {
          data.message = 'error looking up token';
          return res.status(500).json(data);
        }

        if (!user) {
          data.message = 'token not found';
          return res.status(404).json(data);
        }

        // tack user onto req, need both for createJwt
        req.user = user;

        var jot = lib.createJwt(req);

        res.set(req.app.get('authHeader'), jot);
        // send a cookie
        //res.cookie(req.app.get('authHeader'), jot, {
        //  maxAge: new Date(Date.now() + 7884000), // 3 months
        //  httpOnly: true }
        //);

        data.message = 'logged in as user: ' + user.id;
        res.status(200).json(data);
      });
    }

  }

};
<commit_msg>minor formatting<commit_after>'use strict';

var lib     = require('../lib/express-api-template.js'),
    userLib = require('../users/lib.js');

module.exports = {

  login: {

    token: function(req, res) {
    // URI: /login/:token
      var data  = {},
          token = req.params.token;

      userLib.authenticate(token, function(err, user) {
        if (err) {
          data.message = 'error looking up token';
          return res.status(500).json(data);
        }

        if (!user) {
          data.message = 'token not found';
          return res.status(404).json(data);
        }

        // tack user onto req, need both for createJwt
        req.user = user;

        var jot = lib.createJwt(req);

        res.set(req.app.get('authHeader'), jot);
        // send a cookie
        //res.cookie(
        //  req.app.get('authHeader'),
        //  jot,
        //  { maxAge: new Date(Date.now() + 7884000), // 3 months
        //    httpOnly: true}
        //);

        data.message = 'logged in as user: ' + user.id;
        res.status(200).json(data);
      });
    }

  }

};
<|endoftext|>