<commit_before>export { Base, Root };

import * as Pool from "../Pool.js";

/**
 * The base class representing a object could be recycled (i.e. disposed without release its main object memory for re-using in the
 * future).
 *
 * Every sub-class of this Recyclable.Base MUST define a static propery named Pool which is usually an instance of Pool.Base:
 *

 * class SomeClass extends Recyclable.Base {
 *
 *   static Pool = new Pool.Root( "SomeNamespace.SomeClass", SomeClass, SomeClass.setAsConstructor );
 *
 *   static setAsConstructor( ...restArgs ) {
 *     super.setAsConstructor.apply( restArgs ); // All other arguments passed to parent class.
 *
 *       :
 *
 *     return this;
 *   }
 *
 * }
 *

 *
 * Or,
 *

 * class SomeClass extends Recyclable.Base {
 *
 *   ... (if static property definition is not supported by your web browser) ...
 *
 * }
 *
 * SomeClass.Pool = new Pool.Root( "SomeNamespace.SomeClass", SomeClass, SomeClass.setAsConstructor );
 *
 *

 *
 *
 */
let Base = ( ParentClass = Object ) => class Base extends ParentClass {

  /**
   * Sub-class's constructor could call itself SubClassXxx.setAsConstructor() (i.e. not call Base.setAsConstructor() directly here).
   */
  constructor( ...restArgs ) {
    super( ...restArgs );
    Base.setAsConstructor.call( this );
  }

  /**
   * Sub-class should override this static method (and call super.setAsConstructor() in the beginning of this method).
   *
   * @param {Base} this
   *   The Recyclable.Base object to be initialized.
   *
   * @return {Base}
   *   Return the this object.
   */
  static setAsConstructor( ...restArgs ) {

    if ( super.setAsConstructor instanceof Function ) // If parent class has the same method, call it.
      super.setAsConstructor.apply( this, restArgs );

    // Nothing to do here (for Recyclable.Base).

    return this;
  }

  /**
   * Sub-class should override this method (and call super.disposeResources() before return).
   */
  disposeResources() {

    // Nothing to do here (for Recyclable.Base).

    if ( super.disposeResources instanceof Function ) // If parent class has the same method, call it.
      super.disposeResources();
  }

  /**
   * This method will do the following in sequence:
   *   - call this.disposeResources() (if exists)
   *   - call this.constructor.Pool.recycle()
   *
   * Sub-class should NEVER override this method (so NEVER call super.disposeResources_and_recycleToPool()).
   *
   *
   * After calling this method, this object should be viewed as disposed and should not be operated again.
   */
  disposeResources_and_recycleToPool() {
    this.disposeResources();
    this.constructor.Pool.recycle( this );
  }

}

/**
 * Almost the same as Recyclable.Base class except its parent class is fixed to Object. In other words, caller can not specify the
 * parent class of Recyclable.Root (so it is named "Root" which can not have parent class).
 */
class Root extends Base() {
}

<commit_msg>Update Recyclable_Base.js<commit_after>export { Base, Root };

import * as Pool from "../Pool.js";

/**
 * The base class representing a object could be recycled (i.e. disposed without release its main object memory for re-using in the
 * future).
 *
 * Every sub-class of this Recyclable.Base MUST define a static propery named Pool which is usually an instance of Pool.Base:
 *

 * class SomeClass extends Recyclable.Base {
 *
 *   static Pool = new Pool.Root( "SomeNamespace.SomeClass", SomeClass, SomeClass.setAsConstructor );
 *
 *   static setAsConstructor( ...restArgs ) {
 *     super.setAsConstructor.apply( restArgs ); // All other arguments passed to parent class.
 *
 *       :
 *
 *     return this;
 *   }
 *
 * }
 *

 *
 * Or,
 *

 * class SomeClass extends Recyclable.Base {
 *
 *   ... (if static property definition is not supported by your web browser) ...
 *
 * }
 *
 * SomeClass.Pool = new Pool.Root( "SomeNamespace.SomeClass", SomeClass, SomeClass.setAsConstructor );
 *
 *

 *
 *
 */
let Base = ( ParentClass = Object ) => class Base extends ParentClass {

  ///**
  // * Sub-class's constructor could call itself SubClassXxx.setAsConstructor() (i.e. not call Base.setAsConstructor() directly here).
  // */
  //constructor( ...restArgs ) {
  //  super( ...restArgs );
  //  Base.setAsConstructor.call( this );
  //}

  /**
   * Sub-class should override this static method (and call super.setAsConstructor() in the beginning of this method).
   *
   * @param {Base} this
   *   The Recyclable.Base object to be initialized.
   *
   * @return {Base}
   *   Return the this object.
   */
  static setAsConstructor( ...restArgs ) {

    if ( super.setAsConstructor instanceof Function ) // If parent class has the same method, call it.
      super.setAsConstructor.apply( this, restArgs );

    // Nothing to do here (for Recyclable.Base).

    return this;
  }

  /**
   * Sub-class should override this method (and call super.disposeResources() before return).
   */
  disposeResources() {

    // Nothing to do here (for Recyclable.Base).

    if ( super.disposeResources instanceof Function ) // If parent class has the same method, call it.
      super.disposeResources();
  }

  /**
   * This method will do the following in sequence:
   *   - call this.disposeResources() (if exists)
   *   - call this.constructor.Pool.recycle()
   *
   * Sub-class should NEVER override this method (so NEVER call super.disposeResources_and_recycleToPool()).
   *
   *
   * After calling this method, this object should be viewed as disposed and should not be operated again.
   */
  disposeResources_and_recycleToPool() {
    this.disposeResources();
    this.constructor.Pool.recycle( this );
  }

}

/**
 * Almost the same as Recyclable.Base class except its parent class is fixed to Object. In other words, caller can not specify the
 * parent class of Recyclable.Root (so it is named "Root" which can not have parent class).
 */
class Root extends Base() {
}

<|endoftext|>


<commit_before>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you 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.
 */

// load the master sakai object to access all Sakai OAE API methods
require(["jquery", "sakai/sakai.api.core"], function($, sakai) {

    /**
     * @name sakai.htmlblock
     *
     * @class htmlblock
     *
     * @description
     * WIDGET DESCRIPTION
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.htmlblock = function (tuid, showSettings, widgetData) {
        var $rootel = $("#" + tuid);

        var autoSavePoll = false;
        var $toolbar = false;
        var id = false;
        var lastData = "";
        if (widgetData && widgetData.htmlblock){
            lastData = widgetData.htmlblock.content;
        }

        $(window).bind("resize.contentauthoring.sakai", function(){
            updateHeight();
        });
        var updateHeight = function(){
            var $element = $("#" + id + "_ifr");
            if ($element.length){
                try {
                    var docHt = 0, sh, oh;
                    var frame = $element[0];
                    $element.contents().scrollTop(0);
                    var innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
                    $element.css("height", "25px");
                    docHt = sh = innerDoc.body.scrollHeight; docHt = oh = innerDoc.body.offsetHeight;
                    if (sh && oh) {
                        docHt = oh;
                    } else {
                        docHt = sh;
                    }
                    if (docHt < 25){
                        docHt = 25;
                    }
                    if ($element.height() !== docHt) {
                        $element.css("height", docHt + "px");
                    }
                } catch (err){
                    return false;
                }
            }
        }

        var initTinyMCE = function(ui){
            id = ui.id;
            $editor = $("#" + id + "_ifr");
            $toolbar = $("#" + id + "_external");
            $toolbar.css("display", "none");
            $("#inserterbar_widget #inserterbar_tinymce_container").append($toolbar);
            setTimeout(updateHeight, 500);

            // Start the autosave
            if (autoSavePoll){
                clearInterval(autoSavePoll);
                autoSavePoll = false;
            }
            autoSavePoll = setInterval(autoSave, 5000);
            $(window).bind("save.contentauthoring.sakai", function(){
                if ($rootel.is(":visible")) {
                    autoSave();
                    var currentText = tinyMCE.get(id).getContent();
                    $("#htmlblock_view_container", $rootel).html(currentText);
                    sakai.api.Util.renderMath($rootel);
                }
            });
        };

        var stopAutosave = function(){
            if (autoSavePoll){
                clearInterval(autoSavePoll);
                autoSavePoll = false;
            }
            $(window).unbind("save.contentauthoring.sakai");
        }

        var autoSave = function(){
            var currentText = tinyMCE.get(id).getContent();
            if (currentText !== lastData){
                lastData = currentText;
                sakai.api.Widgets.saveWidgetData(tuid, {"content": currentText});
            }
        };

        var tinyMCEEvent = function(ev, ui){
            if ($editor && (!ev || !ev.type || ev.type === "click" || ev.type === "keyup" || ev.type === "mouseup" || ev.type === "paste")) {
                updateHeight();
            }
            return true;
        };

        /**
         * Initialization function DOCUMENTATION
         */
        var doInit = function () {
            if (showSettings){

            } else {
                var $textarea = $("textarea", $rootel).attr("name", tuid).addClass(tuid);
                if (widgetData && widgetData.htmlblock) {
                    var processedContent = sakai.api.i18n.General.process(widgetData.htmlblock.content);
                    $("#htmlblock_view_container", $rootel).html(processedContent);
                    sakai.api.Util.renderMath($rootel);
                    // Fill up the textarea
                    $textarea.val(widgetData.htmlblock.content);
                }
                $textarea.css("height", $("#htmlblock_view_container", $rootel).height());
                if (window["tinyMCE"]) {
                    tinyMCE.init({
                        mode: "textareas",
                        theme: "advanced",
                        skin: "sakai",
                        formats: {
                              "caption": {
                                  "inline": 'span',
                                  "classes": 'caption'
                              }
                        },
                        content_css: "/dev/css/sakai/main.css,/dev/css/sakai/sakai.corev1.css",
                        plugins: "table,advlink,contextmenu,paste,directionality",
                        theme_advanced_blockformats: "h1,h2,h3,h4,h5,h6,p,blockquote,caption",
                        theme_advanced_buttons1: "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontsizeselect,|,bullist,numlist,|,forecolor,|,table,code",
                        theme_advanced_buttons2: "",
                        theme_advanced_buttons3: "",
                        theme_advanced_toolbar_location: "external",
                        theme_advanced_toolbar_align: "left",
                        theme_advanced_statusbar_location: "none",
                        theme_advanced_resizing: false,
                        editor_selector: tuid,
                        handle_event_callback: tinyMCEEvent,
                        init_instance_callback: initTinyMCE,
                        remove_instance_callback: stopAutosave,
                        setup : function(ed) {
                            ed.onClick.add(function(ed, e) {
                                $("#inserterbar_widget #inserterbar_tinymce_container").show();
                                $(".contentauthoring_cell_element_actions").hide();
                            });
                            ed.onInit.add(function(ed) {
                                ed.focus();
                                $(".contentauthoring_cell_element_actions").hide();
                            });
                        }
                    });
                }
            }
        };

        // run the initialization function when the widget object loads
        doInit();
    };

    // inform Sakai OAE that this widget has loaded and is ready to run
    sakai.api.Widgets.widgetLoader.informOnLoad("htmlblock");
});
<commit_msg>SAKIII-4925 Cannot access entire set of World template content<commit_after>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you 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.
 */

// load the master sakai object to access all Sakai OAE API methods
require(["jquery", "sakai/sakai.api.core"], function($, sakai) {

    /**
     * @name sakai.htmlblock
     *
     * @class htmlblock
     *
     * @description
     * WIDGET DESCRIPTION
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.htmlblock = function (tuid, showSettings, widgetData) {
        var $rootel = $("#" + tuid);

        var autoSavePoll = false;
        var $toolbar = false;
        var id = false;
        var lastData = "";
        if (widgetData && widgetData.htmlblock){
            lastData = widgetData.htmlblock.content;
        }

        $(window).bind("resize.contentauthoring.sakai", function(){
            updateHeight();
        });
        var updateHeight = function(){
            var $element = $("#" + id + "_ifr");
            if ($element.length){
                try {
                    var docHt = 0, sh, oh;
                    var frame = $element[0];
                    $element.contents().scrollTop(0);
                    var innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
                    $element.css("height", "25px");
                    docHt = innerDoc.body.scrollHeight;
                    if (docHt < 25){
                        docHt = 25;
                    }
                    if ($element.height() !== docHt) {
                        $element.css("height", docHt + "px");
                    }
                } catch (err){
                    return false;
                }
            }
        }

        var initTinyMCE = function(ui){
            id = ui.id;
            $editor = $("#" + id + "_ifr");
            $toolbar = $("#" + id + "_external");
            $toolbar.css("display", "none");
            $("#inserterbar_widget #inserterbar_tinymce_container").append($toolbar);
            setTimeout(updateHeight, 500);

            // Start the autosave
            if (autoSavePoll){
                clearInterval(autoSavePoll);
                autoSavePoll = false;
            }
            autoSavePoll = setInterval(autoSave, 5000);
            $(window).bind("save.contentauthoring.sakai", function(){
                if ($rootel.is(":visible")) {
                    autoSave();
                    var currentText = tinyMCE.get(id).getContent();
                    $("#htmlblock_view_container", $rootel).html(currentText);
                    sakai.api.Util.renderMath($rootel);
                }
            });
        };

        var stopAutosave = function(){
            if (autoSavePoll){
                clearInterval(autoSavePoll);
                autoSavePoll = false;
            }
            $(window).unbind("save.contentauthoring.sakai");
        }

        var autoSave = function(){
            var currentText = tinyMCE.get(id).getContent();
            if (currentText !== lastData){
                lastData = currentText;
                sakai.api.Widgets.saveWidgetData(tuid, {"content": currentText});
            }
        };

        var tinyMCEEvent = function(ev, ui){
            if ($editor && (!ev || !ev.type || ev.type === "click" || ev.type === "keyup" || ev.type === "mouseup" || ev.type === "paste")) {
                updateHeight();
            }
            return true;
        };

        /**
         * Initialization function DOCUMENTATION
         */
        var doInit = function () {
            if (showSettings){

            } else {
                var $textarea = $("textarea", $rootel).attr("name", tuid).addClass(tuid);
                if (widgetData && widgetData.htmlblock) {
                    var processedContent = sakai.api.i18n.General.process(widgetData.htmlblock.content);
                    $("#htmlblock_view_container", $rootel).html(processedContent);
                    sakai.api.Util.renderMath($rootel);
                    // Fill up the textarea
                    $textarea.val(widgetData.htmlblock.content);
                }
                $textarea.css("height", $("#htmlblock_view_container", $rootel).height());
                if (window["tinyMCE"]) {
                    tinyMCE.init({
                        mode: "textareas",
                        theme: "advanced",
                        skin: "sakai",
                        formats: {
                              "caption": {
                                  "inline": 'span',
                                  "classes": 'caption'
                              }
                        },
                        content_css: "/dev/css/sakai/main.css,/dev/css/sakai/sakai.corev1.css",
                        plugins: "table,advlink,contextmenu,paste,directionality",
                        theme_advanced_blockformats: "h1,h2,h3,h4,h5,h6,p,blockquote,caption",
                        theme_advanced_buttons1: "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontsizeselect,|,bullist,numlist,|,forecolor,|,table,code",
                        theme_advanced_buttons2: "",
                        theme_advanced_buttons3: "",
                        theme_advanced_toolbar_location: "external",
                        theme_advanced_toolbar_align: "left",
                        theme_advanced_statusbar_location: "none",
                        theme_advanced_resizing: false,
                        editor_selector: tuid,
                        handle_event_callback: tinyMCEEvent,
                        init_instance_callback: initTinyMCE,
                        remove_instance_callback: stopAutosave,
                        setup : function(ed) {
                            ed.onClick.add(function(ed, e) {
                                $("#inserterbar_widget #inserterbar_tinymce_container").show();
                                $(".contentauthoring_cell_element_actions").hide();
                            });
                            ed.onInit.add(function(ed) {
                                ed.focus();
                                $(".contentauthoring_cell_element_actions").hide();
                            });
                        }
                    });
                }
            }
        };

        // run the initialization function when the widget object loads
        doInit();
    };

    // inform Sakai OAE that this widget has loaded and is ready to run
    sakai.api.Widgets.widgetLoader.informOnLoad("htmlblock");
});
<|endoftext|>


<commit_before>Meteor.subscribe('events');
Meteor.subscribe('groups');

var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

Template.calendar.created = function() {
	Session.set('selectedMonth', moment().startOf('month').toDate());
};

Template.calendar.helpers({
	monthName: function(month) {
		return monthNames[Session.get('selectedMonth').getMonth()];
	},
	weeks: function() {
		var currentMonth = moment(Session.get('selectedMonth'));
		var firstOfMonth = currentMonth.clone().startOf('month');
		var firstOfWeek = firstOfMonth.clone().startOf('week');
		var endOfMonth = currentMonth.clone().endOf('month');
		var endOfWeek = endOfMonth.clone().endOf('week');
		var weeksOfMonth = [];

		var range = moment().range(firstOfWeek, endOfWeek);

		range.by('weeks', function(week) {
			var currentWeek = [];
			moment()
				.range(week.clone().startOf('week'), week.clone().endOf('week'))
				.by('days', function(day) {
					currentWeek.push(day);
				});
				weeksOfMonth.push(currentWeek);
		});

		return weeksOfMonth;
	},
});

Template.calendar.events({
	'click .increment-month': function() {
		var date = moment(Session.get('selectedMonth'));
		Session.set('selectedMonth', date.add('month', 1).toDate());
	},
	'click .decrement-month': function() {
		var date = moment(Session.get('selectedMonth'));
		Session.set('selectedMonth', date.subtract('month', 1).toDate());
	},
});

Template.day.helpers({
	dayOfMonth: function(date) {
		return date.date();
	},
	isInMonth: function(date) {
		return date.month() === Session.get('selectedMonth').getMonth() ? 'day-in-month' : 'day-out-of-month';
	},
	theEvents: function(date) {
		date = moment(date);
		 return Events.find({ date: { $gte: date.clone().startOf('day').toDate(), $lte: date.clone().endOf('day').toDate() } });
	},
});

Template.day.events({
	'click .calendar-day': function() {
		var date = moment(this).startOf('day');
		 Session.set('selectedDay', date.toDate());
		 $('#add_event_modal').modal();
	},
});

var myGroups = function() {
	return Groups.find({owner: Meteor.userId()});
};

Template.my_groups.helpers({
	groups: myGroups,
});

Template.my_groups.events({
	'click button.new-group': function() {
		var newGroupNameField = $('#new_group_name')[0];

		Meteor.call('createGroup', {
			name: newGroupNameField.value,
			members: [Meteor.userId],
		});

		newGroupNameField.value = "";
	},
});

Template.join_groups.helpers({
	groups: function() {
		return Groups.find({members: {$not: Meteor.userId}});
	},
});

Template.add_event_modal.helpers({
	eventDate: function() {
		return moment(Session.get("selectedDay")).format("dddd, MMMM Do YYYY");
	},
	groups: myGroups,
});

Template.add_event_modal.events({
	'click button.new-event': function() {
		var titleField = $('#new_event_title')[0];
		var timeField = $('#new_event_time')[0];
		var groupField = $('#new_event_group')[0];

		var date = moment(Session.get('selectedDay'));
		var time = moment(timeField.value, "HH:mm");
		date.startOf('day').hour(time.hour());
		date.minute(time.minute());
		var obj = {
			name: titleField.value,
			date: date.toDate(),
			group: groupField.value,
		};

		Meteor.call('createEvent', obj);

		titleField.value = '';
		timeField.value = '';
		$('#add_event_modal').modal('hide');
	},
});

Template.add_event_modal.rendered = function () {
		$('.clockpicker').clockpicker();
};
<commit_msg>Fix hasty code issues.<commit_after>Meteor.subscribe('events');
Meteor.subscribe('groups');

var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

Template.calendar.created = function() {
	Session.set('selectedMonth', moment().startOf('month').toDate());
};

Template.calendar.helpers({
	monthName: function(month) {
		return monthNames[Session.get('selectedMonth').getMonth()];
	},
	weeks: function() {
		var currentMonth = moment(Session.get('selectedMonth'));
		var firstOfMonth = currentMonth.clone().startOf('month');
		var firstOfWeek = firstOfMonth.clone().startOf('week');
		var endOfMonth = currentMonth.clone().endOf('month');
		var endOfWeek = endOfMonth.clone().endOf('week');
		var weeksOfMonth = [];

		var range = moment().range(firstOfWeek, endOfWeek);

		range.by('weeks', function(week) {
			var currentWeek = [];
			moment()
				.range(week.clone().startOf('week'), week.clone().endOf('week'))
				.by('days', function(day) {
					currentWeek.push(day);
				});
				weeksOfMonth.push(currentWeek);
		});

		return weeksOfMonth;
	},
});

Template.calendar.events({
	'click .increment-month': function() {
		var date = moment(Session.get('selectedMonth'));
		Session.set('selectedMonth', date.add('month', 1).toDate());
	},
	'click .decrement-month': function() {
		var date = moment(Session.get('selectedMonth'));
		Session.set('selectedMonth', date.subtract('month', 1).toDate());
	},
});

Template.day.helpers({
	dayOfMonth: function(date) {
		return date.date();
	},
	isInMonth: function(date) {
		return date.month() === Session.get('selectedMonth').getMonth() ? 'day-in-month' : 'day-out-of-month';
	},
	theEvents: function(date) {
		date = moment(date);
		return Events.find({
			date: {
				$gte: date.clone().startOf('day').toDate(),
				$lte: date.clone().endOf('day').toDate()
			},
		});
	},
});

Template.day.events({
	'click .calendar-day': function() {
		var date = moment(this).startOf('day');
		 Session.set('selectedDay', date.toDate());
		 $('#add_event_modal').modal();
	},
});

var myGroups = function() {
	return Groups.find({owner: Meteor.userId()});
};

Template.my_groups.helpers({
	groups: myGroups,
});

Template.my_groups.events({
	'click button.new-group': function() {
		var newGroupNameField = $('#new_group_name')[0];

		Meteor.call('createGroup', {
			name: newGroupNameField.value,
			members: [Meteor.userId()],
		});

		newGroupNameField.value = "";
	},
});

Template.join_groups.helpers({
	groups: function() {
		return Groups.find({members: {$not: Meteor.userId()}, owner: {$not: Meteor.userId()}});
	},
});

Template.add_event_modal.helpers({
	eventDate: function() {
		return moment(Session.get("selectedDay")).format("dddd, MMMM Do YYYY");
	},
	groups: myGroups,
});

Template.add_event_modal.events({
	'click button.new-event': function() {
		var titleField = $('#new_event_title')[0];
		var timeField = $('#new_event_time')[0];
		var groupField = $('#new_event_group')[0];

		var date = moment(Session.get('selectedDay'));
		var time = moment(timeField.value, "HH:mm");
		date.startOf('day').hour(time.hour());
		date.minute(time.minute());
		var obj = {
			name: titleField.value,
			date: date.toDate(),
			group: groupField.value,
		};

		Meteor.call('createEvent', obj);

		titleField.value = '';
		timeField.value = '';
		$('#add_event_modal').modal('hide');
	},
});

Template.add_event_modal.rendered = function () {
		$('.clockpicker').clockpicker();
};
<|endoftext|>


<commit_before>import { notEmpty } from '@ember/object/computed';
import { assert } from '@ember/debug';
import RSVP from 'rsvp';
import { observer } from '@ember/object';
import BsForm from 'ember-bootstrap/components/bs-form';

export default BsForm.extend({
  init() {
    this._super(...arguments);

    this. _initValidation();
  },

  hasValidator: notEmpty('model.validate'),

  validate(model) {
    let m = model;

    assert('Model must be a Changeset instance', m && typeof m.validate === 'function');
    return m.get('isValid') ? RSVP.resolve() : RSVP.reject();
  },

  _initValidation: observer('model', function() {
    if (this.get('hasValidator')) {
      this.get('model').validate();
    }
  })
});
<commit_msg>remove accidental space<commit_after>import { notEmpty } from '@ember/object/computed';
import { assert } from '@ember/debug';
import RSVP from 'rsvp';
import { observer } from '@ember/object';
import BsForm from 'ember-bootstrap/components/bs-form';

export default BsForm.extend({
  init() {
    this._super(...arguments);

    this._initValidation();
  },

  hasValidator: notEmpty('model.validate'),

  validate(model) {
    let m = model;

    assert('Model must be a Changeset instance', m && typeof m.validate === 'function');
    return m.get('isValid') ? RSVP.resolve() : RSVP.reject();
  },

  _initValidation: observer('model', function() {
    if (this.get('hasValidator')) {
      this.get('model').validate();
    }
  })
});
<|endoftext|>


<commit_before>import {moduloActividad, actividadTest} from '../../helpers/actividadTest';

const nombre = 'FutbolRobots';

moduloActividad(nombre);

actividadTest(nombre, {
	solucion: '<xml xmlns="http://www.w3.org/1999/xhtml"><block type="al_empezar_a_ejecutar" id="1" deletable="false" movable="false" editable="false" x="0" y="0"><statement name="program"><block type="repetir" id="14" inline="true"><value name="count"><block type="math_number" id="15"><field name="NUM">7</field></block></value><statement name="block"><block type="procedures_callnoreturn" id="95"><mutation name="Hacer gol"></mutation><next><block type="procedures_callnoreturn" id="99"><mutation name="Volver al inicio"></mutation><next><block type="SiguienteFila" id="87"></block></next></block></next></block></statement><next><block type="procedures_callnoreturn" id="107"><mutation name="Hacer gol"></mutation></block></next></block></statement></block><block type="procedures_defnoreturn" id="21" x="217" y="61"><mutation></mutation><field name="NAME">Hacer gol</field><statement name="STACK"><block type="hasta" id="33" inline="true"><value name="condition"><block type="tocandoPelota" id="70"></block></value><statement name="block"><block type="MoverACasillaDerecha" id="54"></block></statement><next><block type="PatearPelota" id="75"></block></next></block></statement></block><block type="procedures_defnoreturn" id="24" x="6" y="235"><mutation></mutation><field name="NAME">Volver al inicio</field><statement name="STACK"><block type="hasta" id="42" inline="true"><value name="condition"><block type="tocandoInicio" id="62"></block></value><statement name="block"><block type="MoverACasillaIzquierda" id="59"></block></statement></block></statement></block></xml>',
});
<commit_msg>Corregida identacion e referencia a bloques del test fultbol de robots<commit_after>import {moduloActividad, actividadTest} from '../../helpers/actividadTest';

const nombre = 'FutbolRobots';

moduloActividad(nombre);

actividadTest(nombre, {
	solucion: '<xml xmlns="http://www.w3.org/1999/xhtml"><block type="al_empezar_a_ejecutar" id="1" deletable="false" movable="false" editable="false" x="0" y="0"><statement name="program"><block type="repetir" id="14" inline="true"><value name="count"><block type="math_number" id="15"><field name="NUM">7</field></block></value><statement name="block"><block type="procedures_callnoreturn" id="95"><mutation name="Hacer gol"></mutation><next><block type="procedures_callnoreturn" id="99"><mutation name="Volver al inicio"></mutation><next><block type="SiguienteFila" id="87"></block></next></block></next></block></statement><next><block type="procedures_callnoreturn" id="107"><mutation name="Hacer gol"></mutation></block></next></block></statement></block><block type="procedures_defnoreturn" id="21" x="217" y="61"><mutation></mutation><field name="NAME">Hacer gol</field><statement name="STACK"><block type="hasta" id="33" inline="true"><value name="condition"><block type="TocandoPelota" id="70"></block></value><statement name="block"><block type="MoverACasillaDerecha" id="54"></block></statement><next><block type="PatearPelota" id="75"></block></next></block></statement></block><block type="procedures_defnoreturn" id="24" x="6" y="235"><mutation></mutation><field name="NAME">Volver al inicio</field><statement name="STACK"><block type="hasta" id="42" inline="true"><value name="condition"><block type="TocandoInicio" id="62"></block></value><statement name="block"><block type="MoverACasillaIzquierda" id="59"></block></statement></block></statement></block></xml>',
});
<|endoftext|>


<commit_before>import React, { isValidElement } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import icBEM from './utils/icBEM';
import prefixClass from './utils/prefixClass';

import renderToLayer from './mixins/renderToLayer';

import Icon from './Icon';
import Overlay from './Overlay';

import './styles/_animations.scss';
import './styles/Popup.scss';

export const POPUP_SIZE = {
  SMALL: 'small',
  LARGE: 'large',
};

export const COMPONENT_NAME = prefixClass('popup');
const ROOT_BEM = icBEM(COMPONENT_NAME);
export const BEM = {
  root: ROOT_BEM,
  container: ROOT_BEM.element('container'),
  body: ROOT_BEM.element('body'),
  messageTitle: ROOT_BEM.element('message-title'),
  messageDesc: ROOT_BEM.element('message-desc'),
  button: ROOT_BEM.element('button'),
  buttonsGroup: ROOT_BEM.element('buttons-group'),
};

export function PopupIcon({ icon, color }) {
  if (!icon) {
    return null;
  }

  return (

      {isValidElement(icon)
        ? icon
        : <Icon large type={icon} color={color} />}

  );
}
PopupIcon.propTypes = {
  icon: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.element,
  ]),
  color: PropTypes.string,
};
PopupIcon.defaultProps = {
  icon: undefined,
  color: undefined,
};

export function PopupMessage({ message }) {
  // variant: title + desc
  if (message.title) {
    return (
      <>

{message.title}

{message.desc}

      </>
    );
  }

  // variant: simple message
  return message;
}
PopupMessage.propTypes = {
  message: PropTypes.oneOfType([
    PropTypes.node,
    PropTypes.shape({
      title: PropTypes.string.isRequired,
      desc: PropTypes.string.isRequired,
    }),
  ]).isRequired,
};
PopupMessage.defaultProps = {};

function Popup({
  size,
  icon,
  iconColor,
  message,
  messageBottomArea,
  buttons,
  className,
  ...popupProps
}) {
  const rootBEM = BEM.root.modifier(size).toString();
  const rootClassName = classNames(rootBEM, className);

  return (

      <Overlay />

          <PopupIcon icon={icon} color={iconColor} />
          <PopupMessage message={message} />
          {messageBottomArea}

        {buttons && (

            {buttons}

        )}

  );
}

Popup.propTypes = {
  size: PropTypes.oneOf([
    POPUP_SIZE.SMALL,
    POPUP_SIZE.LARGE,
  ]),
  icon: PopupIcon.propTypes.icon,
  iconColor: PopupIcon.propTypes.color,
  message: PopupMessage.propTypes.message,
  messageBottomArea: PropTypes.node,
  buttons: PropTypes.node,
};

Popup.defaultProps = {
  size: POPUP_SIZE.SMALL,
  icon: PopupIcon.defaultProps.icon,
  iconColor: PopupIcon.defaultProps.color,
  message: PopupMessage.defaultProps.message,
  messageBottomArea: undefined,
  buttons: undefined,
};

// export for tests
export { Popup as PurePopup };
export default renderToLayer(Popup);
<commit_msg>Update <Popup> with PR suggestion<commit_after>import React, { isValidElement } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import icBEM from './utils/icBEM';
import prefixClass from './utils/prefixClass';

import renderToLayer from './mixins/renderToLayer';

import Icon from './Icon';
import Overlay from './Overlay';

import './styles/_animations.scss';
import './styles/Popup.scss';

export const POPUP_SIZE = {
  SMALL: 'small',
  LARGE: 'large',
};

export const COMPONENT_NAME = prefixClass('popup');
const ROOT_BEM = icBEM(COMPONENT_NAME);
export const BEM = {
  root: ROOT_BEM,
  container: ROOT_BEM.element('container'),
  body: ROOT_BEM.element('body'),
  messageTitle: ROOT_BEM.element('message-title'),
  messageDesc: ROOT_BEM.element('message-desc'),
  button: ROOT_BEM.element('button'),
  buttonsGroup: ROOT_BEM.element('buttons-group'),
};

export function PopupIcon({ icon, color }) {
  if (!icon) {
    return null;
  }

  return (

      {(isValidElement(icon)
        ? icon
        : <Icon large type={icon} color={color} />
      )}

  );
}
PopupIcon.propTypes = {
  icon: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.element,
  ]),
  color: PropTypes.string,
};
PopupIcon.defaultProps = {
  icon: undefined,
  color: undefined,
};

export function PopupMessage({ message }) {
  // variant: title + desc
  if (message.title) {
    return (
      <>

{message.title}

{message.desc}

      </>
    );
  }

  // variant: simple message
  return message;
}
PopupMessage.propTypes = {
  message: PropTypes.oneOfType([
    PropTypes.node,
    PropTypes.shape({
      title: PropTypes.string.isRequired,
      desc: PropTypes.string.isRequired,
    }),
  ]).isRequired,
};
PopupMessage.defaultProps = {};

function Popup({
  size,
  icon,
  iconColor,
  message,
  messageBottomArea,
  buttons,
  className,
  ...popupProps
}) {
  const rootBEM = BEM.root.modifier(size).toString();
  const rootClassName = classNames(rootBEM, className);

  return (

      <Overlay />

          <PopupIcon icon={icon} color={iconColor} />
          <PopupMessage message={message} />
          {messageBottomArea}

        {buttons && (

            {buttons}

        )}

  );
}

Popup.propTypes = {
  size: PropTypes.oneOf([
    POPUP_SIZE.SMALL,
    POPUP_SIZE.LARGE,
  ]),
  icon: PopupIcon.propTypes.icon,
  iconColor: PopupIcon.propTypes.color,
  message: PopupMessage.propTypes.message,
  messageBottomArea: PropTypes.node,
  buttons: PropTypes.node,
};

Popup.defaultProps = {
  size: POPUP_SIZE.SMALL,
  icon: PopupIcon.defaultProps.icon,
  iconColor: PopupIcon.defaultProps.color,
  message: PopupMessage.defaultProps.message,
  messageBottomArea: undefined,
  buttons: undefined,
};

// export for tests
export { Popup as PurePopup };
export default renderToLayer(Popup);
<|endoftext|>


<commit_before>"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = isFree;

var _requestPromise = _interopRequireDefault(require("request-promise"));

var _idnaUts = _interopRequireDefault(require("idna-uts46"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var returnValues = {
  free: 'FREE',
  not_valid: 'NOT_VALID',
  occupied: 'OCCUPIED'
};

function isFree(domain) {
  var idnEncodedDomain = _idnaUts.default.toAscii(domain);

  var requestUrl = `http://free.iis.se/free?q=${idnEncodedDomain}`;
  return (0, _requestPromise.default)(requestUrl).then(function (data) {
    var domainAvailability = data.split(' ')[0];
    var result = returnValues[domainAvailability];

    if (result) {
      return result;
    }

    return Promise.reject(new Error('Unknown error'));
  });
}

module.exports = exports.default;
<commit_msg>Build new version<commit_after>"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = isFree;

var _nodeFetch = _interopRequireDefault(require("node-fetch"));

var _idnaUts = _interopRequireDefault(require("idna-uts46"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var returnValues = {
  free: 'FREE',
  not_valid: 'NOT_VALID',
  occupied: 'OCCUPIED'
};

function isFree(domain) {
  var idnEncodedDomain = _idnaUts.default.toAscii(domain);

  var requestUrl = `http://free.iis.se/free?q=${idnEncodedDomain}`;
  return (0, _nodeFetch.default)(requestUrl).then(function (res) {
    if (res.ok) {
      return res.text();
    }

    return Promise.reject(new Error(res.statusText));
  }).then(function (body) {
    var domainAvailability = body.split(' ')[0];
    var result = returnValues[domainAvailability];

    if (result) {
      return result;
    }

    return Promise.reject(new Error('Unknown error'));
  });
}

module.exports = exports.default;
<|endoftext|>


<commit_before>/* ========================================================================
 * ZUI: jquery.extensions.js
 * http://openzui.com
 * ========================================================================
 * Copyright (c) 2014-2016 cnezsoft.com; Licensed MIT
 * ======================================================================== */

(function($, window, undefined) {
    'use strict';

    /* Check jquery */
    if(typeof($) === 'undefined') throw new Error('ZUI requires jQuery');

    // ZUI shared object
    if(!$.zui) $.zui = function(obj) {
        if($.isPlainObject(obj)) {
            $.extend($.zui, obj);
        }
    };

    var MOUSE_BUTTON_CODES = {
        all: -1,
        left: 0,
        middle: 1,
        right: 2
    };

    var lastUuidAmend = 0;
    $.zui({
        uuid: function(asNumber) {
            var uuidNumber = (Date.now() - 1580890015292) * 100000000 + Math.floor(Math.random() * 100000) * 1000 + (lastUuidAmend++) % 1000;
            return asNumber ? uuidNumber : uuidNumber.toString(36);
        },

        callEvent: function(func, event, proxy) {
            if($.isFunction(func)) {
                if(proxy !== undefined) {
                    func = $.proxy(func, proxy);
                }
                var result = func(event);
                if(event) event.result = result;
                return !(result !== undefined && (!result));
            }
            return 1;
        },

        strCode: function(str) {
            var code = 0;
            if(str && str.length) {
                for(var i = 0; i < str.length; ++i) {
                    code += i * str.charCodeAt(i);
                }
            }
            return code;
        },

        getMouseButtonCode: function(mouseButton) {
            if(typeof mouseButton !== 'number') {
                mouseButton = MOUSE_BUTTON_CODES[mouseButton];
            }
            if(mouseButton === undefined || mouseButton === null) mouseButton = -1;
            return mouseButton;
        },

        /**
         * default language name
         * @type {string}
         */
        defaultLang: 'en',

        /**
         * Get client language name
         * @return {string}
         */
        clientLang: function() {
            var lang;
            var config = window.config;
            if(typeof(config) != 'undefined' && config.clientLang) {
                lang = config.clientLang;
            }
            if(!lang) {
                var hl = $('html').attr('lang');
                lang = hl ? hl : (navigator.userLanguage || navigator.userLanguage || $.zui.defaultLang);
            }
            return lang.replace('-', '_').toLowerCase();
        },

        /**
         * @type {object}
         * @example
         * {
         *      'zui.pager': {
         *          'zh-cn': {
         *              prev: '上一页',
         *          }
         *      }
         * }
         */
        langDataMap: {},

        /**
         * Add lang data for components
         * @param {string} [langName]
         * @param {string} [componentName]
         * @param {object} data
         * @example
         * // Add lang data to specify language and specify component
         * $.zui.addLangData('zh-cn', 'zui.pager', {
         *      prev: '上一页',
         *      next: '下一页',
         * });
         *
         * // Add lang data to specify language and multiple components
         * $.zui.addLangData('zh-cn', {
         *      'zui.pager': {
         *          prev: '上一页',
         *          next: '下一页',
         *      },
         *      'chosen': {
         *      }
         * });
         *
         * // Add lang data to multiple languages and multiple components
         * $.zui.addLangData({
         *      'zh-cn': {
         *          'zui.pager': {
         *              prev: '上一页',
         *              next: '下一页',
         *          },
         *          'chosen': {
         *          }
         *      },
         *      'zh-tw': {
         *          'zui.pager': {
         *              prev: '上一页',
         *              next: '下一页',
         *          }
         *      }
         * });
         */
        addLangData: function(langName, componentName, data) {
            var langData = {};
            if (data && componentName && langName) {
                langData[componentName] = {};
                langData[componentName][langName] = data;
            } else if (langName && componentName && !data) {
                data = componentName;
                $.each(data, function(comName) {
                    langData[comName] = {};
                    langData[comName][langName] = data[comName];
                });
            } else if (langName && !componentName && !data) {
                $.each(data, function(theLangName) {
                    var comsData = data[theLangName];
                    $.each(comsData, function(comName) {
                        if (!langData[comName]) {
                            langData[comName] = {};
                        }
                        langData[comName][theLangName] = comsData[comName];
                    });
                });
            }
            $.extend(true, $.zui.langDataMap, langData);
        },

        /**
         * Get lang data
         * @example
         * $.zui.getLangData('zui.pager');
         *
         * $.zui.getLangData('zui.pager', 'zh-cn');
         *
         * $.zui.getLangData('zui.pager', 'zh-cn', {
         *      prev: '上一页',
         *      next: '下一页',
         * });
         */
        getLangData: function(componentName, langName, initialData) {
            if (!arguments.length) {
                return $.extend({}, $.zui.langDataMap);
            }
            if (arguments.length === 1) {
                return $.extend({}, $.zui.langDataMap[componentName]);
            }
            if (arguments.length === 2) {
                var comData = $.zui.langDataMap[componentName];
                if (comData) {
                    return langName ? comData[langName] : comData;
                }
                return {};
            }
            if (arguments.length === 3) {
                langName = langName || $.zui.clientLang();
                var comData = $.zui.langDataMap[componentName];
                var langData = comData ? comData[langName] : {};
                return $.extend(true, {}, initialData[langName] || initialData.en || initialData.zh_cn, langData);
            }
            return null;
        },

        lang: function() {
            if (arguments.length && $.isPlainObject(arguments[arguments.length - 1])) {
                return $.zui.addLangData.apply(null, arguments);
            }
            return $.zui.getLangData.apply(null, arguments);
        },
    });

    $.fn.callEvent = function(name, event, model) {
        var $this = $(this);
        var dotIndex = name.indexOf('.zui.');
        var shortName = dotIndex < 0 ? name : name.substring(0, dotIndex);
        var e = $.Event(shortName, event);

        if((model === undefined) && dotIndex > 0) {
            model = $this.data(name.substring(dotIndex + 1));
        }

        if(model && model.options) {
            var func = model.options[shortName];
            if($.isFunction(func)) {
                e.result = $.zui.callEvent(func, e, model);
            }
        }
        $this.trigger(e);
        return e;
    };

    $.fn.callComEvent = function(component, eventName, params) {
        if (params !== undefined && !$.isArray(params)) {
            params = [params];
        }
        var $this = this;
        var result;
        $this.trigger(eventName, params);

        var eventCallback = component.options[eventName];
        if (eventCallback) {
            result = eventCallback.apply(component, params);
        }
        return result;
    };
}(jQuery, window, undefined));
<commit_msg>* improve uuid helper.<commit_after>/* ========================================================================
 * ZUI: jquery.extensions.js
 * http://openzui.com
 * ========================================================================
 * Copyright (c) 2014-2016 cnezsoft.com; Licensed MIT
 * ======================================================================== */

(function($, window, undefined) {
    'use strict';

    /* Check jquery */
    if(typeof($) === 'undefined') throw new Error('ZUI requires jQuery');

    // ZUI shared object
    if(!$.zui) $.zui = function(obj) {
        if($.isPlainObject(obj)) {
            $.extend($.zui, obj);
        }
    };

    var MOUSE_BUTTON_CODES = {
        all: -1,
        left: 0,
        middle: 1,
        right: 2
    };

    var lastUuidAmend = 0;
    $.zui({
        uuid: function(asNumber) {
            var uuidNumber = (Date.now() - 1580890015292) * 10e7 + Math.floor(Math.random() * 10e4) * 10e2 + (lastUuidAmend++) % 10e2;
            return asNumber ? uuidNumber : uuidNumber.toString(36);
        },

        callEvent: function(func, event, proxy) {
            if($.isFunction(func)) {
                if(proxy !== undefined) {
                    func = $.proxy(func, proxy);
                }
                var result = func(event);
                if(event) event.result = result;
                return !(result !== undefined && (!result));
            }
            return 1;
        },

        strCode: function(str) {
            var code = 0;
            if(str && str.length) {
                for(var i = 0; i < str.length; ++i) {
                    code += i * str.charCodeAt(i);
                }
            }
            return code;
        },

        getMouseButtonCode: function(mouseButton) {
            if(typeof mouseButton !== 'number') {
                mouseButton = MOUSE_BUTTON_CODES[mouseButton];
            }
            if(mouseButton === undefined || mouseButton === null) mouseButton = -1;
            return mouseButton;
        },

        /**
         * default language name
         * @type {string}
         */
        defaultLang: 'en',

        /**
         * Get client language name
         * @return {string}
         */
        clientLang: function() {
            var lang;
            var config = window.config;
            if(typeof(config) != 'undefined' && config.clientLang) {
                lang = config.clientLang;
            }
            if(!lang) {
                var hl = $('html').attr('lang');
                lang = hl ? hl : (navigator.userLanguage || navigator.userLanguage || $.zui.defaultLang);
            }
            return lang.replace('-', '_').toLowerCase();
        },

        /**
         * @type {object}
         * @example
         * {
         *      'zui.pager': {
         *          'zh-cn': {
         *              prev: '上一页',
         *          }
         *      }
         * }
         */
        langDataMap: {},

        /**
         * Add lang data for components
         * @param {string} [langName]
         * @param {string} [componentName]
         * @param {object} data
         * @example
         * // Add lang data to specify language and specify component
         * $.zui.addLangData('zh-cn', 'zui.pager', {
         *      prev: '上一页',
         *      next: '下一页',
         * });
         *
         * // Add lang data to specify language and multiple components
         * $.zui.addLangData('zh-cn', {
         *      'zui.pager': {
         *          prev: '上一页',
         *          next: '下一页',
         *      },
         *      'chosen': {
         *      }
         * });
         *
         * // Add lang data to multiple languages and multiple components
         * $.zui.addLangData({
         *      'zh-cn': {
         *          'zui.pager': {
         *              prev: '上一页',
         *              next: '下一页',
         *          },
         *          'chosen': {
         *          }
         *      },
         *      'zh-tw': {
         *          'zui.pager': {
         *              prev: '上一页',
         *              next: '下一页',
         *          }
         *      }
         * });
         */
        addLangData: function(langName, componentName, data) {
            var langData = {};
            if (data && componentName && langName) {
                langData[componentName] = {};
                langData[componentName][langName] = data;
            } else if (langName && componentName && !data) {
                data = componentName;
                $.each(data, function(comName) {
                    langData[comName] = {};
                    langData[comName][langName] = data[comName];
                });
            } else if (langName && !componentName && !data) {
                $.each(data, function(theLangName) {
                    var comsData = data[theLangName];
                    $.each(comsData, function(comName) {
                        if (!langData[comName]) {
                            langData[comName] = {};
                        }
                        langData[comName][theLangName] = comsData[comName];
                    });
                });
            }
            $.extend(true, $.zui.langDataMap, langData);
        },

        /**
         * Get lang data
         * @example
         * $.zui.getLangData('zui.pager');
         *
         * $.zui.getLangData('zui.pager', 'zh-cn');
         *
         * $.zui.getLangData('zui.pager', 'zh-cn', {
         *      prev: '上一页',
         *      next: '下一页',
         * });
         */
        getLangData: function(componentName, langName, initialData) {
            if (!arguments.length) {
                return $.extend({}, $.zui.langDataMap);
            }
            if (arguments.length === 1) {
                return $.extend({}, $.zui.langDataMap[componentName]);
            }
            if (arguments.length === 2) {
                var comData = $.zui.langDataMap[componentName];
                if (comData) {
                    return langName ? comData[langName] : comData;
                }
                return {};
            }
            if (arguments.length === 3) {
                langName = langName || $.zui.clientLang();
                var comData = $.zui.langDataMap[componentName];
                var langData = comData ? comData[langName] : {};
                return $.extend(true, {}, initialData[langName] || initialData.en || initialData.zh_cn, langData);
            }
            return null;
        },

        lang: function() {
            if (arguments.length && $.isPlainObject(arguments[arguments.length - 1])) {
                return $.zui.addLangData.apply(null, arguments);
            }
            return $.zui.getLangData.apply(null, arguments);
        },
    });

    $.fn.callEvent = function(name, event, model) {
        var $this = $(this);
        var dotIndex = name.indexOf('.zui.');
        var shortName = dotIndex < 0 ? name : name.substring(0, dotIndex);
        var e = $.Event(shortName, event);

        if((model === undefined) && dotIndex > 0) {
            model = $this.data(name.substring(dotIndex + 1));
        }

        if(model && model.options) {
            var func = model.options[shortName];
            if($.isFunction(func)) {
                e.result = $.zui.callEvent(func, e, model);
            }
        }
        $this.trigger(e);
        return e;
    };

    $.fn.callComEvent = function(component, eventName, params) {
        if (params !== undefined && !$.isArray(params)) {
            params = [params];
        }
        var $this = this;
        var result;
        $this.trigger(eventName, params);

        var eventCallback = component.options[eventName];
        if (eventCallback) {
            result = eventCallback.apply(component, params);
        }
        return result;
    };
}(jQuery, window, undefined));
<|endoftext|>


<commit_before>//version 2017.3.26 12:00
//dependency:
//d3.js version 3.5.17
//jquery.js version 2.1.1

(function() {
    d3.linechart_light = function() {
        let width = 640,
            height = 480,
            xlabel = "",
            ylabel = "",
            draw_xGrid = false,
            draw_yGrid = false,
            draw_xAxis = false,
            draw_yAxis = false,
            draw_datalabel = false,
            margin = {
                top: 20,
                right: 20,
                bottom: 20,
                left: 20
            },
            duration = 500

        let global_value_extent = undefined

        function chart(selection) {
            //传入的dataset_lines目前只是一条直线的数据
            //dataset_lines是{x:arr1,y:arr2}的形式
            //arr1和arr2都是直接的数字的数组
            selection.each(function(dataset_lines) {
                let innerWidth = width - margin.left - margin.right,
                    innerHeight = height - margin.top - margin.bottom

                let x_scale = d3.scale.linear()
                    .range([0, innerWidth])
                    .domain([
                        d3.min(dataset_lines, line => d3.min(line.x)),
                        d3.max(dataset_lines, line => d3.max(line.x))
                    ])

                //如果传入了global_value_extent,就用它来初始化y的定义域
                let value_domain = global_value_extent != undefined ? global_value_extent :
                    [
                        d3.min(dataset_lines, line => d3.min(line.y)),
                        d3.max(dataset_lines, line => d3.max(line.y))
                    ]

                let y_scale = d3.scale.linear()
                    .range([innerHeight, 0])
                    .domain(value_domain)

                let color_scale = d3.scale.category10()
                    .domain(d3.range(dataset_lines.length))

                let x_axis = d3.svg.axis()
                    .scale(x_scale)
                    .orient("bottom")

                let y_axis = d3.svg.axis()
                    .scale(y_scale)
                    .orient("left")

                let svg = d3.select(this)
                    .attr("width", width)
                    .attr("height", height)

                svg.selectAll(".container")
                    .data([null])
                    .enter().append("g")
                    .attr("class", "container")
                svg.selectAll(".container").transition()
                    .duration(duration)
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                let g = svg.selectAll(".container")

                if (draw_xGrid) //如果需要画x轴向上的grid
                {
                    let x_grid = d3.svg.axis()
                        .scale(x_scale)
                        .orient("bottom")
                        .tickSize(-innerHeight)
                        .tickFormat("");

                    let x_grid_selection = g.selectAll(".x.grid")
                        .data([null])
                    x_grid_selection.enter().append('g')
                        .attr("class", "x grid");
                    g.selectAll(".x.grid").transition()
                        .duration(duration)
                        .attr("transform", "translate(0," + innerHeight + ")")
                        .call(x_grid);
                }

                if (draw_yGrid) //如果需要画y轴向上的grid
                {
                    let y_grid = d3.svg.axis()
                        .scale(y_scale)
                        .orient("left")
                        .tickSize(-innerWidth)
                        .tickFormat("");

                    let y_grid_selection = g.selectAll(".y.grid")
                        .data([null])
                    y_grid_selection.enter().append('g')
                        .attr("class", "y grid");
                    g.selectAll(".y.grid").transition()
                        .duration(duration)
                        .call(y_grid);
                }

                if (draw_xAxis) //如果需要画x轴
                {
                    let xAxis_selection = g.selectAll(".x.axis")
                        .data([null])
                    xAxis_selection.enter().append('g')
                        .attr("class", "x axis")
                    g.selectAll(".x.axis").transition()
                        .duration(duration)
                        .attr("transform", "translate(0," + innerHeight + ")")
                        .call(x_axis)

                    let text_selection = g.selectAll(".x.axis").selectAll('.x.label')
                        .data([null])
                    text_selection.enter().append('text')
                        .attr("class", "x label")
                        .style("text-anchor", "end")
                        .attr("dy", "-.71em")
                    g.selectAll(".x.axis").selectAll('.x.label').transition()
                        .duration(duration)
                        .attr("x", innerWidth)
                        .text(xlabel)
                }

                if (draw_yAxis) //如果需要画y轴
                {
                    let yAxis_selection = g.selectAll(".y.axis")
                        .data([null])
                    yAxis_selection.enter().append('g')
                        .attr("class", "y axis")
                    g.selectAll(".y.axis").transition()
                        .duration(duration)
                        .call(y_axis);

                    let text_selection = g.selectAll(".y.axis").selectAll('.y.label')
                        .data([null])
                    text_selection.enter().append('text')
                        .attr("class", "y label")
                        .attr("transform", "rotate(-90)")
                        .style("text-anchor", "end")
                        .attr("y", 6)
                        .attr("dy", "0.71em")
                    g.selectAll(".y.axis").selectAll('.y.label').transition()
                        .duration(duration)
                        .text(ylabel)
                }

                let draw_line = d3.svg.line()
                    .interpolate("basis")
                    .x(d => x_scale(d[0]))
                    .y(d => y_scale(d[1]))

                let data_lines_selection = g.selectAll(".d3_linechart_line")
                    .data(dataset_lines.map(d => d3.zip(d.x, d.y)))
                data_lines_selection.enter().append("g")
                    .attr("class", "d3_linechart_line")
                data_lines_selection.exit().remove()

                let line_selection = g.selectAll(".d3_linechart_line").selectAll('.line')
                    .data(d => [d])

                line_selection.enter().append('path')
                    .attr("class", "line")
                g.selectAll(".d3_linechart_line").selectAll('.line').transition()
                    .duration(duration)
                    .attr("d", draw_line)
                    .attr("stroke", (_, i) => color_scale(i))

                if (draw_datalabel) //如果需要画线末尾的label
                {
                    g.selectAll(".d3_linechart_line").append("text")
                        .datum(function(d, i) {
                            return {
                                name: dataset_lines[i].label,
                                final: d[d.length - 1]
                            };
                        })
                        .attr("transform", function(d) {
                            return ("translate(" + x_scale(d.final[0]) + "," +
                                y_scale(d.final[1]) + ")");
                        })
                        .attr("x", 3)
                        .attr("dy", ".35em")
                        .attr("fill", (_, i) => color_scale(i))
                        .text(d => d.name)
                }

            });
        }

        chart.width = function(value) {
            if (!arguments.length) return width;
            width = value;
            return chart;
        };

        chart.height = function(value) {
            if (!arguments.length) return height;
            height = value;
            return chart;
        };

        chart.margin = function(value) {
            if (!arguments.length) return margin;
            if (typeof(value) != "object") {
                console.warn("invalid value for margin", value);
                return;
            }
            if (typeof(value.top) == "number")
                margin.top = value.top;
            if (typeof(value.right) == "number")
                margin.right = value.right;
            if (typeof(value.bottom) == "number")
                margin.bottom = value.bottom;
            if (typeof(value.left) == "number")
                margin.left = value.left;
            return chart;
        };

        chart.duration = function(value) {
            if (!arguments.length) return duration;
            if (typeof(value) != "number") {
                console.warn("invalid value for duration", value);
                return;
            }
            duration = value;
            return chart;
        };

        chart.xlabel = function(value) {
            if (!arguments.length) return xlabel;
            xlabel = value;
            return chart;
        };

        chart.ylabel = function(value) {
            if (!arguments.length) return ylabel;
            ylabel = value;
            return chart;
        };

        chart.draw_yAxis = function(value) {
            if (!arguments.length) return draw_yAxis;
            if (typeof(value) != "boolean") {
                console.warn("invalid value for draw_yAxis", value);
                return;
            }
            draw_yAxis = value;
            return chart;
        };

        chart.draw_xAxis = function(value) {
            if (!arguments.length) return draw_xAxis;
            if (typeof(value) != "boolean") {
                console.warn("invalid value for draw_xAxis", value);
                return;
            }
            draw_xAxis = value;
            return chart;
        };

        chart.draw_xGrid = function(value) {
            if (!arguments.length) return draw_xGrid;
            if (typeof(value) != "boolean") {
                console.warn("invalid value for draw_xGrid", value);
                return;
            }
            draw_xGrid = value;
            return chart;
        };

        chart.draw_yGrid = function(value) {
            if (!arguments.length) return draw_yGrid;
            if (typeof(value) != "boolean") {
                console.warn("invalid value for draw_yGrid", value);
                return;
            }
            draw_yGrid = value;
            return chart;
        };

        chart.draw_datalabel = function(value) {
            if (!arguments.length) return draw_datalabel;
            if (typeof(value) != "boolean") {
                console.warn("invalid value for draw_datalabel", value);
                return;
            }
            draw_datalabel = value;
            return chart;
        };

        chart.global_value_extent = function(value) {
            if (!arguments.length) return global_value_extent;
            if (typeof(value) != "object") {
                console.warn("invalid value for global_value_extent", value);
                return;
            }
            global_value_extent = value;
            return chart;
        };

        return chart;
    }
})();<commit_msg>fix bug in color_scale<commit_after>//version 2017.3.26 12:00
//dependency:
//d3.js version 3.5.17
//jquery.js version 2.1.1

(function() {
    d3.linechart_light = function() {
        let width = 640,
            height = 480,
            xlabel = "",
            ylabel = "",
            draw_xGrid = false,
            draw_yGrid = false,
            draw_xAxis = false,
            draw_yAxis = false,
            draw_datalabel = false,
            margin = {
                top: 20,
                right: 20,
                bottom: 20,
                left: 20
            },
            duration = 500,
            color_scale = d3.scale.category10()

        let global_value_extent = undefined

        function chart(selection) {
            //传入的dataset_lines目前只是一条直线的数据
            //dataset_lines是{x:arr1,y:arr2}的形式
            //arr1和arr2都是直接的数字的数组
            selection.each(function(dataset_lines) {
                let innerWidth = width - margin.left - margin.right,
                    innerHeight = height - margin.top - margin.bottom

                let x_scale = d3.scale.linear()
                    .range([0, innerWidth])
                    .domain([
                        d3.min(dataset_lines, line => d3.min(line.x)),
                        d3.max(dataset_lines, line => d3.max(line.x))
                    ])

                //如果传入了global_value_extent,就用它来初始化y的定义域
                let value_domain = global_value_extent != undefined ? global_value_extent :
                    [
                        d3.min(dataset_lines, line => d3.min(line.y)),
                        d3.max(dataset_lines, line => d3.max(line.y))
                    ]

                let y_scale = d3.scale.linear()
                    .range([innerHeight, 0])
                    .domain(value_domain)

                let x_axis = d3.svg.axis()
                    .scale(x_scale)
                    .orient("bottom")

                let y_axis = d3.svg.axis()
                    .scale(y_scale)
                    .orient("left")

                let svg = d3.select(this)
                    .attr("width", width)
                    .attr("height", height)

                svg.selectAll(".container")
                    .data([null])
                    .enter().append("g")
                    .attr("class", "container")
                svg.selectAll(".container").transition()
                    .duration(duration)
                    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                let g = svg.selectAll(".container")

                if (draw_xGrid) //如果需要画x轴向上的grid
                {
                    let x_grid = d3.svg.axis()
                        .scale(x_scale)
                        .orient("bottom")
                        .tickSize(-innerHeight)
                        .tickFormat("")

                    let x_grid_selection = g.selectAll(".x.grid")
                        .data([null])
                    x_grid_selection.enter().append('g')
                        .attr("class", "x grid")
                    g.selectAll(".x.grid").transition()
                        .duration(duration)
                        .attr("transform", "translate(0," + innerHeight + ")")
                        .call(x_grid)
                }

                if (draw_yGrid) //如果需要画y轴向上的grid
                {
                    let y_grid = d3.svg.axis()
                        .scale(y_scale)
                        .orient("left")
                        .tickSize(-innerWidth)
                        .tickFormat("")

                    let y_grid_selection = g.selectAll(".y.grid")
                        .data([null])
                    y_grid_selection.enter().append('g')
                        .attr("class", "y grid")
                    g.selectAll(".y.grid").transition()
                        .duration(duration)
                        .call(y_grid)
                }

                if (draw_xAxis) //如果需要画x轴
                {
                    let xAxis_selection = g.selectAll(".x.axis")
                        .data([null])
                    xAxis_selection.enter().append('g')
                        .attr("class", "x axis")
                    g.selectAll(".x.axis").transition()
                        .duration(duration)
                        .attr("transform", "translate(0," + innerHeight + ")")
                        .call(x_axis)

                    let text_selection = g.selectAll(".x.axis").selectAll('.x.label')
                        .data([null])
                    text_selection.enter().append('text')
                        .attr("class", "x label")
                        .style("text-anchor", "end")
                        .attr("dy", "-.71em")
                    g.selectAll(".x.axis").selectAll('.x.label').transition()
                        .duration(duration)
                        .attr("x", innerWidth)
                        .text(xlabel)
                }

                if (draw_yAxis) //如果需要画y轴
                {
                    let yAxis_selection = g.selectAll(".y.axis")
                        .data([null])
                    yAxis_selection.enter().append('g')
                        .attr("class", "y axis")
                    g.selectAll(".y.axis").transition()
                        .duration(duration)
                        .call(y_axis)

                    let text_selection = g.selectAll(".y.axis").selectAll('.y.label')
                        .data([null])
                    text_selection.enter().append('text')
                        .attr("class", "y label")
                        .attr("transform", "rotate(-90)")
                        .style("text-anchor", "end")
                        .attr("y", 6)
                        .attr("dy", "0.71em")
                    g.selectAll(".y.axis").selectAll('.y.label').transition()
                        .duration(duration)
                        .text(ylabel)
                }

                let draw_line = d3.svg.line()
                    .interpolate("basis")
                    .x(d => x_scale(d[0]))
                    .y(d => y_scale(d[1]))

                let data_lines_selection = g.selectAll(".d3_linechart_line")
                    .data(dataset_lines.map(d => d3.zip(d.x, d.y)))
                data_lines_selection.enter().append("g")
                    .attr("class", "d3_linechart_line")
                data_lines_selection.exit().remove()

                let line_selection = g.selectAll(".d3_linechart_line").selectAll('.line')
                    .data(d => [d])

                line_selection.enter().append('path')
                    .attr("class", "line")

                //这里不能先selectAll d3_linechart_line再selectAll line,否则下面调用的时候i算的是每块中line的下标
                g.selectAll('.line').transition()
                    .duration(duration)
                    .attr("d", draw_line)
                    .attr("stroke", color_scale)

                if (draw_datalabel) //如果需要画线末尾的label
                {
                    g.selectAll(".d3_linechart_line").append("text")
                        .datum(function(d, i) {
                            return {
                                name: dataset_lines[i].label,
                                final: d[d.length - 1]
                            }
                        })
                        .attr("transform", function(d) {
                            return ("translate(" + x_scale(d.final[0]) + "," +
                                y_scale(d.final[1]) + ")")
                        })
                        .attr("x", 3)
                        .attr("dy", ".35em")
                        .attr("fill", color_scale)
                        .text(d => d.name)
                }

            })
        }

        chart.width = function(value) {
            if (!arguments.length) return width
            if (typeof(value) != 'number') {
                console.warn('invalid value for width', value)
                return
            }
            width = value
            return chart
        }

        chart.height = function(value) {
            if (!arguments.length) return height
            if (typeof(value) != 'number') {
                console.warn('invalid value for height', value)
                return
            }
            height = value
            return chart
        }

        chart.margin = function(value) {
            if (!arguments.length) return margin
            if (typeof(value) != "object") {
                console.warn("invalid value for margin", value)
                return
            }
            if (typeof(value.top) == "number")
                margin.top = value.top
            if (typeof(value.right) == "number")
                margin.right = value.right
            if (typeof(value.bottom) == "number")
                margin.bottom = value.bottom
            if (typeof(value.left) == "number")
                margin.left = value.left
            return chart
        }

        chart.duration = function(value) {
            if (!arguments.length) return duration
            if (typeof(value) != "number") {
                console.warn("invalid value for duration", value)
                return
            }
            duration = value
            return chart
        }

        chart.xlabel = function(value) {
            if (!arguments.length) return xlabel
            if (typeof(value) != 'string') {
                console.warn('invalid value for xlabel', value)
                return
            }
            xlabel = value
            return chart
        }

        chart.ylabel = function(value) {
            if (!arguments.length) return ylabel
            if (typeof(value) != 'string') {
                console.warn('invalid value for ylabel', value)
                return
            }
            ylabel = value
            return chart
        }

        chart.draw_yAxis = function(value) {
            if (!arguments.length) return draw_yAxis
            if (typeof(value) != "boolean") {
                console.warn("invalid value for draw_yAxis", value)
                return
            }
            draw_yAxis = value
            return chart
        }

        chart.draw_xAxis = function(value) {
            if (!arguments.length) return draw_xAxis
            if (typeof(value) != "boolean") {
                console.warn("invalid value for draw_xAxis", value)
                return
            }
            draw_xAxis = value
            return chart
        }

        chart.draw_xGrid = function(value) {
            if (!arguments.length) return draw_xGrid
            if (typeof(value) != "boolean") {
                console.warn("invalid value for draw_xGrid", value)
                return
            }
            draw_xGrid = value
            return chart
        }

        chart.draw_yGrid = function(value) {
            if (!arguments.length) return draw_yGrid
            if (typeof(value) != "boolean") {
                console.warn("invalid value for draw_yGrid", value)
                return
            }
            draw_yGrid = value
            return chart
        }

        chart.draw_datalabel = function(value) {
            if (!arguments.length) return draw_datalabel
            if (typeof(value) != "boolean") {
                console.warn("invalid value for draw_datalabel", value)
                return
            }
            draw_datalabel = value
            return chart
        }

        chart.color_scale = function(value) {
            if (!arguments.length) return color_scale
            if (typeof(value) != 'function') {
                console.warn('invalid value for color_scale', value)
                return
            }
            color_scale = value
            return chart
        }

        chart.global_value_extent = function(value) {
            if (!arguments.length) return global_value_extent
            if (typeof(value) != "object") {
                console.warn("invalid value for global_value_extent", value)
                return
            }
            global_value_extent = value
            return chart
        }

        return chart
    }
})()<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

var App = require('app');

App.ServiceConfig = Ember.Object.extend({
  serviceName: '',
  configCategories: [],
  configCategoriesMap: function() {
    var categoriesMap = {};
    this.get('configCategories').forEach(function(c) {
      if (!categoriesMap[c.get('name')]) categoriesMap[c.get('name')] = c;
    });
    return categoriesMap;
  }.property('configCategories.[]'),
  configs: [],
  restartRequired: false,
  restartRequiredMessage: '',
  restartRequiredHostsAndComponents: {},
  configGroups: [],
  dependentServiceNames: [],
  initConfigsLength: 0, // configs length after initialization in order to watch changes

  errorCount: Em.computed.alias('configsWithErrors.length'),

  /**
   * Properties for which some aggregations should be calculated
   * like configsWithErrors, changedConfigProperties etc.
   *
   * @type {Object[]}
   */
  activeProperties: function() {
    return this.get('configs').filter(function(c) {
      return c.get('isVisible') && !c.get('hiddenBySection') && (c.get('isRequiredByAgent') || c.get('isRequired'));
    });
  }.property('configs.@each.isVisible', 'configs.@each.hiddenBySection', 'configs.@each.isRequiredByAgent'),

  configsWithErrors: function() {
    return this.get('activeProperties').filter(function(c) {
      return !c.get('isValid') || !c.get('isValidOverride');
    });
  }.property('activeProperties.@each.isValid', 'activeProperties.@each.isValidOverride'),

  observeErrors: function() {
    this.get('configCategories').setEach('errorCount', 0);
    this.get('configsWithErrors').forEach(function(c) {
      if (this.get('configCategoriesMap')[c.get('category')]) {
        this.get('configCategoriesMap')[c.get('category')].incrementProperty('errorCount');
      }
    }, this);
  }.observes('configsWithErrors'),

  configTypes: function() {
    return App.StackService.find(this.get('serviceName')).get('configTypeList') || [];
  }.property('serviceName'),

  observeForeignKeys: function() {
    //TODO refactor or move this logic to other place
    var configs = this.get('configs');
    configs.forEach(function (item) {
      if (item.get('isVisible')) {
        var options = item.get('options');
        if (options && options.someProperty('foreignKeys')) {
          var options = options.filterProperty('foreignKeys');
          options.forEach(function (opt) {
            opt.foreignKeys.forEach(function (key) {
              var config = configs.findProperty('name', key);
              if (config) {
                config.set('isVisible', item.get('value') === opt.displayName);
              }
            });
          });
        }
      }
    });
  }.observes('configs.@each.isVisible'),

  /**
   * Collection of properties that were changed:
   * for saved properties use - isNotDefaultValue
   * for not saved properties (on wizards, for new services) use
   *    - isNotInitialValue
   * for added properties use - isNotSaved
   * @type {Object[]}
   */
  changedConfigProperties: function() {
    return this.get('activeProperties').filter(function(c) {
      return c.get('isNotDefaultValue') || c.get('isNotSaved') || c.get('isNotInitialValue');
    }, this);
  }.property('activeProperties.@each.isNotDefaultValue', 'activeProperties.@each.isNotSaved', 'activeProperties.@each.isNotInitialValue'),

  /**
   * Config with overrides that has values that differs from saved
   *
   * @type {Object[]}
   */
  configsWithChangedOverrides: Em.computed.filterBy('activeProperties', 'isOverrideChanged', true),

  /**
   * Defines if some configs were added/removed
   * @type {boolean}
   */
  configsLengthWasChanged: Em.computed.notEqualProperties('configs.length', 'initConfigsLength'),

  /**
   * @type {boolean}
   */
  isPropertiesChanged: Em.computed.or(
    'configsLengthWasChanged',
    'changedConfigProperties.length',
    'configsWithChangedOverrides.length'),

  init: function() {
    this._super();
    this.set('dependentServiceNames', App.StackService.find(this.get('serviceName')).get('dependentServiceNames') || []);
  }
});

App.ConfigSiteTag = Ember.Object.extend({
  site: DS.attr('string'),
  tag: DS.attr('string'),
  /**
   * Object map of hostname->override-tag for overrides.
   * Creators should set new object here.
   */
  hostOverrides: null
});
<commit_msg>AMBARI-17220 On click of Radio button is not loading ServiceConfigCategory under Advanced Tab. (ababiichuk)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

var App = require('app');

App.ServiceConfig = Ember.Object.extend({
  serviceName: '',
  configCategories: [],
  configCategoriesMap: function() {
    var categoriesMap = {};
    this.get('configCategories').forEach(function(c) {
      if (!categoriesMap[c.get('name')]) categoriesMap[c.get('name')] = c;
    });
    return categoriesMap;
  }.property('configCategories.[]'),
  configs: [],
  restartRequired: false,
  restartRequiredMessage: '',
  restartRequiredHostsAndComponents: {},
  configGroups: [],
  dependentServiceNames: [],
  initConfigsLength: 0, // configs length after initialization in order to watch changes

  errorCount: Em.computed.alias('configsWithErrors.length'),

  /**
   * Properties for which some aggregations should be calculated
   * like configsWithErrors, changedConfigProperties etc.
   *
   * @type {Object[]}
   */
  activeProperties: function() {
    return this.get('configs').filter(function(c) {
      return c.get('isVisible') && !c.get('hiddenBySection') && (c.get('isRequiredByAgent') || c.get('isRequired'));
    });
  }.property('configs.@each.isVisible', 'configs.@each.hiddenBySection', 'configs.@each.isRequiredByAgent'),

  configsWithErrors: function() {
    return this.get('activeProperties').filter(function(c) {
      return !c.get('isValid') || !c.get('isValidOverride');
    });
  }.property('activeProperties.@each.isValid', 'activeProperties.@each.isValidOverride'),

  observeErrors: function() {
    this.get('configCategories').setEach('errorCount', 0);
    this.get('configsWithErrors').forEach(function(c) {
      if (this.get('configCategoriesMap')[c.get('category')]) {
        this.get('configCategoriesMap')[c.get('category')].incrementProperty('errorCount');
      }
    }, this);
  }.observes('configsWithErrors'),

  configTypes: function() {
    return App.StackService.find(this.get('serviceName')).get('configTypeList') || [];
  }.property('serviceName'),

  radioConfigs: Em.computed.filterBy('configs', 'displayType', 'radio button'),

  observeForeignKeys: function() {
    //TODO refactor or move this logic to other place
    var configs = this.get('configs');
    configs.forEach(function (item) {
      if (item.get('isVisible')) {
        var options = item.get('options');
        if (options && options.someProperty('foreignKeys')) {
          var options = options.filterProperty('foreignKeys');
          options.forEach(function (opt) {
            opt.foreignKeys.forEach(function (key) {
              var config = configs.findProperty('name', key);
              if (config) {
                config.set('isVisible', item.get('value') === opt.displayName);
              }
            });
          });
        }
      }
    });
  }.observes('radioConfigs.@each.value'),

  /**
   * Collection of properties that were changed:
   * for saved properties use - isNotDefaultValue
   * for not saved properties (on wizards, for new services) use
   *    - isNotInitialValue
   * for added properties use - isNotSaved
   * @type {Object[]}
   */
  changedConfigProperties: function() {
    return this.get('activeProperties').filter(function(c) {
      return c.get('isNotDefaultValue') || c.get('isNotSaved') || c.get('isNotInitialValue');
    }, this);
  }.property('activeProperties.@each.isNotDefaultValue', 'activeProperties.@each.isNotSaved', 'activeProperties.@each.isNotInitialValue'),

  /**
   * Config with overrides that has values that differs from saved
   *
   * @type {Object[]}
   */
  configsWithChangedOverrides: Em.computed.filterBy('activeProperties', 'isOverrideChanged', true),

  /**
   * Defines if some configs were added/removed
   * @type {boolean}
   */
  configsLengthWasChanged: Em.computed.notEqualProperties('configs.length', 'initConfigsLength'),

  /**
   * @type {boolean}
   */
  isPropertiesChanged: Em.computed.or(
    'configsLengthWasChanged',
    'changedConfigProperties.length',
    'configsWithChangedOverrides.length'),

  init: function() {
    this._super();
    this.set('dependentServiceNames', App.StackService.find(this.get('serviceName')).get('dependentServiceNames') || []);
    this.observeForeignKeys();
  }
});

App.ConfigSiteTag = Ember.Object.extend({
  site: DS.attr('string'),
  tag: DS.attr('string'),
  /**
   * Object map of hostname->override-tag for overrides.
   * Creators should set new object here.
   */
  hostOverrides: null
});
<|endoftext|>