<commit_before>if (typeof(Joomla) == 'undefined')
{
	Joomla = {};
}
Joomla.submitbutton = function(pressbutton)
{
	return submitbutton(pressbutton);
}
Joomla.submitform = function(pressbutton)
{
	return submitform(pressbutton);
}<commit_msg>[TPL_HUBBASICADMIN] Fix for script that can cause infinite loops under certain circumstances<commit_after>if (typeof(Joomla) == 'undefined')
{
	Joomla = {};

	Joomla.submitbutton = function(pressbutton)
	{
		return submitbutton(pressbutton);
	}
	Joomla.submitform = function(pressbutton)
	{
		return submitform(pressbutton);
	}
}<|endoftext|>


<commit_before>module.exports = [
    {
        test: /\.ts(x?)$/,
        loader: 'ts-loader'
    }, {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
    }, {
        test: /\.scss$/,
        loader: 'style!css!sass'
    }, {
        test: /\.html$/,
        exclude: /node_modules/,
        loader: 'raw'
    }, {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000&mimetype=application/font-woff'
    }, {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader'
    }, {
        test: '\.jpg$',
        exclude: /node_modules/,
        loader: 'file'
    }, {
        test: '\.png$',
        exclude: /node_modules/,
        loader: 'url'
    }
];
<commit_msg>Fix typos<commit_after>module.exports = [
    {
        test: /\.ts(x?)$/,
        loader: 'ts-loader'
    }, {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
    }, {
        test: /\.scss$/,
        loader: 'style-loader!css-loader!sass-loader'
    }, {
        test: /\.html$/,
        exclude: /node_modules/,
        loader: 'raw-loader'
    }, {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000&mimetype=application/font-woff'
    }, {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader'
    }, {
        test: /\.jpg$/,
        exclude: /node_modules/,
        loader: 'file-loader'
    }, {
        test: /\.png$/,
        exclude: /node_modules/,
        loader: 'url-loader'
    }
];
<|endoftext|>


<commit_before>//= require_tree ./app

$(function(){
  app.createViewGetters();
  });

<commit_msg>updates<commit_after>//= require ./app/app
//= require_tree ./app

$(function(){
  app.createViewGetters();
  });

<|endoftext|>


<commit_before>Handlebars.registerHelper('department_code', function (id) {
  return new Handlebars.SafeString(Yacs.models.departments.store.id[id].code);
});

Handlebars.registerHelper('course_credits', function (c) {
  var outString = '';
  // render "credit(s)" properly
  if (c.min_credits != c.max_credits) {
    outString = c.min_credits + '-' + c.max_credits + ' credits';
  }
  else {
    outString = c.max_credits + ' credit' + (c.max_credits == 1 ? '' : 's');
  }
  return new Handlebars.SafeString(outString);
});

Handlebars.registerHelper('join', function (arr) {
  return new Handlebars.SafeString(arr.join(', '));
});

Handlebars.registerHelper('seats_available', function (s) {
  var remaining = s.seats - s.seats_taken;
  return new Handlebars.SafeString(remaining);
});

Handlebars.registerHelper('closed_status', function (s) {
  return new Handlebars.SafeString(s.seats > 0 && s.seats_taken >= s.seats ? 'closed' : '');
});

Handlebars.registerHelper('day_name', function (n) {
  return new Handlebars.SafeString(['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][n]);
});

Handlebars.registerHelper('time_range', function (start, end) {
  return new Handlebars.SafeString([start, end].map(function (time) {
    var hour = Math.floor(time / 100);
    var ampm = hour > 12 ? 'p' : 'a';
    hour = hour > 12 ? hour - 12 : hour == 0 ? 12 : hour;
    var minutes = time % 100;
    minutes = minutes > 9 ? minutes : minutes == 0 ? '' : '0' + minutes;
    return hour + (minutes ? ':' + minutes : '') + ampm;
  }).join('-'));
});
<commit_msg>Added new helper to evaluate section for conflicts<commit_after>Handlebars.registerHelper('department_code', function (id) {
  return new Handlebars.SafeString(Yacs.models.departments.store.id[id].code);
});

Handlebars.registerHelper('course_credits', function (c) {
  var outString = '';
  // render "credit(s)" properly
  if (c.min_credits != c.max_credits) {
    outString = c.min_credits + '-' + c.max_credits + ' credits';
  }
  else {
    outString = c.max_credits + ' credit' + (c.max_credits == 1 ? '' : 's');
  }
  return new Handlebars.SafeString(outString);
});

Handlebars.registerHelper('join', function (arr) {
  return new Handlebars.SafeString(arr.join(', '));
});

Handlebars.registerHelper('seats_available', function (s) {
  var remaining = s.seats - s.seats_taken;
  return new Handlebars.SafeString(remaining);
});

Handlebars.registerHelper('closed_status', function (s) {
  return new Handlebars.SafeString(s.seats > 0 && s.seats_taken >= s.seats ? 'closed' : '');
});

/* Determine whether a section's conflicts list contains any section ids in common with
 * currently selections. Set some variables on this (the current section object)
 * for subsequent Handlebars calls to use.
 * The advantage of this method is that the expensive comparison of section
 * conflicts and selected section ids is only performed once per section.
 */
Handlebars.registerHelper('evaluateConflict', function(block) {
  hasConflict = true; //TODO actually involve section.conflicts
  if(hasConflict) {
    this.conflictClass = 'conflicts';
    this.hasConflict = true;
  }
  else {
    this.conflictClass = '';
    this.hasConflict = false;
  }
  return block.fn(this);
});

Handlebars.registerHelper('day_name', function (n) {
  return new Handlebars.SafeString(['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][n]);
});

Handlebars.registerHelper('time_range', function (start, end) {
  return new Handlebars.SafeString([start, end].map(function (time) {
    var hour = Math.floor(time / 100);
    var ampm = hour > 12 ? 'p' : 'a';
    hour = hour > 12 ? hour - 12 : hour == 0 ? 12 : hour;
    var minutes = time % 100;
    minutes = minutes > 9 ? minutes : minutes == 0 ? '' : '0' + minutes;
    return hour + (minutes ? ':' + minutes : '') + ampm;
  }).join('-'));
});
<|endoftext|>


<commit_before>/**
  A data model representing a link to share a post on a 3rd party site,
  like Twitter, Facebook, and Google+.

  @class ShareLink
  @extends Discourse.Model
  @namespace Discourse
  @module Discourse
**/
Discourse.ShareLink = Discourse.Model.extend({

  href: function() {
    return Discourse.ShareLink.urlFor(this.get('target'), this.get('link'), this.get('topicTitle'));
  }.property('target', 'link', 'topicTitle'),

  title: Discourse.computed.i18n('target', 'share.%@'),

  iconClass: function() {
    return Discourse.ShareLink.iconClasses[this.get('target')];
  }.property('target'),

  openInPopup: function() {
    return( this.get('target') !== 'email' );
  }.property('target')

});

Discourse.ShareLink.reopenClass({

  supportedTargets: ['twitter', 'facebook', 'google+', 'email'],

  urlFor: function(target,link,title) {
    switch(target) {
      case 'twitter':
        return this.twitterUrl(link,title);
      case 'facebook':
        return this.facebookUrl(link,title);
      case 'google+':
        return this.googlePlusUrl(link);
      case 'email':
        return this.emailUrl(link,title);
    }
  },

  twitterUrl: function(link, title) {
    return ("http://twitter.com/intent/tweet?url=" + encodeURIComponent(link) + "&text=" + encodeURIComponent(title) );
  },

  facebookUrl: function(link, title) {
    return ("http://www.facebook.com/sharer.php?u=" + encodeURIComponent(link) + '&t=' + encodeURIComponent(title));
  },

  googlePlusUrl: function(link) {
    return ("https://plus.google.com/share?url=" + encodeURIComponent(link));
  },

  emailUrl: function(link, title) {
    return ("mailto:?to=&subject=" + encodeURIComponent('[' + Discourse.SiteSettings.title + '] ' + title) + "&body=" + encodeURIComponent(link));
  },

  iconClasses: {
    twitter: 'fa-twitter',
    facebook: 'fa-facebook-square',
    'google+': 'fa-google-plus',
    email: 'fa-envelope'
  },

  popupHeights: {
    twitter: 265,
    facebook: 315,
    'google+': 600
  },

  popupHeight: function(target) {
    return (this.popupHeights[target] || 315);
  }
});
<commit_msg>Make Discourse.ShareLink easy for plugins<commit_after>/**
  A data model representing a link to share a post on a 3rd party site,
  like Twitter, Facebook, and Google+.

  @class ShareLink
  @extends Discourse.Model
  @namespace Discourse
  @module Discourse
**/
Discourse.ShareLink = Discourse.Model.extend({

  href: function() {
    return Discourse.ShareLink.urlFor[this.get('target')](this.get('link'), this.get('topicTitle'));
  }.property('target', 'link', 'topicTitle'),

  title: Discourse.computed.i18n('target', 'share.%@'),

  iconClass: function() {
    return Discourse.ShareLink.iconClasses[this.get('target')];
  }.property('target'),

  openInPopup: function() {
    return( Discourse.ShareLink.shouldOpenInPopup[this.get('target')] );
  }.property('target')

});

Discourse.ShareLink.reopenClass({
  supportedTargets: [],
  urlFor: {},
  iconClasses: {},
  popupHeights: {},
  shouldOpenInPopup: {},

  addTarget: function(id, object) {
    var self = this;
    self.supportedTargets.push(id);
    self.urlFor[id] = object.generateUrl;
    self.iconClasses[id] = object.iconClass;
    self.popupHeights[id] = object.popupHeight || 315;
    self.shouldOpenInPopup[id] = object.shouldOpenInPopup;
  },

  popupHeight: function(target) {
    return (this.popupHeights[target] || 315);
  }
});

(function() {
  Discourse.ShareLink.addTarget('twitter', {
    iconClass: 'fa-twitter',
    generateUrl: function(link, title) {
      return ("http://twitter.com/intent/tweet?url=" + encodeURIComponent(link) + "&text=" + encodeURIComponent(title) );
    },
    shouldOpenInPopup: true,
    popupHeight: 265
  });

  Discourse.ShareLink.addTarget('facebook', {
    iconClass: 'fa-facebook-square',
    generateUrl: function(link, title) {
      return ("http://www.facebook.com/sharer.php?u=" + encodeURIComponent(link) + '&t=' + encodeURIComponent(title));
    },
    shouldOpenInPopup: true,
    popupHeight: 315
  });

  Discourse.ShareLink.addTarget('google+', {
    iconClass: 'fa-google-plus',
    generateUrl: function(link) {
      return ("https://plus.google.com/share?url=" + encodeURIComponent(link));
    },
    shouldOpenInPopup: true,
    popupHeight: 600
  });

  Discourse.ShareLink.addTarget('email', {
    iconClass: 'fa-envelope',
    generateUrl: function(link, title) {
      return ("mailto:?to=&subject=" + encodeURIComponent('[' + Discourse.SiteSettings.title + '] ' + title) + "&body=" + encodeURIComponent(link));
    },
    shouldOpenInPopup: false
  });
})();
<|endoftext|>


<commit_before>$(document).on('submit', '.f-newsletter-subscriptions-form__form', function (e) {
  e.preventDefault()

  const $form = $(this)

  if ($form.hasClass('f-newsletter-subscriptions-form--submitting')) return

  const $wrap = $form.closest('.f-newsletter-subscriptions-form')
  $form.addClass('f-newsletter-subscriptions-form-submitting')

  $.post($form.attr('action'), $form.serialize()).always((response) => {
    $wrap.replaceWith(response)
  })
})
<commit_msg>add event trigger to newsletter_subscriptions/form js<commit_after>$(document).on('submit', '.f-newsletter-subscriptions-form__form', function (e) {
  e.preventDefault()

  const $form = $(this)

  if ($form.hasClass('f-newsletter-subscriptions-form--submitting')) return

  const $wrap = $form.closest('.f-newsletter-subscriptions-form')
  $form.addClass('f-newsletter-subscriptions-form-submitting')

  $.post($form.attr('action'), $form.serialize()).always((response) => {
    const $response = $(response)
    $wrap.replaceWith($response)

    $response.trigger('folio:submitted')

    if ($response.find('.f-newsletter-subscriptions-form__message').length) {
      $response.trigger('folio:success')
    } else {
      $response.trigger('folio:failure')
    }
  })
})
<|endoftext|>


<commit_before>var editorBaseModelMixin = {

    defaults_editorBaseModel: {
        value: null,
        hintText: null,
        errorText: null,
        warningText: null,
        labelFloating: false
    },

    initialize_editorBaseModel: function(){
       this.eventManager = new EventManager();
        this.isInited = true;
    },

    transformValue: function (value) {
        return value;
    },

    _setValue: function(value, options) {
        value = this.transformValue(value);
        var
            oldValue = this.get('value'),
            message = {
                oldValue: oldValue,
                newValue: value
            };

        if (value === oldValue) {
            return;
        }

        if(this.isInited){
            if (this.eventManager.trigger('onValueChanging', message)) {
                ContainerModel.prototype.set.call(this, 'value', value, options || {});
                this.trigger('onValueChanged', message);
            }
        }else{
            ContainerModel.prototype.set.call(this, 'value', value, options || {});
        }

    },

    set: function (key, value, options) {
        var attributes, options;
        if (key === null) {
            return this;
        }

        if (typeof key === 'object') {
            attributes = key;
            options = value;
        } else {
            (attributes = {})[key] = value;
        }

        options = options || {};

        if ('value' in attributes) {
            this._setValue(attributes.value, options);
            delete attributes.value;
        }

        var hasAttributes = false;

        for (var i in attributes) {
            hasAttributes = true;
            break;
        }

        if (hasAttributes) {
            return ContainerModel.prototype.set.call(this, attributes, options);
        }

        return false;
    },

    getValue: function () {
        return this.get('value');
    },

    isSetValue: function (value) {
        return value !== null && typeof value !== 'undefined' && value !== '';
    },

    onValueChanging: function (handler) {
        this.eventManager.on('onValueChanging', handler);
    },

    onValueChanged: function (handler) {
        this.on('onValueChanged', handler);
    }
};
<commit_msg>UI-2316: Не исчезает индикатор загрузки после редактирования адреса дома#resolve<commit_after>var editorBaseModelMixin = {

    defaults_editorBaseModel: {
        value: null,
        hintText: null,
        errorText: null,
        warningText: null,
        labelFloating: false
    },

    initialize_editorBaseModel: function(){
       this.eventManager = new EventManager();
        this.isInited = true;
    },

    transformValue: function (value) {
        return value;
    },

    _applyDefaultValue: function (value) {
        var defaults = _.result(this, 'defaults');
        return typeof value === 'undefined' ? defaults['value'] : value;
    },

    _setValue: function(value, options) {
        value = this.transformValue(value);

        value = this._applyDefaultValue(value);

        var
            oldValue = this.get('value'),
            message = {
                oldValue: oldValue,
                newValue: value
            };

        if (value === oldValue) {
            return;
        }

        if(this.isInited){
            if (this.eventManager.trigger('onValueChanging', message)) {
                ContainerModel.prototype.set.call(this, 'value', value, options || {});
                this.trigger('onValueChanged', message);
            }
        }else{
            ContainerModel.prototype.set.call(this, 'value', value, options || {});
        }

    },

    set: function (key, value, options) {
        var attributes, options;
        if (key === null) {
            return this;
        }

        if (typeof key === 'object') {
            attributes = key;
            options = value;
        } else {
            (attributes = {})[key] = value;
        }

        options = options || {};

        if ('value' in attributes) {
            this._setValue(attributes.value, options);
            delete attributes.value;
        }

        var hasAttributes = false;

        for (var i in attributes) {
            hasAttributes = true;
            break;
        }

        if (hasAttributes) {
            return ContainerModel.prototype.set.call(this, attributes, options);
        }

        return false;
    },

    getValue: function () {
        return this.get('value');
    },

    isSetValue: function (value) {
        return value !== null && typeof value !== 'undefined' && value !== '';
    },

    onValueChanging: function (handler) {
        this.eventManager.on('onValueChanging', handler);
    },

    onValueChanged: function (handler) {
        this.on('onValueChanged', handler);
    }
};
<|endoftext|>


<commit_before>import PIXI from 'pixi.js';
import CraftyBlock from './CraftyBlock.js';
import CraftyBlockSpec from './CraftyBlockSpec.js';

let IS_DRAGGING = false;
let MOUSEOVER_BLOCK = null;

var stage;

class CraftyBlockAnimator {
    constructor() {
    }

    makeInteractive(block) {
        block.interactive = true;
        block.hitArea = block.getChildAt(0).getBounds().clone();
        //console.log(`DEBUG:::interactivity enabled for {${this.blockInfo.name}}`);

        //  enable drag and drop for non-parameter blocks, enable mouse over check for parameter blocks
        if (block.blockInfo.type != CraftyBlock.PARAMETER) {
            console.log(`helloo from ${block.blockInfo.name}`);
            block
                .on('mousedown', this.onDragStart)
                .on('touchstart', this.onDragStart)
                .on('mouseup', this.onDragEnd)
                .on('mouseupoutside', this.onDragEnd)
                .on('touchend', this.onDragEnd)
                .on('touchendoutside', this.onDragEnd)
                .on('mousemove', this.onDragMove)
                .on('touchmove', this.onDragMove);
        } else {
            block
                .on('mousedown', this.onParameterStart)
                .on('touchstart', this.onParameterStart)
                .on('mouseup', this.onParameterEnd)
                .on('mouseupoutside', this.onParameterEnd)
                .on('touchend', this.onParameterEnd)
                .on('touchendoutside', this.onParameterEnd)
                .on('mousemove', this.onParameterMove)
                .on('touchmove', this.onParameterMove);
        }
        block
            .on('clickonce', this.onClick)
    }
    onClick() {
        console.log("Clicked!");
        showSetting(this);
    }

    onDragStart(event) {
        stage = this._getStage();
        let relativeMousePosition = event.data.getLocalPosition(this);
        if (this.hitArea.contains(relativeMousePosition.x, relativeMousePosition.y)) {
            //console.log("DEBUG::: drag started by \"" + this.blockInfo.name + "\"");

            //  set toggle that becomes true the moment when drag starts
            this.startedDragging = false;

            //  if parent is sidebar, create copy
            if (this.parent.id == "sidebar") {
                let blockCopy = new CraftyBlock(this.blockInfo);
                this.sidebarRect = this.parent.getChildAt(0).getBounds().clone();
                blockCopy.position = this.position.clone();
                this.parent.addChildAt(blockCopy,1);
                this.renderFrom(0);
            }

            //  save original position and distance from original to mouse position
            let mouseStartPosition = event.data.getLocalPosition(this.parent);
            this.diff = new PIXI.Point(mouseStartPosition.x - this.position.x, mouseStartPosition.y - this.position.y);
            this.originalPosition = new PIXI.Point(this.position.x,this.position.y);

            this.alpha = 0.6;
            this.dragging = true;
            IS_DRAGGING = true;

            $('.delete_btn').remove();
        }
    }

    onDragEnd(event) {
        //  if block had been clicked, check drag or click, and execute by case
        if (this.dragging) {
            // case: dragged

            //  if parent is sidebar, either add new Block to stage or remove depending on mouse location
            if (this.parent.id == "sidebar") {
                let relativeMousePosition = event.data.getLocalPosition(this.parent);
                if (this.sidebarRect.contains(relativeMousePosition.x, relativeMousePosition.y)) {
                    this.parent.removeChild(this);
                } else {
                    this.addToStage();
                }
            }

            if (this.startedDragging) {
                //console.log("DEBUG::: drag ended by \"" + this.blockInfo.name + "\"");

                //  if there is parameter block below, attach
                if (MOUSEOVER_BLOCK) {
                    this.attachTo(MOUSEOVER_BLOCK);
                    MOUSEOVER_BLOCK = null;
                }

                //  render update the taken out block
                if (this.originalBlock) {
                    this.originalBlock.update();
                }

                checkBlockInfoList();
            }
            // case: clicked
            else {
                this.emit('clickonce');
                //  export block
                //  call canvasClicked function
                // canvasClicked(this.stringify());
            }

            this.alpha = 1;
            this.dragging = false;
            IS_DRAGGING = false;
        }
    }

    onDragMove(event) {
        //console.log("DEBUG::: drag moving by \"" + this.blockInfo.name + "\"");

        if (this.dragging)
        {
            //  re-position block to relative mouse position
            let newPosition = event.data.getLocalPosition(this.parent);
            this.position.x = newPosition.x - this.diff.x;
            this.position.y = newPosition.y - this.diff.y;

            //  trigger when first drag after select
            if (!this.startedDragging) {
                this.startedDragging = true;

                //  if block has parent block, detach from parent block and set originalBlock for later update()
                if (this.parent.hasOwnProperty('blockInfo')) {
                    this.originalBlock = this.detachFromParentBlock();
                } else {
                    this.originalBlock = null;
                }
            }
        }
    }

    // "mousemove" event handler for parameter blocks
    onParameterMove(event) {
        //  if mouse position is inside hit area, then set stage.target to this
        if (IS_DRAGGING) {
            let relativeMousePosition = event.data.getLocalPosition(this);
            if (this.hitArea.contains(relativeMousePosition.x, relativeMousePosition.y)) {
                //console.log(`DEBUG::: parameter moving by {${this.blockInfo.name}}`);

                this.getChildAt(0).tint = 0xDDDDDD;
                MOUSEOVER_BLOCK = this;
            } else {
                if (this == MOUSEOVER_BLOCK) {
                    MOUSEOVER_BLOCK = null;
                    this.getChildAt(0).tint = 0xFFFFFF;
                }
            }
        }
    }

    onParameterStart(event) {
        this.clicked = true;
    }

    onParameterEnd(event) {
        if (this.clicked) {
            let constantName = prompt("Type in your constant!");
            if (constantName) {
                let constantBlockInfo = new CraftyBlockSpec(constantName, CraftyBlock.CONSTANT);
                let constantBlock = new CraftyBlock(constantBlockInfo);
                constantBlock.attachTo(this);
            }
            this.clicked = false;
            checkBlockInfoList();
        }
    }
}

function checkBlockInfoList() {
  var numberOfBlocks = stage.children.length - 2;

  var i;
  var BlockInfoList = new Array("");

  for (i = 1; i <= numberOfBlocks; i++) {
    BlockInfoList[i-1] = stage.getChildAt(i+1).stringify();
  }

  //  call canvasChanged function
  canvasChanged(BlockInfoList);
  // getBlockInfoList(BlockInfoList);
}

export default new CraftyBlockAnimator();
<commit_msg>Fix debug log error<commit_after>import PIXI from 'pixi.js';
import CraftyBlock from './CraftyBlock.js';
import CraftyBlockSpec from './CraftyBlockSpec.js';

let IS_DRAGGING = false;
let MOUSEOVER_BLOCK = null;

var stage;

class CraftyBlockAnimator {
    constructor() {
    }

    makeInteractive(block) {
        block.interactive = true;
        block.hitArea = block.getChildAt(0).getBounds().clone();
        console.log(`DEBUG:::interactivity enabled for {${block.blockInfo.name}}`);

        //  enable drag and drop for non-parameter blocks, enable mouse over check for parameter blocks
        if (block.blockInfo.type != CraftyBlock.PARAMETER) {
            console.log(`helloo from ${block.blockInfo.name}`);
            block
                .on('mousedown', this.onDragStart)
                .on('touchstart', this.onDragStart)
                .on('mouseup', this.onDragEnd)
                .on('mouseupoutside', this.onDragEnd)
                .on('touchend', this.onDragEnd)
                .on('touchendoutside', this.onDragEnd)
                .on('mousemove', this.onDragMove)
                .on('touchmove', this.onDragMove);
        } else {
            block
                .on('mousedown', this.onParameterStart)
                .on('touchstart', this.onParameterStart)
                .on('mouseup', this.onParameterEnd)
                .on('mouseupoutside', this.onParameterEnd)
                .on('touchend', this.onParameterEnd)
                .on('touchendoutside', this.onParameterEnd)
                .on('mousemove', this.onParameterMove)
                .on('touchmove', this.onParameterMove);
        }
        block
            .on('clickonce', this.onClick)
    }
    onClick() {
        console.log("Clicked!");
        showSetting(this);
    }

    onDragStart(event) {
        stage = this._getStage();
        let relativeMousePosition = event.data.getLocalPosition(this);
        if (this.hitArea.contains(relativeMousePosition.x, relativeMousePosition.y)) {
            //console.log("DEBUG::: drag started by \"" + this.blockInfo.name + "\"");

            //  set toggle that becomes true the moment when drag starts
            this.startedDragging = false;

            //  if parent is sidebar, create copy
            if (this.parent.id == "sidebar") {
                let blockCopy = new CraftyBlock(this.blockInfo);
                this.sidebarRect = this.parent.getChildAt(0).getBounds().clone();
                blockCopy.position = this.position.clone();
                this.parent.addChildAt(blockCopy,1);
                this.renderFrom(0);
            }

            //  save original position and distance from original to mouse position
            let mouseStartPosition = event.data.getLocalPosition(this.parent);
            this.diff = new PIXI.Point(mouseStartPosition.x - this.position.x, mouseStartPosition.y - this.position.y);
            this.originalPosition = new PIXI.Point(this.position.x,this.position.y);

            this.alpha = 0.6;
            this.dragging = true;
            IS_DRAGGING = true;

            $('.delete_btn').remove();
        }
    }

    onDragEnd(event) {
        //  if block had been clicked, check drag or click, and execute by case
        if (this.dragging) {
            // case: dragged

            //  if parent is sidebar, either add new Block to stage or remove depending on mouse location
            if (this.parent.id == "sidebar") {
                let relativeMousePosition = event.data.getLocalPosition(this.parent);
                if (this.sidebarRect.contains(relativeMousePosition.x, relativeMousePosition.y)) {
                    this.parent.removeChild(this);
                } else {
                    this.addToStage();
                }
            }

            if (this.startedDragging) {
                //console.log("DEBUG::: drag ended by \"" + this.blockInfo.name + "\"");

                //  if there is parameter block below, attach
                if (MOUSEOVER_BLOCK) {
                    this.attachTo(MOUSEOVER_BLOCK);
                    MOUSEOVER_BLOCK = null;
                }

                //  render update the taken out block
                if (this.originalBlock) {
                    this.originalBlock.update();
                }

                checkBlockInfoList();
            }
            // case: clicked
            else {
                this.emit('clickonce');
                //  export block
                //  call canvasClicked function
                // canvasClicked(this.stringify());
            }

            this.alpha = 1;
            this.dragging = false;
            IS_DRAGGING = false;
        }
    }

    onDragMove(event) {
        //console.log("DEBUG::: drag moving by \"" + this.blockInfo.name + "\"");

        if (this.dragging)
        {
            //  re-position block to relative mouse position
            let newPosition = event.data.getLocalPosition(this.parent);
            this.position.x = newPosition.x - this.diff.x;
            this.position.y = newPosition.y - this.diff.y;

            //  trigger when first drag after select
            if (!this.startedDragging) {
                this.startedDragging = true;

                //  if block has parent block, detach from parent block and set originalBlock for later update()
                if (this.parent.hasOwnProperty('blockInfo')) {
                    this.originalBlock = this.detachFromParentBlock();
                } else {
                    this.originalBlock = null;
                }
            }
        }
    }

    // "mousemove" event handler for parameter blocks
    onParameterMove(event) {
        //  if mouse position is inside hit area, then set stage.target to this
        if (IS_DRAGGING) {
            let relativeMousePosition = event.data.getLocalPosition(this);
            if (this.hitArea.contains(relativeMousePosition.x, relativeMousePosition.y)) {
                //console.log(`DEBUG::: parameter moving by {${this.blockInfo.name}}`);

                this.getChildAt(0).tint = 0xDDDDDD;
                MOUSEOVER_BLOCK = this;
            } else {
                if (this == MOUSEOVER_BLOCK) {
                    MOUSEOVER_BLOCK = null;
                    this.getChildAt(0).tint = 0xFFFFFF;
                }
            }
        }
    }

    onParameterStart(event) {
        this.clicked = true;
    }

    onParameterEnd(event) {
        if (this.clicked) {
            let constantName = prompt("Type in your constant!");
            if (constantName) {
                let constantBlockInfo = new CraftyBlockSpec(constantName, CraftyBlock.CONSTANT);
                let constantBlock = new CraftyBlock(constantBlockInfo);
                constantBlock.attachTo(this);
            }
            this.clicked = false;
            checkBlockInfoList();
        }
    }
}

function checkBlockInfoList() {
  var numberOfBlocks = stage.children.length - 2;

  var i;
  var BlockInfoList = new Array("");

  for (i = 1; i <= numberOfBlocks; i++) {
    BlockInfoList[i-1] = stage.getChildAt(i+1).stringify();
  }

  //  call canvasChanged function
  canvasChanged(BlockInfoList);
  // getBlockInfoList(BlockInfoList);
}

export default new CraftyBlockAnimator();
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const placeholderUrl = chrome.extension.getURL('about-flash.html')
const adobeRegex = new RegExp('//(get\\.adobe\\.com/([a-z_-]+/)*flashplayer|www\\.macromedia\\.com/go/getflash|www\\.adobe\\.com/go/getflash)', 'i')

function isAdobeLink (href) {
  if (typeof href !== 'string') {
    return false
  }
  return adobeRegex.test(href)
}

// Open flash links in the same tab so we can intercept them correctly
if (chrome.contentSettings.flashActive != 'allow' &&
    chrome.contentSettings.flashEnabled == 'allow') {
  (function () {
    function replaceAdobeLinks () {
      Array.from(document.querySelectorAll('a[target="_blank"]')).forEach((elem) => {
        const href = elem.getAttribute('href')
        if (isAdobeLink(href)) {
          elem.setAttribute('target', '')
        }
      })
    }
    setTimeout(() => {
      var observer = new window.MutationObserver(function (mutations) {
        replaceAdobeLinks()
      })
      replaceAdobeLinks()
      observer.observe(document.documentElement, {
        childList: true,
        subtree: true
      })
    }, 1000)
  })()
}

/**
 * Whether a src is a .swf file.
 * If so, returns the origin of the file. Otherwise returns false.
 * @param {string} src
 * @return {boolean|string}
 */
function isSWF (src) {
  if (!src) {
    return false
  }
  let a = document.createElement('a')
  a.href = src
  if (a.pathname && a.pathname.toLowerCase().endsWith('.swf')) {
    return a.origin
  } else {
    return false
  }
}

/**
 * Gets all Flash object descendants of an element.
 * Reference:
 * https://helpx.adobe.com/flash/kb/flash-object-embed-tag-attributes.html
 * @param {Element} elem - HTML element to search
 * @return {Array.<Element>}
 */
function getFlashObjects (elem) {
  let results = [] // Array.<{element: Element, origin: string}>
  Array.from(elem.getElementsByTagName('embed')).forEach((el) => {
    let origin = isSWF(el.getAttribute('src'))
    if (origin) {
      results.push({
        element: el,
        origin
      })
    }
  })

  Array.from(elem.getElementsByTagName('object')).forEach((el) => {
    // Skip objects that are contained in other flash objects
    /*
    for (let i = 0; i < results.length; i++) {
      if (results[i].element.contains(el)) {
        return
      }
    }
    */
    let origin = isSWF(el.getAttribute('data'))
    if (origin) {
      results.push({
        element: el,
        origin
      })
    } else {
      // See example at
      // https://helpx.adobe.com/animate/kb/object-tag-syntax.html
      Array.from(el.getElementsByTagName('param')).forEach((param) => {
        let name = param.getAttribute('name')
        let origin = isSWF(param.getAttribute('value'))
        if (name && ['movie', 'src'].includes(name.toLowerCase()) &&
            origin) {
          results.push({
            element: el,
            origin
          })
        }
      })
    }
  })

  // Some sites have custom Flash placeholders which we should replace with our
  // own.
  Array.from(elem.querySelectorAll('a > img')).forEach((el) => {
    let href = el.parentNode ? el.parentNode.href : null
    if (isAdobeLink(href)) {
      results.push({
        element: el
      })
    }
  })

  return results
}

/**
 * Inserts Flash placeholders.
 * @param {Element} elem - HTML element to search
 */
function insertFlashPlaceholders (elem) {
  const minWidth = 200
  const minHeight = 100
  let flashObjects = getFlashObjects(elem)
  flashObjects.forEach((obj) => {
    let el = obj.element
    let pluginRect = el.getBoundingClientRect()
    let height = el.getAttribute('height') || pluginRect.height
    let width = el.getAttribute('width') || pluginRect.width
    if (height > minHeight && width > minWidth) {
      let parent = el.parentNode
      if (!parent) {
        return
      }
      let iframe = document.createElement('iframe')
      let hash = window.location.origin
      if (chrome.contentSettings.flashEnabled == 'allow') {
        hash = hash + '#flashEnabled'
      }
      iframe.setAttribute('src', [placeholderUrl, hash].join('#'))
      iframe.setAttribute('style', `width: ${width}px; height: ${height}px`)
      parent.replaceChild(iframe, el)
    } else {
      // Note when elements are too small so we can improve the heuristic.
      console.log('got too-small Flash element', obj, height, width)
    }
  })
}

if (chrome.contentSettings.flashActive != 'allow' ||
    chrome.contentSettings.flashEnabled != 'allow') {
  insertFlashPlaceholders(document.documentElement)
  setTimeout(() => {
    var observer = new window.MutationObserver(function (mutations) {
      insertFlashPlaceholders(document.documentElement)
    })

    insertFlashPlaceholders(document.documentElement)
    observer.observe(document.documentElement, {
      childList: true,
      subtree: true
    })
  }, 1000)
}
<commit_msg>Use actual pixel height/width for flash placeholder<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const placeholderUrl = chrome.extension.getURL('about-flash.html')
const adobeRegex = new RegExp('//(get\\.adobe\\.com/([a-z_-]+/)*flashplayer|www\\.macromedia\\.com/go/getflash|www\\.adobe\\.com/go/getflash)', 'i')

function isAdobeLink (href) {
  if (typeof href !== 'string') {
    return false
  }
  return adobeRegex.test(href)
}

// Open flash links in the same tab so we can intercept them correctly
if (chrome.contentSettings.flashActive != 'allow' &&
    chrome.contentSettings.flashEnabled == 'allow') {
  (function () {
    function replaceAdobeLinks () {
      Array.from(document.querySelectorAll('a[target="_blank"]')).forEach((elem) => {
        const href = elem.getAttribute('href')
        if (isAdobeLink(href)) {
          elem.setAttribute('target', '')
        }
      })
    }
    setTimeout(() => {
      var observer = new window.MutationObserver(function (mutations) {
        replaceAdobeLinks()
      })
      replaceAdobeLinks()
      observer.observe(document.documentElement, {
        childList: true,
        subtree: true
      })
    }, 1000)
  })()
}

/**
 * Whether a src is a .swf file.
 * If so, returns the origin of the file. Otherwise returns false.
 * @param {string} src
 * @return {boolean|string}
 */
function isSWF (src) {
  if (!src) {
    return false
  }
  let a = document.createElement('a')
  a.href = src
  if (a.pathname && a.pathname.toLowerCase().endsWith('.swf')) {
    return a.origin
  } else {
    return false
  }
}

/**
 * Gets all Flash object descendants of an element.
 * Reference:
 * https://helpx.adobe.com/flash/kb/flash-object-embed-tag-attributes.html
 * @param {Element} elem - HTML element to search
 * @return {Array.<Element>}
 */
function getFlashObjects (elem) {
  let results = [] // Array.<{element: Element, origin: string}>
  Array.from(elem.getElementsByTagName('embed')).forEach((el) => {
    let origin = isSWF(el.getAttribute('src'))
    if (origin) {
      results.push({
        element: el,
        origin
      })
    }
  })

  Array.from(elem.getElementsByTagName('object')).forEach((el) => {
    // Skip objects that are contained in other flash objects
    /*
    for (let i = 0; i < results.length; i++) {
      if (results[i].element.contains(el)) {
        return
      }
    }
    */
    let origin = isSWF(el.getAttribute('data'))
    if (origin) {
      results.push({
        element: el,
        origin
      })
    } else {
      // See example at
      // https://helpx.adobe.com/animate/kb/object-tag-syntax.html
      Array.from(el.getElementsByTagName('param')).forEach((param) => {
        let name = param.getAttribute('name')
        let origin = isSWF(param.getAttribute('value'))
        if (name && ['movie', 'src'].includes(name.toLowerCase()) &&
            origin) {
          results.push({
            element: el,
            origin
          })
        }
      })
    }
  })

  // Some sites have custom Flash placeholders which we should replace with our
  // own.
  Array.from(elem.querySelectorAll('a > img')).forEach((el) => {
    let href = el.parentNode ? el.parentNode.href : null
    if (isAdobeLink(href)) {
      results.push({
        element: el
      })
    }
  })

  return results
}

/**
 * Inserts Flash placeholders.
 * @param {Element} elem - HTML element to search
 */
function insertFlashPlaceholders (elem) {
  const minWidth = 200
  const minHeight = 100
  let flashObjects = getFlashObjects(elem)
  flashObjects.forEach((obj) => {
    let el = obj.element
    let pluginRect = el.getBoundingClientRect()
    let height = pluginRect.height
    let width = pluginRect.width
    if (height > minHeight && width > minWidth) {
      let parent = el.parentNode
      if (!parent) {
        return
      }
      let iframe = document.createElement('iframe')
      let hash = window.location.origin
      if (chrome.contentSettings.flashEnabled == 'allow') {
        hash = hash + '#flashEnabled'
      }
      iframe.setAttribute('src', [placeholderUrl, hash].join('#'))
      iframe.setAttribute('style', `width: ${width}px; height: ${height}px`)
      parent.replaceChild(iframe, el)
    } else {
      // Note when elements are too small so we can improve the heuristic.
      console.log('got too-small Flash element', obj, height, width)
    }
  })
}

if (chrome.contentSettings.flashActive != 'allow' ||
    chrome.contentSettings.flashEnabled != 'allow') {
  insertFlashPlaceholders(document.documentElement)
  setTimeout(() => {
    var observer = new window.MutationObserver(function (mutations) {
      insertFlashPlaceholders(document.documentElement)
    })

    insertFlashPlaceholders(document.documentElement)
    observer.observe(document.documentElement, {
      childList: true,
      subtree: true
    })
  }, 1000)
}
<|endoftext|>


<commit_before>'use strict';

angular
  .module('freelook.info')
  .controller('footer.ctrl', function (url) {

    var vm = this;
    vm.donate = 'https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RFP3HDDXV2NJS';
    vm.company = url.href('company');

  });

<commit_msg>add link to home<commit_after>'use strict';

angular
  .module('freelook.info')
  .controller('footer.ctrl', function ($location, url) {

    var vm = this;
    vm.donate = 'https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RFP3HDDXV2NJS';
    vm.company = $location.path() !== '/company' ? url.href('company') : url.href('');

  });

<|endoftext|>


<commit_before>define(['underscore', 'nprogress', 'angular', 'jquery', 'data/in-session/meetings', 'directives/meetings/documents/in-session', 'bootstrap-notify', 'authentication'], function(_, nprogress, ng, $, meetings) {
	return ["$scope", "$route", "$http", '$q', '$timeout', '$location', 'authentication', function ($scope, $route, $http, $q, $timeout, $location, authentication) {

		var refreshTimeout = 2*60*1000; // 2 minutes

		$scope.meeting = lookupMeeting($route.current.params.meeting);

		if(!$scope.meeting)
			return;

		$q.when(authentication.getUser()).then(function(u){
			$scope.isAdmin = !!_.intersection(u.roles, ["Administrator","EditorialService"]).length;
		});

		//=============================================
		//
		//
		//=============================================
		function lookupMeeting(code)
		{
			var meeting = _.find(meetings, function(m) {
				return code.toUpperCase() == m.code.toUpperCase() ||
					   code.toUpperCase() == m.code.toUpperCase().replace(/-/g, "");
			});

			if(!meeting) {
				$location.url("/404");
				return;
			}

			if(meeting.code!=code) {
				$location.url("/"+meeting.code);
				return;
			}

			return _.clone(meeting, true); //deep clone
		}

		//=============================================
		//
		//
		//=============================================
		$scope.totalDocuments = function () {

			return _($scope.meeting.sections).filter($scope.isVisible).reduce(function(sum, section){

				return sum + _.where($scope.documents, { section : section.code }).length;

			}, 0);
		};

		//=============================================
		//
		//
		//=============================================
		$scope.unlock = function () {

			throw "TO RE-IMPLEMENT";

			// var lockedSections = _.filter(meeting.sections, function(s){
			// 	delete s.error;
			// 	return s.status==="RESTRICTED";
			// });
			//
			// if(lockedSections.length)
			// 	nprogress.start();
			//
			// var queries = _(lockedSections).map(function(s){
			//
			// 	return loadDocuments(s).then(function(d){
			//
			// 		if(d=="RESTRICTED")
			// 			s.error =  "INVALID_BADGE_ID";
			// 	});
			// });
			//
			// $q.all(queries).finally(function() {
			// 	nprogress.done();
			// });
		};

		//=============================================
		//
		//
		//=============================================
		$scope.isVisible = function (section) {

			var visible    = section.visible   || section.visible===undefined;
			var hasDocs    = _($scope.documents||[]).some({ section : section.code });

			return visible && hasDocs;
		};

		//==============================================
		//
		//
		//==============================================
		function cleanBadge(code) {
			return (code||$scope.$root.badgeCode||"").replace(/[^0-9]/g, "");
		}

		//=============================================
		//
		//
		//=============================================
		function load() {

			nprogress.start();

			var query = {
				q : {
					meeting : $scope.meeting.code,
					section : { $in : _.pluck($scope.meeting.sections, "code") }
				},
				s : {
					section : 1,
					position : 1
				}
			};

			return $http.get("/api/v2015/insession-documents", { params : query, headers : { badge : cleanBadge() } }).then(function(res){

				$scope.documents = _(res.data || []).map(function(d) {  //patch serie & tag

					d.visible = d.visible!==false ? true : false;

					return d;

				}).filter(function(d) {

					return d.visible && d.locales && d.locales.length;

				}).value();

				return $scope.documents;

			}).catch(function(e) {

				$scope.error = "ERROR:"+(e||'').toString();

			}).finally(function() {

				nprogress.done();
			});

		}

		//=============================================
		//
		//
		//=============================================
		function refresh() {

			if($('.modal:visible').size()===0) {

				return load().finally(function(){
					$timeout(refresh, refreshTimeout);
				});
			}
			else {
				$timeout(refresh, refreshTimeout);
			}
		}

		//=============================================
		//
		//
		//=============================================
		$scope.$watch("documents", function(_new, _old) {

			if(!_.isArray(_new) || !_.isArray(_old))
				return;

			var now   = new Date();
			var time  = now.getHours() + ":" + now.getMinutes();
			var count = 0;
			var message = null;

			if(_new.length > _old.length) {
				count   = _new.length - _old.length;
				message = time + ' - '+count+' new document(s) available';
			}

			if(_new.length>0 && _new.length == _old.length) {

				var o = _.map(_old, function(d) { return ng.toJson(_.pick(d, ["symbol","superseded","item","title","alert","warning","info","filePattern","locales"])); });
				var n = _.map(_new, function(d) { return ng.toJson(_.pick(d, ["symbol","superseded","item","title","alert","warning","info","filePattern","locales"])); });

				count = _.difference(n, o).length;

				if(count)
					message = time + ' - '+count+' document(s) updated';
			}

			if(message) {
				$.notify({ message: message, icon: "fa fa-files-o" }, {
					delay: 10000,
					type: 'info',
					placement : { align : "center" },
					animate: {
						enter: 'animated bounceInDown',
						exit: 'animated bounceOutUp'
					},
				});
			}

			$timeout(function(){
				$scope.$broadcast('printsmart-refresh');
			}, 500);
		});

		refresh();
	}];
});
<commit_msg>Fix: cannot read property 'badgeCode' of null<commit_after>define(['underscore', 'nprogress', 'angular', 'jquery', 'data/in-session/meetings', 'directives/meetings/documents/in-session', 'bootstrap-notify', 'authentication'], function(_, nprogress, ng, $, meetings) {
	return ["$scope", "$route", "$http", '$q', '$timeout', '$location', 'authentication', function ($scope, $route, $http, $q, $timeout, $location, authentication) {

		var refreshTimeout = 2*60*1000; // 2 minutes

		$scope.meeting = lookupMeeting($route.current.params.meeting);

		if(!$scope.meeting)
			return;

		$q.when(authentication.getUser()).then(function(u){
			$scope.isAdmin = !!_.intersection(u.roles, ["Administrator","EditorialService"]).length;
		});

		//=============================================
		//
		//
		//=============================================
		function lookupMeeting(code)
		{
			var meeting = _.find(meetings, function(m) {
				return code.toUpperCase() == m.code.toUpperCase() ||
					   code.toUpperCase() == m.code.toUpperCase().replace(/-/g, "");
			});

			if(!meeting) {
				$location.url("/404");
				return;
			}

			if(meeting.code!=code) {
				$location.url("/"+meeting.code);
				return;
			}

			return _.clone(meeting, true); //deep clone
		}

		//=============================================
		//
		//
		//=============================================
		$scope.totalDocuments = function () {

			return _($scope.meeting.sections).filter($scope.isVisible).reduce(function(sum, section){

				return sum + _.where($scope.documents, { section : section.code }).length;

			}, 0);
		};

		//=============================================
		//
		//
		//=============================================
		$scope.unlock = function () {

			throw "TO RE-IMPLEMENT";

			// var lockedSections = _.filter(meeting.sections, function(s){
			// 	delete s.error;
			// 	return s.status==="RESTRICTED";
			// });
			//
			// if(lockedSections.length)
			// 	nprogress.start();
			//
			// var queries = _(lockedSections).map(function(s){
			//
			// 	return loadDocuments(s).then(function(d){
			//
			// 		if(d=="RESTRICTED")
			// 			s.error =  "INVALID_BADGE_ID";
			// 	});
			// });
			//
			// $q.all(queries).finally(function() {
			// 	nprogress.done();
			// });
		};

		//=============================================
		//
		//
		//=============================================
		$scope.isVisible = function (section) {

			var visible    = section.visible   || section.visible===undefined;
			var hasDocs    = _($scope.documents||[]).some({ section : section.code });

			return visible && hasDocs;
		};

		//=============================================
		//
		//
		//=============================================
		function load() {

			nprogress.start();

			var query = {
				q : {
					meeting : $scope.meeting.code,
					section : { $in : _.pluck($scope.meeting.sections, "code") }
				},
				s : {
					section : 1,
					position : 1
				}
			};

			return $http.get("/api/v2015/insession-documents", { params : query }).then(function(res){

				$scope.documents = _(res.data || []).map(function(d) {  //patch serie & tag

					d.visible = d.visible!==false ? true : false;

					return d;

				}).filter(function(d) {

					return d.visible && d.locales && d.locales.length;

				}).value();

				return $scope.documents;

			}).catch(function(e) {

				$scope.error = "ERROR:"+(e||'').toString();

			}).finally(function() {

				nprogress.done();
			});

		}

		//=============================================
		//
		//
		//=============================================
		function refresh() {

			if($('.modal:visible').size()===0) {

				return load().finally(function(){
					$timeout(refresh, refreshTimeout);
				});
			}
			else {
				$timeout(refresh, refreshTimeout);
			}
		}

		//=============================================
		//
		//
		//=============================================
		$scope.$watch("documents", function(_new, _old) {

			if(!_.isArray(_new) || !_.isArray(_old))
				return;

			var now   = new Date();
			var time  = now.getHours() + ":" + now.getMinutes();
			var count = 0;
			var message = null;

			if(_new.length > _old.length) {
				count   = _new.length - _old.length;
				message = time + ' - '+count+' new document(s) available';
			}

			if(_new.length>0 && _new.length == _old.length) {

				var o = _.map(_old, function(d) { return ng.toJson(_.pick(d, ["symbol","superseded","item","title","alert","warning","info","filePattern","locales"])); });
				var n = _.map(_new, function(d) { return ng.toJson(_.pick(d, ["symbol","superseded","item","title","alert","warning","info","filePattern","locales"])); });

				count = _.difference(n, o).length;

				if(count)
					message = time + ' - '+count+' document(s) updated';
			}

			if(message) {
				$.notify({ message: message, icon: "fa fa-files-o" }, {
					delay: 10000,
					type: 'info',
					placement : { align : "center" },
					animate: {
						enter: 'animated bounceInDown',
						exit: 'animated bounceOutUp'
					},
				});
			}

			$timeout(function(){
				$scope.$broadcast('printsmart-refresh');
			}, 500);
		});

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


<commit_before>/**
 * ## Like Button
 *
 * Allow users to `like` an object. Likes are not connected to facebook or any other network
 * You can use this as "favorite", "starred", "want"... or of course "like".
 * It also shows the number of likes the object has.
 *
 * ### Examples
 *
 *

 *

 *

 *
 * ### Options
 *
 * - `id`: Target object to show like button for
 *
 * ### Template
 *
 * - `like_button`: Main template. Has 3 states: Unliked, Liked and Working
 *
 */

Hull.define({
  type: "Hull",

  templates: ["like_button"],
  refreshEvents: ['model.hull.me.change'],

  working: false,

  datasources: {
    target: ':id',
    liked: function(){
      return this.api("me/liked/"+this.options.id);
    },
  },

  onTargetError: function () {
    "use strict";
    return { stats: {} };
  },

  beforeRender:function(data){
    data.likes = data.target.stats.likes || 0;
    self.likes = data.likes;
    self.liked = data.liked;
    return data;
  },

  act: function(verb) {
    if (this.working) {
      return;
    }
    this.working = true;
    var self=this;
    var method = verb === 'unlike' ? 'delete' : 'post';
    self.liked=!self.liked;
    self.liked? self.likes++:self.likes--;

    self.render(self.getTemplate(),{working:true, likes:self.likes, liked:self.liked});

    //Events should be emitted automatically here so the likes@hull widget
    //can subscribe and refresh itself.
    this.api(this.id + '/likes', method)
    .done(function(likes) {
      self.likes=likes||0;

    }).fail(function(){
      self.likes--;
      self.liked=!self.liked;

    }).always(function(){
      self.working=false;
      self.render(self.getTemplate(),{working:self.working, liked:self.liked, likes:self.likes});

    });
  },

  actions: {
    like: function() {
      this.act('like');
    },
    unlike: function() {
      this.act('unlike');
    }
  }

});
<commit_msg>Emits hull.like event<commit_after>/**
 * ## Like Button
 *
 * Allow users to `like` an object. Likes are not connected to facebook or any other network
 * You can use this as "favorite", "starred", "want"... or of course "like".
 * It also shows the number of likes the object has.
 *
 * ### Examples
 *
 *

 *

 *

 *
 * ### Options
 *
 * - `id`: Target object to show like button for
 *
 * ### Template
 *
 * - `like_button`: Main template. Has 3 states: Unliked, Liked and Working
 *
 */

Hull.define({
  type: "Hull",

  templates: ["like_button"],
  refreshEvents: ['model.hull.me.change'],

  working: false,

  datasources: {
    target: ':id',
    liked: function(){
      return this.api("me/liked/"+this.options.id);
    },
  },

  onTargetError: function () {
    "use strict";
    return { stats: {} };
  },

  beforeRender:function(data){
    data.likes = data.target.stats.likes || 0;
    self.likes = data.likes;
    self.liked = data.liked;
    return data;
  },

  act: function(verb) {
    if (this.working) {
      return;
    }
    this.working = true;
    var self=this;
    var method = verb === 'unlike' ? 'delete' : 'post';
    self.liked=!self.liked;
    self.liked? self.likes++:self.likes--;

    self.render(self.getTemplate(),{working:true, likes:self.likes, liked:self.liked});

    //Events should be emitted automatically here so the likes@hull widget
    //can subscribe and refresh itself.
    this.api(this.id + '/likes', method)
    .done(function(likes) {
      self.likes=likes||0;
      self.emit('hull.like.' + self.id);
    }).fail(function(){
      self.likes--;
      self.liked=!self.liked;

    }).always(function(){
      self.working=false;
      self.render(self.getTemplate(),{working:self.working, liked:self.liked, likes:self.likes});

    });
  },

  actions: {
    like: function() {
      this.act('like');
    },
    unlike: function() {
      this.act('unlike');
    }
  }

});
<|endoftext|>


<commit_before>var React = require('react');
var assign = require('lodash.assign');
var Natures = require('./Natures');
var CloseButton = require('../images/ic_close_18px.svg');
require('../css/main.css');

var alertStyle = {
    margin: 5 + 'px',
    position: 'relative',
    minHeight: 50 + 'px',
    display: 'flex',
    justifyContent: 'center', /* align horizontal */
    alignItems: 'center', /* align vertical */
    fontFamily: 'roboto'
};

var alertWarning = assign({}, alertStyle, {backgroundColor: '#FDD835'});
var alertFailure = assign({}, alertStyle, {backgroundColor: '#F44336'});
var alertInfo = assign({}, alertStyle, {backgroundColor: '#BBDEFB'});
var alertSuccess = assign({}, alertStyle, {backgroundColor: '#69F0AE'});

var alertCloseButton = {
    position: 'absolute',
    right: 0 + 'px',
    top: 0 + 'px'
};

module.exports = React.createClass({

    getInitialState: function() {
        return {sShow: true};
    },

    dismissAlert: function() {
        this.setState({sShow: false});
        if(this.props.closeCallback) {
            this.props.closeCallback();
        }
    },

    render: function() {

        if(this.state.sShow === false) {
            return (React.createElement('div'));
        }
        var alertType;
        switch(this.props.alert.nature) {
            case Natures.WARNING:
                    alertType = alertWarning;
                break;
                case Natures.FAILURE:
                    alertType = alertFailure;
                break;
                case Natures.SUCCESS:
                    alertType = alertSuccess;
                break;
                case Natures.INFO:
                    alertType = alertInfo;
                break;
        }
        if(alertType !== undefined) {
            var closeElement = React.createElement('img', {onClick: this.dismissAlert, src:CloseButton, style:alertCloseButton});
            var alertBox = React.createElement('span', {dangerouslySetInnerHTML:{__html: this.props.alert.content}, });

            return React.createElement('div', {style:alertType, role:"alert", id:this.props.id}, alertBox, closeElement);

        }

        return (React.createElement('div'));
    }
});<commit_msg>added a pointer to the close button<commit_after>var React = require('react');
var assign = require('lodash.assign');
var Natures = require('./Natures');
var CloseButton = require('../images/ic_close_18px.svg');
require('../css/main.css');

var alertStyle = {
    margin: 5 + 'px',
    position: 'relative',
    minHeight: 50 + 'px',
    display: 'flex',
    justifyContent: 'center', /* align horizontal */
    alignItems: 'center', /* align vertical */
    fontFamily: 'roboto'
};

var alertWarning = assign({}, alertStyle, {backgroundColor: '#FDD835'});
var alertFailure = assign({}, alertStyle, {backgroundColor: '#F44336'});
var alertInfo = assign({}, alertStyle, {backgroundColor: '#BBDEFB'});
var alertSuccess = assign({}, alertStyle, {backgroundColor: '#69F0AE'});

var alertCloseButton = {
    position: 'absolute',
    right: 0 + 'px',
    top: 0 + 'px',
    cursor: 'pointer'
};

module.exports = React.createClass({

    getInitialState: function() {
        return {sShow: true};
    },

    dismissAlert: function() {
        this.setState({sShow: false});
        if(this.props.closeCallback) {
            this.props.closeCallback();
        }
    },

    render: function() {

        if(this.state.sShow === false) {
            return (React.createElement('div'));
        }
        var alertType;
        switch(this.props.alert.nature) {
            case Natures.WARNING:
                    alertType = alertWarning;
                break;
                case Natures.FAILURE:
                    alertType = alertFailure;
                break;
                case Natures.SUCCESS:
                    alertType = alertSuccess;
                break;
                case Natures.INFO:
                    alertType = alertInfo;
                break;
        }
        if(alertType !== undefined) {
            var closeElement = React.createElement('img', {onClick: this.dismissAlert, src:CloseButton, style:alertCloseButton});
            var alertBox = React.createElement('span', {dangerouslySetInnerHTML:{__html: this.props.alert.content}, });

            return React.createElement('div', {style:alertType, role:"alert", id:this.props.id}, alertBox, closeElement);

        }

        return (React.createElement('div'));
    }
});<|endoftext|>


<commit_before>var Waiter = require('./Waiter');
var mime = require('./mime');

var chug;
setImmediate(function immediatelySetChug() {
	chug = require('../chug');
});

/**
 * An Asset is a cache of content.
 * @param path
 * @constructor
 */
var Asset = module.exports = Waiter.extend({

	/**
	 * An asset has a location which is used to cache it.
	 * @param name
	 */
	init: function init(location, load) {
		var self = this;
		self._super(load);
		self.location = location;
		self.type = location.replace(/^.*\./, '').toLowerCase();
		self.dependents = [];
	},

	/**
	 * Set this asset's textual content.
	 * @param content
	 * @returns {Asset}
	 */
	setContent: function setContent(content) {
		if (content !== this.content) {
			this.content = content;

			// Some content can be set for auto-routing.
			if (/^[^a-zA-Z]*AUTOROUTE/.test(content)) {
				this.route();
			}
			console.log('CONTENT: ' + content);
		}
		return this;
	},

	/**
	 * Compile the asset if its type is compilable.
	 * @returns {Asset}
	 */
	compile: function compile() {

		// Get the compiler for this asset's file type.
		var compiler = chug._compilers[this.type];

		// The value false indicates that this file type doesn't need to be compiled.
		if (compiler === false) {
			return this;
		}

		// A string means there's a known compiler, but it's not yet added (i.e. require()'d).
		if (typeof compiler == 'string') {
			compiler = chug.addCompiler(this.type, compiler);
		}
		// Undefined means we expect the compiler to have the same name as the file extension.
		else if (typeof compiler == 'undefined') {
			compiler = chug.addCompiler(this.type, this.type);
		}

		// If the compiler is now loaded, use it to compile.
		if (compiler) {

			var content = this.content || '';
			var compiled;
			if (isFunction(compiler.compile)) {
				var name = this.location.replace(/^.*\/(views)\/(.*)\.[a-z]+$/, '$2');
				compiled = compiler.compile(content, {name: name});
				var cache = compiler.cache;
				if (cache) {
					compiled.cache = cache;
				}
			}
			else if (isFunction(compiler.renderSync)) {
				compiled = compiler.renderSync({ data: content, compressed: true });
			}
			else if (isFunction(compiler.render)) {
				if (this.type == 'less') {
					compiler.render(content, function compilerRender(err, code) {
						compiled = code;
					});
				}
				else {
					compiled = compiler.render(content);
				}
			}
			else if (compiler.markdown) {
				compiled = compiler.markdown.toHTML(content);
			}
			else if (isFunction(compiler)) {
				compiled = compiler(content);
			}
			else {
				chug.error('Unrecognized compiler for type: ' + this.type);
			}

			// If the content has been compiled and is different from the original, set it.
			if (compiled != this.content) {
				console.log('COMPILED: ' + compiled.toString());
				this.compiledContent = compiled;
			}
		}
		return this;
	},

	/**
	 * Minify the asset if its type is minifiable.
	 * @returns {Asset}
	 */
	minify: function minify() {

		// Get the compiler for this asset's file type.
		var minifier = chug._minifiers[this.type];

		// If there's a minifier specified as a string, add it.
		if (typeof minifier == 'string') {
			var minifierName = minifier;
			minifier = chug.addMinifier(this.type, minifierName);
		}

		// If the minifier is now loaded, use it to compile.
		if (minifier) {

			var minified;
			var content = this.compiledContent || this.content;

			// UglifyJs has a minify function.
			if (minifier.minify) {
				minified = minifier.minify(content, {fromString: true}).code;
			}
			// CleanCss requires object instantiation.
			else {
				var m = new minifier();
				minified = m.minify(content);
			}

			// If the content has been compiled and is different from the original, post-process.
			if (minified != this.minifiedContent) {
				this.minifiedContent = minified;
			}
		}
		return this;
	},

	/**
	 * Shrink the asset's minified content.
	 * @returns {Asset}
	 */
	shrink: function shrink() {
		// TODO: Perform shrinkage.
		this.shrunkenContent = this.minifiedContent || this.compiledContent || this.content;
		return this;
	},

	/**
	 * Return the asset's shrunken content.
	 * @returns {string}
	 */
	getShrunkenContent: function shrink() {
		return this.shrunkenContent || this.minifiedContent || this.compiledContent || this.content;
	},

	/**
	 * Add an asset to an app route.
	 * @returns {Asset}
	 */
	route: function route(path) {
		var self = this;
		if (chug._app) {
			path = path || self.location;
			var cwd = process.cwd();
			if (path.substr(0, cwd.length) == cwd) {
				path = path.substr(cwd.length);
				path = path.replace(/^\/[^\/]+/, '');
			}
			var mimeType = mime[self.type] || 'text/html';
			if (mimeType == 'text/html') {
				path = path.replace(/\.[^\.]+$/, '');
				path = path.replace(/\/index$/, '/');
			}
			chug._app.get(path, function (request, response) {
				response.setHeader('Content-Type', mimeType);
				response.statusCode = 200;
				var content = self.getShrunkenContent();
				if (typeof content == 'function') {
					content = content.apply(content.cache, {});
				}
				response.end(content);
			});
		}
		else {
			chug.error('Cannot route until setApp has received an Express-style app.');
		}
		return self;
	}
});

function isFunction(value) {
	return typeof value == 'function';
}<commit_msg>Removed asset content change logs<commit_after>var Waiter = require('./Waiter');
var mime = require('./mime');

var chug;
setImmediate(function immediatelySetChug() {
	chug = require('../chug');
});

/**
 * An Asset is a cache of content.
 * @param path
 * @constructor
 */
var Asset = module.exports = Waiter.extend({

	/**
	 * An asset has a location which is used to cache it.
	 * @param name
	 */
	init: function init(location, load) {
		var self = this;
		self._super(load);
		self.location = location;
		self.type = location.replace(/^.*\./, '').toLowerCase();
		self.dependents = [];
	},

	/**
	 * Set this asset's textual content.
	 * @param content
	 * @returns {Asset}
	 */
	setContent: function setContent(content) {
		if (content !== this.content) {
			this.content = content;

			// Some content can be set for auto-routing.
			if (/^[^a-zA-Z]*AUTOROUTE/.test(content)) {
				this.route();
			}
		}
		return this;
	},

	/**
	 * Compile the asset if its type is compilable.
	 * @returns {Asset}
	 */
	compile: function compile() {

		// Get the compiler for this asset's file type.
		var compiler = chug._compilers[this.type];

		// The value false indicates that this file type doesn't need to be compiled.
		if (compiler === false) {
			return this;
		}

		// A string means there's a known compiler, but it's not yet added (i.e. require()'d).
		if (typeof compiler == 'string') {
			compiler = chug.addCompiler(this.type, compiler);
		}
		// Undefined means we expect the compiler to have the same name as the file extension.
		else if (typeof compiler == 'undefined') {
			compiler = chug.addCompiler(this.type, this.type);
		}

		// If the compiler is now loaded, use it to compile.
		if (compiler) {

			var content = this.content || '';
			var compiled;
			if (isFunction(compiler.compile)) {
				var name = this.location.replace(/^.*\/(views)\/(.*)\.[a-z]+$/, '$2');
				compiled = compiler.compile(content, {name: name});
				var cache = compiler.cache;
				if (cache) {
					compiled.cache = cache;
				}
			}
			else if (isFunction(compiler.renderSync)) {
				compiled = compiler.renderSync({ data: content, compressed: true });
			}
			else if (isFunction(compiler.render)) {
				if (this.type == 'less') {
					compiler.render(content, function compilerRender(err, code) {
						compiled = code;
					});
				}
				else {
					compiled = compiler.render(content);
				}
			}
			else if (compiler.markdown) {
				compiled = compiler.markdown.toHTML(content);
			}
			else if (isFunction(compiler)) {
				compiled = compiler(content);
			}
			else {
				chug.error('Unrecognized compiler for type: ' + this.type);
			}

			// If the content has been compiled and is different from the original, set it.
			if (compiled != this.content) {
				this.compiledContent = compiled;
			}
		}
		return this;
	},

	/**
	 * Minify the asset if its type is minifiable.
	 * @returns {Asset}
	 */
	minify: function minify() {

		// Get the compiler for this asset's file type.
		var minifier = chug._minifiers[this.type];

		// If there's a minifier specified as a string, add it.
		if (typeof minifier == 'string') {
			var minifierName = minifier;
			minifier = chug.addMinifier(this.type, minifierName);
		}

		// If the minifier is now loaded, use it to compile.
		if (minifier) {

			var minified;
			var content = this.compiledContent || this.content;

			// UglifyJs has a minify function.
			if (minifier.minify) {
				minified = minifier.minify(content, {fromString: true}).code;
			}
			// CleanCss requires object instantiation.
			else {
				var m = new minifier();
				minified = m.minify(content);
			}

			// If the content has been compiled and is different from the original, post-process.
			if (minified != this.minifiedContent) {
				this.minifiedContent = minified;
			}
		}
		return this;
	},

	/**
	 * Shrink the asset's minified content.
	 * @returns {Asset}
	 */
	shrink: function shrink() {
		// TODO: Perform shrinkage.
		this.shrunkenContent = this.minifiedContent || this.compiledContent || this.content;
		return this;
	},

	/**
	 * Return the asset's shrunken content.
	 * @returns {string}
	 */
	getShrunkenContent: function shrink() {
		return this.shrunkenContent || this.minifiedContent || this.compiledContent || this.content;
	},

	/**
	 * Add an asset to an app route.
	 * @returns {Asset}
	 */
	route: function route(path) {
		var self = this;
		if (chug._app) {
			path = path || self.location;
			var cwd = process.cwd();
			if (path.substr(0, cwd.length) == cwd) {
				path = path.substr(cwd.length);
				path = path.replace(/^\/[^\/]+/, '');
			}
			var mimeType = mime[self.type] || 'text/html';
			if (mimeType == 'text/html') {
				path = path.replace(/\.[^\.]+$/, '');
				path = path.replace(/\/index$/, '/');
			}
			chug._app.get(path, function (request, response) {
				response.setHeader('Content-Type', mimeType);
				response.statusCode = 200;
				var content = self.getShrunkenContent();
				if (typeof content == 'function') {
					content = content.apply(content.cache, {});
				}
				response.end(content);
			});
		}
		else {
			chug.error('Cannot route until setApp has received an Express-style app.');
		}
		return self;
	}
});

function isFunction(value) {
	return typeof value == 'function';
}<|endoftext|>


<commit_before>(function() {
  var Bacon, Dispatcher, End, Event, EventStream, Initial, Next, Observable, Property, assert, assertEvent, assertFunction, cloneArray, empty, end, head, initial, next, nop, remove, tail, _ref,
    __hasProp = Object.prototype.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; },
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  if ((_ref = this.jQuery || this.Zepto) != null) {
    _ref.fn.asEventStream = function(eventName) {
      var element;
      element = this;
      return new EventStream(function(sink) {
        var handler, unbind;
        handler = function(event) {
          var reply;
          reply = sink(next(event));
          if (reply === Bacon.noMore) return unbind();
        };
        unbind = function() {
          return element.unbind(eventName, handler);
        };
        element.bind(eventName, handler);
        return unbind;
      });
    };
  }

  Bacon = this.Bacon = {
    taste: "delicious"
  };

  Bacon.noMore = "veggies";

  Bacon.more = "moar bacon!";

  Bacon.later = function(delay, value) {
    return Bacon.sequentially(delay, [value]);
  };

  Bacon.sequentially = function(delay, values) {
    var poll, valuesLeft;
    valuesLeft = values;
    poll = function() {
      var value;
      if (valuesLeft.length === 0) {
        return end();
      } else {
        value = head(valuesLeft);
        valuesLeft = tail(valuesLeft);
        return next(value);
      }
    };
    return Bacon.fromPoll(delay, poll);
  };

  Bacon.repeatedly = function(delay, values) {
    var index, poll;
    index = -1;
    poll = function() {
      index++;
      return next(values[index % values.length]);
    };
    return Bacon.fromPoll(delay, poll);
  };

  Bacon.fromPoll = function(delay, poll) {
    return new EventStream(function(sink) {
      var handler, id, unbind;
      id = void 0;
      handler = function() {
        var reply, value;
        value = poll();
        reply = sink(value);
        if (reply === Bacon.noMore || value.isEnd()) return unbind();
      };
      unbind = function() {
        return clearInterval(id);
      };
      id = setInterval(handler, delay);
      return unbind;
    });
  };

  Bacon.interval = function(delay, value) {
    var poll;
    if (value == null) value = {};
    poll = function() {
      return next(value);
    };
    return Bacon.fromPoll(delay, poll);
  };

  Bacon.pushStream = function() {
    var d, pushStream;
    d = new Dispatcher;
    pushStream = d.toEventStream();
    pushStream.push = function(event) {
      return d.push(next(event));
    };
    pushStream.end = function() {
      return d.push(end());
    };
    return pushStream;
  };

  Event = (function() {

    function Event() {}

    Event.prototype.isEvent = function() {
      return true;
    };

    Event.prototype.isEnd = function() {
      return false;
    };

    Event.prototype.isInitial = function() {
      return false;
    };

    Event.prototype.isNext = function() {
      return false;
    };

    Event.prototype.hasValue = function() {
      return false;
    };

    return Event;

  })();

  Next = (function(_super) {

    __extends(Next, _super);

    function Next(value) {
      this.value = value;
    }

    Next.prototype.isNext = function() {
      return true;
    };

    Next.prototype.hasValue = function() {
      return true;
    };

    return Next;

  })(Event);

  Initial = (function(_super) {

    __extends(Initial, _super);

    function Initial() {
      Initial.__super__.constructor.apply(this, arguments);
    }

    Initial.prototype.isInitial = function() {
      return true;
    };

    return Initial;

  })(Next);

  End = (function(_super) {

    __extends(End, _super);

    function End() {}

    End.prototype.isEnd = function() {
      return true;
    };

    return End;

  })(Event);

  Observable = (function() {

    function Observable() {}

    Observable.prototype.onValue = function(f) {
      return this.subscribe(function(event) {
        if (event.hasValue()) return f(event.value);
      });
    };

    return Observable;

  })();

  EventStream = (function(_super) {

    __extends(EventStream, _super);

    function EventStream(subscribe) {
      this["switch"] = __bind(this["switch"], this);
      var dispatcher;
      dispatcher = new Dispatcher(subscribe);
      this.subscribe = dispatcher.subscribe;
      this.hasSubscribers = dispatcher.hasSubscribers;
    }

    EventStream.prototype.filter = function(f) {
      return this.withHandler(function(event) {
        if (event.isEnd() || f(event.value)) {
          return this.push(event);
        } else {
          return Bacon.more;
        }
      });
    };

    EventStream.prototype.takeWhile = function(f) {
      return this.withHandler(function(event) {
        if (event.isEnd() || f(event.value)) {
          return this.push(event);
        } else {
          this.push(end());
          return Bacon.noMore;
        }
      });
    };

    EventStream.prototype.take = function(count) {
      return this.withHandler(function(event) {
        if (event.isEnd() || count > 0) {
          count--;
          return this.push(event);
        } else {
          this.push(end());
          return Bacon.noMore;
        }
      });
    };

    EventStream.prototype.map = function(f) {
      return this.withHandler(function(event) {
        if (event.isEnd()) {
          return this.push(event);
        } else {
          return this.push(next(f(event.value)));
        }
      });
    };

    EventStream.prototype.flatMap = function(f) {
      var root;
      root = this;
      return new EventStream(function(sink) {
        var checkEnd, children, rootEnd, spawner, unbind, unsubRoot;
        children = [];
        rootEnd = false;
        unsubRoot = function() {};
        unbind = function() {
          var unsubChild, _i, _len;
          unsubRoot();
          for (_i = 0, _len = children.length; _i < _len; _i++) {
            unsubChild = children[_i];
            unsubChild();
          }
          return children = [];
        };
        checkEnd = function() {
          if (rootEnd && (children.length === 0)) return sink(end());
        };
        spawner = function(event) {
          var child, handler, removeChild, unsubChild;
          if (event.isEnd()) {
            rootEnd = true;
            return checkEnd();
          } else {
            child = f(event.value);
            unsubChild = void 0;
            removeChild = function() {
              if (unsubChild != null) remove(unsubChild, children);
              return checkEnd();
            };
            handler = function(event) {
              var reply;
              if (event.isEnd()) {
                removeChild();
                return Bacon.noMore;
              } else {
                reply = sink(event);
                if (reply === Bacon.noMore) unbind();
                return reply;
              }
            };
            unsubChild = child.subscribe(handler);
            return children.push(unsubChild);
          }
        };
        unsubRoot = root.subscribe(spawner);
        return unbind;
      });
    };

    EventStream.prototype["switch"] = function(f) {
      var _this = this;
      return this.flatMap(function(value) {
        return f(value).takeUntil(_this);
      });
    };

    EventStream.prototype.delay = function(delay) {
      return this.flatMap(function(value) {
        return Bacon.later(delay, value);
      });
    };

    EventStream.prototype.merge = function(right) {
      var left;
      left = this;
      return new EventStream(function(sink) {
        var ends, smartSink, unsubBoth, unsubLeft, unsubRight;
        unsubLeft = nop;
        unsubRight = nop;
        unsubBoth = function() {
          unsubLeft();
          return unsubRight();
        };
        ends = 0;
        smartSink = function(event) {
          var reply;
          if (event.isEnd()) {
            ends++;
            if (ends === 2) {
              return sink(end());
            } else {
              return Bacon.more;
            }
          } else {
            reply = sink(event);
            if (reply === Bacon.noMore) unsubBoth();
            return reply;
          }
        };
        unsubLeft = left.subscribe(smartSink);
        unsubRight = right.subscribe(smartSink);
        return unsubBoth;
      });
    };

    EventStream.prototype.takeUntil = function(stopper) {
      var src;
      src = this;
      return new EventStream(function(sink) {
        var srcSink, stopperSink, unsubBoth, unsubSrc, unsubStopper;
        unsubSrc = nop;
        unsubStopper = nop;
        unsubBoth = function() {
          unsubSrc();
          return unsubStopper();
        };
        srcSink = function(event) {
          var reply;
          if (event.isEnd()) unsubStopper();
          reply = sink(event);
          if (reply === Bacon.noMore) unsubStopper();
          return reply;
        };
        stopperSink = function(event) {
          if (!event.isEnd()) {
            unsubSrc();
            sink(end());
          }
          return Bacon.noMore;
        };
        unsubSrc = src.subscribe(srcSink);
        unsubStopper = stopper.subscribe(stopperSink);
        return unsubBoth;
      });
    };

    EventStream.prototype.toProperty = function(initValue) {
      return new Property(this, initValue);
    };

    EventStream.prototype.withHandler = function(handler) {
      return new Dispatcher(this.subscribe, handler).toEventStream();
    };

    EventStream.prototype.toString = function() {
      return "EventStream";
    };

    return EventStream;

  })(Observable);

  Property = (function(_super) {

    __extends(Property, _super);

    function Property(stream, initValue) {
      var currentValue, d, handleEvent;
      currentValue = initValue;
      handleEvent = function(event) {
        if (!event.isEnd) currentValue = event.value;
        return this.push(event);
      };
      d = new Dispatcher(stream.subscribe, handleEvent);
      this.subscribe = function(sink) {
        if (currentValue != null) sink(initial(currentValue));
        return d.subscribe(sink);
      };
    }

    return Property;

  })(Observable);

  Dispatcher = (function() {

    function Dispatcher(subscribe, handleEvent) {
      var removeSink, sinks, unsubscribeFromSource,
        _this = this;
      if (subscribe == null) {
        subscribe = function() {
          return nop;
        };
      }
      sinks = [];
      this.hasSubscribers = function() {
        return sinks.length > 0;
      };
      unsubscribeFromSource = nop;
      removeSink = function(sink) {
        return remove(sink, sinks);
      };
      this.push = function(event) {
        var reply, sink, _i, _len, _ref2;
        assertEvent(event);
        _ref2 = cloneArray(sinks);
        for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
          sink = _ref2[_i];
          reply = sink(event);
          if (reply === Bacon.noMore || event.isEnd()) removeSink(sink);
        }
        if (_this.hasSubscribers()) {
          return Bacon.more;
        } else {
          return Bacon.noMore;
        }
      };
      if (handleEvent == null) {
        handleEvent = function(event) {
          return this.push(event);
        };
      }
      this.handleEvent = function(event) {
        assertEvent(event);
        return handleEvent.apply(_this, [event]);
      };
      this.subscribe = function(sink) {
        sinks.push(sink);
        if (sinks.length === 1) {
          unsubscribeFromSource = subscribe(_this.handleEvent);
        }
        assertFunction(unsubscribeFromSource);
        return function() {
          removeSink(sink);
          if (!_this.hasSubscribers()) return unsubscribeFromSource();
        };
      };
    }

    Dispatcher.prototype.toEventStream = function() {
      return new EventStream(this.subscribe);
    };

    Dispatcher.prototype.toString = function() {
      return "Dispatcher";
    };

    return Dispatcher;

  })();

  Bacon.EventStream = EventStream;

  Bacon.Property = Property;

  Bacon.Initial = Initial;

  Bacon.Next = Next;

  Bacon.End = End;

  nop = function() {};

  initial = function(value) {
    return new Initial(value);
  };

  next = function(value) {
    return new Next(value);
  };

  end = function() {
    return new End();
  };

  empty = function(xs) {
    return xs.length === 0;
  };

  head = function(xs) {
    return xs[0];
  };

  tail = function(xs) {
    return xs.slice(1, xs.length);
  };

  cloneArray = function(xs) {
    return xs.slice(0);
  };

  remove = function(x, xs) {
    var i;
    i = xs.indexOf(x);
    if (i >= 0) return xs.splice(i, 1);
  };

  assert = function(message, condition) {
    if (!condition) throw message;
  };

  assertEvent = function(event) {
    assert("not an event : " + event, event.isEvent != null);
    return assert("not event", event.isEvent());
  };

  assertFunction = function(f) {
    return assert("not a function : " + f, typeof f === "function");
  };

}).call(this);
<commit_msg>build js<commit_after>(function() {
  var Bacon, Dispatcher, End, Event, EventStream, Initial, Next, Observable, Property, assert, assertEvent, assertFunction, cloneArray, empty, end, head, initial, next, nop, remove, tail, _ref,
    __hasProp = Object.prototype.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; },
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  if ((_ref = this.jQuery || this.Zepto) != null) {
    _ref.fn.asEventStream = function(eventName) {
      var element;
      element = this;
      return new EventStream(function(sink) {
        var handler, unbind;
        handler = function(event) {
          var reply;
          reply = sink(next(event));
          if (reply === Bacon.noMore) return unbind();
        };
        unbind = function() {
          return element.unbind(eventName, handler);
        };
        element.bind(eventName, handler);
        return unbind;
      });
    };
  }

  Bacon = this.Bacon = {
    taste: "delicious"
  };

  Bacon.noMore = "veggies";

  Bacon.more = "moar bacon!";

  Bacon.later = function(delay, value) {
    return Bacon.sequentially(delay, [value]);
  };

  Bacon.sequentially = function(delay, values) {
    var poll, valuesLeft;
    valuesLeft = values;
    poll = function() {
      var value;
      if (valuesLeft.length === 0) {
        return end();
      } else {
        value = head(valuesLeft);
        valuesLeft = tail(valuesLeft);
        return next(value);
      }
    };
    return Bacon.fromPoll(delay, poll);
  };

  Bacon.repeatedly = function(delay, values) {
    var index, poll;
    index = -1;
    poll = function() {
      index++;
      return next(values[index % values.length]);
    };
    return Bacon.fromPoll(delay, poll);
  };

  Bacon.fromPoll = function(delay, poll) {
    return new EventStream(function(sink) {
      var handler, id, unbind;
      id = void 0;
      handler = function() {
        var reply, value;
        value = poll();
        reply = sink(value);
        if (reply === Bacon.noMore || value.isEnd()) return unbind();
      };
      unbind = function() {
        return clearInterval(id);
      };
      id = setInterval(handler, delay);
      return unbind;
    });
  };

  Bacon.interval = function(delay, value) {
    var poll;
    if (value == null) value = {};
    poll = function() {
      return next(value);
    };
    return Bacon.fromPoll(delay, poll);
  };

  Bacon.pushStream = function() {
    var d, pushStream;
    d = new Dispatcher;
    pushStream = d.toEventStream();
    pushStream.push = function(event) {
      return d.push(next(event));
    };
    pushStream.end = function() {
      return d.push(end());
    };
    return pushStream;
  };

  Event = (function() {

    function Event() {}

    Event.prototype.isEvent = function() {
      return true;
    };

    Event.prototype.isEnd = function() {
      return false;
    };

    Event.prototype.isInitial = function() {
      return false;
    };

    Event.prototype.isNext = function() {
      return false;
    };

    Event.prototype.hasValue = function() {
      return false;
    };

    return Event;

  })();

  Next = (function(_super) {

    __extends(Next, _super);

    function Next(value) {
      this.value = value;
    }

    Next.prototype.isNext = function() {
      return true;
    };

    Next.prototype.hasValue = function() {
      return true;
    };

    Next.prototype.fmap = function(f) {
      return next(f(this.value));
    };

    return Next;

  })(Event);

  Initial = (function(_super) {

    __extends(Initial, _super);

    function Initial() {
      Initial.__super__.constructor.apply(this, arguments);
    }

    Initial.prototype.isInitial = function() {
      return true;
    };

    Initial.prototype.fmap = function(f) {
      return initial(f(this.value));
    };

    return Initial;

  })(Next);

  End = (function(_super) {

    __extends(End, _super);

    function End() {}

    End.prototype.isEnd = function() {
      return true;
    };

    End.prototype.fmap = function() {
      return this;
    };

    return End;

  })(Event);

  Observable = (function() {

    function Observable() {}

    Observable.prototype.onValue = function(f) {
      return this.subscribe(function(event) {
        if (event.hasValue()) return f(event.value);
      });
    };

    return Observable;

  })();

  EventStream = (function(_super) {

    __extends(EventStream, _super);

    function EventStream(subscribe) {
      this["switch"] = __bind(this["switch"], this);
      var dispatcher;
      dispatcher = new Dispatcher(subscribe);
      this.subscribe = dispatcher.subscribe;
      this.hasSubscribers = dispatcher.hasSubscribers;
    }

    EventStream.prototype.filter = function(f) {
      return this.withHandler(function(event) {
        if (event.isEnd() || f(event.value)) {
          return this.push(event);
        } else {
          return Bacon.more;
        }
      });
    };

    EventStream.prototype.takeWhile = function(f) {
      return this.withHandler(function(event) {
        if (event.isEnd() || f(event.value)) {
          return this.push(event);
        } else {
          this.push(end());
          return Bacon.noMore;
        }
      });
    };

    EventStream.prototype.take = function(count) {
      return this.withHandler(function(event) {
        if (event.isEnd() || count > 0) {
          count--;
          return this.push(event);
        } else {
          this.push(end());
          return Bacon.noMore;
        }
      });
    };

    EventStream.prototype.map = function(f) {
      return this.withHandler(function(event) {
        return this.push(event.fmap(f));
      });
    };

    EventStream.prototype.flatMap = function(f) {
      var root;
      root = this;
      return new EventStream(function(sink) {
        var checkEnd, children, rootEnd, spawner, unbind, unsubRoot;
        children = [];
        rootEnd = false;
        unsubRoot = function() {};
        unbind = function() {
          var unsubChild, _i, _len;
          unsubRoot();
          for (_i = 0, _len = children.length; _i < _len; _i++) {
            unsubChild = children[_i];
            unsubChild();
          }
          return children = [];
        };
        checkEnd = function() {
          if (rootEnd && (children.length === 0)) return sink(end());
        };
        spawner = function(event) {
          var child, handler, removeChild, unsubChild;
          if (event.isEnd()) {
            rootEnd = true;
            return checkEnd();
          } else {
            child = f(event.value);
            unsubChild = void 0;
            removeChild = function() {
              if (unsubChild != null) remove(unsubChild, children);
              return checkEnd();
            };
            handler = function(event) {
              var reply;
              if (event.isEnd()) {
                removeChild();
                return Bacon.noMore;
              } else {
                reply = sink(event);
                if (reply === Bacon.noMore) unbind();
                return reply;
              }
            };
            unsubChild = child.subscribe(handler);
            return children.push(unsubChild);
          }
        };
        unsubRoot = root.subscribe(spawner);
        return unbind;
      });
    };

    EventStream.prototype["switch"] = function(f) {
      var _this = this;
      return this.flatMap(function(value) {
        return f(value).takeUntil(_this);
      });
    };

    EventStream.prototype.delay = function(delay) {
      return this.flatMap(function(value) {
        return Bacon.later(delay, value);
      });
    };

    EventStream.prototype.merge = function(right) {
      var left;
      left = this;
      return new EventStream(function(sink) {
        var ends, smartSink, unsubBoth, unsubLeft, unsubRight;
        unsubLeft = nop;
        unsubRight = nop;
        unsubBoth = function() {
          unsubLeft();
          return unsubRight();
        };
        ends = 0;
        smartSink = function(event) {
          var reply;
          if (event.isEnd()) {
            ends++;
            if (ends === 2) {
              return sink(end());
            } else {
              return Bacon.more;
            }
          } else {
            reply = sink(event);
            if (reply === Bacon.noMore) unsubBoth();
            return reply;
          }
        };
        unsubLeft = left.subscribe(smartSink);
        unsubRight = right.subscribe(smartSink);
        return unsubBoth;
      });
    };

    EventStream.prototype.takeUntil = function(stopper) {
      var src;
      src = this;
      return new EventStream(function(sink) {
        var srcSink, stopperSink, unsubBoth, unsubSrc, unsubStopper;
        unsubSrc = nop;
        unsubStopper = nop;
        unsubBoth = function() {
          unsubSrc();
          return unsubStopper();
        };
        srcSink = function(event) {
          var reply;
          if (event.isEnd()) unsubStopper();
          reply = sink(event);
          if (reply === Bacon.noMore) unsubStopper();
          return reply;
        };
        stopperSink = function(event) {
          if (!event.isEnd()) {
            unsubSrc();
            sink(end());
          }
          return Bacon.noMore;
        };
        unsubSrc = src.subscribe(srcSink);
        unsubStopper = stopper.subscribe(stopperSink);
        return unsubBoth;
      });
    };

    EventStream.prototype.toProperty = function(initValue) {
      var currentValue, d, handleEvent, subscribe;
      currentValue = initValue;
      handleEvent = function(event) {
        if (!event.isEnd) currentValue = event.value;
        return this.push(event);
      };
      d = new Dispatcher(this.subscribe, handleEvent);
      subscribe = function(sink) {
        if (currentValue != null) sink(initial(currentValue));
        return d.subscribe(sink);
      };
      return new Property(subscribe);
    };

    EventStream.prototype.withHandler = function(handler) {
      return new Dispatcher(this.subscribe, handler).toEventStream();
    };

    EventStream.prototype.toString = function() {
      return "EventStream";
    };

    return EventStream;

  })(Observable);

  Property = (function(_super) {

    __extends(Property, _super);

    function Property(subscribe) {
      this.subscribe = subscribe;
      this.map = __bind(this.map, this);
    }

    Property.prototype.map = function(f) {
      var _this = this;
      return new Property(function(sink) {
        return _this.subscribe(function(event) {
          return sink(event.fmap(f));
        });
      });
    };

    return Property;

  })(Observable);

  Dispatcher = (function() {

    function Dispatcher(subscribe, handleEvent) {
      var removeSink, sinks, unsubscribeFromSource,
        _this = this;
      if (subscribe == null) {
        subscribe = function() {
          return nop;
        };
      }
      sinks = [];
      this.hasSubscribers = function() {
        return sinks.length > 0;
      };
      unsubscribeFromSource = nop;
      removeSink = function(sink) {
        return remove(sink, sinks);
      };
      this.push = function(event) {
        var reply, sink, _i, _len, _ref2;
        assertEvent(event);
        _ref2 = cloneArray(sinks);
        for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
          sink = _ref2[_i];
          reply = sink(event);
          if (reply === Bacon.noMore || event.isEnd()) removeSink(sink);
        }
        if (_this.hasSubscribers()) {
          return Bacon.more;
        } else {
          return Bacon.noMore;
        }
      };
      if (handleEvent == null) {
        handleEvent = function(event) {
          return this.push(event);
        };
      }
      this.handleEvent = function(event) {
        assertEvent(event);
        return handleEvent.apply(_this, [event]);
      };
      this.subscribe = function(sink) {
        sinks.push(sink);
        if (sinks.length === 1) {
          unsubscribeFromSource = subscribe(_this.handleEvent);
        }
        assertFunction(unsubscribeFromSource);
        return function() {
          removeSink(sink);
          if (!_this.hasSubscribers()) return unsubscribeFromSource();
        };
      };
    }

    Dispatcher.prototype.toEventStream = function() {
      return new EventStream(this.subscribe);
    };

    Dispatcher.prototype.toString = function() {
      return "Dispatcher";
    };

    return Dispatcher;

  })();

  Bacon.EventStream = EventStream;

  Bacon.Property = Property;

  Bacon.Initial = Initial;

  Bacon.Next = Next;

  Bacon.End = End;

  nop = function() {};

  initial = function(value) {
    return new Initial(value);
  };

  next = function(value) {
    return new Next(value);
  };

  end = function() {
    return new End();
  };

  empty = function(xs) {
    return xs.length === 0;
  };

  head = function(xs) {
    return xs[0];
  };

  tail = function(xs) {
    return xs.slice(1, xs.length);
  };

  cloneArray = function(xs) {
    return xs.slice(0);
  };

  remove = function(x, xs) {
    var i;
    i = xs.indexOf(x);
    if (i >= 0) return xs.splice(i, 1);
  };

  assert = function(message, condition) {
    if (!condition) throw message;
  };

  assertEvent = function(event) {
    assert("not an event : " + event, event.isEvent != null);
    return assert("not event", event.isEvent());
  };

  assertFunction = function(f) {
    return assert("not a function : " + f, typeof f === "function");
  };

}).call(this);
<|endoftext|>