<commit_before>/*!
 * jQuery TrackMe v1.2 - 11/01/2016
 * --------------------------------
 * Original author: Marco Trevisani (marco.trevisani@ynap.com)
 * Further changes, comments:
 * Licensed under the MIT license
 */
; (function ($, window, document) {
    "use strict";

    var pluginName = "trackMe";

    function TrackMe(element, options) {
        this.element = element;
        this._name = pluginName;
        this._defaults = $.fn.trackMe.defaults;
        this.options = $.extend({}, this._defaults, options);
        this.trackingData = {};
        this.init();
    }

    // - Private Functions - - -
    var formIsValid = function (formId) {
        if (typeof (formId) !== "undefined") {
            var $formToValidate = $("#" + formId);
            if ($formToValidate.length && !$formToValidate.valid()) {
                return false;
            }
        }
        return true;
    };

    // ( Debug Layer )
    var onlineOrStageEnvironment = function () {
        if (document.location.hostname.match("yoox.com$")) {
            return true;
        }
        return false;
    },
    checkQueryString = function () {
        if (location.search.match("td=1$")) {
            return true;
        }
        return false;
    },
    debugTrackedEvent = function (category, action, label) {
        if (!onlineOrStageEnvironment() && checkQueryString()) {
            var messageText = "[EVENT] --------------------\nCategory: " + category + "\nAction: " + action + "\nLabel: " + label + "\n----------------------------",
                messageHtml = "Category: " + category + "
 Action: " + action + "
 Label: " + label + "
",
                $message = $("
").html("New Event:").after($("
").html(messageHtml)),
                $messageContainer = $("
", { "class": "track-event-notification-layer fade-in" });

            if (!$(".track-event-notification-layer").length) {
                $messageContainer.append($message);
                $("body").append($messageContainer);
            } else {
                clearTimeout(window.closeDebugLayerTimeout);
                $(".track-event-notification-layer").append($message).removeClass("fade-out").addClass("fade-in");
            }

            window.closeDebugLayerTimeout = setTimeout(function () {
                $(".track-event-notification-layer").removeClass("fade-in").addClass("fade-out").html("");
            }, 3000);

            console.log(messageText);
        }
    };

    // - Public Functions - - -
    $.extend(TrackMe.prototype, {
        // Initialization logic
        init: function () {
            this.buildCache();
            this.bindEvents();
        },
        destroy: function () {
            this.unbindEvents();
            this.$element.removeData();
        },

        // Cache DOM nodes for performance
        buildCache: function () {
            this.$element = $(this.element);
        },

        // Bind events that trigger methods
        bindEvents: function () {
            var plugin = this;
            plugin.$element.on("click" + "." + plugin._name, ".js-track-me", function () {
                plugin.startTracking.call(plugin, $(this));
            });
        },

        // Unbind events that trigger methods
        unbindEvents: function () {
            this.$element.off("." + this._name);
        },

        getTrackingData: function ($elm) {
            return {
                category: this.customTrackingData.category === "" ? $elm.data("trackingCategory") : this.customTrackingData.category,
                action: this.customTrackingData.action === "" ? $elm.data("trackingAction") : this.customTrackingData.action,
                label: $elm.data("trackingLabel"),
                labelChecked: $elm.data("trackingLabelChecked"),
                labelNotChecked: $elm.data("trackingLabelNotChecked"),
                event: $elm.data("trackingEvent"),
                formToValidate: $elm.data("trackingFormId")
            };
        },

        startTracking: function ($element) {
            var plugin = this;
            this.trackingData = this.getTrackingData($element);

            // Track checkbox events
            if ($element.is("input[type=checkbox]") && typeof (plugin.trackingData.labelChecked) !== "undefined") {
                var label = $element.is(":checked") ? plugin.trackingData.labelChecked : plugin.trackingData.labelNotChecked;

                if (typeof (plugin.trackingData.event) === "undefined" && label !== "undefined") {
                    plugin.trackUserEvent(plugin.trackingData.category, plugin.trackingData.action, label);
                } else {
                    $("body").off(plugin.trackingData.event).one(plugin.trackingData.event, function () {
                        plugin.trackUserEvent(jsInit.analytics.category, plugin.trackingData.action, label);
                    });
                }

                // Track only if form is valid
            } else if (typeof (plugin.trackingData.formToValidate) !== "undefined") {
                if (formIsValid(plugin.trackingData.formToValidate)) {
                    plugin.trackUserEvent(plugin.trackingData.category, plugin.trackingData.action, plugin.trackingData.label);
                }

                // Track on custom event
            } else {
                if (typeof (plugin.trackingData.event) === "undefined") {
                    plugin.trackUserEvent(plugin.trackingData.category, plugin.trackingData.action, plugin.trackingData.label);
                } else {
                    $("body").off(plugin.trackingData.event).one(plugin.trackingData.event, function () {
                        plugin.trackUserEvent(plugin.trackingData.category, plugin.trackingData.action, plugin.trackingData.label);
                    });
                }
            }

            this.callback();
        },

        setTrackingCategory: function (category) {
            this.customTrackingData.category = category;
        },

        setTrackingAction: function (action) {
            this.customTrackingData.action = action;
        },

        trackUserEvent: function (category, action, label) {
            if (typeof (label) !== "undefined" && typeof (action) !== "undefined") {
                $Y.track.userEvent("ga", { category: category, action: action, label: label });

                if (this.options.debug) {
                    debugTrackedEvent(category, action, label);
                }
            }
        },

        callback: function () {
            // Cache onComplete option
            var onComplete = this.options.onComplete;

            if (typeof onComplete === "function") {
                onComplete.call(this.element);
            }
        },

        trackingData: {
            category: "",
            action: "",
            label: "",
            labelChecked: "",
            labelNotChecked: "",
            event: "",
            formToValidate: ""
        },

        customTrackingData: {
            category: "",
            action: ""
        }
    });

    $.fn.trackMe = function (options) {
        this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new TrackMe(this, options));
            }
        });

        return this;
    };

    $.fn.trackMe.defaults = {
        debug: false,
        onComplete: function () { }
    };

    $.fn.triggerDelayed = function (event, delay) {
        delay = delay || 50;
        var element = $(this);
        setTimeout(function () {
            element.trigger(event);
        }, delay);
    };

})(jQuery, window, document);
<commit_msg>fixed custom data category priority<commit_after>/*!
 * jQuery TrackMe v1.2 - 11/01/2016
 * --------------------------------
 * Original author: Marco Trevisani (marco.trevisani@ynap.com)
 * Further changes, comments:
 * Licensed under the MIT license
 */
; (function ($, window, document) {
    "use strict";

    var pluginName = "trackMe";

    function TrackMe(element, options) {
        this.element = element;
        this._name = pluginName;
        this._defaults = $.fn.trackMe.defaults;
        this.options = $.extend({}, this._defaults, options);
        this.trackingData = {};
        this.init();
    }

    // - Private Functions - - -
    var formIsValid = function (formId) {
        if (typeof (formId) !== "undefined") {
            var $formToValidate = $("#" + formId);
            if ($formToValidate.length && !$formToValidate.valid()) {
                return false;
            }
        }
        return true;
    };

    // ( Debug Layer )
    var onlineOrStageEnvironment = function () {
        if (document.location.hostname.match("yoox.com$")) {
            return true;
        }
        return false;
    },
    checkQueryString = function () {
        if (location.search.match("td=1$")) {
            return true;
        }
        return false;
    },
    debugTrackedEvent = function (category, action, label) {
        if (!onlineOrStageEnvironment() && checkQueryString()) {
            var messageText = "[EVENT] --------------------\nCategory: " + category + "\nAction: " + action + "\nLabel: " + label + "\n----------------------------",
                messageHtml = "Category: " + category + "
 Action: " + action + "
 Label: " + label + "
",
                $message = $("
").html("New Event:").after($("
").html(messageHtml)),
                $messageContainer = $("
", { "class": "track-event-notification-layer fade-in" });

            if (!$(".track-event-notification-layer").length) {
                $messageContainer.append($message);
                $("body").append($messageContainer);
            } else {
                clearTimeout(window.closeDebugLayerTimeout);
                $(".track-event-notification-layer").append($message).removeClass("fade-out").addClass("fade-in");
            }

            window.closeDebugLayerTimeout = setTimeout(function () {
                $(".track-event-notification-layer").removeClass("fade-in").addClass("fade-out").html("");
            }, 3000);

            console.log(messageText);
        }
    };

    // - Public Functions - - -
    $.extend(TrackMe.prototype, {
        // Initialization logic
        init: function () {
            this.buildCache();
            this.bindEvents();
        },
        destroy: function () {
            this.unbindEvents();
            this.$element.removeData();
        },

        // Cache DOM nodes for performance
        buildCache: function () {
            this.$element = $(this.element);
        },

        // Bind events that trigger methods
        bindEvents: function () {
            var plugin = this;
            plugin.$element.on("click" + "." + plugin._name, ".js-track-me", function () {
                plugin.startTracking.call(plugin, $(this));
            });
        },

        // Unbind events that trigger methods
        unbindEvents: function () {
            this.$element.off("." + this._name);
        },

        getTrackingData: function ($elm) {
            return {
                category: typeof ($elm.data("trackingCategory")) === "undefined" ? this.customTrackingData.category : $elm.data("trackingCategory"),
                action: typeof ($elm.data("trackingAction")) === "undefined" ? this.customTrackingData.action : $elm.data("trackingAction"),
                label: $elm.data("trackingLabel"),
                labelChecked: $elm.data("trackingLabelChecked"),
                labelNotChecked: $elm.data("trackingLabelNotChecked"),
                event: $elm.data("trackingEvent"),
                formToValidate: $elm.data("trackingFormId")
            };
        },

        startTracking: function ($element) {
            var plugin = this;
            this.trackingData = this.getTrackingData($element);

            // Track checkbox events
            if ($element.is("input[type=checkbox]") && typeof (plugin.trackingData.labelChecked) !== "undefined") {
                var label = $element.is(":checked") ? plugin.trackingData.labelChecked : plugin.trackingData.labelNotChecked;

                if (typeof (plugin.trackingData.event) === "undefined" && label !== "undefined") {
                    plugin.trackUserEvent(plugin.trackingData.category, plugin.trackingData.action, label);
                } else {
                    $("body").off(plugin.trackingData.event).one(plugin.trackingData.event, function () {
                        plugin.trackUserEvent(jsInit.analytics.category, plugin.trackingData.action, label);
                    });
                }

                // Track only if form is valid
            } else if (typeof (plugin.trackingData.formToValidate) !== "undefined") {
                if (formIsValid(plugin.trackingData.formToValidate)) {
                    plugin.trackUserEvent(plugin.trackingData.category, plugin.trackingData.action, plugin.trackingData.label);
                }

                // Track on custom event
            } else {
                if (typeof (plugin.trackingData.event) === "undefined") {
                    plugin.trackUserEvent(plugin.trackingData.category, plugin.trackingData.action, plugin.trackingData.label);
                } else {
                    $("body").off(plugin.trackingData.event).one(plugin.trackingData.event, function () {
                        plugin.trackUserEvent(plugin.trackingData.category, plugin.trackingData.action, plugin.trackingData.label);
                    });
                }
            }

            this.callback();
        },

        setTrackingCategory: function (category) {
            this.customTrackingData.category = category;
        },

        setTrackingAction: function (action) {
            this.customTrackingData.action = action;
        },

        trackUserEvent: function (category, action, label) {
            if (typeof (label) !== "undefined" && typeof (action) !== "undefined") {
                $Y.track.userEvent("ga", { category: category, action: action, label: label });

                if (this.options.debug) {
                    debugTrackedEvent(category, action, label);
                }
            }
        },

        callback: function () {
            // Cache onComplete option
            var onComplete = this.options.onComplete;

            if (typeof onComplete === "function") {
                onComplete.call(this.element);
            }
        },

        trackingData: {
            category: "",
            action: "",
            label: "",
            labelChecked: "",
            labelNotChecked: "",
            event: "",
            formToValidate: ""
        },

        customTrackingData: {
            category: "",
            action: ""
        }
    });

    $.fn.trackMe = function (options) {
        this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new TrackMe(this, options));
            }
        });

        return this;
    };

    $.fn.trackMe.defaults = {
        debug: false,
        onComplete: function () { }
    };

    $.fn.triggerDelayed = function (event, delay) {
        delay = delay || 50;
        var element = $(this);
        setTimeout(function () {
            element.trigger(event);
        }, delay);
    };

})(jQuery, window, document);
<|endoftext|>


<commit_before>require('angular-ui-router')
require('angular-resource')

var app = angular.module('hyloAdmin', ['ngResource', 'ui.router', 'ngTagsInput'])
var Chart = require('./services/Chart')

require('../app/services/Community')(app)
require('../app/services/Project')(app)
require('../app/directives/masonry')(app)
require('../app/filters')(app)

app.factory('Admin', require('./services/Admin'))

app.directive('chart', function () {
  return {
    restrict: 'E',
    scope: {
      data: '=',
      setup: '='
    },
    replace: true,
    template: '
<svg></svg>
',
    link: function (scope, element, attrs) {
      element.addClass('chart')

      Chart.render({
        data: scope.data,
        to: element.find('svg')[0],
        type: attrs.type || 'bar',
        setup: scope.setup
      })
    }
  }
})

app.config(function ($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('root', {
      url: '/admin',
      template: '

',
      controller: function () {},
      resolve: {
        currentUser: function (Admin, $rootScope) {
          return Admin.get().$promise.then(function (user) {
            $rootScope.currentUser = user
          }, function (err) {
            if (err.status === 403) {
              window.location = '/noo/admin/login'
            }
          })
        }
      }
    })
    .state('communities', {
      parent: 'root',
      url: '/communities',
      views: {
        main: {
          templateUrl: '/admin/communities.tpl.html',
          controller: function ($scope, Community) {
            $scope.sortKey = 'name'
            $scope.sortOrder = 'asc'

            Community.query().$promise.then(cs => {
              $scope.communities = cs
              $scope.resort()
            })

            $scope.resort = function () {
              $scope.communities = _.sortByOrder($scope.communities, [$scope.sortKey], [$scope.sortOrder])
              $scope.$broadcast('masonry.update')
            }
          }
        }
      }
    })
    .state('metrics', {
      parent: 'root',
      url: '/metrics',
      resolve: {
        metrics: function (Admin) {
          return Admin.getMetrics().$promise
        }
      },
      views: {
        main: {
          templateUrl: '/admin/metrics.tpl.html',
          controller: function ($scope, metrics) {
            $scope.metrics = metrics

            $scope.setupNewUserActivity = function (chart) {
              chart.yDomain([0, 1])
            }
          }
        }
      }
    })
})

app.config(function ($locationProvider) {
  $locationProvider.html5Mode(true)
})

angular.element(document).ready(function () {
  angular.bootstrap(document.body, ['hyloAdmin'], {strictDi: true})
})
<commit_msg>fix admin<commit_after>require('angular-ui-router')
require('angular-resource')

var app = angular.module('hyloAdmin', ['ngResource', 'ui.router'])
var Chart = require('./services/Chart')

require('../app/services/Community')(app)
require('../app/services/Project')(app)
require('../app/directives/masonry')(app)
require('../app/filters')(app)

app.factory('Admin', require('./services/Admin'))

app.directive('chart', function () {
  return {
    restrict: 'E',
    scope: {
      data: '=',
      setup: '='
    },
    replace: true,
    template: '
<svg></svg>
',
    link: function (scope, element, attrs) {
      element.addClass('chart')

      Chart.render({
        data: scope.data,
        to: element.find('svg')[0],
        type: attrs.type || 'bar',
        setup: scope.setup
      })
    }
  }
})

app.config(function ($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('root', {
      url: '/admin',
      template: '

',
      controller: function () {},
      resolve: {
        currentUser: function (Admin, $rootScope) {
          return Admin.get().$promise.then(function (user) {
            $rootScope.currentUser = user
          }, function (err) {
            if (err.status === 403) {
              window.location = '/noo/admin/login'
            }
          })
        }
      }
    })
    .state('communities', {
      parent: 'root',
      url: '/communities',
      views: {
        main: {
          templateUrl: '/admin/communities.tpl.html',
          controller: function ($scope, Community) {
            $scope.sortKey = 'name'
            $scope.sortOrder = 'asc'

            Community.query().$promise.then(cs => {
              $scope.communities = cs
              $scope.resort()
            })

            $scope.resort = function () {
              $scope.communities = _.sortByOrder($scope.communities, [$scope.sortKey], [$scope.sortOrder])
              $scope.$broadcast('masonry.update')
            }
          }
        }
      }
    })
    .state('metrics', {
      parent: 'root',
      url: '/metrics',
      resolve: {
        metrics: function (Admin) {
          return Admin.getMetrics().$promise
        }
      },
      views: {
        main: {
          templateUrl: '/admin/metrics.tpl.html',
          controller: function ($scope, metrics) {
            $scope.metrics = metrics

            $scope.setupNewUserActivity = function (chart) {
              chart.yDomain([0, 1])
            }
          }
        }
      }
    })
})

app.config(function ($locationProvider) {
  $locationProvider.html5Mode(true)
})

angular.element(document).ready(function () {
  angular.bootstrap(document.body, ['hyloAdmin'], {strictDi: true})
})
<|endoftext|>


<commit_before>/**
 * Contains the logic for the sidebar.
 *
 * @returns {{}}
 */
webvowlApp.sidebar = function () {

	var sidebar = {};

	/**
	 * Setup the menu bar.
	 */
	sidebar.setup = function () {
		setupCollapsing();
	};

	function setupCollapsing() {
		// adapted version of this example: http://www.normansblog.de/simple-jquery-accordion/
		function collapseContainers(containers) {
			containers.style("display", "none");
		}

		function expandContainers(containers) {
			containers.style("display", null);
		}

		var triggers = d3.selectAll(".accordion-trigger");

		// Collapse all inactive triggers on startup
		collapseContainers(d3.selectAll(".accordion-trigger:not(.accordion-trigger-active) + div"));

		triggers.on("click", function () {
			var selectedTrigger = d3.select(this),
				activeTriggers = d3.selectAll(".accordion-trigger-active");

			if (selectedTrigger.classed("accordion-trigger-active")) {
				// Collapse the active (which is also the selected) trigger
				collapseContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", false);
			} else {
				// Collapse the other trigger ...
				collapseContainers(d3.selectAll(".accordion-trigger-active + div"));
				activeTriggers.classed("accordion-trigger-active", false);
				// ... and expand the selected one
				expandContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", true);
			}
		});
	}

	/**
	 * Updates the information of the passed ontology.
	 * @param data the graph data
	 * @param statistics the statistics module
	 */
	sidebar.updateOntologyInformation = function (data, statistics) {
		displayGraphInformation(data);
		displayGraphStatistics(data.metrics, statistics);
	};

	function displayGraphInformation(data) {
		var header = data.header;

		d3.select("#title").text(header.title);
		d3.select("#about").attr("href", header.uri).attr("target", "_blank").text(header.uri);
		d3.select("#version").text(header.version);
		d3.select("#authors").text(header.author);
		d3.select("#description").text(header.description);
	}

	function displayGraphStatistics(deliveredMetrics, statistics) {
		// Metrics are optional and may be undefined
		deliveredMetrics = deliveredMetrics || {};

		d3.select("#classCount")
			.text(deliveredMetrics.classCount || statistics.classCount());
		d3.select("#datatypeCount")
			.text(deliveredMetrics.datatypeCount || statistics.datatypeCount());
		d3.select("#propertyCount")
			.text(deliveredMetrics.propertyCount || statistics.propertyCount());
		d3.select("#nodeCount")
			.text(statistics.nodeCount());
		d3.select("#edgeCount")
			.text(statistics.edgeCount());
	}

	/**
	 * Update the information of the selected node.
	 * @param selectedElement the selection or null if nothing is selected
	 */
	sidebar.updateSelectionInformation = function (selectedElement) {
		// Click event was prevented when dragging
		if (d3.event.defaultPrevented) {
			return;
		}

		var isTriggerActive = d3.select("#selection-details-trigger").classed("accordion-trigger-active");
		if (selectedElement && !isTriggerActive) {
			d3.select("#selection-details-trigger").node().click();
		} else if (!selectedElement && isTriggerActive) {
			d3.select("#selection-details-trigger").node().click();
			showSelectionAdvice();
			return;
		}

		if (selectedElement instanceof webvowl.labels.BaseLabel) {
			displayLabelInformation(selectedElement);
		} else if (selectedElement instanceof webvowl.nodes.BaseNode) {
			displayNodeInformation(selectedElement);
		}
	};

	function showSelectionAdvice() {
		setSelectionInformationVisibility(false, false, true);
	}

	function setSelectionInformationVisibility(showClasses, showProperties, showAdvice) {
		d3.select("#classSelectionInformation").classed("hidden", !showClasses);
		d3.select("#propertySelectionInformation").classed("hidden", !showProperties);
		d3.select("#noSelectionInformation").classed("hidden", !showAdvice);
	}

	function displayLabelInformation(property) {
		showPropertyInformations();

		setUriLabel(d3.select("#propname"), property.label(), property.uri());
		d3.select("#typeProp").text(property.type());

		if (property.inverse() !== undefined) {
			d3.select("#inverse").style("display", "block");
			setUriLabel(d3.select("#inverse span"), property.inverse().label(), property.inverse().uri());
		} else {
			d3.select("#inverse").style("display", "none");
		}

		var equivalentUriSpan = d3.select("#propEquivUri");
		displayEquivalentElements(property.equivalent(), equivalentUriSpan);

		if (property.minCardinality() !== undefined) {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "block");
			d3.select("#minCardinality span").text(property.minCardinality());
			d3.select("#maxCardinality").style("display", "block");

			if (property.maxCardinality() !== undefined) {
				d3.select("#maxCardinality span").text(property.maxCardinality());
			} else {
				d3.select("#maxCardinality span").text("*");
			}

		} else if (property.cardinality() !== undefined) {
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
			d3.select("#infoCardinality").style("display", "block");
			d3.select("#infoCardinality span").text(property.cardinality());
		} else {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
		}

		setUriLabel(d3.select("#domain"), property.domain().label(), property.domain().uri());
		setUriLabel(d3.select("#range"), property.range().label(), property.range().uri());

		displayAttributes(property.attributes(), d3.select("#propAttributes"));
	}

	function showPropertyInformations() {
		setSelectionInformationVisibility(false, true, false);
	}

	function setUriLabel(element, name, uri) {
		element.selectAll("*").remove();
		appendUriLabel(element, name, uri);
	}

	function appendUriLabel(element, name, uri) {
		var tag;

		if (uri) {
			tag = element.append("a").attr("href", uri).attr("target", "_blank");
		} else {
			tag = element.append("span");
		}
		tag.text(name);
	}

	function displayAttributes(attributes, textSpan) {
		var spanParent = d3.select(textSpan.node().parentNode);

		if (attributes && attributes.length > 0) {
			textSpan.text(attributes.join(", "));

			spanParent.classed("hidden", false);
		} else {
			spanParent.classed("hidden", true);
		}
	}

	function displayNodeInformation(node) {
		showClassInformations();

		setUriLabel(d3.select("#name"), node.label(), node.uri());

		/* Equivalent stuff. */
		var equivalentUriSpan = d3.select("#classEquivUri");
		displayEquivalentElements(node.equivalent(), equivalentUriSpan);

		d3.select("#typeNode").text(node.type());

		/* Disjoint stuff. */
		var disjointNodes = d3.select("#disjointNodes");
		var disjointNodesParent = d3.select(disjointNodes.node().parentNode);

		if (node.disjointWith() !== undefined) {
			disjointNodes.selectAll("*").remove();

			node.disjointWith().forEach(function (element, index) {
				if (index > 0) {
					disjointNodes.append("span").text(", ");
				}
				appendUriLabel(disjointNodes, element.label(), element.uri());
			});

			disjointNodesParent.classed("hidden", false);
		} else {
			disjointNodesParent.classed("hidden", true);
		}

		displayAttributes(node.attributes(), d3.select("#classAttributes"));
	}

	function showClassInformations() {
		setSelectionInformationVisibility(true, false, false);
	}

	function displayEquivalentElements(equivalentElements, equivalentUriSpan) {
		var equivalentUriSpanParent = d3.select(equivalentUriSpan.node().parentNode);

		if (equivalentElements && equivalentElements.length) {
			equivalentUriSpan.selectAll("*").remove();
			equivalentElements.forEach(function (element, index) {
				if (index > 0) {
					equivalentUriSpan.append("span").text(", ");
				}
				appendUriLabel(equivalentUriSpan, element.label(), element.uri());
			});

			equivalentUriSpanParent.classed("hidden", false);
		} else {
			equivalentUriSpanParent.classed("hidden", true);
		}
	}

	return sidebar;
};
<commit_msg>Reset selection info on ontology switch<commit_after>/**
 * Contains the logic for the sidebar.
 *
 * @returns {{}}
 */
webvowlApp.sidebar = function () {

	var sidebar = {};

	/**
	 * Setup the menu bar.
	 */
	sidebar.setup = function () {
		setupCollapsing();
	};

	function setupCollapsing() {
		// adapted version of this example: http://www.normansblog.de/simple-jquery-accordion/
		function collapseContainers(containers) {
			containers.style("display", "none");
		}

		function expandContainers(containers) {
			containers.style("display", null);
		}

		var triggers = d3.selectAll(".accordion-trigger");

		// Collapse all inactive triggers on startup
		collapseContainers(d3.selectAll(".accordion-trigger:not(.accordion-trigger-active) + div"));

		triggers.on("click", function () {
			var selectedTrigger = d3.select(this),
				activeTriggers = d3.selectAll(".accordion-trigger-active");

			if (selectedTrigger.classed("accordion-trigger-active")) {
				// Collapse the active (which is also the selected) trigger
				collapseContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", false);
			} else {
				// Collapse the other trigger ...
				collapseContainers(d3.selectAll(".accordion-trigger-active + div"));
				activeTriggers.classed("accordion-trigger-active", false);
				// ... and expand the selected one
				expandContainers(d3.select(selectedTrigger.node().nextElementSibling));
				selectedTrigger.classed("accordion-trigger-active", true);
			}
		});
	}

	/**
	 * Updates the information of the passed ontology.
	 * @param data the graph data
	 * @param statistics the statistics module
	 */
	sidebar.updateOntologyInformation = function (data, statistics) {
		displayGraphInformation(data);
		displayGraphStatistics(data.metrics, statistics);
		// Reset the sidebar selection
		sidebar.updateSelectionInformation(undefined);
	};

	function displayGraphInformation(data) {
		var header = data.header;

		d3.select("#title").text(header.title);
		d3.select("#about").attr("href", header.uri).attr("target", "_blank").text(header.uri);
		d3.select("#version").text(header.version);
		d3.select("#authors").text(header.author);
		d3.select("#description").text(header.description);
	}

	function displayGraphStatistics(deliveredMetrics, statistics) {
		// Metrics are optional and may be undefined
		deliveredMetrics = deliveredMetrics || {};

		d3.select("#classCount")
			.text(deliveredMetrics.classCount || statistics.classCount());
		d3.select("#datatypeCount")
			.text(deliveredMetrics.datatypeCount || statistics.datatypeCount());
		d3.select("#propertyCount")
			.text(deliveredMetrics.propertyCount || statistics.propertyCount());
		d3.select("#nodeCount")
			.text(statistics.nodeCount());
		d3.select("#edgeCount")
			.text(statistics.edgeCount());
	}

	/**
	 * Update the information of the selected node.
	 * @param selectedElement the selection or null if nothing is selected
	 */
	sidebar.updateSelectionInformation = function (selectedElement) {
		// Click event was prevented when dragging
		if (d3.event && d3.event.defaultPrevented) {
			return;
		}

		var isTriggerActive = d3.select("#selection-details-trigger").classed("accordion-trigger-active");
		if (selectedElement && !isTriggerActive) {
			d3.select("#selection-details-trigger").node().click();
		} else if (!selectedElement && isTriggerActive) {
			d3.select("#selection-details-trigger").node().click();
			showSelectionAdvice();
			return;
		}

		if (selectedElement instanceof webvowl.labels.BaseLabel) {
			displayLabelInformation(selectedElement);
		} else if (selectedElement instanceof webvowl.nodes.BaseNode) {
			displayNodeInformation(selectedElement);
		}
	};

	function showSelectionAdvice() {
		setSelectionInformationVisibility(false, false, true);
	}

	function setSelectionInformationVisibility(showClasses, showProperties, showAdvice) {
		d3.select("#classSelectionInformation").classed("hidden", !showClasses);
		d3.select("#propertySelectionInformation").classed("hidden", !showProperties);
		d3.select("#noSelectionInformation").classed("hidden", !showAdvice);
	}

	function displayLabelInformation(property) {
		showPropertyInformations();

		setUriLabel(d3.select("#propname"), property.label(), property.uri());
		d3.select("#typeProp").text(property.type());

		if (property.inverse() !== undefined) {
			d3.select("#inverse").style("display", "block");
			setUriLabel(d3.select("#inverse span"), property.inverse().label(), property.inverse().uri());
		} else {
			d3.select("#inverse").style("display", "none");
		}

		var equivalentUriSpan = d3.select("#propEquivUri");
		displayEquivalentElements(property.equivalent(), equivalentUriSpan);

		if (property.minCardinality() !== undefined) {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "block");
			d3.select("#minCardinality span").text(property.minCardinality());
			d3.select("#maxCardinality").style("display", "block");

			if (property.maxCardinality() !== undefined) {
				d3.select("#maxCardinality span").text(property.maxCardinality());
			} else {
				d3.select("#maxCardinality span").text("*");
			}

		} else if (property.cardinality() !== undefined) {
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
			d3.select("#infoCardinality").style("display", "block");
			d3.select("#infoCardinality span").text(property.cardinality());
		} else {
			d3.select("#infoCardinality").style("display", "none");
			d3.select("#minCardinality").style("display", "none");
			d3.select("#maxCardinality").style("display", "none");
		}

		setUriLabel(d3.select("#domain"), property.domain().label(), property.domain().uri());
		setUriLabel(d3.select("#range"), property.range().label(), property.range().uri());

		displayAttributes(property.attributes(), d3.select("#propAttributes"));
	}

	function showPropertyInformations() {
		setSelectionInformationVisibility(false, true, false);
	}

	function setUriLabel(element, name, uri) {
		element.selectAll("*").remove();
		appendUriLabel(element, name, uri);
	}

	function appendUriLabel(element, name, uri) {
		var tag;

		if (uri) {
			tag = element.append("a").attr("href", uri).attr("target", "_blank");
		} else {
			tag = element.append("span");
		}
		tag.text(name);
	}

	function displayAttributes(attributes, textSpan) {
		var spanParent = d3.select(textSpan.node().parentNode);

		if (attributes && attributes.length > 0) {
			textSpan.text(attributes.join(", "));

			spanParent.classed("hidden", false);
		} else {
			spanParent.classed("hidden", true);
		}
	}

	function displayNodeInformation(node) {
		showClassInformations();

		setUriLabel(d3.select("#name"), node.label(), node.uri());

		/* Equivalent stuff. */
		var equivalentUriSpan = d3.select("#classEquivUri");
		displayEquivalentElements(node.equivalent(), equivalentUriSpan);

		d3.select("#typeNode").text(node.type());

		/* Disjoint stuff. */
		var disjointNodes = d3.select("#disjointNodes");
		var disjointNodesParent = d3.select(disjointNodes.node().parentNode);

		if (node.disjointWith() !== undefined) {
			disjointNodes.selectAll("*").remove();

			node.disjointWith().forEach(function (element, index) {
				if (index > 0) {
					disjointNodes.append("span").text(", ");
				}
				appendUriLabel(disjointNodes, element.label(), element.uri());
			});

			disjointNodesParent.classed("hidden", false);
		} else {
			disjointNodesParent.classed("hidden", true);
		}

		displayAttributes(node.attributes(), d3.select("#classAttributes"));
	}

	function showClassInformations() {
		setSelectionInformationVisibility(true, false, false);
	}

	function displayEquivalentElements(equivalentElements, equivalentUriSpan) {
		var equivalentUriSpanParent = d3.select(equivalentUriSpan.node().parentNode);

		if (equivalentElements && equivalentElements.length) {
			equivalentUriSpan.selectAll("*").remove();
			equivalentElements.forEach(function (element, index) {
				if (index > 0) {
					equivalentUriSpan.append("span").text(", ");
				}
				appendUriLabel(equivalentUriSpan, element.label(), element.uri());
			});

			equivalentUriSpanParent.classed("hidden", false);
		} else {
			equivalentUriSpanParent.classed("hidden", true);
		}
	}

	return sidebar;
};
<|endoftext|>


<commit_before>'use strict';

var _ = require( '../utils' );

var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
var sampleRate = audioContext.sampleRate;

function toFreq( note ) {
  // A4 is 69.
  return Math.pow( 2, ( note - 69 ) / 12 ) * 440;
}

// delay is in seconds.
function playSound( sound, delay ) {
  var source = audioContext.createBufferSource();
  source.buffer = sound;
  source.connect( audioContext.destination );
  source.start( delay ? audioContext.currentTime + delay : 0 );
}

// duration is in seconds.
function generateAudioBuffer( freq, fn, duration, volume ) {
  var length = duration * sampleRate;

  var buffer = audioContext.createBuffer( 1, length, sampleRate );
  var channel = buffer.getChannelData(0);
  for ( var i = 0; i < length; i++ ) {
    channel[i] = fn( freq * i / sampleRate, i / length ) * volume;
  }

  return buffer;
}

var BPM = 140;
var NOTE = 2 * 60 / BPM * 1000;

var N = 1e-3 * NOTE;
var N2 = N / 2;
var N4 = N2 / 2;
var N8 = N4 / 2;

function sine( sample ) {
  return Math.sin( sample * 2  * Math.PI );
}

function createWaveform( noise, decay ) {
  return function waveform( sample, time ) {
    var wave = _.clamp( sine( sample ) + _.randFloatSpread( noise ), -1, 1 );
    var env = Math.exp( -time * decay );
    return wave * env;
  };
}

function bass( sample, time ) {
  var wave = 0.5 * ( sine( sample ) + sine( 0.5 * sample ) );
  var env = Math.exp( -time * 8 );
  return wave * env;
}

var kick = createWaveform( 0.05, 24 );
var snare = createWaveform( 0.8, 16 );

var E3 = toFreq( 52 );

var snareNote = generateAudioBuffer( E3, snare, N2, 0.5 );
// playSound( snareNote );

var kickNote = generateAudioBuffer( toFreq( 28 ), kick, N2 + N8, 1 );
playSound( kickNote );

var bassNote = generateAudioBuffer( toFreq( 32 ), bass, N, 0.5 );
// playSound( bassNote );

var noteNames = [ 'c', 'cs', 'd', 'ds', 'e', 'f', 'fs', 'g', 'gs', 'a', 'as', 'b' ];

function toNoteString( note ) {
  var name = noteNames[ note % 12 ];
  var octave = Math.floor( note / 12 ) - 1;
  return name + octave;
}

function generateNotes( fn, duration, volume ) {
  var notes = {};

  function createNoteProperty( note ) {
    var sound;

    Object.defineProperty( notes, toNoteString( note ), {
      get: function() {
        if ( !sound ) {
          sound = generateAudioBuffer( toFreq( note ), fn, duration, volume );
        }

        return sound;
      }
    });
  }

  // From A1 (21) to A6 (93).
  for ( var i = 21; i <= 93; i++ ) {
    createNoteProperty( i );
  }

  return notes;
}

console.time( 'generate' );
var snares = generateNotes( snare, N4, 0.5 );
var basses = generateNotes( bass, N2, 0.5 );
console.timeEnd( 'generate' );
<commit_msg>Add batched sounds tests.<commit_after>'use strict';

var _ = require( '../utils' );

var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
var sampleRate = audioContext.sampleRate;

function toFreq( note ) {
  // A4 is 69.
  return Math.pow( 2, ( note - 69 ) / 12 ) * 440;
}

// delay is in seconds.
function playSound( sound, delay ) {
  var source = audioContext.createBufferSource();
  source.buffer = sound;
  source.connect( audioContext.destination );
  source.start( delay ? audioContext.currentTime + delay : 0 );
}

// duration is in seconds.
function generateAudioBuffer( freq, fn, duration, volume ) {
  var length = duration * sampleRate;

  var buffer = audioContext.createBuffer( 1, length, sampleRate );
  var channel = buffer.getChannelData(0);
  for ( var i = 0; i < length; i++ ) {
    channel[i] = fn( freq * i / sampleRate, i / length ) * volume;
  }

  return buffer;
}

var BPM = 140;
var NOTE = 2 * 60 / BPM * 1000;

var N = 1e-3 * NOTE;
var N2 = N / 2;
var N4 = N2 / 2;
var N8 = N4 / 2;

function sine( sample ) {
  return Math.sin( sample * 2  * Math.PI );
}

function createWaveform( noise, decay ) {
  return function waveform( sample, time ) {
    var wave = _.clamp( sine( sample ) + _.randFloatSpread( noise ), -1, 1 );
    var env = Math.exp( -time * decay );
    return wave * env;
  };
}

function bass( sample, time ) {
  var wave = 0.5 * ( sine( sample ) + sine( 0.5 * sample ) );
  var env = Math.exp( -time * 8 );
  return wave * env;
}

var kick = createWaveform( 0.05, 24 );
var snare = createWaveform( 0.8, 16 );

var E3 = toFreq( 52 );

var snareNote = generateAudioBuffer( E3, snare, N2, 0.5 );
// playSound( snareNote );

var kickNote = generateAudioBuffer( toFreq( 28 ), kick, N2 + N8, 1 );
// playSound( kickNote );

var bassNote = generateAudioBuffer( toFreq( 32 ), bass, N, 0.5 );
// playSound( bassNote );

var noteNames = [ 'c', 'cs', 'd', 'ds', 'e', 'f', 'fs', 'g', 'gs', 'a', 'as', 'b' ];

function toNoteString( note ) {
  var name = noteNames[ note % 12 ];
  var octave = Math.floor( note / 12 ) - 1;
  return name + octave;
}

function generateNotes( fn, duration, volume ) {
  var notes = {};

  function createNoteProperty( note ) {
    var sound;

    Object.defineProperty( notes, toNoteString( note ), {
      get: function() {
        if ( !sound ) {
          sound = generateAudioBuffer( toFreq( note ), fn, duration, volume );
        }

        return sound;
      }
    });
  }

  // From A1 (21) to A6 (93).
  for ( var i = 21; i <= 93; i++ ) {
    createNoteProperty( i );
  }

  return notes;
}

console.time( 'generate' );
var snares = generateNotes( snare, N4, 0.5 );
var kicks = generateNotes( kick, N2 + N8, 0.5 );
var basses = generateNotes( bass, N2 + N4, 0.5 );
console.timeEnd( 'generate' );

function playNotes( sounds, bars, barDuration ) {
  bars( sounds ).map(function( bar, barIndex ) {
    var barDelay = barIndex * barDuration;
    for ( var i = 0; i < bar.length; i += 2 ) {
      var note = bar[ i ];
      var delay = bar[ i + 1 ];
      playSound( note, barDelay + delay );
    }
  });
}

playNotes( snares, function( _ ) { return [
  [
    _.a2, 0,
    _.g3, N2,
    _.g3, N2 + N4
  ],
  [
    _.g3, 0,
    _.g3, N8,
    _.g3, N4,
    _.g3, N4 + N8,
    _.g3, N2
  ]
]; }, N );

playNotes( basses, function( _ ) { return [
  [
    _.a4, 0,
    _.c5, N4,
    _.e5, N2,
    _.c5, N2 + N4
  ],
  [
    _.a4, 0,
    _.c5, N4,
    _.e5, N2,
    _.e5, N2 + N8,
    _.c5, N2 + N4
  ],
  [
    _.f5, 0,
    _.e5, N2
  ],
  [
    _.d5, 0,
    _.a4, N2
  ],
  [
    _.c5, 0
  ],
  [
    _.d5, 0
  ],
  [
    _.b4, 0
  ]

]; }, N );
<|endoftext|>


<commit_before>/**
 * @copyright Devexperts
 *
 * @requires DX
 * @requires DX.Dom
 * @requires DX.Bem
 * @requires DX.Event
 * @requires DropDown
 * @namespace
 */
var Colorpicker = (function(DX, window, document, undefined) {
	'use strict';

	var event = DX.Event,
		CN_COLORPICKER = 'colorPicker',
		M_OPEN = 'opened',
		CN_COLORPICKER_LABEL = CN_COLORPICKER + '--label',
		CN_COLORPICKER_VALUE = CN_COLORPICKER + '--value',
		defaults = {
			colorList: ['#511717', '#d90100', '#ff504f', '#dddddd']
		},
		INNER_TMPL = [
			'
',
			'<button class="button" type="button">',
			'',
			'',
			'',
			'</button>',
			'
'
		].join(''),
		OPTION_TMPL = '

';

	/**
	 * Creates new Colorpicker
	 * @constructor Colorpicker
	 * @param {HTMLInputElement} input
	 * @param {Array} colorList
	 */
	return function Colorpicker(input, colorList) {
		var block, valueElement, dropDown, disabled = input.disabled;

		function init() {
			initAppearance();
			dropDown = new DropDown(block, {
				optionTmpl: OPTION_TMPL,
				modifiers: [CN_COLORPICKER]
			});
			initListeners();
			setColorListHandler();

			DX.Event.trigger(input, Colorpicker.E_CREATED, {
				detail: {
					block: block,
					eventTarget: input
				}
			});
		}

		function initListeners() {
			var dropDownEventTarget = dropDown.getEventTarget();

			block.addEventListener(DX.Event.TOUCH_CLICK, toggleDropDown, true);

			dropDownEventTarget.addEventListener(DropDown.E_SHOWN, setOpenedState, true);
			dropDownEventTarget.addEventListener(DropDown.E_HIDDEN, removeOpenedState, true);
			dropDownEventTarget.addEventListener(DropDown.E_CHANGED, dropdownIndexChangeHandler, true);

			input.addEventListener(Colorpicker.E_SET_COLOR_LIST, setColorListHandler);
			input.addEventListener(Colorpicker.E_SET_COLOR, setColorByInputValue);
		}

		function initAppearance() {
			var parent = DX.Dom.getParent(input);

			block = DX.Dom.createElement('div', {
				className: CN_COLORPICKER,
				innerHTML: INNER_TMPL
			});

			valueElement = block.querySelector('.' + CN_COLORPICKER_VALUE);

			parent.insertBefore(block, input);
			block.appendChild(input);
		}

		function setColorListHandler() {
			colorList = input.colorList || colorList || Colorpicker.colorList;
			setColorList(colorList);
		}

		/**
		 * @method setColorList
		 * @param {Array} colors
		 */
		function setColorList(colors) {
			if (!colors || colors.length === 0) {
				colorList = defaults.colorList;
			} else {
				colorList = colors.map(function(color) {
					return color.toLowerCase();
				});
			}

			dropDown.setDataList(prepareDataForDropDown(colorList));
			setColor(colorList[0]);
		}

		function dropdownIndexChangeHandler() {
			setColor(colorList[dropDown.getSelectedIndex()]);
			event.trigger(input, Colorpicker.E_CHANGED);
		}

		function prepareDataForDropDown(colors) {
			return colors.map(function(value) {
				return {
					value: value
				};
			});
		}

		function setColorByInputValue() {
			setColor(input.value);
		}

		function showDropDown() {
			dropDown.show();
		}

		function hideDropDown() {
			dropDown.hide();
		}

		function toggleDropDown() {
			if (!disabled) {
				if (isOpenedState()) {
					hideDropDown();
				} else {
					showDropDown();
				}
			}
		}

		function setOpenedState() {
			DX.Bem.addModifier(block, M_OPEN, CN_COLORPICKER);
		}

		function removeOpenedState() {
			DX.Bem.removeModifier(block, M_OPEN, CN_COLORPICKER);
		}

		function isOpenedState() {
			DX.Bem.hasModifier(block, M_OPEN, CN_COLORPICKER);
		}

		/**
		 * @method setDisabled
		 */
		function setDisabled() {
			disabled = true;
		}

		/**
		 * @method setEnabled
		 */
		function setEnabled() {
			disabled = false;
		}

		/**
		 * @method setColor
		 * @param {String} color
		 */
		function setColor(color) {
			color = color.toLowerCase();
			var index = colorList.indexOf(color);

			if (index < 0) {
				index = 0;
			}

			valueElement.style.backgroundColor = colorList[index];
			dropDown.setSelectedIndex(index);
			input.value = colorList[index];
		}

		init();

		this.setDisabled = setDisabled;
		this.setEnabled = setEnabled;

		this.setColor = setColor;
		this.setColorList = setColorList;
		/**
		 * Get HTMLNode containing colorpicker
		 * @method getBlock
		 * @returns {Node}
		 */
		this.getBlock = function() {
			return block;
		};
		/**
		 * Get element which listens to events
		 * @method getEventTarget
		 * @returns {Node}
		 */
		this.getEventTarget = function() {
			return input;
		};
	};
})(DX, window, document);
/** @constant
 * @type {string}
 * @default
 * @memberof Colorpicker
 */
Colorpicker.E_CREATED = 'colorpicker:created';
/** @constant
 * @type {string}
 * @default
 * @memberof Colorpicker
 */
Colorpicker.E_SET_COLOR_LIST = 'colorpicker:setcolorlist';
/** @constant
 * @type {string}
 * @default
 * @memberof Colorpicker
 */
Colorpicker.E_SET_COLOR = 'colorpicker:setcolor';
/** @constant
 * @type {string}
 * @default
 * @memberof Colorpicker
 */
Colorpicker.E_CHANGED = 'colorpicker:changed';<commit_msg>hide dropdown on disable<commit_after>/**
 * @copyright Devexperts
 *
 * @requires DX
 * @requires DX.Dom
 * @requires DX.Bem
 * @requires DX.Event
 * @requires DropDown
 * @namespace
 */
var Colorpicker = (function(DX, window, document, undefined) {
	'use strict';

	var event = DX.Event,
		CN_COLORPICKER = 'colorPicker',
		M_OPEN = 'opened',
		CN_COLORPICKER_LABEL = CN_COLORPICKER + '--label',
		CN_COLORPICKER_VALUE = CN_COLORPICKER + '--value',
		defaults = {
			colorList: ['#511717', '#d90100', '#ff504f', '#dddddd']
		},
		INNER_TMPL = [
			'
',
			'<button class="button" type="button">',
			'',
			'',
			'',
			'</button>',
			'
'
		].join(''),
		OPTION_TMPL = '

';

	/**
	 * Creates new Colorpicker
	 * @constructor Colorpicker
	 * @param {HTMLInputElement} input
	 * @param {Array} colorList
	 */
	return function Colorpicker(input, colorList) {
		var block, valueElement, dropDown, disabled = input.disabled;

		function init() {
			initAppearance();
			dropDown = new DropDown(block, {
				optionTmpl: OPTION_TMPL,
				modifiers: [CN_COLORPICKER]
			});
			initListeners();
			setColorListHandler();

			DX.Event.trigger(input, Colorpicker.E_CREATED, {
				detail: {
					block: block,
					eventTarget: input
				}
			});
		}

		function initListeners() {
			var dropDownEventTarget = dropDown.getEventTarget();

			block.addEventListener(DX.Event.TOUCH_CLICK, toggleDropDown, true);

			dropDownEventTarget.addEventListener(DropDown.E_SHOWN, setOpenedState, true);
			dropDownEventTarget.addEventListener(DropDown.E_HIDDEN, removeOpenedState, true);
			dropDownEventTarget.addEventListener(DropDown.E_CHANGED, dropdownIndexChangeHandler, true);

			input.addEventListener(Colorpicker.E_SET_COLOR_LIST, setColorListHandler);
			input.addEventListener(Colorpicker.E_SET_COLOR, setColorByInputValue);
		}

		function initAppearance() {
			var parent = DX.Dom.getParent(input);

			block = DX.Dom.createElement('div', {
				className: CN_COLORPICKER,
				innerHTML: INNER_TMPL
			});

			valueElement = block.querySelector('.' + CN_COLORPICKER_VALUE);

			parent.insertBefore(block, input);
			block.appendChild(input);
		}

		function setColorListHandler() {
			colorList = input.colorList || colorList || Colorpicker.colorList;
			setColorList(colorList);
		}

		/**
		 * @method setColorList
		 * @param {Array} colors
		 */
		function setColorList(colors) {
			if (!colors || colors.length === 0) {
				colorList = defaults.colorList;
			} else {
				colorList = colors.map(function(color) {
					return color.toLowerCase();
				});
			}

			dropDown.setDataList(prepareDataForDropDown(colorList));
			setColor(colorList[0]);
		}

		function dropdownIndexChangeHandler() {
			setColor(colorList[dropDown.getSelectedIndex()]);
			event.trigger(input, Colorpicker.E_CHANGED);
		}

		function prepareDataForDropDown(colors) {
			return colors.map(function(value) {
				return {
					value: value
				};
			});
		}

		function setColorByInputValue() {
			setColor(input.value);
		}

		function showDropDown() {
			dropDown.show();
		}

		function hideDropDown() {
			dropDown.hide();
		}

		function toggleDropDown() {
			if (!disabled) {
				if (isOpenedState()) {
					hideDropDown();
				} else {
					showDropDown();
				}
			}
		}

		function setOpenedState() {
			DX.Bem.addModifier(block, M_OPEN, CN_COLORPICKER);
		}

		function removeOpenedState() {
			DX.Bem.removeModifier(block, M_OPEN, CN_COLORPICKER);
		}

		function isOpenedState() {
			DX.Bem.hasModifier(block, M_OPEN, CN_COLORPICKER);
		}

		/**
		 * @method setDisabled
		 */
		function setDisabled() {
			hideDropDown();
			disabled = true;
		}

		/**
		 * @method setEnabled
		 */
		function setEnabled() {
			disabled = false;
		}

		/**
		 * @method setColor
		 * @param {String} color
		 */
		function setColor(color) {
			color = color.toLowerCase();
			var index = colorList.indexOf(color);

			if (index < 0) {
				index = 0;
			}

			valueElement.style.backgroundColor = colorList[index];
			dropDown.setSelectedIndex(index);
			input.value = colorList[index];
		}

		init();

		this.setDisabled = setDisabled;
		this.setEnabled = setEnabled;

		this.setColor = setColor;
		this.setColorList = setColorList;
		/**
		 * Get HTMLNode containing colorpicker
		 * @method getBlock
		 * @returns {Node}
		 */
		this.getBlock = function() {
			return block;
		};
		/**
		 * Get element which listens to events
		 * @method getEventTarget
		 * @returns {Node}
		 */
		this.getEventTarget = function() {
			return input;
		};
	};
})(DX, window, document);
/** @constant
 * @type {string}
 * @default
 * @memberof Colorpicker
 */
Colorpicker.E_CREATED = 'colorpicker:created';
/** @constant
 * @type {string}
 * @default
 * @memberof Colorpicker
 */
Colorpicker.E_SET_COLOR_LIST = 'colorpicker:setcolorlist';
/** @constant
 * @type {string}
 * @default
 * @memberof Colorpicker
 */
Colorpicker.E_SET_COLOR = 'colorpicker:setcolor';
/** @constant
 * @type {string}
 * @default
 * @memberof Colorpicker
 */
Colorpicker.E_CHANGED = 'colorpicker:changed';<|endoftext|>


<commit_before>/*===============================================================================
************   Fast Clicks   ************
************   Inspired by https://github.com/ftlabs/fastclick   ************
===============================================================================*/
app.initFastClicks = function () {
    if (app.params.activeState) {
        $('html').addClass('watch-active-state');
    }

    var touchStartX, touchStartY, touchStartTime, targetElement, trackClick, activeSelection, scrollParent, lastClickTime, isMoved;
    var activableElement, activeTimeout;

    function findActivableElement(e) {
        var target = $(e.target);
        var parents = target.parents(app.params.activeStateElements);

        return (parents.length > 0) ? parents : target;
    }
    function isInsideScrollableView() {
        var pageContent = activableElement.parents('.page-content, .panel');

        if (pageContent.length === 0) {
            return false;
        }

        // This event handler covers the "tap to stop scrolling".
        if (pageContent.prop('scrollHandlerSet') !== 'yes') {
            pageContent.on('scroll', function() {
              clearTimeout(activeTimeout);
            });
            pageContent.prop('scrollHandlerSet', 'yes');
        }

        return true;
    }
    function addActive() {
        activableElement.addClass('active-state');
    }
    function removeActive(el) {
        activableElement.removeClass('active-state');
    }

    function androidNeedsBlur(el) {
        var noBlur = ('button checkbox file image radio submit input textarea').split(' ');
        if (document.activeElement && el !== document.activeElement && document.activeElement !== document.body) {
            if (noBlur.indexOf(el.nodeName.toLowerCase()) >= 0) {
                return false;
            }
            else {
                return true;
            }
        }
        else {
            return false;
        }
    }
    function targetNeedsFocus(el) {
        if (document.activeElement === el) {
            return false;
        }
        var tag = el.nodeName.toLowerCase();
        var skipInputs = ('button checkbox file image radio submit').split(' ');
        if (el.disabled || el.readOnly) return false;
        if (tag === 'textarea') return true;
        if (tag === 'select') {
            if (app.device.os === 'android') return false;
            else return true;
        }
        if (tag === 'input' && skipInputs.indexOf(el.type) < 0) return true;
    }
    function targetNeedsPrevent(el) {
        el = $(el);
        if (el.is('label') || el.parents('label').length > 0) {
            if (app.device.os === 'android') {
                var osv = app.device.osVersion.split('.');
                if (osv[0] * 1 > 4 || (osv[0] * 1 === 4 && osv[1] * 1 >= 4)) {
                    return false;
                }
                else return true;
            }
            else return false;
        }
        return true;
    }

    // Mouse Handlers
    function handleMouseDown (e) {
        findActivableElement(e).addClass('active-state');
        if ('which' in e && e.which === 3) {
            setTimeout(function () {
                $('.active-state').removeClass('active-state');
            }, 0);
        }
    }
    function handleMouseMove (e) {
        $('.active-state').removeClass('active-state');
    }
    function handleMouseUp (e) {
        $('.active-state').removeClass('active-state');
    }

    // Touch Handlers
    function handleTouchStart(e) {
        isMoved = false;
        if (e.targetTouches.length > 1) {
            return true;
        }

        if (app.device.os === 'ios') {
            var selection = window.getSelection();
            if (selection.rangeCount && (!selection.isCollapsed || document.activeElement === selection.focusNode)) {
                activeSelection = true;
                return true;
            }
            else {
                activeSelection = false;
            }
        }
        if (app.device.os === 'android')  {
            if (androidNeedsBlur(e.target)) {
                document.activeElement.blur();
            }
        }

        trackClick = true;
        targetElement = e.target;
        touchStartTime = (new Date()).getTime();
        touchStartX = e.targetTouches[0].pageX;
        touchStartY = e.targetTouches[0].pageY;

        // Detect scroll parent
        if (app.device.os === 'ios') {
            scrollParent = undefined;
            $(targetElement).parents().each(function () {
                var parent = this;
                if (parent.scrollHeight > parent.offsetHeight && !scrollParent) {
                    scrollParent = parent;
                    scrollParent.f7ScrollTop = scrollParent.scrollTop;
                }
            });
        }
        if ((e.timeStamp - lastClickTime) < 200) {
            e.preventDefault();
        }
        if (app.params.activeState) {
            activableElement = findActivableElement(e);
            // If it's inside a scrollable view, we don't trigger active-state yet,
            // because it can be a scroll instead. Based on the link:
            // http://labnote.beedesk.com/click-scroll-and-pseudo-active-on-mobile-webk
            if (!isInsideScrollableView(e)) {
                addActive();
            } else {
                activeTimeout = setTimeout(addActive, 80);
            }
        }
    }
    function handleTouchMove(e) {
        if (!trackClick) return;
        trackClick = false;
        targetElement = null;
        isMoved = true;

        if (app.params.activeState) {
            clearTimeout(activeTimeout);
            removeActive();
        }
    }
    function handleTouchEnd(e) {
        clearTimeout(activeTimeout);

        if (!trackClick) {
            if (!activeSelection) e.preventDefault();
            return true;
        }

        if (document.activeElement === e.target) {
            return true;
        }

        if (!activeSelection) {
            e.preventDefault();
        }

        if ((e.timeStamp - lastClickTime) < 200) {
            return true;
        }

        lastClickTime = e.timeStamp;
        touchStartTime = 0;

        trackClick = false;

        if (app.device.os === 'ios' && scrollParent) {
            if (scrollParent.scrollTop !== scrollParent.f7ScrollTop) {
                return false;
            }
        }

        // Add active-state here because, in a very fast tap, the timeout didn't
        // have the chance to execute. Removing active-state in a timeout gives
        // the chance to the animation execute.
        if (app.params.activeState) {
            addActive();
            setTimeout(removeActive, 0);
        }

        // Trigger focus when required
        if (targetNeedsFocus(targetElement)) {
            targetElement.focus();
        }

        e.preventDefault();
        var touch = e.changedTouches[0];
        var evt = document.createEvent('MouseEvents');
        var eventType = 'click';
        if (app.device.os === 'android' && targetElement.nodeName.toLowerCase() === 'select') {
            eventType = 'mousedown';
        }
        evt.initMouseEvent(eventType, true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
        evt.forwardedTouchEvent = true;
        targetElement.dispatchEvent(evt);

        return false;

    }
    function handleTouchCancel(e) {
        trackClick = false;
        targetElement = null;
    }

    function handleClick(e) {
        var allowClick = false;

        if (trackClick) {
            targetElement = null;
            trackClick = false;
            return true;
        }

        if (e.target.type === 'submit' && e.detail === 0) {
            return true;
        }

        if (!targetElement) {
            allowClick =  true;
        }
        if (document.activeElement === targetElement) {
            allowClick =  true;
        }
        if (e.forwardedTouchEvent) {
            allowClick =  true;
        }
        if (!e.cancelable) {
            allowClick =  true;
        }

        if (!allowClick) {
            e.stopImmediatePropagation();
            e.stopPropagation();
            if (targetElement) {
                if (targetNeedsPrevent(targetElement) || isMoved) e.preventDefault();
            }
            else {
                e.preventDefault();
            }
            targetElement = null;
        }

        return allowClick;
    }
    if (app.support.touch) {
        document.addEventListener('click', handleClick, true);
        app.addGlobalEventListener('touchstart', handleTouchStart);
        app.addGlobalEventListener('touchmove', handleTouchMove);
        app.addGlobalEventListener('touchend', handleTouchEnd);
        app.addGlobalEventListener('touchcancel', handleTouchCancel);
    }
    else {
        if (app.params.activeState) {
            app.addGlobalEventListener('mousedown', handleMouseDown);
            app.addGlobalEventListener('mousemove', handleMouseMove);
            app.addGlobalEventListener('mouseup', handleMouseUp);
        }
    }

};
<commit_msg>Disable fast clicks on input:file<commit_after>/*===============================================================================
************   Fast Clicks   ************
************   Inspired by https://github.com/ftlabs/fastclick   ************
===============================================================================*/
app.initFastClicks = function () {
    if (app.params.activeState) {
        $('html').addClass('watch-active-state');
    }

    var touchStartX, touchStartY, touchStartTime, targetElement, trackClick, activeSelection, scrollParent, lastClickTime, isMoved;
    var activableElement, activeTimeout, needsFastClick;

    function findActivableElement(e) {
        var target = $(e.target);
        var parents = target.parents(app.params.activeStateElements);

        return (parents.length > 0) ? parents : target;
    }
    function isInsideScrollableView() {
        var pageContent = activableElement.parents('.page-content, .panel');

        if (pageContent.length === 0) {
            return false;
        }

        // This event handler covers the "tap to stop scrolling".
        if (pageContent.prop('scrollHandlerSet') !== 'yes') {
            pageContent.on('scroll', function() {
              clearTimeout(activeTimeout);
            });
            pageContent.prop('scrollHandlerSet', 'yes');
        }

        return true;
    }
    function addActive() {
        activableElement.addClass('active-state');
    }
    function removeActive(el) {
        activableElement.removeClass('active-state');
    }

    function androidNeedsBlur(el) {
        var noBlur = ('button checkbox file image radio submit input textarea').split(' ');
        if (document.activeElement && el !== document.activeElement && document.activeElement !== document.body) {
            if (noBlur.indexOf(el.nodeName.toLowerCase()) >= 0) {
                return false;
            }
            else {
                return true;
            }
        }
        else {
            return false;
        }
    }
    function targetNeedsFastClick(el) {
        if (el.nodeName.toLowerCase() === 'input' && el.type === 'file') return false;
        if (el.className.indexOf('no-fastclick') >= 0) return false;
        return true;
    }
    function targetNeedsFocus(el) {
        if (document.activeElement === el) {
            return false;
        }
        var tag = el.nodeName.toLowerCase();
        var skipInputs = ('button checkbox file image radio submit').split(' ');
        if (el.disabled || el.readOnly) return false;
        if (tag === 'textarea') return true;
        if (tag === 'select') {
            if (app.device.os === 'android') return false;
            else return true;
        }
        if (tag === 'input' && skipInputs.indexOf(el.type) < 0) return true;
    }
    function targetNeedsPrevent(el) {
        el = $(el);
        if (el.is('label') || el.parents('label').length > 0) {
            if (app.device.os === 'android') {
                var osv = app.device.osVersion.split('.');
                if (osv[0] * 1 > 4 || (osv[0] * 1 === 4 && osv[1] * 1 >= 4)) {
                    return false;
                }
                else return true;
            }
            else return false;
        }
        return true;
    }

    // Mouse Handlers
    function handleMouseDown (e) {
        findActivableElement(e).addClass('active-state');
        if ('which' in e && e.which === 3) {
            setTimeout(function () {
                $('.active-state').removeClass('active-state');
            }, 0);
        }
    }
    function handleMouseMove (e) {
        $('.active-state').removeClass('active-state');
    }
    function handleMouseUp (e) {
        $('.active-state').removeClass('active-state');
    }

    // Touch Handlers
    function handleTouchStart(e) {
        isMoved = false;
        if (e.targetTouches.length > 1) {
            return true;
        }
        needsFastClick = targetNeedsFastClick(e.target);

        if (!needsFastClick) {
            trackClick = false;
            return true;
        }
        if (app.device.os === 'ios') {
            var selection = window.getSelection();
            if (selection.rangeCount && (!selection.isCollapsed || document.activeElement === selection.focusNode)) {
                activeSelection = true;
                return true;
            }
            else {
                activeSelection = false;
            }
        }
        if (app.device.os === 'android')  {
            if (androidNeedsBlur(e.target)) {
                document.activeElement.blur();
            }
        }

        trackClick = true;
        targetElement = e.target;
        touchStartTime = (new Date()).getTime();
        touchStartX = e.targetTouches[0].pageX;
        touchStartY = e.targetTouches[0].pageY;

        // Detect scroll parent
        if (app.device.os === 'ios') {
            scrollParent = undefined;
            $(targetElement).parents().each(function () {
                var parent = this;
                if (parent.scrollHeight > parent.offsetHeight && !scrollParent) {
                    scrollParent = parent;
                    scrollParent.f7ScrollTop = scrollParent.scrollTop;
                }
            });
        }
        if ((e.timeStamp - lastClickTime) < 200) {
            e.preventDefault();
        }
        if (app.params.activeState) {
            activableElement = findActivableElement(e);
            // If it's inside a scrollable view, we don't trigger active-state yet,
            // because it can be a scroll instead. Based on the link:
            // http://labnote.beedesk.com/click-scroll-and-pseudo-active-on-mobile-webk
            if (!isInsideScrollableView(e)) {
                addActive();
            } else {
                activeTimeout = setTimeout(addActive, 80);
            }
        }
    }
    function handleTouchMove(e) {
        if (!trackClick) return;
        trackClick = false;
        targetElement = null;
        isMoved = true;

        if (app.params.activeState) {
            clearTimeout(activeTimeout);
            removeActive();
        }
    }
    function handleTouchEnd(e) {
        clearTimeout(activeTimeout);

        if (!trackClick) {
            if (!activeSelection && needsFastClick) e.preventDefault();
            return true;
        }

        if (document.activeElement === e.target) {
            return true;
        }

        if (!activeSelection) {
            e.preventDefault();
        }

        if ((e.timeStamp - lastClickTime) < 200) {
            return true;
        }

        lastClickTime = e.timeStamp;
        touchStartTime = 0;

        trackClick = false;

        if (app.device.os === 'ios' && scrollParent) {
            if (scrollParent.scrollTop !== scrollParent.f7ScrollTop) {
                return false;
            }
        }

        // Add active-state here because, in a very fast tap, the timeout didn't
        // have the chance to execute. Removing active-state in a timeout gives
        // the chance to the animation execute.
        if (app.params.activeState) {
            addActive();
            setTimeout(removeActive, 0);
        }

        // Trigger focus when required
        if (targetNeedsFocus(targetElement)) {
            targetElement.focus();
        }

        e.preventDefault();
        var touch = e.changedTouches[0];
        var evt = document.createEvent('MouseEvents');
        var eventType = 'click';
        if (app.device.os === 'android' && targetElement.nodeName.toLowerCase() === 'select') {
            eventType = 'mousedown';
        }
        evt.initMouseEvent(eventType, true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
        evt.forwardedTouchEvent = true;
        targetElement.dispatchEvent(evt);

        return false;

    }
    function handleTouchCancel(e) {
        trackClick = false;
        targetElement = null;
    }

    function handleClick(e) {
        var allowClick = false;

        if (trackClick) {
            targetElement = null;
            trackClick = false;
            return true;
        }

        if (e.target.type === 'submit' && e.detail === 0) {
            return true;
        }

        if (!targetElement) {
            allowClick =  true;
        }
        if (document.activeElement === targetElement) {
            allowClick =  true;
        }
        if (e.forwardedTouchEvent) {
            allowClick =  true;
        }
        if (!e.cancelable) {
            allowClick =  true;
        }

        if (!allowClick) {
            e.stopImmediatePropagation();
            e.stopPropagation();
            if (targetElement) {
                if (targetNeedsPrevent(targetElement) || isMoved) {
                    e.preventDefault();
                }
            }
            else {
                e.preventDefault();
            }
            targetElement = null;
        }

        return allowClick;
    }
    if (app.support.touch) {
        document.addEventListener('click', handleClick, true);
        app.addGlobalEventListener('touchstart', handleTouchStart);
        app.addGlobalEventListener('touchmove', handleTouchMove);
        app.addGlobalEventListener('touchend', handleTouchEnd);
        app.addGlobalEventListener('touchcancel', handleTouchCancel);
    }
    else {
        if (app.params.activeState) {
            app.addGlobalEventListener('mousedown', handleMouseDown);
            app.addGlobalEventListener('mousemove', handleMouseMove);
            app.addGlobalEventListener('mouseup', handleMouseUp);
        }
    }

};
<|endoftext|>