<commit_before>/* globals
 _, Backbone, Content, Discussion, DiscussionUtil, DiscussionUser, DiscussionCourseSettings,
 DiscussionThreadListView, DiscussionThreadView, NewPostView
 */

(function() {
    'use strict';

    this.DiscussionInlineView = Backbone.View.extend({
        events: {
            'click .discussion-show': 'toggleDiscussion',
            'keydown .discussion-show': function(event) {
                return DiscussionUtil.activateOnSpace(event, this.toggleDiscussion);
            },
            'click .new-post-btn': 'toggleNewPost',
            'click .all-posts-btn': 'navigateToAllPosts',
            keydown: 'handleKeydown',
            'keydown .new-post-btn': function(event) {
                return DiscussionUtil.activateOnSpace(event, this.toggleNewPost);
            }
        },

        page_re: /\?discussion_page=(\d+)/,

        initialize: function(options) {
            var match;

            this.$el = options.el;
            this.readOnly = options.readOnly;
            this.showByDefault = options.showByDefault || false;
            this.toggleDiscussionBtn = this.$('.discussion-show');
            this.listenTo(this.model, 'change', this.render);
            this.escKey = 27;

            match = this.page_re.exec(window.location.href);
            if (match) {
                this.page = parseInt(match[1], 10);
            } else {
                this.page = 1;
            }

            // By default the view is displayed in a hidden state. If you want it to be shown by default (e.g. in Teams)
            // pass showByDefault as an option. This code will open it on initialization.
            if (this.showByDefault) {
                this.toggleDiscussion();
            }
        },

        loadDiscussions: function($elem, error) {
            var discussionId = this.$el.data('discussion-id'),
                url = DiscussionUtil.urlFor('retrieve_discussion', discussionId) + ('?page=' + this.page),
                self = this;

            DiscussionUtil.safeAjax({
                $elem: this.$el,
                $loading: this.$el,
                takeFocus: true,
                url: url,
                type: 'GET',
                dataType: 'json',
                success: function(response, textStatus) {
                    self.renderDiscussion(self.$el, response, textStatus, discussionId);
                },
                error: error
            });
        },

        renderDiscussion: function($elem, response, textStatus, discussionId) {
            var discussionHtml,
                user = new DiscussionUser(response.user_info),
                self = this;

            $elem.focus();

            window.user = user;
            DiscussionUtil.setUser(user);
            Content.loadContentInfos(response.annotated_content_info);
            DiscussionUtil.loadRoles(response.roles);

            this.course_settings = new DiscussionCourseSettings(response.course_settings);

            this.discussion = new Discussion(undefined, {pages: response.num_pages});
            this.discussion.reset(response.discussion_data, {
                silent: false
            });

            discussionHtml = edx.HtmlUtils.template($('#inline-discussion-template').html())({
                threads: response.discussion_data,
                read_only: this.readOnly,
                discussionId: discussionId
            });

            if (this.$('section.discussion').length) {
                edx.HtmlUtils.setHtml(this.$el, discussionHtml);
                this.$('section.discussion').replaceWith(edx.HtmlUtils.ensureHtml(discussionHtml).toString());
            } else {
                edx.HtmlUtils.append(this.$el, discussionHtml);
            }

            this.threadListView = new DiscussionThreadListView({
                el: this.$('.inline-threads'),
                collection: self.discussion,
                courseSettings: self.course_settings,
                hideRefineBar: true  // TODO: re-enable the search/filter bar when it works correctly
            });

            this.threadListView.render();

            this.threadListView.on('thread:selected', _.bind(this.navigateToThread, this));

            DiscussionUtil.bulkUpdateContentInfo(window.$$annotated_content_info);

            this.newPostForm = this.$el.find('.new-post-article');

            this.newPostView = new NewPostView({
                el: this.newPostForm,
                collection: this.discussion,
                course_settings: this.course_settings,
                topicId: discussionId,
                is_commentable_cohorted: response.is_commentable_cohorted
            });

            this.newPostView.render();

            this.listenTo(this.newPostView, 'newPost:createPost', this.onNewPostCreated);
            this.listenTo(this.newPostView, 'newPost:cancel', this.hideNewPost);
            this.discussion.on('add', this.addThread);

            this.retrieved = true;
            this.showed = true;

            if (this.isWaitingOnNewPost) {
                this.newPostForm.removeClass('is-hidden').focus();
            }

            // Hide the thread view initially
            this.$('.inline-thread').addClass('is-hidden');
        },

        navigateToThread: function(threadId) {
            var thread = this.discussion.get(threadId);
            this.threadView = new DiscussionThreadView({
                el: this.$('.forum-content'),
                model: thread,
                mode: 'inline',
                course_settings: this.course_settings
            });
            this.threadView.render();
            this.listenTo(this.threadView.showView, 'thread:_delete', this.navigateToAllPosts);
            this.threadListView.$el.addClass('is-hidden');
            this.$('.inline-thread').removeClass('is-hidden');
        },

        navigateToAllPosts: function() {
            // Hide the inline thread section
            this.$('.inline-thread').addClass('is-hidden');

            // Delete the thread view
            this.threadView.$el.empty().off();
            this.threadView.stopListening();
            this.threadView = null;

            // Show the thread list view
            this.threadListView.$el.removeClass('is-hidden');

            // Set focus to thread list item that was saved as active
            this.threadListView.$('.is-active').focus();
        },

        toggleDiscussion: function() {
            var self = this;

            if (this.showed) {
                this.hideDiscussion();
            } else {
                this.toggleDiscussionBtn.addClass('shown');
                this.toggleDiscussionBtn.find('.button-text').text(gettext('Hide Discussion'));
                if (this.retrieved) {
                    this.$('section.discussion').removeClass('is-hidden');
                    this.showed = true;
                } else {
                    this.loadDiscussions(this.$el, function() {
                        self.hideDiscussion();
                        DiscussionUtil.discussionAlert(
                            gettext('Error'),
                            gettext('This discussion could not be loaded. Refresh the page and try again.')
                        );
                    });
                }
            }
        },

        hideDiscussion: function() {
            this.$('section.discussion').addClass('is-hidden');
            this.toggleDiscussionBtn.removeClass('shown');
            this.toggleDiscussionBtn.find('.button-text').text(gettext('Show Discussion'));
            this.showed = false;
        },

        toggleNewPost: function(event) {
            event.preventDefault();
            if (!this.newPostForm) {
                this.toggleDiscussion();
                this.isWaitingOnNewPost = true;
                return;
            }
            if (this.showed) {
                this.$('section.discussion').find('.inline-discussion-thread-container').addClass('is-hidden');
                this.$('section.discussion').find('.add_post_btn_container').addClass('is-hidden');
                this.newPostForm.removeClass('is-hidden');
            }
            this.newPostView.$el.removeClass('is-hidden');
            this.toggleDiscussionBtn.addClass('shown');
            this.toggleDiscussionBtn.find('.button-text').text(gettext('Hide Discussion'));
            this.showed = true;
        },

        onNewPostCreated: function() {
            this.navigateToAllPosts();
            this.hideNewPost();
        },

        hideNewPost: function() {
            this.$('section.discussion').find('.inline-discussion-thread-container').removeClass('is-hidden');
            this.$('section.discussion').find('.add_post_btn_container')
                .removeClass('is-hidden')
                .focus();
            this.newPostForm.addClass('is-hidden');
        },

        handleKeydown: function(event) {
            var keyCode = event.keyCode;
            if (keyCode === this.escKey) {
                this.$('section.discussion').find('.cancel').trigger('click');
            }
        }
    });
}).call(window);
<commit_msg>Fix bug on new post creation where we would try to hide an element that wasn't there<commit_after>/* globals
 _, Backbone, Content, Discussion, DiscussionUtil, DiscussionUser, DiscussionCourseSettings,
 DiscussionThreadListView, DiscussionThreadView, NewPostView
 */

(function() {
    'use strict';

    this.DiscussionInlineView = Backbone.View.extend({
        events: {
            'click .discussion-show': 'toggleDiscussion',
            'keydown .discussion-show': function(event) {
                return DiscussionUtil.activateOnSpace(event, this.toggleDiscussion);
            },
            'click .new-post-btn': 'toggleNewPost',
            'click .all-posts-btn': 'navigateToAllPosts',
            keydown: 'handleKeydown',
            'keydown .new-post-btn': function(event) {
                return DiscussionUtil.activateOnSpace(event, this.toggleNewPost);
            }
        },

        page_re: /\?discussion_page=(\d+)/,

        initialize: function(options) {
            var match;

            this.$el = options.el;
            this.readOnly = options.readOnly;
            this.showByDefault = options.showByDefault || false;
            this.toggleDiscussionBtn = this.$('.discussion-show');
            this.listenTo(this.model, 'change', this.render);
            this.escKey = 27;

            match = this.page_re.exec(window.location.href);
            if (match) {
                this.page = parseInt(match[1], 10);
            } else {
                this.page = 1;
            }

            // By default the view is displayed in a hidden state. If you want it to be shown by default (e.g. in Teams)
            // pass showByDefault as an option. This code will open it on initialization.
            if (this.showByDefault) {
                this.toggleDiscussion();
            }
        },

        loadDiscussions: function($elem, error) {
            var discussionId = this.$el.data('discussion-id'),
                url = DiscussionUtil.urlFor('retrieve_discussion', discussionId) + ('?page=' + this.page),
                self = this;

            DiscussionUtil.safeAjax({
                $elem: this.$el,
                $loading: this.$el,
                takeFocus: true,
                url: url,
                type: 'GET',
                dataType: 'json',
                success: function(response, textStatus) {
                    self.renderDiscussion(self.$el, response, textStatus, discussionId);
                },
                error: error
            });
        },

        renderDiscussion: function($elem, response, textStatus, discussionId) {
            var discussionHtml,
                user = new DiscussionUser(response.user_info),
                self = this;

            $elem.focus();

            window.user = user;
            DiscussionUtil.setUser(user);
            Content.loadContentInfos(response.annotated_content_info);
            DiscussionUtil.loadRoles(response.roles);

            this.course_settings = new DiscussionCourseSettings(response.course_settings);

            this.discussion = new Discussion(undefined, {pages: response.num_pages});
            this.discussion.reset(response.discussion_data, {
                silent: false
            });

            discussionHtml = edx.HtmlUtils.template($('#inline-discussion-template').html())({
                threads: response.discussion_data,
                read_only: this.readOnly,
                discussionId: discussionId
            });

            if (this.$('section.discussion').length) {
                edx.HtmlUtils.setHtml(this.$el, discussionHtml);
                this.$('section.discussion').replaceWith(edx.HtmlUtils.ensureHtml(discussionHtml).toString());
            } else {
                edx.HtmlUtils.append(this.$el, discussionHtml);
            }

            this.threadListView = new DiscussionThreadListView({
                el: this.$('.inline-threads'),
                collection: self.discussion,
                courseSettings: self.course_settings,
                hideRefineBar: true  // TODO: re-enable the search/filter bar when it works correctly
            });

            this.threadListView.render();

            this.threadListView.on('thread:selected', _.bind(this.navigateToThread, this));

            DiscussionUtil.bulkUpdateContentInfo(window.$$annotated_content_info);

            this.newPostForm = this.$el.find('.new-post-article');

            this.newPostView = new NewPostView({
                el: this.newPostForm,
                collection: this.discussion,
                course_settings: this.course_settings,
                topicId: discussionId,
                is_commentable_cohorted: response.is_commentable_cohorted
            });

            this.newPostView.render();

            this.listenTo(this.newPostView, 'newPost:createPost', this.onNewPostCreated);
            this.listenTo(this.newPostView, 'newPost:cancel', this.hideNewPost);
            this.discussion.on('add', this.addThread);

            this.retrieved = true;
            this.showed = true;

            if (this.isWaitingOnNewPost) {
                this.newPostForm.removeClass('is-hidden').focus();
            }

            // Hide the thread view initially
            this.$('.inline-thread').addClass('is-hidden');
        },

        navigateToThread: function(threadId) {
            var thread = this.discussion.get(threadId);
            this.threadView = new DiscussionThreadView({
                el: this.$('.forum-content'),
                model: thread,
                mode: 'inline',
                course_settings: this.course_settings
            });
            this.threadView.render();
            this.listenTo(this.threadView.showView, 'thread:_delete', this.navigateToAllPosts);
            this.threadListView.$el.addClass('is-hidden');
            this.$('.inline-thread').removeClass('is-hidden');
        },

        navigateToAllPosts: function() {
            // Hide the inline thread section
            this.$('.inline-thread').addClass('is-hidden');

            // Delete the thread view
            if (this.threadView) {
                this.threadView.$el.empty().off();
                this.threadView.stopListening();
                this.threadView = null;
            }

            // Show the thread list view
            this.threadListView.$el.removeClass('is-hidden');

            // Set focus to thread list item that was saved as active
            this.threadListView.$('.is-active').focus();
        },

        toggleDiscussion: function() {
            var self = this;

            if (this.showed) {
                this.hideDiscussion();
            } else {
                this.toggleDiscussionBtn.addClass('shown');
                this.toggleDiscussionBtn.find('.button-text').text(gettext('Hide Discussion'));
                if (this.retrieved) {
                    this.$('section.discussion').removeClass('is-hidden');
                    this.showed = true;
                } else {
                    this.loadDiscussions(this.$el, function() {
                        self.hideDiscussion();
                        DiscussionUtil.discussionAlert(
                            gettext('Error'),
                            gettext('This discussion could not be loaded. Refresh the page and try again.')
                        );
                    });
                }
            }
        },

        hideDiscussion: function() {
            this.$('section.discussion').addClass('is-hidden');
            this.toggleDiscussionBtn.removeClass('shown');
            this.toggleDiscussionBtn.find('.button-text').text(gettext('Show Discussion'));
            this.showed = false;
        },

        toggleNewPost: function(event) {
            event.preventDefault();
            if (!this.newPostForm) {
                this.toggleDiscussion();
                this.isWaitingOnNewPost = true;
                return;
            }
            if (this.showed) {
                this.$('section.discussion').find('.inline-discussion-thread-container').addClass('is-hidden');
                this.$('section.discussion').find('.add_post_btn_container').addClass('is-hidden');
                this.newPostForm.removeClass('is-hidden');
            }
            this.newPostView.$el.removeClass('is-hidden');
            this.toggleDiscussionBtn.addClass('shown');
            this.toggleDiscussionBtn.find('.button-text').text(gettext('Hide Discussion'));
            this.showed = true;
        },

        onNewPostCreated: function() {
            this.navigateToAllPosts();
            this.hideNewPost();
        },

        hideNewPost: function() {
            this.$('section.discussion').find('.inline-discussion-thread-container').removeClass('is-hidden');
            this.$('section.discussion').find('.add_post_btn_container')
                .removeClass('is-hidden')
                .focus();
            this.newPostForm.addClass('is-hidden');
        },

        handleKeydown: function(event) {
            var keyCode = event.keyCode;
            if (keyCode === this.escKey) {
                this.$('section.discussion').find('.cancel').trigger('click');
            }
        }
    });
}).call(window);
<|endoftext|>


<commit_before>/**
* TaskFeedController
* @namespace crowdsource.template.controllers
 * @author dmorina
*/
(function () {
  'use strict';

  angular
    .module('crowdsource.template.controllers')
    .controller('TemplateController', TemplateController);

    TemplateController.$inject = ['$window', '$location', '$scope', 'Template', '$filter', '$sce',
      'Project', 'Authentication', '$mdDialog'];

  /**
  * @namespace TemplateController
  */
  function TemplateController($window, $location, $scope, Template, $filter, $sce,
    Project, Authentication, $mdDialog) {
    var self = this;
    self.userAccount = Authentication.getAuthenticatedAccount();
    if (!self.userAccount) {
      $location.path('/login');
      return;
    }

    var idGenIndex = 0;

    // Retrieve from service if possible.
    $scope.project.currentProject = Project.retrieve();
    if ($scope.project.currentProject.template) {
      self.templateName = $scope.project.currentProject.template.name || generateRandomTemplateName();
      self.items = $scope.project.currentProject.template.items || [];
    } else {
      self.templateName = generateRandomTemplateName();
      self.items = [];
    }

    self.selectedTab = 0;
    self.buildHtml = buildHtml;
    self.setSelectedItem = setSelectedItem;
    self.removeItem = removeItem;
    self.selectedItem = null;
    $scope.onOver = onOver;
    $scope.onDrop = onDrop;
    self.templateComponents = [
      {
        id: 1,
        name: "Label",
        icon: null,
        type: 'label',
        description: "Use for static text: labels, headings, paragraphs"
      },
      {
        id: 2,
        name: "Checkbox",
        icon: null,
        type: 'checkbox',
        description: "Use for selecting multiple options"
      },
      {
        id: 3,
        name: "Radio Button",
        icon: null,
        type: 'radio',
        description: "Use when only one option needs to be selected"
      },
      {
        id: 4,
        name: "Select list",
        icon: null,
        type: 'select',
        description: "Use for selecting multiple options from a larger set"
      },
      {
        id: 5,
        name: "Text field",
        icon: null,
        type: 'text_field',
        description: "Use for short text input"
      },
      {
        id: 6,
        name: "Text Area",
        icon: null,
        type: 'text_area',
        description: "Use for longer text input"
      },
      {
        id: 7,
        name: "Image Container",
        icon: null,
        type: 'image',
        description: "A placeholder for the image"
      },
      // {
      //   id: 8,
      //   name: "Video Container",
      //   icon: null,
      //   type: 'video',
      //   description: "A placeholder for the video player"
      // },
      // {
      //   id: 9,
      //   name: "Audio Container",
      //   icon: null,
      //   type: 'audio',
      //   description: "A placeholder for the audio player"
      // }
    ];

    function buildHtml(item) {
      var html = '';
      if (item.type === 'label') {
        html = '<' + item.sub_type + '>' + item.values + '</' + item.sub_type + '>';
      }
      else if (item.type === 'image') {
        //html = ''+'';
        html = '<md-icon class="image-container" md-svg-src="' + item.icon + '"></md-icon>';
      }
      else if (item.type === 'radio') {
        html = '<md-radio-group class="template-item" ng-model="item.answer" layout="' + item.layout + '">' +
            '<md-radio-button ng-repeat="option in item.values.split(\',\')" value="{{option}}">{{option}}</md-radio-button>';
      }
      else if (item.type === 'checkbox') {
        html = '

' +
            '<md-checkbox> {{ option }}</md-checkbox>

 ';
      } else if (item.type === 'text_area') {
        html = '<md-input-container><textarea class="template-item" ng-model="item.answer" layout="' + item.layout + '"></textarea></md-input-container>';
      } else if (item.type === 'text_field') {
        html = '<md-input-container><input type="text" class="template-item" ng-model="item.answer" layout="' + item.layout + '"/></md-input-container>';
      } else if (item.type === 'select') {
        html = '<md-select class="template-item" ng-model="item.answer" layout="' + item.layout + '">' +
            '<md-option ng-repeat="option in item.values.split(\',\')" value="{{option}}">{{option}}</md-option></md-select>';
      }
      return $sce.trustAsHtml(html);
    }

    function setSelectedItem(item) {
      self.selectedItem = item;
      self.selectedTab = 1;
    }

    function removeItem(item) {
      for (var i = 0; i < self.items.length; i++) {
        if (self.items[i].id_string === item.id_string) {
          self.items.splice(i, 1);
          break;
        }
      }
      sync();
    }

    function onDrop(event, ui) {
      var item_type = $(ui.draggable).attr('data-type');
      var curId = generateId();
      if(item_type==='label') {
        var item = {
          id_string: curId,
          name: 'label' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: 'Label 1',
          role: 'display',
          sub_type: 'h4',
          layout: 'column',
          icon: null,
          data_source: null
        };
        self.items.push(item);
      }
      else if(item_type==='image') {
        var item = {
          id_string: curId,
          name: 'image_placeholder' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: null,
          role: 'display',
          sub_type: 'div',
          layout: 'column',
          icon: '/static/bower_components/material-design-icons/image/svg/production/ic_panorama_24px.svg',
          data_source: null
        };
        self.items.push(item);
      }
      else if(item_type==='radio'||item_type==='checkbox') {
        var item = {
          id_string: curId,
          name: 'select_control' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: 'Option 1',
          role: 'display',
          sub_type: 'div',
          layout: 'column',
          icon: null,
          data_source: null
        };
        self.items.push(item);

      } else if (item_type === 'text_area') {

        var item = {
          id_string: curId,
          name: 'text_area_placeholder' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: null,
          role: 'display',
          sub_type: 'div',
          layout: 'column',
          data_source: null
        };
        self.items.push(item);

      } else if (item_type === 'text_field') {

        var item = {
          id_string: curId,
          name: 'text_field_placeholder' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: null,
          role: 'display',
          sub_type: 'div',
          layout: 'column',
          data_source: null
        };
        self.items.push(item);

      } else if (item_type === 'select') {

        var item = {
          id_string: curId,
          name: 'select_placeholder' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: null,
          role: 'display',
          sub_type: 'div',
          layout: 'column',
          data_source: null
        };
        self.items.push(item);
      }
      sync();
    }

    function onOver(event, ui) {
      console.log('onOver');
    }

    function generateId() {
      return 'id' + ++idGenIndex;
    }

    function generateRandomTemplateName() {
      var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      var random = _.sample(possible, 8).join('');
      return 'template_' + random;
    }

    function sync() {
      $scope.project.currentProject.template = {
        name: self.templateName,
        items: self.items
      }
    }

    //Show Modal Pop-up of the Task Design Output
    self.showTaskDesign = function(previewButton){
      $mdDialog.show({
      template: '<md-dialog>' +
            '<md-dialog-content>' +
            '

' +
            '' +
            '<md-divider></md-divider>' +
            '
' +
            '
' +
            '

' +
            '
' +
            '
' +
            '</md-dialog-content>' +
            '</md-dialog>',
      parent: angular.element(document.body),
      scope: $scope,
      targetEvent: previewButton,
      preserveScope: true,
      clickOutsideToClose: true
    });
    };

    $scope.$on("$destroy", function() {
      Project.syncLocally($scope.project.currentProject);
    });
  }

})();<commit_msg>fixing template items roles and adding labels to text areas/fields<commit_after>/**
* TaskFeedController
* @namespace crowdsource.template.controllers
 * @author dmorina
*/
(function () {
  'use strict';

  angular
    .module('crowdsource.template.controllers')
    .controller('TemplateController', TemplateController);

    TemplateController.$inject = ['$window', '$location', '$scope', 'Template', '$filter', '$sce',
      'Project', 'Authentication', '$mdDialog'];

  /**
  * @namespace TemplateController
  */
  function TemplateController($window, $location, $scope, Template, $filter, $sce,
    Project, Authentication, $mdDialog) {
    var self = this;
    self.userAccount = Authentication.getAuthenticatedAccount();
    if (!self.userAccount) {
      $location.path('/login');
      return;
    }

    var idGenIndex = 0;

    // Retrieve from service if possible.
    $scope.project.currentProject = Project.retrieve();
    if ($scope.project.currentProject.template) {
      self.templateName = $scope.project.currentProject.template.name || generateRandomTemplateName();
      self.items = $scope.project.currentProject.template.items || [];
    } else {
      self.templateName = generateRandomTemplateName();
      self.items = [];
    }

    self.selectedTab = 0;
    self.buildHtml = buildHtml;
    self.setSelectedItem = setSelectedItem;
    self.removeItem = removeItem;
    self.selectedItem = null;
    $scope.onOver = onOver;
    $scope.onDrop = onDrop;
    self.templateComponents = [
      {
        id: 1,
        name: "Label",
        icon: null,
        type: 'label',
        description: "Use for static text: labels, headings, paragraphs"
      },
      {
        id: 2,
        name: "Checkbox",
        icon: null,
        type: 'checkbox',
        description: "Use for selecting multiple options"
      },
      {
        id: 3,
        name: "Radio Button",
        icon: null,
        type: 'radio',
        description: "Use when only one option needs to be selected"
      },
      {
        id: 4,
        name: "Select list",
        icon: null,
        type: 'select',
        description: "Use for selecting multiple options from a larger set"
      },
      {
        id: 5,
        name: "Text field",
        icon: null,
        type: 'text_field',
        description: "Use for short text input"
      },
      {
        id: 6,
        name: "Text Area",
        icon: null,
        type: 'text_area',
        description: "Use for longer text input"
      },
      {
        id: 7,
        name: "Image Container",
        icon: null,
        type: 'image',
        description: "A placeholder for the image"
      },
      // {
      //   id: 8,
      //   name: "Video Container",
      //   icon: null,
      //   type: 'video',
      //   description: "A placeholder for the video player"
      // },
      // {
      //   id: 9,
      //   name: "Audio Container",
      //   icon: null,
      //   type: 'audio',
      //   description: "A placeholder for the audio player"
      // }
    ];

    function buildHtml(item) {
      var html = '';
      if (item.type === 'label') {
        html = '<' + item.sub_type + '>' + item.values + '</' + item.sub_type + '>';
      }
      else if (item.type === 'image') {
        //html = ''+'';
        html = '<md-icon class="image-container" md-svg-src="' + item.icon + '"></md-icon>';
      }
      else if (item.type === 'radio') {
        html = '<md-radio-group class="template-item" ng-model="item.answer" layout="' + item.layout + '">' +
            '<md-radio-button ng-repeat="option in item.values.split(\',\')" value="{{option}}">{{option}}</md-radio-button>';
      }
      else if (item.type === 'checkbox') {
        html = '

' +
            '<md-checkbox> {{ option }}</md-checkbox>

 ';
      } else if (item.type === 'text_area') {
        html = '<md-input-container>'+item.values+'<textarea class="template-item" ng-model="item.answer" layout="' + item.layout + '"></textarea></md-input-container>';
      } else if (item.type === 'text_field') {
        html = '<md-input-container>'+item.values+'<input type="text" class="template-item" ng-model="item.answer" layout="' + item.layout + '"/></md-input-container>';
      } else if (item.type === 'select') {
        html = '<md-select class="template-item" ng-model="item.answer" layout="' + item.layout + '">' +
            '<md-option ng-repeat="option in item.values.split(\',\')" value="{{option}}">{{option}}</md-option></md-select>';
      }
      return $sce.trustAsHtml(html);
    }

    function setSelectedItem(item) {
      self.selectedItem = item;
      self.selectedTab = 1;
    }

    function removeItem(item) {
      for (var i = 0; i < self.items.length; i++) {
        if (self.items[i].id_string === item.id_string) {
          self.items.splice(i, 1);
          break;
        }
      }
      sync();
    }

    function onDrop(event, ui) {
      var item_type = $(ui.draggable).attr('data-type');
      var curId = generateId();
      if(item_type==='label') {
        var item = {
          id_string: curId,
          name: 'label' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: 'Label 1',
          role: 'display',
          sub_type: 'h4',
          layout: 'column',
          icon: null,
          data_source: null
        };
        self.items.push(item);
      }
      else if(item_type==='image') {
        var item = {
          id_string: curId,
          name: 'image_placeholder' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: null,
          role: 'display',
          sub_type: 'div',
          layout: 'column',
          icon: '/static/bower_components/material-design-icons/image/svg/production/ic_panorama_24px.svg',
          data_source: null
        };
        self.items.push(item);
      }
      else if(item_type==='radio'||item_type==='checkbox') {
        var item = {
          id_string: curId,
          name: 'select_control' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: 'Option 1',
          role: 'input',
          sub_type: 'div',
          layout: 'column',
          icon: null,
          data_source: null
        };
        self.items.push(item);

      } else if (item_type === 'text_area') {

        var item = {
          id_string: curId,
          name: 'text_area_placeholder' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: 'Text placeholder',
          role: 'input',
          sub_type: 'div',
          layout: 'column',
          data_source: null
        };
        self.items.push(item);

      } else if (item_type === 'text_field') {

        var item = {
          id_string: curId,
          name: 'text_field_placeholder' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: 'Text placeholder',
          role: 'input',
          sub_type: 'div',
          layout: 'column',
          data_source: null
        };
        self.items.push(item);

      } else if (item_type === 'select') {

        var item = {
          id_string: curId,
          name: 'select_placeholder' + curId,
          type: item_type,
          width: 100,
          height: 100,
          values: null,
          role: 'input',
          sub_type: 'div',
          layout: 'column',
          data_source: null
        };
        self.items.push(item);
      }
      sync();
    }

    function onOver(event, ui) {
      console.log('onOver');
    }

    function generateId() {
      return 'id' + ++idGenIndex;
    }

    function generateRandomTemplateName() {
      var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      var random = _.sample(possible, 8).join('');
      return 'template_' + random;
    }

    function sync() {
      $scope.project.currentProject.template = {
        name: self.templateName,
        items: self.items
      }
    }

    //Show Modal Pop-up of the Task Design Output
    self.showTaskDesign = function(previewButton){
      $mdDialog.show({
      template: '<md-dialog>' +
            '<md-dialog-content>' +
            '

' +
            '' +
            '<md-divider></md-divider>' +
            '
' +
            '
' +
            '

' +
            '
' +
            '
' +
            '</md-dialog-content>' +
            '</md-dialog>',
      parent: angular.element(document.body),
      scope: $scope,
      targetEvent: previewButton,
      preserveScope: true,
      clickOutsideToClose: true
    });
    };

    $scope.$on("$destroy", function() {
      Project.syncLocally($scope.project.currentProject);
    });
  }

})();<|endoftext|>


<commit_before>// I18N constants
// LANG: "ja", ENCODING: UTF-8
{
  "You must select some text before making a new link.": "リンクを作成するにはテキストを選択する必要があります",
  "Are you sure you wish to remove this link?": "本当にこのリンクを削除しますか?",
  "REMOVE LINK": "リンク削除",
  "CANCEL": "中止",
  "URL Link": "URLリンク",
  "Ordinary Link": "標準リンク",
  "Same Window (jump out of frames)": "同一ウィンドウ (フレーム最上位)",
  "New Window": "新しいウィンドウ",
  "Popup Window": "ポップアップウィンドウ",
  "Email Link": "Eメールリンク",
  "Email Address:": "アドレス:",
  "Subject:": "件名:",
  "Message Template:": "本文雛形:",
  "Size:": "サイズ:",
  "Name:": "名前:",
  "Menu Bar:": "メニュー",
  "Toolbar:": "ツールバー",
  "Location Bar:": "アドレスバー",
  "Status Bar:": "ステータスバー",
  "Scrollbars:": "スクロール",
  "Resizeable:": "リサイズ"
};<commit_msg>Japanese translation follow Lnker update [728]<commit_after>// I18N constants
// LANG: "ja", ENCODING: UTF-8
{
  "You must select some text before making a new link.": "リンクを作成するにはテキストを選択する必要があります",
  "Are you sure you wish to remove this link?": "本当にこのリンクを削除しますか?",
  "Remove Link": "リンク削除",
  "URL Link": "URLリンク",
  "Ordinary Link": "標準リンク",
  "Same Window (jump out of frames)": "同一ウィンドウ (フレーム最上位)",
  "New Window": "新しいウィンドウ",
  "Popup Window": "ポップアップウィンドウ",
  "Email Link": "Eメールリンク",
  "Email Address:": "アドレス:",
  "Subject:": "件名:",
  "Message Template:": "本文雛形:",
  "Size:": "サイズ:",
  "Name:": "名前:",
  "Menu Bar:": "メニュー",
  "Toolbar:": "ツールバー",
  "Location Bar:": "アドレスバー",
  "Status Bar:": "ステータスバー",
  "Scrollbars:": "スクロール",
  "Resizeable:": "リサイズ"
};<|endoftext|>


<commit_before>const info = {
  name: ['pl add '],
  description: 'Add a new playlist.',
  usage: '`' + config.discriminator + 'pl add [playlist name]`',
  type: CommandType.TTPlaylist
};

const playlistHandler = require(global.paths.lib + 'playlist-handler');
const tt = require(global.paths.lib + 'turntable-handler');
const Discord = require('discord.js');
const url = require('url');

const handleMessage = function(bot, message) {
  const playlistName = message.content.substring(config.discriminator.length + 7, message.content.length);

  if (!playlistName) {
    // TODO: Generate a playlist name in this situation
    return message.reply('please provide a name for this playlist!');
  }

  // If it's a YT playlist link, attempt to load all tracks
  const messageUrl = url.parse(playlistName);

  if (messageUrl.host.indexOf('youtube.com') > -1 && messageUrl.query.indexOf('list=') > -1) {
    const plStart = messageUrl.query.substring(messageUrl.query.indexOf('list='), messageUrl.query.length);

    const playlistId = plStart.substring(5, plStart.indexOf('&') > -1 ? plStart.indexOf('&') : plStart.length);

    return playlistHandler.addYoutubePlaylist(message, playlistId);
  }

  playlistHandler.addPlaylist(bot, message, playlistName);
};

const matches = function(input) {
  return _.startsWith(input, config.discriminator + 'pl add')
};

module.exports = {
  info: info,
  handleMessage: handleMessage,
  matches: matches
};
<commit_msg>Fix bounds bug in pl add<commit_after>const info = {
  name: ['pl add '],
  description: 'Add a new playlist.',
  usage: '`' + config.discriminator + 'pl add [playlist name]`',
  type: CommandType.TTPlaylist
};

const playlistHandler = require(global.paths.lib + 'playlist-handler');
const tt = require(global.paths.lib + 'turntable-handler');
const Discord = require('discord.js');
const url = require('url');

const handleMessage = function(bot, message) {
  const playlistName = message.content.substring(config.discriminator.length + 7, message.content.length);

  if (!playlistName) {
    // TODO: Generate a playlist name in this situation
    return message.reply('please provide a name for this playlist!');
  }

  // If it's a YT playlist link, attempt to load all tracks
  const messageUrl = url.parse(playlistName);

  if (messageUrl.host && messageUrl.host.indexOf('youtube.com') > -1 && messageUrl.query && messageUrl.query.indexOf('list=') > -1) {
    const plStart = messageUrl.query.substring(messageUrl.query.indexOf('list='), messageUrl.query.length);

    const playlistId = plStart.substring(5, plStart.indexOf('&') > -1 ? plStart.indexOf('&') : plStart.length);

    return playlistHandler.addYoutubePlaylist(message, playlistId);
  }

  playlistHandler.addPlaylist(bot, message, playlistName);
};

const matches = function(input) {
  return _.startsWith(input, config.discriminator + 'pl add')
};

module.exports = {
  info: info,
  handleMessage: handleMessage,
  matches: matches
};
<|endoftext|>


<commit_before>require("./patch-buffer");

var util = require("util");
var EventEmitter = require("events").EventEmitter;

var net = require("net");
var BufferReader = require("buffer-reader");

var packetTypes = {
	PACKET_SERVER_FULL: 0,
	PACKET_SERVER_FULL: 1,
	PACKET_CLIENT_JOIN: 2,
	PACKET_SERVER_ERROR: 3,
	PACKET_CLIENT_COMPANY_INFO: 4,
	PACKET_SERVER_COMPANY_INFO: 5,
	PACKET_SERVER_CHECK_NEWGRFS: 6,
	PACKET_CLIENT_NEWGRFS_CHECKED: 7,
	PACKET_SERVER_NEED_GAME_PASSWORD: 8,
	PACKET_CLIENT_GAME_PASSWORD: 9,
	PACKET_SERVER_NEED_COMPANY_PASSWORD: 10,
	PACKET_CLIENT_COMPANY_PASSWORD: 11,
	PACKET_SERVER_WELCOME: 12,
	PACKET_SERVER_CLIENT_INFO: 13,
	PACKET_CLIENT_GETMAP: 14,
	PACKET_SERVER_WAIT: 15,
	PACKET_SERVER_MAP_BEGIN: 16,
	PACKET_SERVER_MAP_SIZE: 17,
	PACKET_SERVER_MAP_DATA: 18,
	PACKET_SERVER_MAP_DONE: 19,
	PACKET_CLIENT_MAP_OK: 20,
	PACKET_SERVER_JOIN: 21,
	PACKET_SERVER_FRAME: 22,
	PACKET_CLIENT_ACK: 23,
	PACKET_SERVER_SYNC: 24,
	PACKET_CLIENT_COMMAND: 25,
	PACKET_SERVER_COMMAND: 26,
	PACKET_CLIENT_CHAT: 27,
	PACKET_SERVER_CHAT: 28,
	PACKET_CLIENT_RCON: 29,
	PACKET_SERVER_RCON: 30,
	PACKET_CLIENT_MOVE: 31,
	PACKET_SERVER_MOVE: 32,
	PACKET_CLIENT_SET_PASSWORD: 33,
	PACKET_CLIENT_SET_NAME: 34,
	PACKET_SERVER_COMPANY_UPDATE: 35,
	PACKET_SERVER_CONFIG_UPDATE: 36,
	PACKET_SERVER_NEWGAME: 37,
	PACKET_SERVER_SHUTDOWN: 38,
	PACKET_CLIENT_QUIT: 39,
	PACKET_SERVER_QUIT: 40,
	PACKET_CLIENT_ERROR: 41,
	PACKET_SERVER_ERROR_QUIT: 42,
	PACKET_END: 43,
};

function Client() {
	var self = this;

	self.socket = null;

	self.clientID = null;
	self.clients = {};
	self.ackToken = null;
	self.frameCnt = 0;

	self.on("packet", function(packet) {
		self.emit("packet#" + packet.readUInt8(0), packet.slice(1));
	});

	self.on("packet#5", function(buffer) {
		var moreData = !!buffer.readUInt8(1);
		if (!moreData) {
			/*var newGrfBuffer = new Buffer(4);
			newGrfBuffer.writeUInt32LE(0, 0);*/
			var newGrfBuffer = new Buffer([0x46, 0x6B, 0x38, 0x15]);

			var packet = Buffer.concat([
				new Buffer([0x02]),
				new Buffer("1.5.3\0"),
				newGrfBuffer,
				new Buffer("simbot\0"),
				new Buffer([0xFF, 0x00]),
			]);
			self.send(packet);
		}
	});

	self.on("packet#12", function(buffer) {
		self.clientId = buffer.readUInt32LE(0);
	});

	self.on("packet#13", function(buffer) {
		var reader = new BufferReader(buffer);

		var client = {};
		client.id = reader.nextUInt32LE();
		client.playAs = reader.nextUInt8();
		client.name = reader.nextStringZero();

		self.clients[client.id] = client;

		self.send(new Buffer([0x0E]));
	});

	self.on("packet#19", function(buffer) {
		self.send(new Buffer([0x14]));
	});

	self.on("packet#22", function(buffer) {
		var reader = new BufferReader(buffer);

		var frame = reader.nextUInt32LE();
		var frameMax = reader.nextUInt32LE();
		try {
			self.ackToken = reader.nextUInt8();
		}
		catch (e) {

		}

		if (++self.frameCnt >= 100) {
			var frameBuffer = new Buffer(4);
			frameBuffer.writeUInt32LE(frame, 0);

			var packet = Buffer.concat([
				new Buffer([0x17]),
				frameBuffer,
				new Buffer([self.ackToken]),
			]);
			self.send(packet);

			self.frameCnt = 0;
		}
	});

	self.on("packet#28", function(buffer) {
		var reader = new BufferReader(buffer);

		var chat = {
			actionId: reader.nextUInt8(),
			clientId: reader.nextUInt32LE(),
			self: !!reader.nextUInt8(),
			msg: reader.nextStringZero(),
			data: reader.nextUInt64LE(),
		};
		console.log("chat", chat);
	});

	EventEmitter.call(self);
}

util.inherits(Client, EventEmitter);

Client.prototype.connect = function(addr, port) {
	var self = this;

	self.socket = net.connect(port, addr);
	self.data = new Buffer(0);

	self.socket.on("connect", function() {
		console.log("connect");
		self.send(new Buffer([0x04]));
	});

	self.socket.on("data", function(buffer) {
		//console.log("data", buffer);
		self.data = Buffer.concat([self.data, buffer]);
		self.handle();
	});

	self.socket.on("close", function(had_error) {
		console.log("close", had_error);
	});
};

Client.prototype.send = function(packet) {
	var self = this;

	var lenBuffer = new Buffer(2);
	lenBuffer.writeUInt16LE(packet.length + lenBuffer.length, 0);

	var outBuffer = Buffer.concat([lenBuffer, packet]);
	//console.log("send", outBuffer);
	self.socket.write(outBuffer);
};

Client.prototype.handle = function() {
	var self = this;

	if (self.data.length >= 2) {
		var len = self.data.readUInt16LE(0);
		if (len <= self.data.length) {
			var packet = new Buffer(len - 2);
			self.data.copy(packet, 0, 2, len);
			//console.log("packet", packet);
			self.emit("packet", packet);

			self.data = self.data.slice(len);
			self.handle();
		}
	}
};

module.exports = Client;
<commit_msg>openttd: Client can send chat<commit_after>require("./patch-buffer");

var util = require("util");
var EventEmitter = require("events").EventEmitter;

var net = require("net");
var BufferReader = require("buffer-reader");

var packetTypes = {
	PACKET_SERVER_FULL: 0,
	PACKET_SERVER_FULL: 1,
	PACKET_CLIENT_JOIN: 2,
	PACKET_SERVER_ERROR: 3,
	PACKET_CLIENT_COMPANY_INFO: 4,
	PACKET_SERVER_COMPANY_INFO: 5,
	PACKET_SERVER_CHECK_NEWGRFS: 6,
	PACKET_CLIENT_NEWGRFS_CHECKED: 7,
	PACKET_SERVER_NEED_GAME_PASSWORD: 8,
	PACKET_CLIENT_GAME_PASSWORD: 9,
	PACKET_SERVER_NEED_COMPANY_PASSWORD: 10,
	PACKET_CLIENT_COMPANY_PASSWORD: 11,
	PACKET_SERVER_WELCOME: 12,
	PACKET_SERVER_CLIENT_INFO: 13,
	PACKET_CLIENT_GETMAP: 14,
	PACKET_SERVER_WAIT: 15,
	PACKET_SERVER_MAP_BEGIN: 16,
	PACKET_SERVER_MAP_SIZE: 17,
	PACKET_SERVER_MAP_DATA: 18,
	PACKET_SERVER_MAP_DONE: 19,
	PACKET_CLIENT_MAP_OK: 20,
	PACKET_SERVER_JOIN: 21,
	PACKET_SERVER_FRAME: 22,
	PACKET_CLIENT_ACK: 23,
	PACKET_SERVER_SYNC: 24,
	PACKET_CLIENT_COMMAND: 25,
	PACKET_SERVER_COMMAND: 26,
	PACKET_CLIENT_CHAT: 27,
	PACKET_SERVER_CHAT: 28,
	PACKET_CLIENT_RCON: 29,
	PACKET_SERVER_RCON: 30,
	PACKET_CLIENT_MOVE: 31,
	PACKET_SERVER_MOVE: 32,
	PACKET_CLIENT_SET_PASSWORD: 33,
	PACKET_CLIENT_SET_NAME: 34,
	PACKET_SERVER_COMPANY_UPDATE: 35,
	PACKET_SERVER_CONFIG_UPDATE: 36,
	PACKET_SERVER_NEWGAME: 37,
	PACKET_SERVER_SHUTDOWN: 38,
	PACKET_CLIENT_QUIT: 39,
	PACKET_SERVER_QUIT: 40,
	PACKET_CLIENT_ERROR: 41,
	PACKET_SERVER_ERROR_QUIT: 42,
	PACKET_END: 43,
};

function Client() {
	var self = this;

	self.socket = null;

	self.clientId = null;
	self.clients = {};
	self.ackToken = null;
	self.frameCnt = 0;

	self.on("packet", function(packet) {
		self.emit("packet#" + packet.readUInt8(0), packet.slice(1));
	});

	self.on("packet#5", function(buffer) {
		var moreData = !!buffer.readUInt8(1);
		if (!moreData) {
			/*var newGrfBuffer = new Buffer(4);
			newGrfBuffer.writeUInt32LE(0, 0);*/
			var newGrfBuffer = new Buffer([0x46, 0x6B, 0x38, 0x15]);

			var packet = Buffer.concat([
				new Buffer([0x02]),
				new Buffer("1.5.3\0"),
				newGrfBuffer,
				new Buffer("simbot\0"),
				new Buffer([0xFF, 0x00]),
			]);
			self.send(packet);
		}
	});

	self.on("packet#12", function(buffer) {
		self.clientId = buffer.readUInt32LE(0);
	});

	self.on("packet#13", function(buffer) {
		var reader = new BufferReader(buffer);

		var client = {};
		client.id = reader.nextUInt32LE();
		client.playAs = reader.nextUInt8();
		client.name = reader.nextStringZero();

		self.clients[client.id] = client;

		self.send(new Buffer([0x0E]));
	});

	self.on("packet#19", function(buffer) {
		self.send(new Buffer([0x14]));
	});

	self.on("packet#22", function(buffer) {
		var reader = new BufferReader(buffer);

		var frame = reader.nextUInt32LE();
		var frameMax = reader.nextUInt32LE();
		try {
			self.ackToken = reader.nextUInt8();
		}
		catch (e) {

		}

		if (++self.frameCnt >= 100) {
			var frameBuffer = new Buffer(4);
			frameBuffer.writeUInt32LE(frame, 0);

			var packet = Buffer.concat([
				new Buffer([0x17]),
				frameBuffer,
				new Buffer([self.ackToken]),
			]);
			self.send(packet);

			self.frameCnt = 0;
		}
	});

	self.on("packet#28", function(buffer) {
		var reader = new BufferReader(buffer);

		var chat = {
			actionId: reader.nextUInt8(),
			clientId: reader.nextUInt32LE(),
			self: !!reader.nextUInt8(),
			msg: reader.nextStringZero(),
			data: reader.nextUInt64LE(),
		};
		console.log("chat", chat);
	});

	EventEmitter.call(self);
}

util.inherits(Client, EventEmitter);

Client.prototype.connect = function(addr, port) {
	var self = this;

	self.socket = net.connect(port, addr);
	self.data = new Buffer(0);

	self.socket.on("connect", function() {
		console.log("connect");
		self.send(new Buffer([0x04]));
	});

	self.socket.on("data", function(buffer) {
		//console.log("data", buffer);
		self.data = Buffer.concat([self.data, buffer]);
		self.handle();
	});

	self.socket.on("close", function(had_error) {
		console.log("close", had_error);
	});
};

Client.prototype.send = function(packet) {
	var self = this;

	var lenBuffer = new Buffer(2);
	lenBuffer.writeUInt16LE(packet.length + lenBuffer.length, 0);

	var outBuffer = Buffer.concat([lenBuffer, packet]);
	//console.log("send", outBuffer);
	self.socket.write(outBuffer);
};

Client.prototype.handle = function() {
	var self = this;

	if (self.data.length >= 2) {
		var len = self.data.readUInt16LE(0);
		if (len <= self.data.length) {
			var packet = new Buffer(len - 2);
			self.data.copy(packet, 0, 2, len);
			//console.log("packet", packet);
			self.emit("packet", packet);

			self.data = self.data.slice(len);
			self.handle();
		}
	}
};

Client.prototype.chat = function(msg) {
	var self = this;

	var destBuffer = new Buffer(4);
	destBuffer.writeUInt32LE(1, 0);

	var packet = Buffer.concat([
		new Buffer([0x1B, 0x03, 0x00]),
		destBuffer,
		new Buffer(msg + "\0"),
		new Buffer(8),
	]);
	self.send(packet);
};

module.exports = Client;
<|endoftext|>


<commit_before>// Closes the sidebar menu
    $("#menu-close").click(function(e) {
        e.preventDefault();
        $("#sidebar-wrapper").toggleClass("active");
    });
    // Opens the sidebar menu
    $("#menu-toggle").click(function(e) {
        e.preventDefault();
        $("#sidebar-wrapper").toggleClass("active");
    });
    // Scrolls to the selected menu item on the page
    $(function() {
        $('a[href*=#]:not([href=#],[data-toggle],[data-target],[data-slide])').click(function() {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    //TODO - unhide the bottom pages
                    $('.pokemonInfo').css('display', 'block');
                    $('html,body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    return false;
                }
            }
        });
    });
    //#to-top button appears after scrolling
    var fixed = false;
    $(document).scroll(function() {
        if ($(this).scrollTop() > 250) {
            if (!fixed) {
                fixed = true;
                // $('#to-top').css({position:'fixed', display:'block'});
                $('#to-top').show("slow", function() {
                    $('#to-top').css({
                        position: 'fixed',
                        display: 'block'
                    });
                });
            }
        } else {
            if (fixed) {
                fixed = false;
                $('#to-top').hide("slow", function() {
                    $('#to-top').css({
                        display: 'none'
                    });
                });
            }
        }
    });
    // Disable Google Maps scrolling
    // See http://stackoverflow.com/a/25904582/1607849
    // Disable scroll zooming and bind back the click event
    var onMapMouseleaveHandler = function(event) {
        var that = $(this);
        that.on('click', onMapClickHandler);
        that.off('mouseleave', onMapMouseleaveHandler);
        that.find('iframe').css("pointer-events", "none");
    }
    var onMapClickHandler = function(event) {
            var that = $(this);
            // Disable the click handler until the user leaves the map area
            that.off('click', onMapClickHandler);
            // Enable scrolling zoom
            that.find('iframe').css("pointer-events", "auto");
            // Handle the mouse leave event
            that.on('mouseleave', onMapMouseleaveHandler);
        }
        // Enable map zooming with mouse scroll when the user clicks the map
    $('.map').on('click', onMapClickHandler);

    var findPokemon = function() {
        var a = $('#slider1').val();
        var b = $('#slider2').val();
        var c = $('#slider3').val();
        var d = $('#slider4').val();

        serverService(a, b, c, d);
        return true;
    };
    var pickColor = function(t) {
        var type = t || "normal";
        var color = "";
        switch(type) {
            case "fire":
                color = "B22222";
                break;
            case "grass":
                color = "228b22";
                break;
            case "water":
                color = "1E90FF";
                break;
            case "electric":
                color = "E6c300";
                break;
            case "poison":
                color = "8a2be2";
                break;
            case "bug":
                color = "c3df41";
                break;
            case "dark":
                color = "2d1606";
                break;
            case "ghost":
                color = "4e3cc3";
                break;
            case "normal":
                color = "cecece";
                break;
            case "fighting":
                color = "a22a2a";
                break;
            case "psychic":
                color = "f08080";
                break;
            case "rock":
                color = "d2b48c";
                break;
            case "ground":
                color = "c7a14b";
                break;
            case "steel" :
                color = "7b7c79";
                break;
            default:
                color = "black";
                break;
        }
        return color;

    }

    //Service to talk to node server
    //param: toSend represents the JSON object to post to the server
    var serverService = function(a, b, c, d) {
        //data is a single pokemon's data sent from the server
        var success = function(data, status, xhr) {
            //TODO: *figure out what data is received from the server
            //      *populate the page with the pokemon data and paragraph
            var pokeName = data.name;

            //get the pokemon move names from the json
            var moves = {};
            data.moves.forEach(function(move) {
                moves.push(move.move.name);
            });

            var spritesUrl = {
                front: data.sprites.front_default,
                frontShiny: data.sprites.front_shiny,
                back: data.sprites.back_default,
                backShiny: data.sprites.back_shiny,
            }

            var height = data.height;
            var weight = data.weight;

            //get main pokemon type
            var types = data.types[data.types.length - 1].type.name;
            /*
                get pokemon types
            data.types.forEach(function(type) {
                types.push(type.type.name);
            });*/
        }

        var piData = {
            a: a,
            b: b,
            c: c,
            d: d
        }
        console.log("1: " + a + " 2: " + b + " 3: " + c + " 4: " + d);
        //TODO: enter server url here
        var url = "enter here";

        //$.post(url, piData, success, "json");
    }

    function sliderOutputDisplay (sliderOutput, sliderProp) {
      document.sliders[sliderOutput].value = document.sliders[sliderProp].value + ' Sigma';
    }

    for (var x = 1; x < 5; x++){
      var sliderProp = "slider" + x;
      var sliderOutput = "slider" + x + "Output";

      document.sliders[sliderProp].oninput = sliderOutputDisplay.bind(undefined, sliderOutput, sliderProp);
    }
<commit_msg>Added function to change background-color<commit_after>// Closes the sidebar menu
    $("#menu-close").click(function(e) {
        e.preventDefault();
        $("#sidebar-wrapper").toggleClass("active");
    });
    // Opens the sidebar menu
    $("#menu-toggle").click(function(e) {
        e.preventDefault();
        $("#sidebar-wrapper").toggleClass("active");
    });
    // Scrolls to the selected menu item on the page
    $(function() {
        $('a[href*=#]:not([href=#],[data-toggle],[data-target],[data-slide])').click(function() {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    //TODO - unhide the bottom pages
                    $('.pokemonInfo').css('display', 'block');
                    $('html,body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    return false;
                }
            }
        });
    });
    //#to-top button appears after scrolling
    var fixed = false;
    $(document).scroll(function() {
        if ($(this).scrollTop() > 250) {
            if (!fixed) {
                fixed = true;
                // $('#to-top').css({position:'fixed', display:'block'});
                $('#to-top').show("slow", function() {
                    $('#to-top').css({
                        position: 'fixed',
                        display: 'block'
                    });
                });
            }
        } else {
            if (fixed) {
                fixed = false;
                $('#to-top').hide("slow", function() {
                    $('#to-top').css({
                        display: 'none'
                    });
                });
            }
        }
    });
    // Disable Google Maps scrolling
    // See http://stackoverflow.com/a/25904582/1607849
    // Disable scroll zooming and bind back the click event
    var onMapMouseleaveHandler = function(event) {
        var that = $(this);
        that.on('click', onMapClickHandler);
        that.off('mouseleave', onMapMouseleaveHandler);
        that.find('iframe').css("pointer-events", "none");
    }
    var onMapClickHandler = function(event) {
            var that = $(this);
            // Disable the click handler until the user leaves the map area
            that.off('click', onMapClickHandler);
            // Enable scrolling zoom
            that.find('iframe').css("pointer-events", "auto");
            // Handle the mouse leave event
            that.on('mouseleave', onMapMouseleaveHandler);
        }
        // Enable map zooming with mouse scroll when the user clicks the map
    $('.map').on('click', onMapClickHandler);

    var findPokemon = function() {
        var a = $('#slider1').val();
        var b = $('#slider2').val();
        var c = $('#slider3').val();
        var d = $('#slider4').val();

        serverService(a, b, c, d);
        return true;
    };
    var pickColor = function(t) {
        var type = t || "normal";
        var color = "";
        switch(type) {
            case "fire":
                color = "B22222";
                break;
            case "grass":
                color = "228b22";
                break;
            case "water":
                color = "1E90FF";
                break;
            case "electric":
                color = "E6c300";
                break;
            case "poison":
                color = "8a2be2";
                break;
            case "bug":
                color = "c3df41";
                break;
            case "dark":
                color = "2d1606";
                break;
            case "ghost":
                color = "4e3cc3";
                break;
            case "normal":
                color = "cecece";
                break;
            case "fighting":
                color = "a22a2a";
                break;
            case "psychic":
                color = "f08080";
                break;
            case "rock":
                color = "d2b48c";
                break;
            case "ground":
                color = "c7a14b";
                break;
            case "steel" :
                color = "7b7c79";
                break;
            default:
                color = "black";
                break;
        }
        return color;

    }

    //Service to talk to node server
    //param: toSend represents the JSON object to post to the server
    var serverService = function(a, b, c, d) {
        //data is a single pokemon's data sent from the server
        var success = function(data, status, xhr) {
            //TODO: *figure out what data is received from the server
            //      *populate the page with the pokemon data and paragraph
            var pokeName = data.name;

            //get the pokemon move names from the json
            var moves = {};
            data.moves.forEach(function(move) {
                moves.push(move.move.name);
            });

            var spritesUrl = {
                front: data.sprites.front_default,
                frontShiny: data.sprites.front_shiny,
                back: data.sprites.back_default,
                backShiny: data.sprites.back_shiny,
            }

            var height = data.height;
            var weight = data.weight;

            //get main pokemon type
            var type = data.types[data.types.length - 1].type.name;
            /*
                get pokemon types
            data.types.forEach(function(type) {
                types.push(type.type.name);
            });*/
        }

        var piData = {
            a: a,
            b: b,
            c: c,
            d: d
        }

        var type = "electric";
        $('#pokeDescription').css('background-color', '#' + pickColor(type));

        console.log("1: " + a + " 2: " + b + " 3: " + c + " 4: " + d);
        //TODO: enter server url here
        var url = "enter here";

        //$.post(url, piData, success, "json");
    }

    function sliderOutputDisplay (sliderOutput, sliderProp) {
      document.sliders[sliderOutput].value = document.sliders[sliderProp].value + ' Sigma';
    }

    for (var x = 1; x < 5; x++){
      var sliderProp = "slider" + x;
      var sliderOutput = "slider" + x + "Output";

      document.sliders[sliderProp].oninput = sliderOutputDisplay.bind(undefined, sliderOutput, sliderProp);
    }
<|endoftext|>


<commit_before>/* jQRangeSlider
 * A javascript slider selector that supports dates
 *
 * Copyright (C) Guillaume Gautreau 2012
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 */

(function(){
	var editSetup = new TestCase(
		'Setup for EditSlider',
		function(){
			el.empty();
		},
		null);

	var ctorTest = new TestCase(
		"Default ctor test",
		function(){
			el.editRangeSlider();
		},
		function(){
			ok(el.hasClass("ui-editRangeSlider"), "ui-editRangeSlider class should have been added " + el.attr("class"));

			var inputs = el.find(".ui-rangeSlider-label input.ui-editRangeSlider-inputValue");

			equal(inputs.length, 2, "Input should have been created");
			equal(inputs.attr("type"), "text", "Default type is text");
			equal(el.editRangeSlider("option", "round"), 1, "Default rounding value is 1");
		}
	);

	var destroyTest = new TestCase(
		"Destroy test",
		function(){
			el.editRangeSlider("destroy");
		},
		function(){
			equal(el.attr("class"), "", "Class should be empty after destroy");
		}
	);

	var destroy = new TestCase(
		"Destroy",
		function(){
			el.editRangeSlider("destroy");
		},
		null);

	function testDisplayedValues(min, max){
		var inputs = el.find("input"),
				first = $(inputs[0]),
				second = $(inputs[1]);

			ok(first.val() === min.toString() || first.val() === max.toString(), "Displayed value should be rounded");
			ok(second.val() === min.toString() || second.val() === max.toString(), "Displayed value should be rounded");
			ok(first.val() != second.val(), "Values should be different");
	}

	var roundCtor = new TestCase(
		"Ctor specifying the round value",
		function(){
			el.editRangeSlider({
				round: 10,
				defaultValues: {min: 11, max: 33}
			});
		},
		function(){
			equal(el.editRangeSlider("option", "round"), 10, "The round option should have been set");
			testDisplayedValues(10, 30);
		}
	);

	var setRoundOption = new TestCase(
		"Set round option",
		function(){
			el.editRangeSlider("option", "round", 1);
			el.editRangeSlider("values", 11.3, 55.5);
		},
		function(){
			var values = el.editRangeSlider("values");
			equal(values.min, 11.3, "Values should not have been rounded");
			equal(values.max, 55.5, "Values should not have been rounded");

			testDisplayedValues(11, 56);

			el.editRangeSlider("option", "round", 10);
			testDisplayedValues(10, 60);
			equal(el.editRangeSlider("option", "round"), 10, "Option should have been set");
		}
	);

	var setRoundZero = new TestCase(
		"Assign a zero value to the round",
		function(){
			el.editRangeSlider("option", "round", 1);
			el.editRangeSlider("values", 11, 55);
			el.editRangeSlider("option", "round", 0);
		},
		function(){
			equal(el.editRangeSlider("option", "round"), 1, "zero should not have been assigned");
			testDisplayedValues(11, 55);
		}
	);

	var typeCtor = new TestCase(
		"Ctor specifying input type",
		function(){
			el.editRangeSlider({
				type: "number"
			});
		},
		function(){
			equal(el.find("input").attr("type"), "number", "Input type should have been modified");
		}
	);

	var setType = new TestCase(
		"Input type setter",
		function(){},
		function(){
			testInputType("text");
			testInputType("number");
		}
	);

	function testInputType(type){
		el.editRangeSlider("option", "type", type);
		equal(el.editRangeSlider("option", "type"), type, "Type option should have been set");
		equal(el.find("input").attr("type"), type, "Type should be used by inputs");
	}

	var setInvalidType = new TestCase(
		"Invalid input type",
		function(){
			el.editRangeSlider("option", "type", "date");
		},
		function(){
			ok(el.editRangeSlider("option", "type") != "date", "Invalid input type should not be set");
			ok(el.find("input").attr("type") != "date", "Invalid input type");
		}
	);

	var enterKeyBindingTest = new TestCase(
		"Value change on enter",
		function(){
			el.editRangeSlider("values", 11, 55);

			var input = $(el.find("input")[0]);

			input.val("40")
				.simulate("keyup", {which: 13});
			this.type = "editRangeSlider";
		},
		function(){
			ok(this.min() == 40 || this.max() == 40, "Entered value should have been set");
		}
	);

	var clickBindingTest = new TestCase(
		"Value change on click",
		function(){
			el.editRangeSlider("option", "type", "number");
			el.editRangeSlider("values", 11, 55);

			var input = $(el.find("input")[0]);
			input.val("40").focus().click();
			this.type = "editRangeSlider";
		},

		function(){
			ok(this.min() == 40 || this.max() == 40, "Value should have been set")
		}
	);

	var clickBindingWithoutFocusTest = new TestCase(
		"Click on number input without focus",
		function(){
			el.editRangeSlider("option", "type", "number");
			el.editRangeSlider("values", 11, 55);
			var input = $(el.find("input")[0]);

			input.blur().val("40").click();
			this.type = "editRangeSlider";
		},
		function(){
			ok(this.min() != 40 || this.max() != 40, "Value should not have been set")
		}
	);

	var blurBinding = new TestCase(
		"Change values on blur",
		function(){
			el.editRangeSlider("values", 11, 55);

			var input = $(el.find("input")[0]);
			input.focus().val("40").blur();
			this.type = "editRangeSlider";
		},
		function(){
			ok(this.min() == 40 || this.max() == 40, "Value should have been set")
		}
	);

	testRunner.add("jQEditRangeSlider", [
		editSetup,
		ctorTest,
		destroy,

		roundCtor, setRoundOption, setRoundZero,
		destroy,

		typeCtor, setType, setInvalidType,
		enterKeyBindingTest, clickBindingTest, clickBindingWithoutFocusTest, blurBinding,

		destroyTest
	]);
})();<commit_msg>Unit tests for #27, input names based on id<commit_after>/* jQRangeSlider
 * A javascript slider selector that supports dates
 *
 * Copyright (C) Guillaume Gautreau 2012
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 */

(function(){
	var editSetup = new TestCase(
		'Setup for EditSlider',
		function(){
			el.empty();
		},
		null);

	var ctorTest = new TestCase(
		"Default ctor test",
		function(){
			el.editRangeSlider();
		},
		function(){
			ok(el.hasClass("ui-editRangeSlider"), "ui-editRangeSlider class should have been added " + el.attr("class"));

			var inputs = el.find(".ui-rangeSlider-label input.ui-editRangeSlider-inputValue");

			equal(inputs.length, 2, "Input should have been created");
			equal(inputs.attr("type"), "text", "Default type is text");
			equal(el.editRangeSlider("option", "round"), 1, "Default rounding value is 1");
		}
	);

	var destroyTest = new TestCase(
		"Destroy test",
		function(){
			el.editRangeSlider("destroy");
		},
		function(){
			equal(el.attr("class"), "", "Class should be empty after destroy");
		}
	);

	var destroy = new TestCase(
		"Destroy",
		function(){
			el.editRangeSlider("destroy");
		},
		null);

	function testDisplayedValues(min, max){
		var inputs = el.find("input"),
				first = $(inputs[0]),
				second = $(inputs[1]);

			ok(first.val() === min.toString() || first.val() === max.toString(), "Displayed value should be rounded");
			ok(second.val() === min.toString() || second.val() === max.toString(), "Displayed value should be rounded");
			ok(first.val() != second.val(), "Values should be different");
	}

	var roundCtor = new TestCase(
		"Ctor specifying the round value",
		function(){
			el.editRangeSlider({
				round: 10,
				defaultValues: {min: 11, max: 33}
			});
		},
		function(){
			equal(el.editRangeSlider("option", "round"), 10, "The round option should have been set");
			testDisplayedValues(10, 30);
		}
	);

	var setRoundOption = new TestCase(
		"Set round option",
		function(){
			el.editRangeSlider("option", "round", 1);
			el.editRangeSlider("values", 11.3, 55.5);
		},
		function(){
			var values = el.editRangeSlider("values");
			equal(values.min, 11.3, "Values should not have been rounded");
			equal(values.max, 55.5, "Values should not have been rounded");

			testDisplayedValues(11, 56);

			el.editRangeSlider("option", "round", 10);
			testDisplayedValues(10, 60);
			equal(el.editRangeSlider("option", "round"), 10, "Option should have been set");
		}
	);

	var setRoundZero = new TestCase(
		"Assign a zero value to the round",
		function(){
			el.editRangeSlider("option", "round", 1);
			el.editRangeSlider("values", 11, 55);
			el.editRangeSlider("option", "round", 0);
		},
		function(){
			equal(el.editRangeSlider("option", "round"), 1, "zero should not have been assigned");
			testDisplayedValues(11, 55);
		}
	);

	var typeCtor = new TestCase(
		"Ctor specifying input type",
		function(){
			el.editRangeSlider({
				type: "number"
			});
		},
		function(){
			equal(el.find("input").attr("type"), "number", "Input type should have been modified");
		}
	);

	var setType = new TestCase(
		"Input type setter",
		function(){},
		function(){
			testInputType("text");
			testInputType("number");
		}
	);

	function testInputType(type){
		el.editRangeSlider("option", "type", type);
		equal(el.editRangeSlider("option", "type"), type, "Type option should have been set");
		equal(el.find("input").attr("type"), type, "Type should be used by inputs");
	}

	var setInvalidType = new TestCase(
		"Invalid input type",
		function(){
			el.editRangeSlider("option", "type", "date");
		},
		function(){
			ok(el.editRangeSlider("option", "type") != "date", "Invalid input type should not be set");
			ok(el.find("input").attr("type") != "date", "Invalid input type");
		}
	);

	var enterKeyBindingTest = new TestCase(
		"Value change on enter",
		function(){
			el.editRangeSlider("values", 11, 55);

			var input = $(el.find("input")[0]);

			input.val("40")
				.simulate("keyup", {which: 13});
			this.type = "editRangeSlider";
		},
		function(){
			ok(this.min() == 40 || this.max() == 40, "Entered value should have been set");
		}
	);

	var clickBindingTest = new TestCase(
		"Value change on click",
		function(){
			el.editRangeSlider("option", "type", "number");
			el.editRangeSlider("values", 11, 55);

			var input = $(el.find("input")[0]);
			input.val("40").focus().click();
			this.type = "editRangeSlider";
		},

		function(){
			ok(this.min() == 40 || this.max() == 40, "Value should have been set")
		}
	);

	var clickBindingWithoutFocusTest = new TestCase(
		"Click on number input without focus",
		function(){
			el.editRangeSlider("option", "type", "number");
			el.editRangeSlider("values", 11, 55);
			var input = $(el.find("input")[0]);

			input.blur().val("40").click();
			this.type = "editRangeSlider";
		},
		function(){
			ok(this.min() != 40 || this.max() != 40, "Value should not have been set")
		}
	);

	var blurBinding = new TestCase(
		"Change values on blur",
		function(){
			el.editRangeSlider("values", 11, 55);

			var input = $(el.find("input")[0]);
			input.focus().val("40").blur();
			this.type = "editRangeSlider";
		},
		function(){
			ok(this.min() == 40 || this.max() == 40, "Value should have been set")
		}
	);

	var nameBasedOnId = new TestCase(
		"#27 name based on id",
		function(){
		},
		function(){
			equal(el.find(".ui-rangeSlider-leftLabel input").attr("name"), "testleft");
			equal(el.find(".ui-rangeSlider-rightLabel input").attr("name"), "testright");
		}
	);

	testRunner.add("jQEditRangeSlider", [
		editSetup,
		ctorTest,
		destroy,

		roundCtor, setRoundOption, setRoundZero,
		destroy,

		typeCtor, setType, setInvalidType,
		enterKeyBindingTest, clickBindingTest, clickBindingWithoutFocusTest, blurBinding,
		nameBasedOnId,

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


<commit_before>

if (Meteor.is_client) {
  Meteor.startup(function () {
    if (! Session.get("input"))
      Session.set("input", "var x = 3");
    if (! Session.get("output-type"))
      Session.set("output-type", "parse");
  });

  Template.page.input = function () {
    return Session.get("input") || '';
  };

  Template.page.output = function () {
    var input = Session.get("input") || "";

    var outputType = Session.get("output-type");

    if (outputType === "lex") {
      // LEXER

      var lexer = new JSLexer(input);
      var html = "";
      var L;
      do {
        L = lexer.next();
        var content;
        if (L.type() === "NEWLINE") {
          content = '
';
        } else if (L.type() === "EOF") {
          content = Handlebars._escape("<EOF>");
        } else {
          content = Handlebars._escape(L.text() || ' ');
          content = content.replace(/(?!.)\s/g, '
'); // for multiline comments
          content = content.replace(/\s/g, ' ');
        }
        html += Spark.setDataContext(
          L,
          '' +
            content + '');
      } while (! L.isError() && ! L.isEOF());
      return new Handlebars.SafeString(html);

    } else if (outputType === "parse") {

      // PARSER
      var html;
      var tree = null;
      var parser = new JSParser(input, {includeComments: true});
      try {
        tree = parser.getSyntaxTree();
      } catch (parseError) {
        var errorLexeme = parser.lexer.lastLexeme;

        html = Handlebars._escape(
          input.substring(0, errorLexeme.startPos()));
        html += Spark.setDataContext(
          errorLexeme,
          '' +
            Handlebars._escape(errorLexeme.text() || '<EOF>') +
            '');
        html = html.replace(/(?!.)\s/g, '
');
        html += '
' +
          Handlebars._escape(parseError.toString()) + '
';
      }
      if (tree) {
        var curPos = 0;
        var unclosedInfos = [];
        var toHtml = function (obj) {
          if (obj instanceof ParseNode) {
            var head = obj.name || '';
            var children = obj.children;
            var info = { startPos: curPos };
            var isStatement = (head.indexOf('Stmnt') >= 0 ||
                               head === "comment" ||
                               head === "functionDecl");
            var html = Spark.setDataContext(
              info,
              '

' + Handlebars._escape(head) + '
' +
                _.map(children, toHtml).join('') + '
');
            unclosedInfos.push(info);
            return html;
          } else if (obj.text) {
            // token
            _.each(unclosedInfos, function (info) {
              info.endPos = curPos;
            });
            curPos = obj.endPos();
            unclosedInfos.length = 0;
            var text = obj.text();
            // insert zero-width spaces to allow wrapping
            text = text.replace(/.{20}/g, "$&\u200b");
            text = Handlebars._escape(text);
            text = text.replace(/\u200b/g, '');
            text = text.replace(/\n/g, '
');
            return Spark.setDataContext(
              obj,
              '
' + text + '
');
          } else {
            // other?
            return '
' +
              Handlebars._escape(JSON.stringify(obj)) + '
';
          }
        };
        html = toHtml(tree);
        curPos = parser.lexer.pos;
        _.each(unclosedInfos, function (info) {
          info.endPos = curPos;
        });
      }

      return new Handlebars.SafeString(html);
    }
    else return ''; // unknown output tab?
  };

  Template.page.events({
    'keyup #inputarea textarea': function (event) {
      var input = event.currentTarget.value;
      Session.set("input", input);
    },
    'mouseover .box.named, mouseover .box.token': function (event) {
      event.currentTarget.setAttribute('mousehover', 'mousehover');
      event.stopImmediatePropagation();
    },
    'mouseout .box.named, mouseout .box.token': function (event) {
      event.currentTarget.removeAttribute('mousehover');
      event.stopImmediatePropagation();
    },
    'click .box.token': function (event) {
      selectInputText(this.startPos(), this.endPos());
      return false;
    },
    'click .box.named': function (event) {
      selectInputText(this.startPos, this.endPos);
      return false;
    },
    'click .parseerror': function (event) {
      selectInputText(this.startPos(), this.endPos());
      return false;
    },
    'click .output-type': function (event) {
      Session.set("output-type", this.value);
    },
    'click .lex': function (event) {
      selectInputText(this.startPos(), this.endPos());
      return false;
    },
  });

  Template.page.outputTypes = [
    {name: "Lex", value: "lex"},
    {name: "Parse", value: "parse"}
  ];

  Template.page.is_outputtype_selected = function (which) {
    return Session.equals("output-type", which) ? "selected" : "";
  };

  var selectTextInArea = function (e, start, end){
    e.focus();
    if (e.setSelectionRange) {
      e.setSelectionRange(start, end);
    } else if (e.createTextRange) {
      var r = e.createTextRange();
      r.collapse(true);
      r.moveEnd('character', end);
      r.moveStart('character', start);
      r.select();
    }
  };

  var selectInputText = function (start, end) {
    var textarea = DomUtils.find(document, '#inputarea textarea');
    selectTextInArea(textarea, start, end);
  };

}
<commit_msg>rename tabs to JS Lex and JS Parse<commit_after>

if (Meteor.is_client) {
  Meteor.startup(function () {
    if (! Session.get("input"))
      Session.set("input", "var x = 3");
    if (! Session.get("output-type"))
      Session.set("output-type", "jsparse");
  });

  Template.page.input = function () {
    return Session.get("input") || '';
  };

  Template.page.output = function () {
    var input = Session.get("input") || "";

    var outputType = Session.get("output-type");

    if (outputType === "jslex") {
      // LEXER

      var lexer = new JSLexer(input);
      var html = "";
      var L;
      do {
        L = lexer.next();
        var content;
        if (L.type() === "NEWLINE") {
          content = '
';
        } else if (L.type() === "EOF") {
          content = Handlebars._escape("<EOF>");
        } else {
          content = Handlebars._escape(L.text() || ' ');
          content = content.replace(/(?!.)\s/g, '
'); // for multiline comments
          content = content.replace(/\s/g, ' ');
        }
        html += Spark.setDataContext(
          L,
          '' +
            content + '');
      } while (! L.isError() && ! L.isEOF());
      return new Handlebars.SafeString(html);

    } else if (outputType === "jsparse") {

      // PARSER
      var html;
      var tree = null;
      var parser = new JSParser(input, {includeComments: true});
      try {
        tree = parser.getSyntaxTree();
      } catch (parseError) {
        var errorLexeme = parser.lexer.lastLexeme;

        html = Handlebars._escape(
          input.substring(0, errorLexeme.startPos()));
        html += Spark.setDataContext(
          errorLexeme,
          '' +
            Handlebars._escape(errorLexeme.text() || '<EOF>') +
            '');
        html = html.replace(/(?!.)\s/g, '
');
        html += '
' +
          Handlebars._escape(parseError.toString()) + '
';
      }
      if (tree) {
        var curPos = 0;
        var unclosedInfos = [];
        var toHtml = function (obj) {
          if (obj instanceof ParseNode) {
            var head = obj.name || '';
            var children = obj.children;
            var info = { startPos: curPos };
            var isStatement = (head.indexOf('Stmnt') >= 0 ||
                               head === "comment" ||
                               head === "functionDecl");
            var html = Spark.setDataContext(
              info,
              '

' + Handlebars._escape(head) + '
' +
                _.map(children, toHtml).join('') + '
');
            unclosedInfos.push(info);
            return html;
          } else if (obj.text) {
            // token
            _.each(unclosedInfos, function (info) {
              info.endPos = curPos;
            });
            curPos = obj.endPos();
            unclosedInfos.length = 0;
            var text = obj.text();
            // insert zero-width spaces to allow wrapping
            text = text.replace(/.{20}/g, "$&\u200b");
            text = Handlebars._escape(text);
            text = text.replace(/\u200b/g, '');
            text = text.replace(/\n/g, '
');
            return Spark.setDataContext(
              obj,
              '
' + text + '
');
          } else {
            // other?
            return '
' +
              Handlebars._escape(JSON.stringify(obj)) + '
';
          }
        };
        html = toHtml(tree);
        curPos = parser.lexer.pos;
        _.each(unclosedInfos, function (info) {
          info.endPos = curPos;
        });
      }

      return new Handlebars.SafeString(html);
    }
    else return ''; // unknown output tab?
  };

  Template.page.events({
    'keyup #inputarea textarea': function (event) {
      var input = event.currentTarget.value;
      Session.set("input", input);
    },
    'mouseover .box.named, mouseover .box.token': function (event) {
      event.currentTarget.setAttribute('mousehover', 'mousehover');
      event.stopImmediatePropagation();
    },
    'mouseout .box.named, mouseout .box.token': function (event) {
      event.currentTarget.removeAttribute('mousehover');
      event.stopImmediatePropagation();
    },
    'click .box.token': function (event) {
      selectInputText(this.startPos(), this.endPos());
      return false;
    },
    'click .box.named': function (event) {
      selectInputText(this.startPos, this.endPos);
      return false;
    },
    'click .parseerror': function (event) {
      selectInputText(this.startPos(), this.endPos());
      return false;
    },
    'click .output-type': function (event) {
      Session.set("output-type", this.value);
    },
    'click .lex': function (event) {
      selectInputText(this.startPos(), this.endPos());
      return false;
    },
  });

  Template.page.outputTypes = [
    {name: "JS Lex", value: "jslex"},
    {name: "JS Parse", value: "jsparse"}
  ];

  Template.page.is_outputtype_selected = function (which) {
    return Session.equals("output-type", which) ? "selected" : "";
  };

  var selectTextInArea = function (e, start, end){
    e.focus();
    if (e.setSelectionRange) {
      e.setSelectionRange(start, end);
    } else if (e.createTextRange) {
      var r = e.createTextRange();
      r.collapse(true);
      r.moveEnd('character', end);
      r.moveStart('character', start);
      r.select();
    }
  };

  var selectInputText = function (start, end) {
    var textarea = DomUtils.find(document, '#inputarea textarea');
    selectTextInArea(textarea, start, end);
  };

}
<|endoftext|>


<commit_before>describe('Functions', function() {
	it('should return true when checking a string with isString', function() {
		expect(leaf.isString('John Doe')).toBe(true);
	});

	it('should return true when checking a number with isNumber', function() {
		expect(leaf.isNumber(1)).toBe(true);
	});

	it('should return true when checking a Boolean with isBoolean', function() {
		expect(leaf.isBoolean(true)).toBe(true);
	});

	it('should return true when checking an Array with isArray', function() {
		expect(leaf.isArray([1,2,3])).toBe(true);
	});

	it('should return true when checking a Function with isFunction', function() {
		expect(leaf.isFunction(function() {})).toBe(true);
	});

	it('should return true when checking an Object with isObject', function() {
		expect(leaf.isObject({})).toBe(true);
	});

	it('should return true when checking a Date with isDate', function() {
		expect(leaf.isDate(new Date())).toBe(true);
	});

	it('should return true when checking a defined variable with isDefined', function() {
		var person = 'John Doe';

		expect(leaf.isDefined(person).toBe(true);
	});

	it('should return true when checking an udefined variable with isUndefined', function() {
		var person;

		expect(leaf.isUndefined(person).toBe(true);
	});

	it('should return true when checking a null value with isNull', function() {
		expect(leaf.isNull('').toBe(true);
	});
});
<commit_msg>Updated<commit_after>describe('Functions', function() {
	it('should return true when checking a string with isString', function() {
		expect(leaf.isString('John Doe')).toBe(true);
	});

	it('should return true when checking a number with isNumber', function() {
		expect(leaf.isNumber(1)).toBe(true);
	});

	it('should return true when checking a Boolean with isBoolean', function() {
		expect(leaf.isBoolean(true)).toBe(true);
	});

	it('should return true when checking an Array with isArray', function() {
		expect(leaf.isArray([1,2,3])).toBe(true);
	});

	it('should return true when checking a Function with isFunction', function() {
		expect(leaf.isFunction(function() {})).toBe(true);
	});

	it('should return true when checking an Object with isObject', function() {
		expect(leaf.isObject({})).toBe(true);
	});

	it('should return true when checking a Date with isDate', function() {
		expect(leaf.isDate(new Date())).toBe(true);
	});

	it('should return true when checking a defined variable with isDefined', function() {
		var person = 'John Doe';

		expect(leaf.isDefined(person)).toBe(true);
	});

	it('should return true when checking an udefined variable with isUndefined', function() {
		var person;

		expect(leaf.isUndefined(person)).toBe(true);
	});

	it('should return true when checking a null value with isNull', function() {
		expect(leaf.isNull('')).toBe(true);
	});
});
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////

'use strict';

var TESTS = {
    ListTests: require('./list-tests'),
    ObjectTests: require('./object-tests'),
    RealmTests: require('./realm-tests'),
    ResultsTests: require('./results-tests'),
    QueryTests: require('./query-tests'),
    QueryTests: require('./encryption-tests'),
};

var SPECIAL_METHODS = {
    beforeEach: true,
    afterEach: true,
};

exports.getTestNames = function() {
    var testNames = {};

    for (var suiteName in TESTS) {
        var testSuite = TESTS[suiteName];

        testNames[suiteName] = Object.keys(testSuite).filter(function(testName) {
            return !(testName in SPECIAL_METHODS) && typeof testSuite[testName] == 'function';
        });
    }

    return testNames;
};

exports.registerTests = function(tests) {
    for (var suiteName in tests) {
        TESTS[suiteName] = tests[suiteName];
    }
};

exports.runTest = function(suiteName, testName) {
    var testSuite = TESTS[suiteName];
    var testMethod = testSuite && testSuite[testName];

    if (testMethod) {
        testMethod.call(testSuite);
    } else if (!testSuite || !(testName in SPECIAL_METHODS)) {
        throw new Error('Missing test: ' + suiteName + '.' + testName);
    }
};
<commit_msg>fix for test naming<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////

'use strict';

var TESTS = {
    ListTests: require('./list-tests'),
    ObjectTests: require('./object-tests'),
    RealmTests: require('./realm-tests'),
    ResultsTests: require('./results-tests'),
    QueryTests: require('./query-tests'),
    EncryptionTests: require('./encryption-tests'),
};

var SPECIAL_METHODS = {
    beforeEach: true,
    afterEach: true,
};

exports.getTestNames = function() {
    var testNames = {};

    for (var suiteName in TESTS) {
        var testSuite = TESTS[suiteName];

        testNames[suiteName] = Object.keys(testSuite).filter(function(testName) {
            return !(testName in SPECIAL_METHODS) && typeof testSuite[testName] == 'function';
        });
    }

    return testNames;
};

exports.registerTests = function(tests) {
    for (var suiteName in tests) {
        TESTS[suiteName] = tests[suiteName];
    }
};

exports.runTest = function(suiteName, testName) {
    var testSuite = TESTS[suiteName];
    var testMethod = testSuite && testSuite[testName];

    if (testMethod) {
        testMethod.call(testSuite);
    } else if (!testSuite || !(testName in SPECIAL_METHODS)) {
        throw new Error('Missing test: ' + suiteName + '.' + testName);
    }
};
<|endoftext|>