<commit_before>(function($) {
    $.fn.repeat = function(trigger, opts) {
        var options = $.extend({
            deleteTrigger: null,
            onReady: function() { }
        }, opts || {});
        var container = this;
        var selected = null;

        $('.repeat', container).each(function() {
            addEvent($(this));
        });
        $(trigger).click(function(ev) {
        	ev.preventDefault();
            var last = $('.repeat:last', container);
            var newNode = last.clone();
            last.after(newNode);
            newNode.each(function () {
                $(':input', this).each(function() {
                    var name = $(this).attr('name');
                    var n = /(.*)(\d+)$/.exec(name);
                    $(this).attr('name', n[1] + (Number(n[2]) + 1));
                    if (this.value != '')
                        this.value = '';
                });
            });
            addEvent(newNode);
            $('.repeat', container).removeClass('repeat-selected');
            options.onReady.call(newNode);
        });
        if (options.deleteTrigger != null)
            $(options.deleteTrigger).click(function(ev) {
                deleteCurrent();
                ev.preventDefault();
            });
        function addEvent(repeat) {
            repeat.click(function() {
                selected = repeat;
                $('.repeat', container).removeClass('repeat-selected');
                repeat.addClass('repeat-selected');
            });
        }

        function deleteCurrent() {
            if (selected) {
                selected.remove();
            }
        }
    }
})(jQuery);

/**
 * jQuery pagination plugin. Used by the jquery.xql XQuery library.
 * The passed URL should return an HTML table with one row for each
 * record to display. Each row should have two or more columns: the first one
 * contains the record number, the remaining columns the data to be displayed.
 *
 * @param url the URL to call to retrieve a page.
 * @param opts option object to configure the plugin.
 */
(function($) {
    $.fn.pagination = function(url, opts) {
        var target = this;
        var options = $.extend({
            totalItems: 0,
            itemsPerPage: 10,
            startParam: "start",
            countParam: "count",
            navContainer: null,
            readyCallback: function() { },
            itemCallback: function () { }
        }, opts || {});
        if (options.totalItems == 1)
            options.itemsPerPage = 1;
        if (options.totalItems > 0)
            retrievePage(1);
        return target;

        function displayPage(data) {
            target.empty();
            navbar(target, Number($('tr:first > td:first', data).text()));
            var table = $('

');
            target.append(table);
            $('> tr', data).each(function (i) {
                var current = $('> td:first', this).text();
                var tr = $('

');
                var td = $('	');
                td.text(current + ".");
                tr.append(td);
                $('> td:gt(0)', this).each(function () {
                    tr.append($(this).clone().addClass('pagination-data'));
                });
                table.append(tr);
                $('.pagination-toggle', tr).click(function (ev) {
                    ev.preventDefault();
                    options.itemsPerPage = 1;
                    retrievePage(current);
                });
                options.itemCallback.call(target, current, tr);
            });
            options.readyCallback.call(target, options);
        }

        function navbar(targetDiv, currentItem) {
            var div;
            if (options.navContainer) {
                div = $(options.navContainer);
            } else {
                div = $('

');
                targetDiv.append(div);
            }
            div.empty().addClass('pagination-links');
            if (options.itemsPerPage == 1) {

                var span = $('|<');
                div.append(span);
                if (currentItem <= 1) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(1);
                        return false;
                    });
                }

                var span = $('<');
                div.append(span);
                if (currentItem <= 1) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(currentItem - 1);
                        return false;
                    });
                }

				span = $('');
                span.text('Record ' + currentItem);
                div.append(span);

                span = $('>');
                div.append(span);
                if (currentItem >= options.totalItems) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(currentItem + 1);
                        return false;
                    });
                }

                var span = $('>|');
                div.append(span);
                if (currentItem == options.totalItems) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(options.totalItems);
                        return false;
                    });
                }

                span = $('');
                var listLink = $('List view');
                listLink.click(function (ev) {
                    ev.preventDefault();
                    options.itemsPerPage = 10;
                    var currentPage = Math.floor(currentItem / options.itemsPerPage);
                    currentItem = currentPage * options.itemsPerPage;
                    if (currentItem == 0)
                        currentItem = 1;
                    retrievePage(currentItem);
                });
                span.append(listLink);
                div.append(span);
            } else {

                var span = $('|<');
                div.append(span);
                if (currentItem <= 1) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(1);
                        return false;
                    });
                }

                var span = $('<');
                div.append(span);
                if (currentItem <= 10) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(currentItem - options.itemsPerPage);
                        return false;
                    });
                }

                span = $('');
                if (options.totalItems == currentItem)
                	recordSpan = ('Record ' + currentItem)
                else if (options.totalItems < (currentItem + options.itemsPerPage - 1))
                	recordSpan = ('Records ' + currentItem + ' to ' + options.totalItems)
                else recordSpan = ('Records ' + currentItem + ' to ' + ((currentItem + options.itemsPerPage - 1)))
                span.text(recordSpan);
                div.append(span);

				span = $('>');
                div.append(span);
                if (options.totalItems == currentItem) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(currentItem + options.itemsPerPage);
                        return false;
                    });
                }

				var span = $('>|');
                div.append(span);
                if (options.totalItems < (currentItem + options.itemsPerPage - 1)) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(options.totalItems);
                        return false;
                    });
                }

            }
            return div;
        }

        function appendPageLink(div, start, end) {
            var span = $('');
            span.text(start + '-' + end);
            div.append(span);
            span.click(function () {
                retrievePage(start);
            });
        }

        function retrievePage(start) {
            $.ajax({
                type: "GET",
                url: url,
                data: {
                    start: start,
                    count: options.itemsPerPage
                },
                dataType: "xml",
                success: function(data) { displayPage(data.documentElement); },
                error: function (req, status, errorThrown) {
                    alert(status);
                }
            });
        }
    }

})(jQuery);

(function($) {
    $.fn.form = function(opts) {
    	var options = $.extend({
            done: function() { },
            cancel: function () { }
        }, opts || {});
    	var container = this;
    	var pages = container.find("fieldset");
    	var currentPage = 0;

    	// append back and next buttons to container
    	var panel = document.createElement("div");
    	panel.className = "eXist_wizard_buttons";
    	panel.style.position = "absolute";
    	panel.style.bottom = "0";
    	panel.style.right = "0";

    	var btn = document.createElement("button");
    	btn.className = "eXist_wizard_back";
    	btn.appendChild(document.createTextNode("Back"));
    	panel.appendChild(btn);

    	btn = document.createElement("button");
    	btn.className = "eXist_wizard_next";
    	btn.appendChild(document.createTextNode("Next"));
    	panel.appendChild(btn);

    	btn = document.createElement("button");
    	btn.className = "eXist_wizard_cancel";
    	btn.appendChild(document.createTextNode("Cancel"));
    	panel.appendChild(btn);

    	btn = document.createElement("button");
    	btn.className = "eXist_wizard_done";
    	btn.appendChild(document.createTextNode("Done"));
    	panel.appendChild(btn);
    	container.append(panel);

    	$("button", container).button();

    	for (var i = 1; i < pages.length; i++) {
    		$(pages[i]).css("display", "none");
    	}
    	$(".eXist_wizard_back", container).button("disable");

    	$(".eXist_wizard_next", container).click(function () {
    		if (currentPage == pages.length - 1)
    			return;
    		$(pages[currentPage]).css("display", "none");
    		$(pages[++currentPage]).css("display", "");
    		if (currentPage == 1) {
    			$(".eXist_wizard_back", container).button("enable");
    		} else if (currentPage == pages.length - 1) {
    			$(this).button("disable");
    		}
    	});
    	$(".eXist_wizard_back", container).click(function () {
    		if (currentPage == 0)
    			return;
    		if (currentPage == pages.length - 1) {
    			$(".eXist_wizard_next", container).button("enable");
    		}
    		$(pages[currentPage]).css("display", "none");
    		$(pages[--currentPage]).css("display", "");
    		if (currentPage == 0) {
    			$(this).button("disable");
    		}
    	});
    	$(".eXist_wizard_cancel", container).click(function () {
    		// Cancel.
    		options.cancel.call(container);
    	});
    	$(".eXist_wizard_done", container).click(function () {
    		options.done.call(container);
    	});
    	return container;
    }
})(jQuery);<commit_msg>[tamboti] Clean-up of commit 15151.<commit_after>(function($) {
    $.fn.repeat = function(trigger, opts) {
        var options = $.extend({
            deleteTrigger: null,
            onReady: function() { }
        }, opts || {});
        var container = this;
        var selected = null;

        $('.repeat', container).each(function() {
            addEvent($(this));
        });
        $(trigger).click(function(ev) {
        	ev.preventDefault();
            var last = $('.repeat:last', container);
            var newNode = last.clone();
            last.after(newNode);
            newNode.each(function () {
                $(':input', this).each(function() {
                    var name = $(this).attr('name');
                    var n = /(.*)(\d+)$/.exec(name);
                    $(this).attr('name', n[1] + (Number(n[2]) + 1));
                    if (this.value != '')
                        this.value = '';
                });
            });
            addEvent(newNode);
            $('.repeat', container).removeClass('repeat-selected');
            options.onReady.call(newNode);
        });
        if (options.deleteTrigger != null)
            $(options.deleteTrigger).click(function(ev) {
                deleteCurrent();
                ev.preventDefault();
            });
        function addEvent(repeat) {
            repeat.click(function() {
                selected = repeat;
                $('.repeat', container).removeClass('repeat-selected');
                repeat.addClass('repeat-selected');
            });
        }

        function deleteCurrent() {
            if (selected) {
                selected.remove();
            }
        }
    }
})(jQuery);

/**
 * jQuery pagination plugin. Used by the jquery.xql XQuery library.
 * The passed URL should return an HTML table with one row for each
 * record to display. Each row should have two or more columns: the first one
 * contains the record number, the remaining columns the data to be displayed.
 *
 * @param url the URL to call to retrieve a page.
 * @param opts option object to configure the plugin.
 */
(function($) {
    $.fn.pagination = function(url, opts) {
        var target = this;
        var options = $.extend({
            totalItems: 0,
            itemsPerPage: 10,
            startParam: "start",
            countParam: "count",
            navContainer: null,
            readyCallback: function() { },
            itemCallback: function () { }
        }, opts || {});
        if (options.totalItems == 1)
            options.itemsPerPage = 1;
        if (options.totalItems > 0)
            retrievePage(1);
        return target;

        function displayPage(data) {
            target.empty();
            navbar(target, Number($('tr:first > td:first', data).text()));
            var table = $('

');
            target.append(table);
            $('> tr', data).each(function (i) {
                var current = $('> td:first', this).text();
                var tr = $('

');
                var td = $('	');
                td.text(current + ".");
                tr.append(td);
                $('> td:gt(0)', this).each(function () {
                    tr.append($(this).clone().addClass('pagination-data'));
                });
                table.append(tr);
                $('.pagination-toggle', tr).click(function (ev) {
                    ev.preventDefault();
                    options.itemsPerPage = 1;
                    retrievePage(current);
                });
                options.itemCallback.call(target, current, tr);
            });
            options.readyCallback.call(target, options);
        }

        function navbar(targetDiv, currentItem) {
            var div;
            if (options.navContainer) {
                div = $(options.navContainer);
            } else {
                div = $('

');
                targetDiv.append(div);
            }
            div.empty().addClass('pagination-links');
            if (options.itemsPerPage == 1) {

                var span = $('|<');
                div.append(span);
                if (currentItem <= 1) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(1);
                        return false;
                    });
                }

                var span = $('<');
                div.append(span);
                if (currentItem <= 1) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(currentItem - 1);
                        return false;
                    });
                }

				span = $('');
                span.text('Record ' + currentItem);
                div.append(span);

                span = $('>');
                div.append(span);
                if (currentItem >= options.totalItems) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(currentItem + 1);
                        return false;
                    });
                }

                var span = $('>|');
                div.append(span);
                if (currentItem == options.totalItems) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(options.totalItems);
                        return false;
                    });
                }

                span = $('');
                var listLink = $('List view');
                listLink.click(function (ev) {
                    ev.preventDefault();
                    options.itemsPerPage = 10;
                    var currentPage = Math.floor(currentItem / options.itemsPerPage);
                    currentItem = currentPage * options.itemsPerPage;
                    if (currentItem == 0)
                        currentItem = 1;
                    retrievePage(currentItem);
                });
                span.append(listLink);
                div.append(span);
            } else {

                var span = $('|<');
                div.append(span);
                if (currentItem <= 1) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(1);
                        return false;
                    });
                }

                var span = $('<');
                div.append(span);
                if (currentItem <= options.itemsPerPage) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(currentItem - options.itemsPerPage);
                        return false;
                    });
                }

                span = $('');
                if (options.totalItems == currentItem)
                	recordSpan = ('Record ' + currentItem)
                else if (options.totalItems < (currentItem + options.itemsPerPage - 1))
                	recordSpan = ('Records ' + currentItem + ' to ' + options.totalItems)
                else recordSpan = ('Records ' + currentItem + ' to ' + ((currentItem + options.itemsPerPage - 1)))
                span.text(recordSpan);
                div.append(span);

				span = $('>');
                div.append(span);
                if (options.totalItems - options.itemsPerPage < currentItem ) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(currentItem + options.itemsPerPage);
                        return false;
                    });
                }

				var span = $('>|');
                div.append(span);
                if (options.totalItems < (currentItem + options.itemsPerPage - 1)) {
                    span.addClass("inactive");
                } else {
                    span.click(function () {
                        retrievePage(options.totalItems);
                        return false;
                    });
                }

            }
            return div;
        }

        function appendPageLink(div, start, end) {
            var span = $('');
            span.text(start + '-' + end);
            div.append(span);
            span.click(function () {
                retrievePage(start);
            });
        }

        function retrievePage(start) {
            $.ajax({
                type: "GET",
                url: url,
                data: {
                    start: start,
                    count: options.itemsPerPage
                },
                dataType: "xml",
                success: function(data) { displayPage(data.documentElement); },
                error: function (req, status, errorThrown) {
                    alert(status);
                }
            });
        }
    }

})(jQuery);

(function($) {
    $.fn.form = function(opts) {
    	var options = $.extend({
            done: function() { },
            cancel: function () { }
        }, opts || {});
    	var container = this;
    	var pages = container.find("fieldset");
    	var currentPage = 0;

    	// append back and next buttons to container
    	var panel = document.createElement("div");
    	panel.className = "eXist_wizard_buttons";
    	panel.style.position = "absolute";
    	panel.style.bottom = "0";
    	panel.style.right = "0";

    	var btn = document.createElement("button");
    	btn.className = "eXist_wizard_back";
    	btn.appendChild(document.createTextNode("Back"));
    	panel.appendChild(btn);

    	btn = document.createElement("button");
    	btn.className = "eXist_wizard_next";
    	btn.appendChild(document.createTextNode("Next"));
    	panel.appendChild(btn);

    	btn = document.createElement("button");
    	btn.className = "eXist_wizard_cancel";
    	btn.appendChild(document.createTextNode("Cancel"));
    	panel.appendChild(btn);

    	btn = document.createElement("button");
    	btn.className = "eXist_wizard_done";
    	btn.appendChild(document.createTextNode("Done"));
    	panel.appendChild(btn);
    	container.append(panel);

    	$("button", container).button();

    	for (var i = 1; i < pages.length; i++) {
    		$(pages[i]).css("display", "none");
    	}
    	$(".eXist_wizard_back", container).button("disable");

    	$(".eXist_wizard_next", container).click(function () {
    		if (currentPage == pages.length - 1)
    			return;
    		$(pages[currentPage]).css("display", "none");
    		$(pages[++currentPage]).css("display", "");
    		if (currentPage == 1) {
    			$(".eXist_wizard_back", container).button("enable");
    		} else if (currentPage == pages.length - 1) {
    			$(this).button("disable");
    		}
    	});
    	$(".eXist_wizard_back", container).click(function () {
    		if (currentPage == 0)
    			return;
    		if (currentPage == pages.length - 1) {
    			$(".eXist_wizard_next", container).button("enable");
    		}
    		$(pages[currentPage]).css("display", "none");
    		$(pages[--currentPage]).css("display", "");
    		if (currentPage == 0) {
    			$(this).button("disable");
    		}
    	});
    	$(".eXist_wizard_cancel", container).click(function () {
    		// Cancel.
    		options.cancel.call(container);
    	});
    	$(".eXist_wizard_done", container).click(function () {
    		options.done.call(container);
    	});
    	return container;
    }
})(jQuery);<|endoftext|>


<commit_before>import Em from 'ember';

export default Em.Component.extend({
  classNames: ['button-select'],
  buttons: null,
  selected: null,

  setup: Em.on('init', function() {
    this.buttons = [];
  }),

  actions: {
    select: function(button) {
      this.set('selected', button.get('value'));
    },

    register: function(button) {
      this.buttons.addObject(button);
    },

    unregister: function(button) {
      // how should we handle the case where the object being destroyed
      // is the selected button?
      this.buttons.removeObject(button);
    }
  }
});
<commit_msg>Use Em.A rather than [] to allow for unextended prototypes<commit_after>import Em from 'ember';

export default Em.Component.extend({
  classNames: ['button-select'],
  buttons: null,
  selected: null,

  setup: Em.on('init', function() {
    this.buttons = Em.A();
  }),

  actions: {
    select: function(button) {
      this.set('selected', button.get('value'));
    },

    register: function(button) {
      this.buttons.addObject(button);
    },

    unregister: function(button) {
      // how should we handle the case where the object being destroyed
      // is the selected button?
      this.buttons.removeObject(button);
    }
  }
});
<|endoftext|>


<commit_before>/**
 * Copyright 2014-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule warning
 */

'use strict';

/**
 * Similar to invariant but only logs a warning if the condition is not met.
 * This can be used to log issues in development environments in critical
 * paths. Removing the logging code for production environments will keep the
 * same logic and follow the same code paths.
 */

var __DEV__ = process.env.NODE_ENV !== 'production';

var warning = function() {};

if (__DEV__) {
  warning = function(condition, format, args) {
    var len = arguments.length;
    args = new Array(len > 2 ? len - 2 : 0);
    for (var key = 2; key < len; key++) {
      args[key - 2] = arguments[key];
    }
    if (format === undefined) {
      throw new Error(
        '`warning(condition, format, ...args)` requires a warning ' +
        'message argument'
      );
    }

    if (format.length < 10 || (/^[s\W]*$/).test(format)) {
      throw new Error(
        'The warning format should be able to uniquely identify this ' +
        'warning. Please, use a more descriptive format than: ' + format
      );
    }

    if (!condition) {
      var argIndex = 0;
      var message = 'Warning: ' +
        format.replace(/%s/g, function() {
          args[argIndex++];
        });
      if (typeof console !== 'undefined') {
        console.error(message);
      }
      try {
        // This error was thrown as a convenience so that you can use this stack
        // to find the callsite that caused this warning to fire.
        throw new Error(message);
      } catch(x) {}
    }
  };
}

module.exports = warning;
<commit_msg>fix return args in replace<commit_after>/**
 * Copyright 2014-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

/**
 * Similar to invariant but only logs a warning if the condition is not met.
 * This can be used to log issues in development environments in critical
 * paths. Removing the logging code for production environments will keep the
 * same logic and follow the same code paths.
 */

var __DEV__ = process.env.NODE_ENV !== 'production';

var warning = function() {};

if (__DEV__) {
  warning = function(condition, format, args) {
    var len = arguments.length;
    args = new Array(len > 2 ? len - 2 : 0);
    for (var key = 2; key < len; key++) {
      args[key - 2] = arguments[key];
    }
    if (format === undefined) {
      throw new Error(
        '`warning(condition, format, ...args)` requires a warning ' +
        'message argument'
      );
    }

    if (format.length < 10 || (/^[s\W]*$/).test(format)) {
      throw new Error(
        'The warning format should be able to uniquely identify this ' +
        'warning. Please, use a more descriptive format than: ' + format
      );
    }

    if (!condition) {
      var argIndex = 0;
      var message = 'Warning: ' +
        format.replace(/%s/g, function() {
          return args[argIndex++];
        });
      if (typeof console !== 'undefined') {
        console.error(message);
      }
      try {
        // This error was thrown as a convenience so that you can use this stack
        // to find the callsite that caused this warning to fire.
        throw new Error(message);
      } catch(x) {}
    }
  };
}

module.exports = warning;
<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Children, Component, PropTypes } from 'react';
import classnames from 'classnames';
import iconsMap from '../index-icons';

const CLASS_ROOT = 'anchor';

export default class Anchor extends Component {

  render () {
    let icon;
    if (this.props.icon) {
      let CustomIcon  = iconsMap[this.props.icon];
      if (! CustomIcon) {
        console.warn(
          `Warning: Anchor is unable to find the icon named ${this.props.icon}`
        );
      } else {
        icon = <CustomIcon />;
      }
    } else if (this.props.primary) {
      let LinkNextIcon = iconsMap.LinkNext;
      icon = <LinkNextIcon />;
    }

    if (icon && !this.props.primary && !this.props.label) {
      icon = <span className={`${CLASS_ROOT}__icon`}>{icon};
    }

    let hasIcon = icon !== undefined;
    let children = Children.map(this.props.children, child => {
      if (child && child.type && child.type.icon) {
        hasIcon = true;
        child = <span className={`${CLASS_ROOT}__icon`}>{child};
      }
      return child;
    });

    let classes = classnames(
      CLASS_ROOT,
      this.props.className,
      {
        [`${CLASS_ROOT}--disabled`]: this.props.disabled,
        [`${CLASS_ROOT}--icon`]: icon,
        [`${CLASS_ROOT}--icon-label`]: hasIcon && this.props.label,
        [`${CLASS_ROOT}--primary`]: this.props.primary,
        [`${CLASS_ROOT}--reverse`]: this.props.reverse
      }
    );

    if (!children) {
      children = this.props.label;
    }

    if (this.props.reverse) {
      return (
        <this.props.tag id={this.props.id} className={classes}
          href={this.props.href}
          target={this.props.target}
          onClick={this.props.onClick}
          aria-label={this.props.a11yTitle}>
          {children}
          {icon}
        </this.props.tag>
      );
    } else {
      return (
        <this.props.tag id={this.props.id} className={classes}
          href={this.props.href}
          target={this.props.target}
          onClick={this.props.onClick}
          aria-label={this.props.a11yTitle}>
          {icon}
          {children}
        </this.props.tag>
      );
    }
  }
};

Anchor.propTypes = {
  a11yTitle: PropTypes.string,
  icon: PropTypes.string,
  disabled: PropTypes.bool,
  href: PropTypes.string,
  id: PropTypes.string,
  label: PropTypes.node,
  onClick: PropTypes.func,
  primary: PropTypes.bool,
  tag: PropTypes.string,
  target: PropTypes.string,
  reverse: PropTypes.bool
};

Anchor.defaultProps = {
  tag: 'a'
};
<commit_msg>refactoring reverse logic<commit_after>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Children, Component, PropTypes } from 'react';
import classnames from 'classnames';
import iconsMap from '../index-icons';

const CLASS_ROOT = 'anchor';

export default class Anchor extends Component {

  render () {
    let icon;
    if (this.props.icon) {
      let CustomIcon  = iconsMap[this.props.icon];
      if (! CustomIcon) {
        console.warn(
          `Warning: Anchor is unable to find the icon named ${this.props.icon}`
        );
      } else {
        icon = <CustomIcon />;
      }
    } else if (this.props.primary) {
      let LinkNextIcon = iconsMap.LinkNext;
      icon = <LinkNextIcon />;
    }

    if (icon && !this.props.primary && !this.props.label) {
      icon = <span className={`${CLASS_ROOT}__icon`}>{icon};
    }

    let hasIcon = icon !== undefined;
    let children = Children.map(this.props.children, child => {
      if (child && child.type && child.type.icon) {
        hasIcon = true;
        child = <span className={`${CLASS_ROOT}__icon`}>{child};
      }
      return child;
    });

    let classes = classnames(
      CLASS_ROOT,
      this.props.className,
      {
        [`${CLASS_ROOT}--disabled`]: this.props.disabled,
        [`${CLASS_ROOT}--icon`]: icon,
        [`${CLASS_ROOT}--icon-label`]: hasIcon && this.props.label,
        [`${CLASS_ROOT}--primary`]: this.props.primary,
        [`${CLASS_ROOT}--reverse`]: this.props.reverse
      }
    );

    if (!children) {
      children = this.props.label;
    }

    const first = this.props.reverse ? children : icon;
    const second = this.props.reverse ? icon : children;

    return (
      <this.props.tag id={this.props.id} className={classes}
        href={this.props.href}
        target={this.props.target}
        onClick={this.props.onClick}
        aria-label={this.props.a11yTitle}>
        {first}
        {second}
      </this.props.tag>
    );
  }
};

Anchor.propTypes = {
  a11yTitle: PropTypes.string,
  icon: PropTypes.string,
  disabled: PropTypes.bool,
  href: PropTypes.string,
  id: PropTypes.string,
  label: PropTypes.node,
  onClick: PropTypes.func,
  primary: PropTypes.bool,
  tag: PropTypes.string,
  target: PropTypes.string,
  reverse: PropTypes.bool
};

Anchor.defaultProps = {
  tag: 'a'
};
<|endoftext|>


<commit_before>/*! Pickyfill - Offline caching for picturefill responsive image polyfill. Author: Rich Trott | Copyright: Regents of University of California, 2012 | License: MIT */

(function( w ) {
    "use strict";

    var localStorage = w.localStorage,
        applicationCache = w.applicationCache,
        image,
        dataUri,
        pf_index_string,
        pf_index,
        canvasTest = document.createElement('canvas');

    // Don't run any of this stuff if application cache, localStorage or canvas are not available.
    if ( (! applicationCache) || (! localStorage) || (!(canvasTest.getContext && canvasTest.getContext('2d'))) ) {
            return;
    }

    pf_index_string = localStorage.getItem('pf_index') || '{}';
    pf_index = JSON.parse(pf_index_string);

    // We'll use this to clear the pickyfill cache when appcache updates.
    var clearCache = function () {
        localStorage.removeItem('pf_index');
        for (var prop in pf_index) {
            localStorage.removeItem(prop);
        }
    };

    // Unfortunately, reloading is the most reliable way to get stuff into the
    //  pickyfill cache. If you wait for the user to reload, they may be offline
    //  at that time. If we just had an updateready event, chances are very good
    //  that they are still online. Another possibility is to just try to reload
    //  the images that are currently shown, but there's no guarantee that those
    //  images are in the new page or that the current page isn't missing important
    //  images that will display in the new page and need to be cached.
    var refreshCache = function () {
        clearCache();
        w.location.reload();
    };

    // If appcache updates, refresh the pickyfill cache to get new items.
    // If appcache is obsolete, clear the pickyfill cache.
    // Appcache == IE10 or later == no need to worry about attachEvent (IE8 and earlier)
    // Anything that has appcache is going to have addEventListener.
    applicationCache.addEventListener('updateready', refreshCache, false);
    applicationCache.addEventListener('obsolete', clearCache, false);

    // If the event has already fired and we missed it, clear/refresh the pickyfill cache.
    if(applicationCache.status === applicationCache.UPDATEREADY) {
        refreshCache();
    }

    if (applicationCache.status === applicationCache.OBSOLETE) {
        clearCache();
    }

    var srcFromCacheRan = false;
    var srcFromCache = function ( ps ) {
        var sources, src, newSrc;

        // Loop the pictures
        for( var i = 0, il = ps.length; i < il; i++ ){
            if( ps[ i ].getAttribute( "data-picture" ) !== null ){

                sources = ps[ i ].getElementsByTagName( "div" );
                // See which ones are cached in localStorage. Use the cached value.
                for( var j = 0, jl = sources.length; j < jl; j++ ){
                    if ((src = sources[j].getAttribute( "data-src" )) !== null ) {
                        if ( pf_index.hasOwnProperty('pf_s_' + src)) {
                            newSrc = localStorage.getItem('pf_s_' + src);
                            if (newSrc !== null) {
                                sources[j].setAttribute('data-src', localStorage.getItem('pf_s_' + src));
                            }
                        }
                    }
                }
            }
        }
    };

    var cacheImage = function () {
        var canvas,
            ctx,
            imageSrc;

        imageSrc = this.getAttribute("src");

        if ((pf_index.hasOwnProperty('pf_s_' + imageSrc)) ||
            (imageSrc.substr(0,5) === "data:") ||
            (imageSrc === null) || (imageSrc.length === 0)) {
                return;
        }

        canvas = w.document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;

        ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);
        try {
            dataUri = canvas.toDataURL();
        } catch (e) {
            // TODO: Improve error handling here. For now, if canvas.toDataURL()
            //   throws an exception, don't cache the image and move on.
            return;
        }

        // Do not cache if the resulting cache item will take more than 128Kb.
        if (dataUri.length > 131072) {
            return;
        }

        pf_index["pf_s_"+imageSrc] = 1;

        try {
            localStorage.setItem("pf_s_"+imageSrc, dataUri);
            localStorage.setItem("pf_index", JSON.stringify(pf_index));
        } catch (e) {
            // Caching failed. Remove item from index object so next cached item
            //   doesn't wrongly indicate this item was successfully cached.
            delete pf_index["pf_s_"+imageSrc];
        }
    };

    // Exit here if uncached. If updateready fires later, it will reload,
    //   and status will not be uncached on the that load.
    if (applicationCache.status === applicationCache.UNCACHED) {
        return;
    }
    w.picturefillOrig = w.picturefill;
    w.picturefill = function () {
        var ps = w.document.getElementsByTagName( "div" ),
        i,
        il;

        if (! srcFromCacheRan ) {
            srcFromCacheRan = true;
            srcFromCache( ps );
        }

        w.picturefillOrig();

        // Loop the pictures
        for( i = 0, il = ps.length; i < il; i++ ) {
            if( ps[ i ].getAttribute( "data-picture" ) !== null ){
                image = ps[ i ].getElementsByTagName( "img" )[0];
                if (image) {
                    if (image.getAttribute("src") !== null) {
                        image.addEventListener('load', cacheImage, false);
//TODO: What to do (if anything) if we missed the load event. image.complete
//  cannot be trusted, at least not on Firefox 14.0.1 on the Mac. Seems to remain
//  set to "true" even after window is resized and src attribute is changed to an
//  image that is not yet loaded.
                    }
                }
            }
        }
    };
    w.addEventListener('resize', w.picturefill, false);
    w.removeEventListener('resize', w.picturefillOrig, false);

}( this ));
<commit_msg>Remove unneeded event handlers<commit_after>/*! Pickyfill - Offline caching for picturefill responsive image polyfill. Author: Rich Trott | Copyright: Regents of University of California, 2012 | License: MIT */

(function( w ) {
    "use strict";

    var localStorage = w.localStorage,
        applicationCache = w.applicationCache,
        image,
        dataUri,
        pf_index_string,
        pf_index,
        canvasTest = document.createElement('canvas');

    // Don't run any of this stuff if application cache, localStorage or canvas are not available.
    if ( (! applicationCache) || (! localStorage) || (!(canvasTest.getContext && canvasTest.getContext('2d'))) ) {
            return;
    }

    pf_index_string = localStorage.getItem('pf_index') || '{}';
    pf_index = JSON.parse(pf_index_string);

    // We'll use this to clear the pickyfill cache when appcache updates.
    var clearCache = function () {
        localStorage.removeItem('pf_index');
        for (var prop in pf_index) {
            localStorage.removeItem(prop);
        }
    };

    // Unfortunately, reloading is the most reliable way to get stuff into the
    //  pickyfill cache. If you wait for the user to reload, they may be offline
    //  at that time. If we just had an updateready event, chances are very good
    //  that they are still online. Another possibility is to just try to reload
    //  the images that are currently shown, but there's no guarantee that those
    //  images are in the new page or that the current page isn't missing important
    //  images that will display in the new page and need to be cached.
    var refreshCache = function () {
        clearCache();
        w.location.reload();
    };

    // If appcache updates, refresh the pickyfill cache to get new items.
    // If appcache is obsolete, clear the pickyfill cache.
    // Appcache == IE10 or later == no need to worry about attachEvent (IE8 and earlier)
    // Anything that has appcache is going to have addEventListener.
    applicationCache.addEventListener('updateready', refreshCache, false);
    applicationCache.addEventListener('obsolete', clearCache, false);

    // If the event has already fired and we missed it, clear/refresh the pickyfill cache.
    if(applicationCache.status === applicationCache.UPDATEREADY) {
        refreshCache();
    }

    if (applicationCache.status === applicationCache.OBSOLETE) {
        clearCache();
    }

    var srcFromCacheRan = false;
    var srcFromCache = function ( ps ) {
        var sources, src, newSrc;

        // Loop the pictures
        for( var i = 0, il = ps.length; i < il; i++ ){
            if( ps[ i ].getAttribute( "data-picture" ) !== null ){

                sources = ps[ i ].getElementsByTagName( "div" );
                // See which ones are cached in localStorage. Use the cached value.
                for( var j = 0, jl = sources.length; j < jl; j++ ){
                    if ((src = sources[j].getAttribute( "data-src" )) !== null ) {
                        if ( pf_index.hasOwnProperty('pf_s_' + src)) {
                            newSrc = localStorage.getItem('pf_s_' + src);
                            if (newSrc !== null) {
                                sources[j].setAttribute('data-src', localStorage.getItem('pf_s_' + src));
                            }
                        }
                    }
                }
            }
        }
    };

    var cacheImage = function ( param ) {
        var canvas,
            ctx,
            imageSrc;

        imageSrc = this.getAttribute("src");

        if ((pf_index.hasOwnProperty('pf_s_' + imageSrc)) ||
            (imageSrc.substr(0,5) === "data:") ||
            (imageSrc === null) || (imageSrc.length === 0)) {
                return;
        }

        canvas = w.document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;

        ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);
        try {
            dataUri = canvas.toDataURL();
        } catch (e) {
            // TODO: Improve error handling here. For now, if canvas.toDataURL()
            //   throws an exception, don't cache the image and move on.
            return;
        }

        // Do not cache if the resulting cache item will take more than 128Kb.
        if (dataUri.length > 131072) {
            return;
        }

        pf_index["pf_s_"+imageSrc] = 1;

        try {
            localStorage.setItem("pf_s_"+imageSrc, dataUri);
            localStorage.setItem("pf_index", JSON.stringify(pf_index));
        } catch (e) {
            // Caching failed. Remove item from index object so next cached item
            //   doesn't wrongly indicate this item was successfully cached.
            delete pf_index["pf_s_"+imageSrc];
        }
    };

    // Exit here if uncached. If updateready fires later, it will reload,
    //   and status will not be uncached on the that load.
    if (applicationCache.status === applicationCache.UNCACHED) {
        return;
    }
    w.picturefillOrig = w.picturefill;
    w.picturefill = function () {
        var ps = w.document.getElementsByTagName( "div" ),
        i,
        il;

        if (! srcFromCacheRan ) {
            srcFromCacheRan = true;
            srcFromCache( ps );
        }

        w.picturefillOrig();

        // Loop the pictures
        for( i = 0, il = ps.length; i < il; i++ ) {
            if( ps[ i ].getAttribute( "data-picture" ) !== null ){
                image = ps[ i ].getElementsByTagName( "img" )[0];
                if (image) {
                    if (image.getAttribute("src") !== null) {
                        image.addEventListener('load', cacheImage, false);
//TODO: What to do (if anything) if we missed the load event. image.complete
//  cannot be used for this, at least not on Firefox 14.0.1 on the Mac. It is
//  set to "true" even after window is resized and src attribute is changed to an
//  image that is not yet loaded.
                    }
                }
            }
        }
    };
    // WAT?!?! UserAgent sniffing?! Yes, lame, but Firefox will cache truncated
    // images if you're resize happens at the wrong moment and there's not a
    // an efficient way that I'm aware of to detect that this has happened.
    //
    // So we only cache images in Firefox on load, not on resize. I have not seen
    // it happen on document load...yet.
    //
    // If you think you have a better way to handle this, see details at
    // http://stackoverflow.com/q/11928878/436641 and submit an answer or
    // comment there.
    // if (navigator.userAgent.indexOf("Firefox") === -1) {
    //     w.addEventListener('resize', w.picturefill, false);
    //     w.removeEventListener('resize', w.picturefillOrig, false);
    // }

}( this ));
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/ember-blockly';

export default Ember.Component.extend({
  layout,
  disablePreloadAudio: true,
  classNames: ['ember-blockly-container'],
  blocks: [],
  current_blocks: Ember.computed.oneWay('blocks'),
  workspaceElement: null,
  workspace: '<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',
  showCode: false,
  disableNotConnectedToMainBlock: false,

  withZoom: true,       // definirá el parámetro "zoom" al llamar a inject.
  withTrash: true,      // definirá el parámetro "trashcan" al llamar a inject.

  collapse: false,
  comments: true,
  css: true,
  disable: true,
  grid: false,
  horizontalLayout: false,
  maxBlocks: Infinity,
  mediaFolder: "blockly-package/media/",
  oneBasedIndex: true,
  readOnly: false,
  rtl: false,
  scrollbars: true,
  sounds: true,
  toolboxPosition: "start",

  /* Context menu options. */
  duplicate: true,
  help: true,
  comment: true,
  disableBlock: true,
  contextMenu: true,

  disableResize: false,

  lastContextMenuFunction: null,
  originalContextMenu: null,

  /* Highlighted block */
  highlightedBlock: null,

  style: Ember.computed('showCode', function() {
    if (this.get('showCode')) {
      return Ember.String.htmlSafe("");
    } else {
      return Ember.String.htmlSafe("display: none;");
    }
  }),

  observeContextMenu: Ember.observer('contextMenu', function() {

    if (this.get('contextMenu')) {
      this.enableContextMenu();
    } else {
      this.disableContextMenu();
    }
  }),

  observeBlocks: Ember.observer('blocks', function() {
    this.set('current_blocks', this.get('blocks'));
    this.updateToolbox(this.get('current_blocks'));
  }),

  observeWorkspace: Ember.observer('workspace', function() {

    let workspace = this.get('workspaceElement');
    let xml_text = this.get('workspace');

    workspace.clear();

    if (xml_text) {
      let dom = Blockly.Xml.textToDom(xml_text);
      this._moveBlocksFromBehindToolbox(dom);
      Blockly.Xml.domToWorkspace(dom, workspace);
    }

  }),

  observeHighlightedBlock: Ember.observer('highlightedBlock', function() {
    this.get('workspaceElement').highlightBlock(this.get("highlightedBlock"));
  }),

  _moveBlocksFromBehindToolbox(dom){
    // TODO: This method should go away once Blockly is updated.
    if( this.get("current_blocks").some(block => block.category && block.category !== 'Separator') ) return dom;

    // Issue: https://github.com/google/blockly/issues/1924
    // If we don't have categories (which means we have just blocks in the toolbox)
    // then the workspace can be behind the toolbox, then
    // we need to move every block which is under the toolbox.

    // Does not consider RTL workspaces
    var toolboxBorder = this.get('workspaceElement').getFlyout_().width_;
    var x = domChild => parseInt(domChild.getAttribute('x'), 10);

    dom.childNodes.forEach( domChild => {
      var name = domChild.nodeName.toLowerCase();
      if ((name == 'block' || name == 'shadow') && domChild.hasAttribute('x')
        && x(domChild) < toolboxBorder) {
        domChild.setAttribute('x', toolboxBorder + 15);
      }
    });
  },

  didInsertElement() {

    if (this.get('disablePreloadAudio')) {
      Blockly.WorkspaceSvg.prototype.preloadAudio_ = function() {};
    }

    this.createSection("section_control", "Control");
    this.createSection("section_logic", "Lógica");

    let options = {
       toolbox: this.createToolbox(this.get("current_blocks")),
       trashcan: this.get("withTrash"),

       collapse: this.get("collapse"),
       comments: this.get("comments"),
       css: this.get("css"),
       disable: this.get("disable"),
       horizontalLayout: this.get("horizontalLayout"),
       maxBlocks: this.get("maxBlocks"),
       rtl: this.get("rtl"),
       media: this.get("mediaFolder"),
       oneBasedIndex: this.get("oneBasedIndex"),
       readOnly: this.get("readOnly"),
       scrollbars: this.get("scrollbars"),
       sounds: this.get("sounds"),
       toolboxPosition: this.get("toolboxPosition"),
     };

     if (this.get('grid')) {
       options['grid'] = this._get_default_grid();
     }

     if (this.get("withZoom")) {
       options['zoom'] = this._get_default_zoom();
     }

    let blocklyDiv = this.$().find("div")[0];
    let blocklyArea = this.$()[0];

    let workspace = Blockly.inject(blocklyDiv, options);

    this.set('workspaceElement', workspace);

    this.set('blocklyDiv', blocklyDiv);
    this.set('blocklyArea', blocklyArea);

    if (!this.get('contextMenu')) {
      this.disableContextMenu();
    }

    this.set('originalContextMenu', Blockly.ContextMenu.show);

    // Intenta modificar la función que muestra el menú para
    // habilitar o deshabilitar opciones.
    Blockly.ContextMenu.show = (a, b, c) => {
      b = this._filtrar_items_del_menu(b);
      this.get('originalContextMenu')(a, b, c);
    };

    $(window).bind("resize.blockly", () => {
      this._onresize();
    });

    Ember.run(() => {
      if (this.get('disableNotConnectedToMainBlock')) {
        workspace.addChangeListener(Blockly.Events.disableOrphans);
      }
    });

    Ember.run(() => {
      workspace.addChangeListener(() => {
        this.onUpdate();
        this._onresize();
      });
    });

    this._onresize();

    Ember.run.scheduleOnce('afterRender', () => {
      this.set('workspace', this.get('workspace') + ' ');
    });
  },

  /**
   * Procesa los items del menú contextual de blockly para habilitar o
   * deshabilitar algunas opciones.
   */
  _filtrar_items_del_menu(items) {
    return items.filter((i) => {

      if (i.text === Blockly.Msg.DUPLICATE_BLOCK) {
        i.enabled = this.get('duplicate');
      }

      if (i.text === Blockly.Msg.HELP) {
        i.enabled = this.get('help');
      }

      if (i.text === Blockly.Msg.ADD_COMMENT || i.text === Blockly.Msg.REMOVE_COMMENT) {
        i.enabled = this.get('comment');
      }

      if (i.text === Blockly.Msg.DISABLE_BLOCK || i.text === Blockly.Msg.ENABLE_BLOCK) {
        i.enabled = this.get('disableBlock');
      }

      return true;
    });
  },

  disableContextMenu() {
    this.set('lastContextMenuFunction', Blockly.ContextMenu.show);
    Blockly.ContextMenu.show = function() {};
  },

  enableContextMenu() {
    Blockly.ContextMenu.show = this.get('lastContextMenuFunction');
  },

  _get_default_grid() {
    return {
      spacing: 20,
      length: 3,
      colour: '#ccc',
      snap: true
    };
  },

  _get_default_zoom() {
    return {
      controls: true,
      wheel: false,
      startScale: 1.0,
      maxScale: 3,
      minScale: 0.3,
      scaleSpeed: 1.2
    };
  },

  _onresize() {
    if (this.get('disableResize')) {
      return null;
    }

    let blocklyDiv = this.get('blocklyDiv');
    let blocklyArea = this.get('blocklyArea');
    let element = blocklyArea;
    let x = 0;
    let y = 0;

    // itera 'hacia arriba' en el dom para conocer el desplazamiento total.
    do {
      x += element.offsetLeft;
      y += element.offsetTop;
      element = element.offsetParent;
    } while (element);

    blocklyDiv.style.left = `${x}px`;
    blocklyDiv.style.top = `${y}px`;
    blocklyDiv.style.width = `${blocklyArea.offsetWidth}px`;
    blocklyDiv.style.height = `${blocklyArea.offsetHeight}px`;
    Blockly.svgResize(this.get('workspaceElement'));
  },

  willDestroyElement() {
    $(window).unbind("resize.blockly");
  },

  onUpdate(event) {
    Ember.run(() => {
      let xml = Blockly.Xml.workspaceToDom(this.get('workspaceElement'));
      let xml_text = Blockly.Xml.domToText(xml);
      this.sendAction("onChangeWorkspace", xml_text);

      //if (this.get('showCode')) {
        try {
          let code = Blockly.JavaScript.workspaceToCode(this.get('workspaceElement'));
          this.set('javascriptCode', js_beautify(code));
        } catch (e) {
          console.warn("No se puede generar el código. Esto seguramente se produce porque la solución tiene un bloque inexistente.", e);
        }
      //}
    });
  },

  createSection(name, label) {
    Blockly.Blocks[name] = {
      init: function() {
        this.appendDummyInput().appendField(`  ${label}  `);
        this.setOutput(false);
        this.setNextStatement(false);
        this.setPreviousStatement(false);
        this.setDisabled(true);
      }
    };
  },

  createToolbox(bloques) {
    let toolbox = [];

    toolbox.push('<xml>');

    bloques.forEach((bloque) => {

      if (bloque.isSeparator) {
        toolbox.push('<sep></sep>');

      } else if (bloque['category']) {

        if (bloque['custom']) {
          toolbox.push(`<category name="${bloque.category}" custom="${bloque.custom}">`);
        } else {
          toolbox.push(`<category name="${bloque.category}">`);

          bloque.blocks.forEach((bloque_en_categoria) => {

            if (!Blockly.Blocks[bloque_en_categoria]) {
              throw new Error(`This block named '${bloque_en_categoria}' don't exist.`);
            }

            if(Blockly.Blocks[bloque_en_categoria].toolbox)
            {
              toolbox.push(Blockly.Blocks[bloque_en_categoria].toolbox);
            }
            else {
              toolbox.push(`  <block type="${bloque_en_categoria}"></block>`);
            }
          });
        }

        toolbox.push('</category>');

      } else {

        if (!Blockly.Blocks[bloque]) {
          throw new Error(`This block named '${bloque}' don't exist.`);
        }

        if (Blockly.Blocks[bloque].toolbox) {
          toolbox.push(Blockly.Blocks[bloque].toolbox);
        } else {
          toolbox.push(`  <block type="${bloque}"></block>`);
        }
      }
    });

    toolbox.push('</xml>');

    return toolbox.join("\n");
  },

  updateToolbox(bloques) {
    let toolbox = null;

    // Si se envió un string XML, lo inserta directamente
    // como toolbox.
    if (/xml/.test(bloques)) {
      toolbox = bloques;
    } else {
      toolbox = this.createToolbox(this.get("current_blocks"));
    }

    this.get('workspaceElement').updateToolbox(toolbox);
  }
});
<commit_msg>Added xp compatibility<commit_after>import Ember from 'ember';
import layout from '../templates/components/ember-blockly';

export default Ember.Component.extend({
  layout,
  disablePreloadAudio: true,
  classNames: ['ember-blockly-container'],
  blocks: [],
  current_blocks: Ember.computed.oneWay('blocks'),
  workspaceElement: null,
  workspace: '<xml xmlns="http://www.w3.org/1999/xhtml"></xml>',
  showCode: false,
  disableNotConnectedToMainBlock: false,

  withZoom: true,       // definirá el parámetro "zoom" al llamar a inject.
  withTrash: true,      // definirá el parámetro "trashcan" al llamar a inject.

  collapse: false,
  comments: true,
  css: true,
  disable: true,
  grid: false,
  horizontalLayout: false,
  maxBlocks: Infinity,
  mediaFolder: "blockly-package/media/",
  oneBasedIndex: true,
  readOnly: false,
  rtl: false,
  scrollbars: true,
  sounds: true,
  toolboxPosition: "start",

  /* Context menu options. */
  duplicate: true,
  help: true,
  comment: true,
  disableBlock: true,
  contextMenu: true,

  disableResize: false,

  lastContextMenuFunction: null,
  originalContextMenu: null,

  /* Highlighted block */
  highlightedBlock: null,

  style: Ember.computed('showCode', function() {
    if (this.get('showCode')) {
      return Ember.String.htmlSafe("");
    } else {
      return Ember.String.htmlSafe("display: none;");
    }
  }),

  observeContextMenu: Ember.observer('contextMenu', function() {

    if (this.get('contextMenu')) {
      this.enableContextMenu();
    } else {
      this.disableContextMenu();
    }
  }),

  observeBlocks: Ember.observer('blocks', function() {
    this.set('current_blocks', this.get('blocks'));
    this.updateToolbox(this.get('current_blocks'));
  }),

  observeWorkspace: Ember.observer('workspace', function() {

    let workspace = this.get('workspaceElement');
    let xml_text = this.get('workspace');

    workspace.clear();

    if (xml_text) {
      let dom = Blockly.Xml.textToDom(xml_text);
      this._moveBlocksFromBehindToolbox(dom);
      Blockly.Xml.domToWorkspace(dom, workspace);
    }

  }),

  observeHighlightedBlock: Ember.observer('highlightedBlock', function() {
    this.get('workspaceElement').highlightBlock(this.get("highlightedBlock"));
  }),

  _moveBlocksFromBehindToolbox(dom){
    // TODO: This method should go away once Blockly is updated.
    if( this.get("current_blocks").some(block => block.category && block.category !== 'Separator') ) return dom;

    // Issue: https://github.com/google/blockly/issues/1924
    // If we don't have categories (which means we have just blocks in the toolbox)
    // then the workspace can be behind the toolbox, then
    // we need to move every block which is under the toolbox.

    // Does not consider RTL workspaces
    var toolboxBorder = this.get('workspaceElement').getFlyout_().width_;
    var x = domChild => parseInt(domChild.getAttribute('x'), 10);

    Array.from(dom.childNodes).forEach( domChild => {
      var name = domChild.nodeName.toLowerCase();
      if ((name == 'block' || name == 'shadow') && domChild.hasAttribute('x')
        && x(domChild) < toolboxBorder) {
        domChild.setAttribute('x', toolboxBorder + 15);
      }
    });
  },

  didInsertElement() {

    if (this.get('disablePreloadAudio')) {
      Blockly.WorkspaceSvg.prototype.preloadAudio_ = function() {};
    }

    this.createSection("section_control", "Control");
    this.createSection("section_logic", "Lógica");

    let options = {
       toolbox: this.createToolbox(this.get("current_blocks")),
       trashcan: this.get("withTrash"),

       collapse: this.get("collapse"),
       comments: this.get("comments"),
       css: this.get("css"),
       disable: this.get("disable"),
       horizontalLayout: this.get("horizontalLayout"),
       maxBlocks: this.get("maxBlocks"),
       rtl: this.get("rtl"),
       media: this.get("mediaFolder"),
       oneBasedIndex: this.get("oneBasedIndex"),
       readOnly: this.get("readOnly"),
       scrollbars: this.get("scrollbars"),
       sounds: this.get("sounds"),
       toolboxPosition: this.get("toolboxPosition"),
     };

     if (this.get('grid')) {
       options['grid'] = this._get_default_grid();
     }

     if (this.get("withZoom")) {
       options['zoom'] = this._get_default_zoom();
     }

    let blocklyDiv = this.$().find("div")[0];
    let blocklyArea = this.$()[0];

    let workspace = Blockly.inject(blocklyDiv, options);

    this.set('workspaceElement', workspace);

    this.set('blocklyDiv', blocklyDiv);
    this.set('blocklyArea', blocklyArea);

    if (!this.get('contextMenu')) {
      this.disableContextMenu();
    }

    this.set('originalContextMenu', Blockly.ContextMenu.show);

    // Intenta modificar la función que muestra el menú para
    // habilitar o deshabilitar opciones.
    Blockly.ContextMenu.show = (a, b, c) => {
      b = this._filtrar_items_del_menu(b);
      this.get('originalContextMenu')(a, b, c);
    };

    $(window).bind("resize.blockly", () => {
      this._onresize();
    });

    Ember.run(() => {
      if (this.get('disableNotConnectedToMainBlock')) {
        workspace.addChangeListener(Blockly.Events.disableOrphans);
      }
    });

    Ember.run(() => {
      workspace.addChangeListener(() => {
        this.onUpdate();
        this._onresize();
      });
    });

    this._onresize();

    Ember.run.scheduleOnce('afterRender', () => {
      this.set('workspace', this.get('workspace') + ' ');
    });
  },

  /**
   * Procesa los items del menú contextual de blockly para habilitar o
   * deshabilitar algunas opciones.
   */
  _filtrar_items_del_menu(items) {
    return items.filter((i) => {

      if (i.text === Blockly.Msg.DUPLICATE_BLOCK) {
        i.enabled = this.get('duplicate');
      }

      if (i.text === Blockly.Msg.HELP) {
        i.enabled = this.get('help');
      }

      if (i.text === Blockly.Msg.ADD_COMMENT || i.text === Blockly.Msg.REMOVE_COMMENT) {
        i.enabled = this.get('comment');
      }

      if (i.text === Blockly.Msg.DISABLE_BLOCK || i.text === Blockly.Msg.ENABLE_BLOCK) {
        i.enabled = this.get('disableBlock');
      }

      return true;
    });
  },

  disableContextMenu() {
    this.set('lastContextMenuFunction', Blockly.ContextMenu.show);
    Blockly.ContextMenu.show = function() {};
  },

  enableContextMenu() {
    Blockly.ContextMenu.show = this.get('lastContextMenuFunction');
  },

  _get_default_grid() {
    return {
      spacing: 20,
      length: 3,
      colour: '#ccc',
      snap: true
    };
  },

  _get_default_zoom() {
    return {
      controls: true,
      wheel: false,
      startScale: 1.0,
      maxScale: 3,
      minScale: 0.3,
      scaleSpeed: 1.2
    };
  },

  _onresize() {
    if (this.get('disableResize')) {
      return null;
    }

    let blocklyDiv = this.get('blocklyDiv');
    let blocklyArea = this.get('blocklyArea');
    let element = blocklyArea;
    let x = 0;
    let y = 0;

    // itera 'hacia arriba' en el dom para conocer el desplazamiento total.
    do {
      x += element.offsetLeft;
      y += element.offsetTop;
      element = element.offsetParent;
    } while (element);

    blocklyDiv.style.left = `${x}px`;
    blocklyDiv.style.top = `${y}px`;
    blocklyDiv.style.width = `${blocklyArea.offsetWidth}px`;
    blocklyDiv.style.height = `${blocklyArea.offsetHeight}px`;
    Blockly.svgResize(this.get('workspaceElement'));
  },

  willDestroyElement() {
    $(window).unbind("resize.blockly");
  },

  onUpdate(event) {
    Ember.run(() => {
      let xml = Blockly.Xml.workspaceToDom(this.get('workspaceElement'));
      let xml_text = Blockly.Xml.domToText(xml);
      this.sendAction("onChangeWorkspace", xml_text);

      //if (this.get('showCode')) {
        try {
          let code = Blockly.JavaScript.workspaceToCode(this.get('workspaceElement'));
          this.set('javascriptCode', js_beautify(code));
        } catch (e) {
          console.warn("No se puede generar el código. Esto seguramente se produce porque la solución tiene un bloque inexistente.", e);
        }
      //}
    });
  },

  createSection(name, label) {
    Blockly.Blocks[name] = {
      init: function() {
        this.appendDummyInput().appendField(`  ${label}  `);
        this.setOutput(false);
        this.setNextStatement(false);
        this.setPreviousStatement(false);
        this.setDisabled(true);
      }
    };
  },

  createToolbox(bloques) {
    let toolbox = [];

    toolbox.push('<xml>');

    bloques.forEach((bloque) => {

      if (bloque.isSeparator) {
        toolbox.push('<sep></sep>');

      } else if (bloque['category']) {

        if (bloque['custom']) {
          toolbox.push(`<category name="${bloque.category}" custom="${bloque.custom}">`);
        } else {
          toolbox.push(`<category name="${bloque.category}">`);

          bloque.blocks.forEach((bloque_en_categoria) => {

            if (!Blockly.Blocks[bloque_en_categoria]) {
              throw new Error(`This block named '${bloque_en_categoria}' don't exist.`);
            }

            if(Blockly.Blocks[bloque_en_categoria].toolbox)
            {
              toolbox.push(Blockly.Blocks[bloque_en_categoria].toolbox);
            }
            else {
              toolbox.push(`  <block type="${bloque_en_categoria}"></block>`);
            }
          });
        }

        toolbox.push('</category>');

      } else {

        if (!Blockly.Blocks[bloque]) {
          throw new Error(`This block named '${bloque}' don't exist.`);
        }

        if (Blockly.Blocks[bloque].toolbox) {
          toolbox.push(Blockly.Blocks[bloque].toolbox);
        } else {
          toolbox.push(`  <block type="${bloque}"></block>`);
        }
      }
    });

    toolbox.push('</xml>');

    return toolbox.join("\n");
  },

  updateToolbox(bloques) {
    let toolbox = null;

    // Si se envió un string XML, lo inserta directamente
    // como toolbox.
    if (/xml/.test(bloques)) {
      toolbox = bloques;
    } else {
      toolbox = this.createToolbox(this.get("current_blocks"));
    }

    this.get('workspaceElement').updateToolbox(toolbox);
  }
});
<|endoftext|>


<commit_before>import Delta from 'quill-delta';
import Editor from '../../../core/editor';

const tableDelta = new Delta()
  .insert('A1')
  .insert('\n', { table: { row: 'a' } })
  .insert('A2')
  .insert('\n', { table: { row: 'a' } })
  .insert('A3')
  .insert('\n', { table: { row: 'a' } })
  .insert('B1')
  .insert('\n', { table: { row: 'b' } })
  .insert('B2')
  .insert('\n', { table: { row: 'b' } })
  .insert('B3')
  .insert('\n', { table: { row: 'b' } })
  .insert('C1')
  .insert('\n', { table: { row: 'c' } })
  .insert('C2')
  .insert('\n', { table: { row: 'c' } })
  .insert('C3')
  .insert('\n', { table: { row: 'c' } });

const tableHTML = `

        A1
        A2
        A3

        B1
        B2
        B3

        C1
        C2
        C3

`;

describe('Table', function() {
  it('initialize', function() {
    const editor = this.initialize(Editor, tableHTML);
    expect(editor.getDelta()).toEqual(tableDelta);
    expect(this.container).toEqualHTML(tableHTML);
  });

  it('add', function() {
    const editor = this.initialize(Editor, '');
    editor.applyDelta(tableDelta.delete(1));
    expect(this.container).toEqualHTML(tableHTML);
  });

  it('add format plaintext', function() {
    const editor = this.initialize(Editor, '
Test
');
    editor.formatLine(0, 5, { table: { row: 'a' } });
    expect(this.container).toEqualHTML(
      '

Test

',
    );
  });

  it('add format replace', function() {
    const editor = this.initialize(Editor, '
Test
');
    editor.formatLine(0, 5, { table: { row: 'a' } });
    expect(this.container).toEqualHTML(
      '

Test

',
    );
  });

  it('remove format plaintext', function() {
    const editor = this.initialize(
      Editor,
      '

Test

',
    );
    editor.formatLine(0, 5, { table: null });
    expect(this.container).toEqualHTML('
Test
');
  });

  it('remove format replace', function() {
    const editor = this.initialize(
      Editor,
      '

Test

',
    );
    editor.formatLine(0, 5, { header: 1 });
    expect(this.container).toEqualHTML('
Test
');
  });

  it('balance cells', function() {
    this.initialize(
      Editor,
      `

            A1

            B1
            B2

            C1
            C2
            C3

`,
    );
    expect(this.container).toEqualHTML(
      `

            A1

            B1
            B2

            C1
            C2
            C3

`,
    );
  });
});
<commit_msg>more table tests<commit_after>import Delta from 'quill-delta';
import Editor from '../../../core/editor';

const tableDelta = new Delta()
  .insert('A1')
  .insert('\n', { table: { row: 'a' } })
  .insert('A2')
  .insert('\n', { table: { row: 'a' } })
  .insert('A3')
  .insert('\n', { table: { row: 'a' } })
  .insert('B1')
  .insert('\n', { table: { row: 'b' } })
  .insert('B2')
  .insert('\n', { table: { row: 'b' } })
  .insert('B3')
  .insert('\n', { table: { row: 'b' } })
  .insert('C1')
  .insert('\n', { table: { row: 'c' } })
  .insert('C2')
  .insert('\n', { table: { row: 'c' } })
  .insert('C3')
  .insert('\n', { table: { row: 'c' } });

const tableHTML = `

        A1
        A2
        A3

        B1
        B2
        B3

        C1
        C2
        C3

`;

describe('Table', function() {
  it('initialize', function() {
    const editor = this.initialize(Editor, tableHTML);
    expect(editor.getDelta()).toEqual(tableDelta);
    expect(this.container).toEqualHTML(tableHTML);
  });

  it('add', function() {
    const editor = this.initialize(Editor, '');
    editor.applyDelta(tableDelta.delete(1));
    expect(this.container).toEqualHTML(tableHTML);
  });

  it('add format plaintext', function() {
    const editor = this.initialize(Editor, '
Test
');
    editor.formatLine(0, 5, { table: { row: 'a' } });
    expect(this.container).toEqualHTML(
      '

Test

',
    );
  });

  it('add format replace', function() {
    const editor = this.initialize(Editor, '
Test
');
    editor.formatLine(0, 5, { table: { row: 'a' } });
    expect(this.container).toEqualHTML(
      '

Test

',
    );
  });

  it('remove format plaintext', function() {
    const editor = this.initialize(
      Editor,
      '

Test

',
    );
    editor.formatLine(0, 5, { table: null });
    expect(this.container).toEqualHTML('
Test
');
  });

  it('remove format replace', function() {
    const editor = this.initialize(
      Editor,
      '

Test

',
    );
    editor.formatLine(0, 5, { header: 1 });
    expect(this.container).toEqualHTML('
Test
');
  });

  it('group rows', function() {
    const editor = this.initialize(
      Editor,
      `

A

B

    `,
    );
    editor.scroll.children.head.children.head.children.head.optimize();
    expect(this.container).toEqualHTML(`

A	B

    `);
  });

  it('split rows', function() {
    const editor = this.initialize(
      Editor,
      `

A	B

    `,
    );
    editor.scroll.children.head.children.head.children.head.optimize();
    expect(this.container).toEqualHTML(`

A

B

    `);
  });

  it('group and split rows', function() {
    const editor = this.initialize(
      Editor,
      `

A	B1

B2

    `,
    );
    editor.scroll.children.head.children.head.children.head.optimize();
    expect(this.container).toEqualHTML(`

A

B1	B2

    `);
  });

  it('balance cells', function() {
    const editor = this.initialize(
      Editor,
      `

            A1

            B1
            B2

            C1
            C2
            C3

`,
    );
    editor.scroll.children.head.balanceCells();
    expect(this.container).toEqualHTML(
      `

            A1

            B1
            B2

            C1
            C2
            C3

`,
    );
  });

  it('format', function() {
    const editor = this.initialize(Editor, '
a

b

1

2
');
    editor.formatLine(0, 4, { table: { row: 'a' } });
    editor.formatLine(4, 4, { table: { row: 'b' } });
    expect(this.container).toEqualHTML(
      `

            a
            b

            1
            2

`,
    );
  });

  it('applyDelta', function() {
    const editor = this.initialize(Editor, '

');
    editor.applyDelta(
      new Delta()
        .insert('\n\n', { table: { row: 'a' } })
        .insert('\n\n', { table: { row: 'b' } }),
    );
    expect(this.container).toEqualHTML(
      `

`,
    );
  });

  it('unbalanced table applyDelta', function() {
    const editor = this.initialize(Editor, '

');
    editor.applyDelta(
      new Delta()
        .insert('A1\nB1\nC1\n', { table: { row: 1 } })
        .insert('A2\nB2\nC2\n', { table: { row: 2 } })
        .insert('A3\nB3\n', { table: { row: 3 } }),
    );
    expect(this.container).toEqualHTML(
      `

            A1
            B1
            C1

            A2
            B2
            C2

            A3
            B3

`,
    );
  });

  it('existing table applyDelta', function() {
    const editor = this.initialize(
      Editor,
      `

            A1

            B1

`,
    );
    editor.applyDelta(
      new Delta()
        .retain(3)
        .retain(1, { table: { row: 1 } })
        .insert('\n', { table: { row: 2 } }),
    );
    expect(this.container).toEqualHTML(
      `

            A1

            B1

`,
    );
  });
});
<|endoftext|>


<commit_before>(function () {
  'use strict';

  describe('uiGridScroller', function() {
    var element, scrollHandler, gridUtil, uiGridScroller, uiGridScrollerConstants;

    beforeEach(function() {
      element = {
        0: {
          children: {
            0: {}
          }
        },
        on: jasmine.createSpy('on'),
        off: jasmine.createSpy('off')
      };
      scrollHandler = jasmine.createSpy('scrollHandler');

      module('ui.grid.customScrolling');

      inject(function(_uiGridScroller_, _uiGridScrollerConstants_, _gridUtil_) {
        uiGridScroller = _uiGridScroller_;
        uiGridScrollerConstants = _uiGridScrollerConstants_;
        gridUtil = _gridUtil_;
      });

      spyOn(window, 'requestAnimationFrame').and.callFake(angular.noop);
    });

    describe('when gridUtils.isTouchEnabled returns true', function() {
      var preventDefaultSpy;

      beforeEach(function() {
        spyOn(gridUtil, 'isTouchEnabled').and.returnValue(true);
        preventDefaultSpy = jasmine.createSpy('preventDefault');

        element.on.and.callFake(function(eventName, callback) {
          switch (eventName) {
            case 'touchstart':
              callback({
                type: eventName,
                touches: [true]
              });
              break;
            case 'touchmove':
              callback({
                type: eventName,
                touches: [true],
                preventDefault: preventDefaultSpy
              });
              break;
            case 'touchend':
              callback({
                type: eventName,
                touches: [true]
              });
              break;
            case 'touchcancel':
              callback({
                type: eventName,
                touches: [true]
              });
              break;
          }
        });
        uiGridScroller(element, scrollHandler);
      });
      it('should initialize uiGridScroller.initiated to NONE', function() {
        expect(uiGridScroller.initiated).toEqual(uiGridScrollerConstants.scrollType.NONE);
      });
      describe('events', function() {
        describe('on touchstart', function() {
          beforeEach(function() {
            uiGridScroller(element, scrollHandler);
          });
          it('should be initialized', function() {
            expect(element.on).toHaveBeenCalledWith('touchstart', jasmine.any(Function));
          });
          it('should remove the scroll event from the element', function() {
            expect(element.off).toHaveBeenCalledWith('scroll', scrollHandler);
          });
          afterEach(function() {
            element.on.and.callFake(angular.noop);
          });
        });
        describe('on touchmove', function() {
          beforeEach(function() {
            uiGridScroller.initiated = uiGridScrollerConstants.scrollType.TOUCHABLE;
            uiGridScroller(element, scrollHandler);
          });
          it('should be initialized', function() {
            expect(element.on).toHaveBeenCalledWith('touchmove', jasmine.any(Function));
          });
          it('should prevent the default behavior', function() {
            expect(preventDefaultSpy).toHaveBeenCalled();
          });
          it('should call the scrollHandler', function() {
            expect(scrollHandler).toHaveBeenCalled();
          });
        });
        function testEndFunction() {
          describe('when the uiGridScroller has been initiated with a touch event', function() {
            beforeEach(function() {
              uiGridScroller.initiated = uiGridScrollerConstants.scrollType.TOUCHABLE;
              uiGridScroller(element, scrollHandler);
            });
            it('should update the uiGridScroller.initiated value to NONE', function() {
              expect(uiGridScroller.initiated).toEqual(uiGridScrollerConstants.scrollType.NONE);
            });
          });
        }
        describe('on touchend', function() {
          it('should be initialized', function() {
            expect(element.on).toHaveBeenCalledWith('touchend', jasmine.any(Function));
          });
          testEndFunction();
        });
        describe('on touchcancel', function() {
          it('should be initialized', function() {
            expect(element.on).toHaveBeenCalledWith('touchcancel', jasmine.any(Function));
          });
          testEndFunction();
        });
      });
      afterEach(function() {
        element.on.calls.reset();
        element.off.calls.reset();
        gridUtil.isTouchEnabled.calls.reset();
      });
    });

    describe('when gridUtils.isTouchEnabled returns false', function() {
      beforeEach(function() {
        spyOn(gridUtil, 'isTouchEnabled').and.returnValue(false);
        uiGridScroller(element, scrollHandler);
      });
      it('should initialize uiGridScroller.initiated to NONE', function() {
        expect(uiGridScroller.initiated).toEqual(uiGridScrollerConstants.scrollType.NONE);
      });
      describe('events', function() {
        describe('on scroll', function() {
          it('should be initialized', function() {
            expect(element.on).toHaveBeenCalledWith('scroll', scrollHandler);
          });
        });
        describe('on touchstart', function() {
          it('should not be initialized', function() {
            expect(element.on).not.toHaveBeenCalledWith('touchstart', jasmine.any(Function));
          });
        });
        describe('on touchmove', function() {
          it('should not be initialized', function() {
            expect(element.on).not.toHaveBeenCalledWith('touchmove', jasmine.any(Function));
          });
        });
        describe('on touchend', function() {
          it('should not be initialized', function() {
            expect(element.on).not.toHaveBeenCalledWith('touchend', jasmine.any(Function));
          });
        });
        describe('on touchcancel', function() {
          it('should not be initialized', function() {
            expect(element.on).not.toHaveBeenCalledWith('touchcancel', jasmine.any(Function));
          });
        });
      });
      afterEach(function() {
        element.on.calls.reset();
        element.off.calls.reset();
        gridUtil.isTouchEnabled.calls.reset();
      });
    });

    afterEach(function() {
      uiGridScroller = null;
    });
  });
})();
<commit_msg>test(scroller): Updating scroller factory test to skip touchmove.<commit_after>(function () {
  'use strict';

  describe('uiGridScroller', function() {
    var element, scrollHandler, gridUtil, uiGridScroller, uiGridScrollerConstants;

    beforeEach(function() {
      element = {
        0: {
          children: {
            0: {}
          }
        },
        on: jasmine.createSpy('on'),
        off: jasmine.createSpy('off')
      };
      scrollHandler = jasmine.createSpy('scrollHandler');

      module('ui.grid.customScrolling');

      inject(function(_uiGridScroller_, _uiGridScrollerConstants_, _gridUtil_) {
        uiGridScroller = _uiGridScroller_;
        uiGridScrollerConstants = _uiGridScrollerConstants_;
        gridUtil = _gridUtil_;
      });

      spyOn(window, 'requestAnimationFrame').and.callFake(angular.noop);
    });

    describe('when gridUtils.isTouchEnabled returns true', function() {
      var preventDefaultSpy;

      beforeEach(function() {
        spyOn(gridUtil, 'isTouchEnabled').and.returnValue(true);
        preventDefaultSpy = jasmine.createSpy('preventDefault');

        element.on.and.callFake(function(eventName, callback) {
          switch (eventName) {
            case 'touchstart':
              callback({
                type: eventName,
                touches: [true]
              });
              break;
            case 'touchmove':
              callback({
                type: eventName,
                touches: [true],
                preventDefault: preventDefaultSpy
              });
              break;
            case 'touchend':
              callback({
                type: eventName,
                touches: [true]
              });
              break;
            case 'touchcancel':
              callback({
                type: eventName,
                touches: [true]
              });
              break;
          }
        });
        uiGridScroller(element, scrollHandler);
      });
      it('should initialize uiGridScroller.initiated to NONE', function() {
        expect(uiGridScroller.initiated).toEqual(uiGridScrollerConstants.scrollType.NONE);
      });
      describe('events', function() {
        describe('on touchstart', function() {
          beforeEach(function() {
            uiGridScroller(element, scrollHandler);
          });
          it('should be initialized', function() {
            expect(element.on).toHaveBeenCalledWith('touchstart', jasmine.any(Function));
          });
          it('should remove the scroll event from the element', function() {
            expect(element.off).toHaveBeenCalledWith('scroll', scrollHandler);
          });
        });
        xdescribe('on touchmove', function() {
          beforeEach(function() {
            uiGridScroller.initiated = uiGridScrollerConstants.scrollType.TOUCHABLE;
            uiGridScroller(element, scrollHandler);
          });
          it('should be initialized', function() {
            expect(element.on).toHaveBeenCalledWith('touchmove', jasmine.any(Function));
          });
          it('should prevent the default behavior', function() {
            expect(preventDefaultSpy).toHaveBeenCalled();
          });
          it('should call the scrollHandler', function() {
            expect(scrollHandler).toHaveBeenCalled();
          });
        });
        function testEndFunction() {
          xdescribe('when the uiGridScroller has been initiated with a touch event', function() {
            beforeEach(function() {
              uiGridScroller.initiated = uiGridScrollerConstants.scrollType.TOUCHABLE;
              uiGridScroller(element, scrollHandler);
            });
            it('should update the uiGridScroller.initiated value to NONE', function() {
              expect(uiGridScroller.initiated).toEqual(uiGridScrollerConstants.scrollType.NONE);
            });
          });
        }
        describe('on touchend', function() {
          it('should be initialized', function() {
            expect(element.on).toHaveBeenCalledWith('touchend', jasmine.any(Function));
          });
          testEndFunction();
        });
        describe('on touchcancel', function() {
          it('should be initialized', function() {
            expect(element.on).toHaveBeenCalledWith('touchcancel', jasmine.any(Function));
          });
          testEndFunction();
        });
      });
      afterEach(function() {
        element.on.calls.reset();
        element.off.calls.reset();
        gridUtil.isTouchEnabled.calls.reset();
      });
    });

    describe('when gridUtils.isTouchEnabled returns false', function() {
      beforeEach(function() {
        spyOn(gridUtil, 'isTouchEnabled').and.returnValue(false);
        uiGridScroller(element, scrollHandler);
      });
      it('should initialize uiGridScroller.initiated to NONE', function() {
        expect(uiGridScroller.initiated).toEqual(uiGridScrollerConstants.scrollType.NONE);
      });
      describe('events', function() {
        describe('on scroll', function() {
          it('should be initialized', function() {
            expect(element.on).toHaveBeenCalledWith('scroll', scrollHandler);
          });
        });
        describe('on touchstart', function() {
          it('should not be initialized', function() {
            expect(element.on).not.toHaveBeenCalledWith('touchstart', jasmine.any(Function));
          });
        });
        describe('on touchmove', function() {
          it('should not be initialized', function() {
            expect(element.on).not.toHaveBeenCalledWith('touchmove', jasmine.any(Function));
          });
        });
        describe('on touchend', function() {
          it('should not be initialized', function() {
            expect(element.on).not.toHaveBeenCalledWith('touchend', jasmine.any(Function));
          });
        });
        describe('on touchcancel', function() {
          it('should not be initialized', function() {
            expect(element.on).not.toHaveBeenCalledWith('touchcancel', jasmine.any(Function));
          });
        });
      });
      afterEach(function() {
        element.on.calls.reset();
        element.off.calls.reset();
        gridUtil.isTouchEnabled.calls.reset();
      });
    });

    afterEach(function() {
      uiGridScroller = null;
    });
  });
})();
<|endoftext|>


<commit_before>/**
 * @file databaseConfig.js
 * @brief This file contains the configuration to be used for the host
 *        system's mysql server. IFS database and table names are configuable
 *        here.
 **/
module.exports = {
    // database user authentication
    // WARNING: the password here is stored in plain-text. It is recommended
    // that the database user has permissions restricted only to access and
    // modify the database specified below.
    'connection': {
        'host' :                        'localhost',
        'user' :                        'ifs-admin',
        'password' :                    'testing123',
        'connectionLimit':              500
    },
    // database name
    'database':                         'IFS',
};<commit_msg>readded the default values<commit_after>/**
 * @file databaseConfig.js
 * @brief This file contains the configuration to be used for the host
 *        system's mysql server. IFS database and table names are configuable
 *        here.
 **/
module.exports = {
    // database user authentication
    // WARNING: the password here is stored in plain-text. It is recommended
    // that the database user has permissions restricted only to access and
    // modify the database specified below.
    'connection': {
        'host' :                        'localhost',
        'user' :                        'USER',
        'password' :                    'PASSWORD',
        'connectionLimit':              500
    },
    // database name
    'database':                         'IFS',
};
<|endoftext|>


<commit_before>var Tinkerforge = require('tinkerforge');
var LIGHT,
  LIGHT_2,
  BARO,
  HUMI,
  al,
  h,
  b,
  ipcon,
  output_data = [];
/* istanbul ignore next */
function ipcon_connect(HOST, PORT) {
  ipcon.connect(HOST, PORT,
    function(error) {
      console.log(require('./error.js').error(error));
      process.exit();
    }
  );
}
/* istanbul ignore next */
function get_uid(HOST, PORT) {
  ipcon = new Tinkerforge.IPConnection();
  ipcon_connect(HOST, PORT);
  ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
    function() {
      ipcon.enumerate();
    }
  );
  ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
    function(uid, a, b, c, d, deviceIdentifier) {
      switch (deviceIdentifier) {
        case Tinkerforge.BrickletAmbientLight.DEVICE_IDENTIFIER:
          LIGHT = uid;
          break;
        case Tinkerforge.BrickletAmbientLightV2.DEVICE_IDENTIFIER:
          LIGHT_2 = uid;
          break;
        case Tinkerforge.BrickletBarometer.DEVICE_IDENTIFIER:
          BARO = uid;
          break;
        case Tinkerforge.BrickletHumidity.DEVICE_IDENTIFIER:
          HUMI = uid;
          break;
      }
    }
  );
}
/* istanbul ignore next */
function tfinit(HOST, PORT) {
  ipcon = new Tinkerforge.IPConnection();
  if (LIGHT_2) {
    al = new Tinkerforge.BrickletAmbientLightV2(LIGHT, ipcon);
  } else if (LIGHT) {
    al = new Tinkerforge.BrickletAmbientLight(LIGHT, ipcon);
  }
  if (BARO) {
    b = new Tinkerforge.BrickletBarometer(BARO, ipcon);
  }
  if (HUMI) {
    h = new Tinkerforge.BrickletHumidity(HUMI, ipcon);
  }
  if ((al || b || h) !== undefined) {
    ipcon_connect(HOST, PORT);
  } else {
    console.log('ERROR: nothing connected');
    process.exit();
  }
}
/* istanbul ignore next */
function tfdata_get() {
  if (h) {
    h.getHumidity(
      function(humidity) {
        output_data[0] = ('Relative Humidity:\t' + humidity / 10 + ' %RH');
        //console.log('Relative Humidity:\t' + humidity / 10 + ' %RH');
      },
      function(error) {
        output_data[0] = ('Relative Humidity:\t' + require('./error.js').error(error));
      }
    );
  }
  if (b) {
    b.getAirPressure(
      function(air_pressure) {
        output_data[1] = ('Air pressure:\t\t' + air_pressure / 1000 + ' mbar');
      },
      function(error) {
        output_data[1] = ('Air pressure:\t\t' + require('./error.js').error(error));
      }
    );
    b.getChipTemperature(
      function(temperature) {
        output_data[2] = ('Temperature:\t\t' + temperature / 100 + ' \u00B0C');
      },
      function(error) {
        output_data[2] = ('Temperature:\t\t' + require('./error.js').error(error));
      }
    );
  }
  if (al) {
    al.getIlluminance(
      function(illuminance) {
        output_data[3] = ('Illuminance:\t\t' + illuminance / 10 + ' Lux');
      },
      function(error) {
        output_data[3] = ('Illuminance:\t\t' + require('./error.js').error(error));
      }
    );
  }
}
/* istanbul ignore next */
function getTime(date) {
  return ((date.getHours() < 10 ? "0" : "") + date.getHours()) + ":" + ((date.getMinutes() < 10 ? "0" : "") + date.getMinutes()) + ":" + ((date.getSeconds() < 10 ? "0" : "") + date.getSeconds());
}
/* istanbul ignore next */
exports.get = function tfget(HOST, PORT, WAIT, live) {
  get_uid(HOST, PORT);
  if (live === true) {
    setTimeout(function() {
      ipcon.disconnect();
      tfinit(HOST, PORT);
    }, 150);
    setTimeout(function() {
      process.stdin.on('data',
        function() {
          ipcon.disconnect();
          process.exit();
        }
      );
      tfdata_get();
      setInterval(function() {
        tfdata_get();
        console.log('\033[2J');
        output_data.forEach(function(output) {
          console.log(output);
        });
        console.log('\nTime:\t\t\t' + getTime(new Date()));
      }, WAIT);
    }, 200);
  } else {
    setTimeout(function() {
      tfinit(HOST, PORT);
      ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
        function() {
          tfdata_get();
        }
      );
      setTimeout(function() {
        console.log('');
        output_data.forEach(function(output) {
          console.log(output);
        });
        console.log('\nTime:\t\t\t' + getTime(new Date()));
        console.log('');
        ipcon.disconnect();
        process.exit(0);
      }, 10);
    }, 25);
  }
};
<commit_msg>remove some unnecessary lines<commit_after>var Tinkerforge = require('tinkerforge'), LIGHT, LIGHT_2, BARO, HUMI, al, h, b, ipcon, output_data = [];
/* istanbul ignore next */
function ipcon_connect(HOST, PORT) {
  ipcon.connect(HOST, PORT,
    function(error) {
      console.log(require('./error.js').error(error));
      process.exit();
    }
  );
}
/* istanbul ignore next */
function get_uid(HOST, PORT) {
  ipcon = new Tinkerforge.IPConnection();
  ipcon_connect(HOST, PORT);
  ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
    function() {
      ipcon.enumerate();
    }
  );
  ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
    function(uid, a, b, c, d, deviceIdentifier) {
      switch (deviceIdentifier) {
        case Tinkerforge.BrickletAmbientLight.DEVICE_IDENTIFIER:
          LIGHT = uid;
          break;
        case Tinkerforge.BrickletAmbientLightV2.DEVICE_IDENTIFIER:
          LIGHT_2 = uid;
          break;
        case Tinkerforge.BrickletBarometer.DEVICE_IDENTIFIER:
          BARO = uid;
          break;
        case Tinkerforge.BrickletHumidity.DEVICE_IDENTIFIER:
          HUMI = uid;
          break;
      }
    }
  );
}
/* istanbul ignore next */
function tfinit(HOST, PORT) {
  ipcon = new Tinkerforge.IPConnection();
  if (LIGHT_2) {
    al = new Tinkerforge.BrickletAmbientLightV2(LIGHT, ipcon);
  } else if (LIGHT) {
    al = new Tinkerforge.BrickletAmbientLight(LIGHT, ipcon);
  }
  if (BARO) {
    b = new Tinkerforge.BrickletBarometer(BARO, ipcon);
  }
  if (HUMI) {
    h = new Tinkerforge.BrickletHumidity(HUMI, ipcon);
  }
  if ((al || b || h) !== undefined) {
    ipcon_connect(HOST, PORT);
  } else {
    console.log('ERROR: nothing connected');
    process.exit();
  }
}
/* istanbul ignore next */
function tfdata_get() {
  if (h) {
    h.getHumidity(
      function(humidity) {
        output_data[0] = ('Relative Humidity:\t' + humidity / 10 + ' %RH');
      },
      function(error) {
        output_data[0] = ('Relative Humidity:\t' + require('./error.js').error(error));
      }
    );
  }
  if (b) {
    b.getAirPressure(
      function(air_pressure) {
        output_data[1] = ('Air pressure:\t\t' + air_pressure / 1000 + ' mbar');
      },
      function(error) {
        output_data[1] = ('Air pressure:\t\t' + require('./error.js').error(error));
      }
    );
    b.getChipTemperature(
      function(temperature) {
        output_data[2] = ('Temperature:\t\t' + temperature / 100 + ' \u00B0C');
      },
      function(error) {
        output_data[2] = ('Temperature:\t\t' + require('./error.js').error(error));
      }
    );
  }
  if (al) {
    al.getIlluminance(
      function(illuminance) {
        output_data[3] = ('Illuminance:\t\t' + illuminance / 10 + ' Lux');
      },
      function(error) {
        output_data[3] = ('Illuminance:\t\t' + require('./error.js').error(error));
      }
    );
  }
}
/* istanbul ignore next */
function getTime(date) {
  return ((date.getHours() < 10 ? "0" : "") + date.getHours()) + ":" + ((date.getMinutes() < 10 ? "0" : "") + date.getMinutes()) + ":" + ((date.getSeconds() < 10 ? "0" : "") + date.getSeconds());
}
/* istanbul ignore next */
exports.get = function tfget(HOST, PORT, WAIT, live) {
  get_uid(HOST, PORT);
  if (live === true) {
    setTimeout(function() {
      ipcon.disconnect();
      tfinit(HOST, PORT);
    }, 150);
    setTimeout(function() {
      process.stdin.on('data',
        function() {
          ipcon.disconnect();
          process.exit();
        }
      );
      tfdata_get();
      setInterval(function() {
        tfdata_get();
        console.log('\033[2J');
        output_data.forEach(function(output) {
          console.log(output);
        });
        console.log('\nTime:\t\t\t' + getTime(new Date()));
      }, WAIT);
    }, 200);
  } else {
    setTimeout(function() {
      tfinit(HOST, PORT);
      ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
        function() {
          tfdata_get();
        }
      );
      setTimeout(function() {
        console.log('');
        output_data.forEach(function(output) {
          console.log(output);
        });
        console.log('\nTime:\t\t\t' + getTime(new Date()));
        console.log('');
        ipcon.disconnect();
        process.exit(0);
      }, 10);
    }, 25);
  }
};
<|endoftext|>