<commit_before>/*!
 * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2013
 * @version 1.0.0
 *
 * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced
 * features including the FileReader API. This plugin is inspired by the blog article at
 * http://www.abeautifulsite.net/blog/2013/08/whipping-file-inputs-into-shape-with-bootstrap-3/
 * and Jasny's File Input plugin http://jasny.github.io/bootstrap/javascript/#fileinput
 *
 * The plugin drastically enhances the file input to preview multiple files on the client before
 * upload. In addition it provides the ability to preview content of images and text files.
 *
 * Author: Kartik Visweswaran
 * Copyright: 2013, Kartik Visweswaran, Krajee.com
 * For more JQuery plugins visit http://plugins.krajee.com
 * For more Yii related demos visit http://demos.krajee.com
 */
(function($) {
    var MAIN_TEMPLATE_1 =
        '{preview}\n' +
        '
\n' +
        '   {caption}\n' +
        '
\n' +
        '       {remove}\n' +
        '       {upload}\n' +
        '       {browse}\n' +
        '
\n' +
        '
';

    var MAIN_TEMPLATE_2 = '{preview}\n{remove}\n{upload}\n{browse}\n';

    var PREVIEW_TEMPLATE =
        '
\n' +
        '

\n' +
        '
×
\n' +
        '

\n' +
        '

' +
        '
';

    var CAPTION_TEMPLATE =
        '
\n' +
        '    \n' +
        '
';

    var isEmpty = function(value, trim) {
        return value === null || value === undefined || value == []
            || value === '' || trim && $.trim(value) === '';
    };
    var getValue = function(options, param, value) {
        return (isEmpty(options) || isEmpty(options[param])) ? value : options[param];
    };
    var isImageFile = function(type, name) {
        return (typeof type !== "undefined") ? type.match('image.*') : name.match(/\.(gif|png|jpe?g)$/i);
    };
    var isTextFile = function(type, name) {
        return (typeof type !== "undefined") ? type.match('text.*') : name.match(/\.(txt|md|csv|htm|html|php|ini)$/i);
    };
    var uniqId = function() {
        return Math.round(new Date().getTime() + (Math.random() * 100));
    };
    var FileInput = function(element, options) {
        this.$element = $(element);
        this.showCaption = options.showCaption;
        this.showPreview = options.showPreview;
        this.showRemove = options.showRemove;
        this.showUpload = options.showUpload;
        this.captionClass = options.captionClass;
        this.previewClass = options.previewClass;
        this.mainClass = options.mainClass;
        if (isEmpty(options.mainTemplate)) {
            this.mainTemplate = this.showCaption ? MAIN_TEMPLATE_1 : MAIN_TEMPLATE_2;
        }
        else {
            this.mainTemplate = options.mainTemplate;
        }
        this.previewTemplate = options.previewTemplate;
        this.captionTemplate = options.captionTemplate;
        this.browseLabel = options.browseLabel;
        this.browseIcon = options.browseIcon;
        this.browseClass = options.browseClass;
        this.removeLabel = options.removeLabel;
        this.removeIcon = options.removeIcon;
        this.removeClass = options.removeClass;
        this.uploadLabel = options.uploadLabel;
        this.uploadIcon = options.uploadIcon;
        this.uploadClass = options.uploadClass;
        this.uploadUrl = options.uploadUrl;
        this.msgLoading = options.msgLoading;
        this.msgProgress = options.msgProgress;
        this.msgSelected = options.msgSelected;
        this.previewFileType = options.previewFileType;
        this.wrapTextLength = options.wrapTextLength;
        this.wrapIndicator = options.wrapIndicator;
        this.isDisabled = this.$element.attr('disabled') || this.$element.attr('readonly');
        if (isEmpty(this.$element.attr('id'))) {
            this.$element.attr('id', uniqId());
        }
        this.$container = this.createContainer();
        /* Initialize plugin option parameters */
        this.$captionContainer = getValue(options, 'elCaptionContainer', this.$container.find('.file-caption'));
        this.$caption = getValue(options, 'elCaptionText', this.$container.find('.file-caption-name'));
        this.$previewContainer = getValue(options, 'elPreviewContainer', this.$container.find('.file-preview'));
        this.$preview = getValue(options, 'elPreviewImage', this.$container.find('.file-preview-thumbnails'));
        this.$previewStatus = getValue(options, 'elPreviewStatus', this.$container.find('.file-preview-status'));
        this.$name = this.$element.attr('name') || options.name;
        this.$hidden = this.$container.find('input[type=hidden][name="' + this.$name + '"]');
        if (this.$hidden.length === 0) {
            this.$hidden = $('<input type="hidden" />');
            this.$container.prepend(this.$hidden);
        }
        this.original = {
            preview: this.$preview.html(),
            hiddenVal: this.$hidden.val()
        };
        this.listen()
    };

    FileInput.prototype = {
        constructor: FileInput,
        listen: function() {
            var self = this;
            self.$element.on('change', $.proxy(self.change, self));
            $(self.$element[0].form).on('reset', $.proxy(self.reset, self));
            self.$container.find('.fileinput-remove').on('click', $.proxy(self.clear, self));
        },
        trigger: function(e) {
            var self = this;
            self.$element.trigger('click');
            e.preventDefault();
        },
        clear: function(e) {
            var self = this;
            if (e) {
                e.preventDefault();
            }

            self.$hidden.val('');
            self.$hidden.attr('name', self.name);
            self.$element.attr('name', '');
            self.$element.val('');
            if (e !== false) {
                self.$element.trigger('change');
                self.$element.trigger('fileclear');
            }
            self.$preview.html('');
            self.$caption.html('');
            self.$container.removeClass('file-input-new').addClass('file-input-new');
        },
        reset: function(e) {
            var self = this;
            self.clear(false);
            self.$hidden.val(self.original.hiddenVal);
            self.$preview.html(self.original.preview);
            self.$container.find('.fileinput-filename').text('');
            self.$element.trigger('filereset');
        },
        change: function(e) {
            var self = this;
            var elem = self.$element, files = elem.get(0).files, numFiles = files ? files.length : 1,
                label = elem.val().replace(/\\/g, '/').replace(/.*\//, ''), preview = self.$preview,
                container = self.$previewContainer, status = self.$previewStatus, msgLoading = self.msgLoading,
                msgProgress = self.msgProgress, msgSelected = self.msgSelected, tfiles,
                fileType = self.previewFileType, wrapLen = parseInt(self.wrapTextLength),
                wrapInd = self.wrapIndicator;

            if (e.target.files === undefined) {
                tfiles = e.target && e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
            }
            else {
                tfiles = e.target.files;
            }
            if (tfiles.length === 0) {
                return;
            }
            preview.html('');
            var total = tfiles.length, self = self;
            for (var i = 0; i < total; i++) {
                (function(file) {
                    var caption = file.name;
                    var isImg = isImageFile(file.type, file.name);
                    var isTxt = isTextFile(file.type, file.name);
                    if (preview.length > 0 && (fileType == "any" ? (isImg || isTxt) : (fileType == "text" ? isTxt : isImg)) && typeof FileReader !== "undefined") {
                        var reader = new FileReader();
                        status.html(msgLoading);
                        container.addClass('loading');
                        reader.onload = function(theFile) {
                            var content = '';
                            if (isTxt) {
                                var strText = theFile.target.result;
                                if (strText.length > wrapLen) {
                                    wrapInd = wrapInd.replace("{title}", strText);
                                    strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
                                }
                                content = '

' + strText + '

';
                            }
                            else {
                                content = '

';
                            }
                            preview.append("\n" + content);
                            if (i >= total - 1) {
                                container.removeClass('loading');
                                status.html('');
                            }
                        };
                        reader.onprogress = function(data) {
                            if (data.lengthComputable) {
                                var progress = parseInt(((data.loaded / data.total) * 100), 10);
                                var msg = msgProgress.replace('{percent}', progress).replace('{file}', file.name);
                                status.html(msg);
                            }
                        };
                        if (isTxt) {
                            reader.readAsText(file);
                        }
                        else {
                            reader.readAsDataURL(file);
                        }
                    }
                    else {
                        preview.append("\n" + '

' + caption + '

');
                    }
                })(tfiles[i]);
            }
            var log = numFiles > 1 ? msgSelected.replace('{n}', numFiles) : label;
            self.$caption.html(log);
            self.$container.removeClass('file-input-new');
            elem.trigger('fileselect', [numFiles, label]);
        },
        createContainer: function() {
            var self = this;
            var container = $(document.createElement("div")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
            self.$element.before(container);
            container.find('.btn-file').append(self.$element);
            return container;
        },
        renderMain: function() {
            var self = this;
            var preview = self.previewTemplate.replace('{class}', self.previewClass);
            var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
            var caption = self.captionTemplate.replace('{class}', css);
            return self.mainTemplate.replace('{class}', self.mainClass).
                replace('{preview}', preview).
                replace('{caption}', caption).
                replace('{upload}', self.renderUpload()).
                replace('{remove}', self.renderRemove()).
                replace('{browse}', self.renderBrowse());
        },
        renderBrowse: function() {
            var self = this, css = self.browseClass + ' btn-file', status = '';
            if (self.isDisabled) {
                status = ' disabled ';
            }
            return '
 ' + self.browseIcon + self.browseLabel + '
';
        },
        renderRemove: function() {
            var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
			if (!self.showRemove) {
				return '';
			}
            if (self.isDisabled) {
                status = ' disabled ';
            }
            return '<button type="button" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
        },
        renderUpload: function() {
            var self = this, content = '', status = '';
			if (!self.showUpload) {
				return '';
			}
            if (self.isDisabled) {
                status = ' disabled ';
            }
            if (isEmpty(self.uploadUrl)) {
                content = '<button type="submit" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
            }
            else {
                content = '' + self.uploadIcon + self.uploadLabel + '';
            }
            return content;
        },
    }

    $.fn.fileinput = function(options) {
        return this.each(function() {
            var $this = $(this), data = $this.data('fileinput')
            if (!data) {
                $this.data('fileinput', (data = new FileInput(this, options)))
            }
            if (typeof options == 'string') {
                data[options]()
            }
        })
    };

    //FileInput plugin definition
    $.fn.fileinput = function(option) {
        var args = Array.apply(null, arguments);
        args.shift();
        return this.each(function() {
            var $this = $(this),
                data = $this.data('fileinput'),
                options = typeof option === 'object' && option;

            if (!data) {
                $this.data('fileinput', (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
            }

            if (typeof option === 'string') {
                data[option].apply(data, args);
            }
        });
    };

    $.fn.fileinput.defaults = {
        showCaption: true,
        showPreview: true,
        showRemove: true,
        showUpload: true,
        captionClass: '',
        previewClass: '',
        mainClass: '',
        mainTemplate: null,
        previewTemplate: PREVIEW_TEMPLATE,
        captionTemplate: CAPTION_TEMPLATE,
        browseLabel: 'Browse …',
        browseIcon: '  ',
        browseClass: 'btn btn-primary',
        removeLabel: 'Remove',
        removeIcon: ' ',
        removeClass: 'btn btn-default',
        uploadLabel: 'Upload',
        uploadIcon: ' ',
        uploadClass: 'btn btn-default',
        uploadUrl: null,
        msgLoading: 'Loading …',
        msgProgress: 'Loaded {percent}% of {file}',
        msgSelected: '{n} files selected',
        previewFileType: 'image',
        wrapTextLength: 250,
        wrapIndicator: ' […]',
        elCaptionContainer: null,
        elCaptionText: null,
        elPreviewContainer: null,
        elPreviewImage: null,
        elPreviewStatus: null
    };

    /**
     * Convert automatically file inputs with class 'file'
     * into a bootstrap fileinput control.
     */
    $(function() {
        var $element = $('input.file[type=file]');
        if ($element.length > 0) {
            $element.fileinput();
        }
    });

})(window.jQuery);<commit_msg>Updated buttons display condition<commit_after>/*!
 * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2013
 * @version 1.0.0
 *
 * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced
 * features including the FileReader API. This plugin is inspired by the blog article at
 * http://www.abeautifulsite.net/blog/2013/08/whipping-file-inputs-into-shape-with-bootstrap-3/
 * and Jasny's File Input plugin http://jasny.github.io/bootstrap/javascript/#fileinput
 *
 * The plugin drastically enhances the file input to preview multiple files on the client before
 * upload. In addition it provides the ability to preview content of images and text files.
 *
 * Author: Kartik Visweswaran
 * Copyright: 2013, Kartik Visweswaran, Krajee.com
 * For more JQuery plugins visit http://plugins.krajee.com
 * For more Yii related demos visit http://demos.krajee.com
 */
(function ($) {
	var MAIN_TEMPLATE_1 =
		'{preview}\n' +
			'
\n' +
			'   {caption}\n' +
			'
\n' +
			'       {remove}\n' +
			'       {upload}\n' +
			'       {browse}\n' +
			'
\n' +
			'
';

	var MAIN_TEMPLATE_2 = '{preview}\n{remove}\n{upload}\n{browse}\n';

	var PREVIEW_TEMPLATE =
		'
\n' +
			'

\n' +
			'
×
\n' +
			'

\n' +
			'

' +
			'
';

	var CAPTION_TEMPLATE =
		'
\n' +
			'    \n' +
			'
';

	var isEmpty = function (value, trim) {
		return value === null || value === undefined || value == []
			|| value === '' || trim && $.trim(value) === '';
	};
	var getValue = function (options, param, value) {
		return (isEmpty(options) || isEmpty(options[param])) ? value : options[param];
	};
	var isImageFile = function (type, name) {
		return (typeof type !== "undefined") ? type.match('image.*') : name.match(/\.(gif|png|jpe?g)$/i);
	};
	var isTextFile = function (type, name) {
		return (typeof type !== "undefined") ? type.match('text.*') : name.match(/\.(txt|md|csv|htm|html|php|ini)$/i);
	};
	var uniqId = function () {
		return Math.round(new Date().getTime() + (Math.random() * 100));
	};
	var FileInput = function (element, options) {
		this.$element = $(element);
		this.showCaption = options.showCaption;
		this.showPreview = options.showPreview;
		this.showRemove = options.showRemove;
		this.showUpload = options.showUpload;
		this.captionClass = options.captionClass;
		this.previewClass = options.previewClass;
		this.mainClass = options.mainClass;
		if (isEmpty(options.mainTemplate)) {
			this.mainTemplate = this.showCaption ? MAIN_TEMPLATE_1 : MAIN_TEMPLATE_2;
		}
		else {
			this.mainTemplate = options.mainTemplate;
		}
		this.previewTemplate = options.previewTemplate;
		this.captionTemplate = options.captionTemplate;
		this.browseLabel = options.browseLabel;
		this.browseIcon = options.browseIcon;
		this.browseClass = options.browseClass;
		this.removeLabel = options.removeLabel;
		this.removeIcon = options.removeIcon;
		this.removeClass = options.removeClass;
		this.uploadLabel = options.uploadLabel;
		this.uploadIcon = options.uploadIcon;
		this.uploadClass = options.uploadClass;
		this.uploadUrl = options.uploadUrl;
		this.msgLoading = options.msgLoading;
		this.msgProgress = options.msgProgress;
		this.msgSelected = options.msgSelected;
		this.previewFileType = options.previewFileType;
		this.wrapTextLength = options.wrapTextLength;
		this.wrapIndicator = options.wrapIndicator;
		this.isDisabled = this.$element.attr('disabled') || this.$element.attr('readonly');
		if (isEmpty(this.$element.attr('id'))) {
			this.$element.attr('id', uniqId());
		}
		this.$container = this.createContainer();
		/* Initialize plugin option parameters */
		this.$captionContainer = getValue(options, 'elCaptionContainer', this.$container.find('.file-caption'));
		this.$caption = getValue(options, 'elCaptionText', this.$container.find('.file-caption-name'));
		this.$previewContainer = getValue(options, 'elPreviewContainer', this.$container.find('.file-preview'));
		this.$preview = getValue(options, 'elPreviewImage', this.$container.find('.file-preview-thumbnails'));
		this.$previewStatus = getValue(options, 'elPreviewStatus', this.$container.find('.file-preview-status'));
		this.$name = this.$element.attr('name') || options.name;
		this.$hidden = this.$container.find('input[type=hidden][name="' + this.$name + '"]');
		if (this.$hidden.length === 0) {
			this.$hidden = $('<input type="hidden" />');
			this.$container.prepend(this.$hidden);
		}
		this.original = {
			preview: this.$preview.html(),
			hiddenVal: this.$hidden.val()
		};
		this.listen()
	};

	FileInput.prototype = {
		constructor: FileInput,
		listen: function () {
			var self = this;
			self.$element.on('change', $.proxy(self.change, self));
			$(self.$element[0].form).on('reset', $.proxy(self.reset, self));
			self.$container.find('.fileinput-remove').on('click', $.proxy(self.clear, self));
		},
		trigger: function (e) {
			var self = this;
			self.$element.trigger('click');
			e.preventDefault();
		},
		clear: function (e) {
			var self = this;
			if (e) {
				e.preventDefault();
			}

			self.$hidden.val('');
			self.$hidden.attr('name', self.name);
			self.$element.attr('name', '');
			self.$element.val('');
			if (e !== false) {
				self.$element.trigger('change');
				self.$element.trigger('fileclear');
			}
			self.$preview.html('');
			self.$caption.html('');
			self.$container.removeClass('file-input-new').addClass('file-input-new');
		},
		reset: function (e) {
			var self = this;
			self.clear(false);
			self.$hidden.val(self.original.hiddenVal);
			self.$preview.html(self.original.preview);
			self.$container.find('.fileinput-filename').text('');
			self.$element.trigger('filereset');
		},
		change: function (e) {
			var self = this;
			var elem = self.$element, files = elem.get(0).files, numFiles = files ? files.length : 1,
				label = elem.val().replace(/\\/g, '/').replace(/.*\//, ''), preview = self.$preview,
				container = self.$previewContainer, status = self.$previewStatus, msgLoading = self.msgLoading,
				msgProgress = self.msgProgress, msgSelected = self.msgSelected, tfiles,
				fileType = self.previewFileType, wrapLen = parseInt(self.wrapTextLength),
				wrapInd = self.wrapIndicator;

			if (e.target.files === undefined) {
				tfiles = e.target && e.target.value ? [
					{name: e.target.value.replace(/^.+\\/, '')}
				] : [];
			}
			else {
				tfiles = e.target.files;
			}
			if (tfiles.length === 0) {
				return;
			}
			preview.html('');
			var total = tfiles.length, self = self;
			for (var i = 0; i < total; i++) {
				(function (file) {
					var caption = file.name;
					var isImg = isImageFile(file.type, file.name);
					var isTxt = isTextFile(file.type, file.name);
					if (preview.length > 0 && (fileType == "any" ? (isImg || isTxt) : (fileType == "text" ? isTxt : isImg)) && typeof FileReader !== "undefined") {
						var reader = new FileReader();
						status.html(msgLoading);
						container.addClass('loading');
						reader.onload = function (theFile) {
							var content = '';
							if (isTxt) {
								var strText = theFile.target.result;
								if (strText.length > wrapLen) {
									wrapInd = wrapInd.replace("{title}", strText);
									strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
								}
								content = '

' + strText + '

';
							}
							else {
								content = '

';
							}
							preview.append("\n" + content);
							if (i >= total - 1) {
								container.removeClass('loading');
								status.html('');
							}
						};
						reader.onprogress = function (data) {
							if (data.lengthComputable) {
								var progress = parseInt(((data.loaded / data.total) * 100), 10);
								var msg = msgProgress.replace('{percent}', progress).replace('{file}', file.name);
								status.html(msg);
							}
						};
						if (isTxt) {
							reader.readAsText(file);
						}
						else {
							reader.readAsDataURL(file);
						}
					}
					else {
						preview.append("\n" + '

' + caption + '

');
					}
				})(tfiles[i]);
			}
			var log = numFiles > 1 ? msgSelected.replace('{n}', numFiles) : label;
			self.$caption.html(log);
			self.$container.removeClass('file-input-new');
			elem.trigger('fileselect', [numFiles, label]);
		},
		createContainer: function () {
			var self = this;
			var container = $(document.createElement("div")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
			self.$element.before(container);
			container.find('.btn-file').append(self.$element);
			return container;
		},
		renderMain: function () {
			var self = this;
			var preview = self.previewTemplate.replace('{class}', self.previewClass);
			var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
			var caption = self.captionTemplate.replace('{class}', css);
			return self.mainTemplate.replace('{class}', self.mainClass).
				replace('{preview}', preview).
				replace('{caption}', caption).
				replace('{upload}', self.renderUpload()).
				replace('{remove}', self.renderRemove()).
				replace('{browse}', self.renderBrowse());
		},
		renderBrowse: function () {
			var self = this, css = self.browseClass + ' btn-file', status = '';
			if (self.isDisabled) {
				status = ' disabled ';
			}
			return '
 ' + self.browseIcon + self.browseLabel + '
';
		},
		renderRemove: function () {
			var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
			if (!self.showRemove) {
				return '';
			}
			if (self.isDisabled) {
				status = ' disabled ';
			}
			return '<button type="button" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
		},
		renderUpload: function () {
			var self = this, content = '', status = '';
			if (!self.showUpload) {
				return '';
			}
			if (self.isDisabled) {
				status = ' disabled ';
			}
			if (isEmpty(self.uploadUrl)) {
				content = '<button type="submit" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
			}
			else {
				content = '' + self.uploadIcon + self.uploadLabel + '';
			}
			return content;
		},
	}

	$.fn.fileinput = function (options) {
		return this.each(function () {
			var $this = $(this), data = $this.data('fileinput')
			if (!data) {
				$this.data('fileinput', (data = new FileInput(this, options)))
			}
			if (typeof options == 'string') {
				data[options]()
			}
		})
	};

	//FileInput plugin definition
	$.fn.fileinput = function (option) {
		var args = Array.apply(null, arguments);
		args.shift();
		return this.each(function () {
			var $this = $(this),
				data = $this.data('fileinput'),
				options = typeof option === 'object' && option;

			if (!data) {
				$this.data('fileinput', (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
			}

			if (typeof option === 'string') {
				data[option].apply(data, args);
			}
		});
	};

	$.fn.fileinput.defaults = {
		showCaption: true,
		showPreview: true,
		showRemove: true,
		showUpload: true,
		captionClass: '',
		previewClass: '',
		mainClass: '',
		mainTemplate: null,
		previewTemplate: PREVIEW_TEMPLATE,
		captionTemplate: CAPTION_TEMPLATE,
		browseLabel: 'Browse …',
		browseIcon: '  ',
		browseClass: 'btn btn-primary',
		removeLabel: 'Remove',
		removeIcon: ' ',
		removeClass: 'btn btn-default',
		uploadLabel: 'Upload',
		uploadIcon: ' ',
		uploadClass: 'btn btn-default',
		uploadUrl: null,
		msgLoading: 'Loading …',
		msgProgress: 'Loaded {percent}% of {file}',
		msgSelected: '{n} files selected',
		previewFileType: 'image',
		wrapTextLength: 250,
		wrapIndicator: ' […]',
		elCaptionContainer: null,
		elCaptionText: null,
		elPreviewContainer: null,
		elPreviewImage: null,
		elPreviewStatus: null
	};

	/**
	 * Convert automatically file inputs with class 'file'
	 * into a bootstrap fileinput control.
	 */
	$(function () {
		var $element = $('input.file[type=file]');
		if ($element.length > 0) {
			$element.fileinput();
		}
	});

})(window.jQuery);<|endoftext|>


<commit_before>import { SYNC_RENDER, NO_RENDER, FORCE_RENDER, ASYNC_RENDER, ATTR_KEY } from '../constants';
import options from '../options';
import { extend } from '../util';
import { enqueueRender } from '../render-queue';
import { getNodeProps } from './index';
import { diff, mounts, diffLevel, flushMounts, recollectNodeTree, removeChildren } from './diff';
import { createComponent, collectComponent } from './component-recycler';

/** Set a component's `props` (generally derived from JSX attributes).
 *	@param {Object} props
 *	@param {Object} [opts]
 *	@param {boolean} [opts.renderSync=false]	If `true` and {@link options.syncComponentUpdates} is `true`, triggers synchronous rendering.
 *	@param {boolean} [opts.render=true]			If `false`, no render will be triggered.
 */
export function setComponentProps(component, props, opts, context, mountAll) {
	if (component._disable) return;
	component._disable = true;

	if ((component.__ref = props.ref)) delete props.ref;
	if ((component.__key = props.key)) delete props.key;

	if (!component.base || mountAll) {
		if (component.componentWillMount) component.componentWillMount();
	}
	else if (component.componentWillReceiveProps) {
		component.componentWillReceiveProps(props, context);
	}

	if (context && context!==component.context) {
		if (!component.prevContext) component.prevContext = component.context;
		component.context = context;
	}

	if (!component.prevProps) component.prevProps = component.props;
	component.props = props;

	component._disable = false;

	if (opts!==NO_RENDER) {
		if (opts===SYNC_RENDER || options.syncComponentUpdates!==false || !component.base) {
			renderComponent(component, SYNC_RENDER, mountAll);
		}
		else {
			enqueueRender(component);
		}
	}

	if (component.__ref) component.__ref(component);
}

/** Render a Component, triggering necessary lifecycle events and taking High-Order Components into account.
 *	@param {Component} component
 *	@param {Object} [opts]
 *	@param {boolean} [opts.build=false]		If `true`, component will build and store a DOM node if not already associated with one.
 *	@private
 */
export function renderComponent(component, opts, mountAll, isChild) {
	if (component._disable) return;

	let skip, rendered,
		props = component.props,
		state = component.state,
		context = component.context,
		previousProps = component.prevProps || props,
		previousState = component.prevState || state,
		previousContext = component.prevContext || context,
		isUpdate = component.base,
		nextBase = component.nextBase,
		initialBase = isUpdate || nextBase,
		initialChildComponent = component._component,
		inst, cbase;

	// if updating
	if (isUpdate) {
		component.props = previousProps;
		component.state = previousState;
		component.context = previousContext;
		if (opts!==FORCE_RENDER
			&& component.shouldComponentUpdate
			&& component.shouldComponentUpdate(props, state, context) === false) {
			skip = true;
		}
		else if (component.componentWillUpdate) {
			component.componentWillUpdate(props, state, context);
		}
		component.props = props;
		component.state = state;
		component.context = context;
	}

	component.prevProps = component.prevState = component.prevContext = component.nextBase = null;
	component._dirty = false;

	if (!skip) {
		if (component.render) rendered = component.render(props, state, context);

		// context to pass to the child, can be updated via (grand-)parent component
		if (component.getChildContext) {
			context = extend(extend({}, context), component.getChildContext());
		}

		let childComponent = rendered && rendered.nodeName,
			toUnmount, base;

		if (typeof childComponent==='function') {
			// set up high order component link

			let childProps = getNodeProps(rendered);
			inst = initialChildComponent;

			if (inst && inst.constructor===childComponent && childProps.key==inst.__key) {
				setComponentProps(inst, childProps, SYNC_RENDER, context, false);
			}
			else {
				toUnmount = inst;

				inst = createComponent(childComponent, childProps, context);
				inst.nextBase = inst.nextBase || nextBase;
				inst._parentComponent = component;
				component._component = inst;
				setComponentProps(inst, childProps, NO_RENDER, context, false);
				renderComponent(inst, SYNC_RENDER, mountAll, true);
			}

			base = inst.base;
		}
		else {
			cbase = initialBase;

			// destroy high order component link
			toUnmount = initialChildComponent;
			if (toUnmount) {
				cbase = component._component = null;
			}

			if (initialBase || opts===SYNC_RENDER) {
				if (cbase) cbase._component = null;
				base = diff(cbase, rendered, context, mountAll || !isUpdate, initialBase && initialBase.parentNode, true);
			}
		}

		if (initialBase && base!==initialBase && inst!==initialChildComponent) {
			let baseParent = initialBase.parentNode;
			if (baseParent && base!==baseParent) {
				baseParent.replaceChild(base, initialBase);

				if (!toUnmount) {
					initialBase._component = null;
					recollectNodeTree(initialBase, false);
				}
			}
		}

		if (toUnmount) {
			unmountComponent(toUnmount);
		}

		component.base = base;
		if (base && !isChild) {
			let componentRef = component,
				t = component;
			while ((t=t._parentComponent)) {
				(componentRef = t).base = base;
			}
			base._component = componentRef;
			base._componentConstructor = componentRef.constructor;
		}
	}

	if (!isUpdate || mountAll) {
		mounts.unshift(component);
	}
	else if (!skip) {
		if (component.componentDidUpdate) {
			component.componentDidUpdate(previousProps, previousState, previousContext);
		}
		if (options.afterUpdate) options.afterUpdate(component);
	}

	let cb = component._renderCallbacks, fn;
	if (cb) while ( (fn = cb.pop()) ) fn.call(component);

	if (!diffLevel && !isChild) flushMounts();
}

/** Apply the Component referenced by a VNode to the DOM.
 *	@param {Element} dom	The DOM node to mutate
 *	@param {VNode} vnode	A Component-referencing VNode
 *	@returns {Element} dom	The created/mutated element
 *	@private
 */
export function buildComponentFromVNode(dom, vnode, context, mountAll) {
	let c = dom && dom._component,
		originalComponent = c,
		oldDom = dom,
		isDirectOwner = c && dom._componentConstructor===vnode.nodeName,
		isOwner = isDirectOwner,
		props = getNodeProps(vnode);
	while (c && !isOwner && (c=c._parentComponent)) {
		isOwner = c.constructor===vnode.nodeName;
	}

	if (c && isOwner && (!mountAll || c._component)) {
		setComponentProps(c, props, ASYNC_RENDER, context, mountAll);
		dom = c.base;
	}
	else {
		if (originalComponent && !isDirectOwner) {
			unmountComponent(originalComponent);
			dom = oldDom = null;
		}

		c = createComponent(vnode.nodeName, props, context);
		if (dom && !c.nextBase) {
			c.nextBase = dom;
			// passing dom/oldDom as nextBase will recycle it if unused, so bypass recycling on L241:
			oldDom = null;
		}
		setComponentProps(c, props, SYNC_RENDER, context, mountAll);
		dom = c.base;

		if (oldDom && dom!==oldDom) {
			oldDom._component = null;
			recollectNodeTree(oldDom, false);
		}
	}

	return dom;
}

/** Remove a component from the DOM and recycle it.
 *	@param {Element} dom			A DOM node from which to unmount the given Component
 *	@param {Component} component	The Component instance to unmount
 *	@private
 */
export function unmountComponent(component) {
	if (options.beforeUnmount) options.beforeUnmount(component);

	// console.log(`${remove?'Removing':'Unmounting'} component: ${component.constructor.name}`);
	let base = component.base;

	component._disable = true;

	if (component.componentWillUnmount) component.componentWillUnmount();

	component.base = null;

	// recursively tear down & recollect high-order component children:
	let inner = component._component;
	if (inner) {
		unmountComponent(inner);
	}
	else if (base) {
		if (base[ATTR_KEY] && base[ATTR_KEY].ref) base[ATTR_KEY].ref(null);

		component.nextBase = base;

		base.remove();
		collectComponent(component);

		removeChildren(base);
		// removeOrphanedChildren(base.childNodes, true);
	}

	if (component.__ref) component.__ref(null);
	if (component.componentDidUnmount) component.componentDidUnmount();
}
<commit_msg>Small optimizations for `renderComponent()`<commit_after>import { SYNC_RENDER, NO_RENDER, FORCE_RENDER, ASYNC_RENDER, ATTR_KEY } from '../constants';
import options from '../options';
import { extend } from '../util';
import { enqueueRender } from '../render-queue';
import { getNodeProps } from './index';
import { diff, mounts, diffLevel, flushMounts, recollectNodeTree, removeChildren } from './diff';
import { createComponent, collectComponent } from './component-recycler';

/** Set a component's `props` (generally derived from JSX attributes).
 *	@param {Object} props
 *	@param {Object} [opts]
 *	@param {boolean} [opts.renderSync=false]	If `true` and {@link options.syncComponentUpdates} is `true`, triggers synchronous rendering.
 *	@param {boolean} [opts.render=true]			If `false`, no render will be triggered.
 */
export function setComponentProps(component, props, opts, context, mountAll) {
	if (component._disable) return;
	component._disable = true;

	if ((component.__ref = props.ref)) delete props.ref;
	if ((component.__key = props.key)) delete props.key;

	if (!component.base || mountAll) {
		if (component.componentWillMount) component.componentWillMount();
	}
	else if (component.componentWillReceiveProps) {
		component.componentWillReceiveProps(props, context);
	}

	if (context && context!==component.context) {
		if (!component.prevContext) component.prevContext = component.context;
		component.context = context;
	}

	if (!component.prevProps) component.prevProps = component.props;
	component.props = props;

	component._disable = false;

	if (opts!==NO_RENDER) {
		if (opts===SYNC_RENDER || options.syncComponentUpdates!==false || !component.base) {
			renderComponent(component, SYNC_RENDER, mountAll);
		}
		else {
			enqueueRender(component);
		}
	}

	if (component.__ref) component.__ref(component);
}

/** Render a Component, triggering necessary lifecycle events and taking High-Order Components into account.
 *	@param {Component} component
 *	@param {Object} [opts]
 *	@param {boolean} [opts.build=false]		If `true`, component will build and store a DOM node if not already associated with one.
 *	@private
 */
export function renderComponent(component, opts, mountAll, isChild) {
	if (component._disable) return;

	let props = component.props,
		state = component.state,
		context = component.context,
		previousProps = component.prevProps || props,
		previousState = component.prevState || state,
		previousContext = component.prevContext || context,
		isUpdate = component.base,
		nextBase = component.nextBase,
		initialBase = isUpdate || nextBase,
		initialChildComponent = component._component,
		skip = false,
		rendered, inst, cbase;

	// if updating
	if (isUpdate) {
		component.props = previousProps;
		component.state = previousState;
		component.context = previousContext;
		if (opts!==FORCE_RENDER
			&& component.shouldComponentUpdate
			&& component.shouldComponentUpdate(props, state, context) === false) {
			skip = true;
		}
		else if (component.componentWillUpdate) {
			component.componentWillUpdate(props, state, context);
		}
		component.props = props;
		component.state = state;
		component.context = context;
	}

	component.prevProps = component.prevState = component.prevContext = component.nextBase = null;
	component._dirty = false;

	if (!skip) {
		rendered = component.render(props, state, context);

		// context to pass to the child, can be updated via (grand-)parent component
		if (component.getChildContext) {
			context = extend(extend({}, context), component.getChildContext());
		}

		let childComponent = rendered && rendered.nodeName,
			toUnmount, base;

		if (typeof childComponent==='function') {
			// set up high order component link

			let childProps = getNodeProps(rendered);
			inst = initialChildComponent;

			if (inst && inst.constructor===childComponent && childProps.key==inst.__key) {
				setComponentProps(inst, childProps, SYNC_RENDER, context, false);
			}
			else {
				toUnmount = inst;

				component._component = inst = createComponent(childComponent, childProps, context);
				inst.nextBase = inst.nextBase || nextBase;
				inst._parentComponent = component;
				setComponentProps(inst, childProps, NO_RENDER, context, false);
				renderComponent(inst, SYNC_RENDER, mountAll, true);
			}

			base = inst.base;
		}
		else {
			cbase = initialBase;

			// destroy high order component link
			toUnmount = initialChildComponent;
			if (toUnmount) {
				cbase = component._component = null;
			}

			if (initialBase || opts===SYNC_RENDER) {
				if (cbase) cbase._component = null;
				base = diff(cbase, rendered, context, mountAll || !isUpdate, initialBase && initialBase.parentNode, true);
			}
		}

		if (initialBase && base!==initialBase && inst!==initialChildComponent) {
			let baseParent = initialBase.parentNode;
			if (baseParent && base!==baseParent) {
				baseParent.replaceChild(base, initialBase);

				if (!toUnmount) {
					initialBase._component = null;
					recollectNodeTree(initialBase, false);
				}
			}
		}

		if (toUnmount) {
			unmountComponent(toUnmount);
		}

		component.base = base;
		if (base && !isChild) {
			let componentRef = component,
				t = component;
			while ((t=t._parentComponent)) {
				(componentRef = t).base = base;
			}
			base._component = componentRef;
			base._componentConstructor = componentRef.constructor;
		}
	}

	if (!isUpdate || mountAll) {
		mounts.unshift(component);
	}
	else if (!skip) {
		if (component.componentDidUpdate) {
			component.componentDidUpdate(previousProps, previousState, previousContext);
		}
		if (options.afterUpdate) options.afterUpdate(component);
	}

	if (component._renderCallbacks!=null) {
		while (component._renderCallbacks.length) component._renderCallbacks.pop().call(component);
	}

	if (!diffLevel && !isChild) flushMounts();
}

/** Apply the Component referenced by a VNode to the DOM.
 *	@param {Element} dom	The DOM node to mutate
 *	@param {VNode} vnode	A Component-referencing VNode
 *	@returns {Element} dom	The created/mutated element
 *	@private
 */
export function buildComponentFromVNode(dom, vnode, context, mountAll) {
	let c = dom && dom._component,
		originalComponent = c,
		oldDom = dom,
		isDirectOwner = c && dom._componentConstructor===vnode.nodeName,
		isOwner = isDirectOwner,
		props = getNodeProps(vnode);
	while (c && !isOwner && (c=c._parentComponent)) {
		isOwner = c.constructor===vnode.nodeName;
	}

	if (c && isOwner && (!mountAll || c._component)) {
		setComponentProps(c, props, ASYNC_RENDER, context, mountAll);
		dom = c.base;
	}
	else {
		if (originalComponent && !isDirectOwner) {
			unmountComponent(originalComponent);
			dom = oldDom = null;
		}

		c = createComponent(vnode.nodeName, props, context);
		if (dom && !c.nextBase) {
			c.nextBase = dom;
			// passing dom/oldDom as nextBase will recycle it if unused, so bypass recycling on L241:
			oldDom = null;
		}
		setComponentProps(c, props, SYNC_RENDER, context, mountAll);
		dom = c.base;

		if (oldDom && dom!==oldDom) {
			oldDom._component = null;
			recollectNodeTree(oldDom, false);
		}
	}

	return dom;
}

/** Remove a component from the DOM and recycle it.
 *	@param {Element} dom			A DOM node from which to unmount the given Component
 *	@param {Component} component	The Component instance to unmount
 *	@private
 */
export function unmountComponent(component) {
	if (options.beforeUnmount) options.beforeUnmount(component);

	// console.log(`${remove?'Removing':'Unmounting'} component: ${component.constructor.name}`);
	let base = component.base;

	component._disable = true;

	if (component.componentWillUnmount) component.componentWillUnmount();

	component.base = null;

	// recursively tear down & recollect high-order component children:
	let inner = component._component;
	if (inner) {
		unmountComponent(inner);
	}
	else if (base) {
		if (base[ATTR_KEY] && base[ATTR_KEY].ref) base[ATTR_KEY].ref(null);

		component.nextBase = base;

		base.remove();
		collectComponent(component);

		removeChildren(base);
		// removeOrphanedChildren(base.childNodes, true);
	}

	if (component.__ref) component.__ref(null);
	if (component.componentDidUnmount) component.componentDidUnmount();
}
<|endoftext|>


<commit_before>try {
  window;
} catch(e) {
  var BUTTONS = require('./input');
}

function Character(team, spawnPoint) {
  this.breakingCoefficient = 0.025;
  this.accelerationCoefficient = 0.012;
  this.MAX_HP = 10;
  this.team = team;
  this.onCP = false;
  this.kills = 0;
  this.deaths = 0;
  this.captures = 0;
  this.init(spawnPoint);
}

Character.MAX_SHIELD_ARC = 0.2 * Math.PI;
Character.OVERHEAT_THRESHOLD = 1.5;
Character.BODY_RADIUS = 0.6;

Character.prototype.init = function(spawnPoint) {
  if (spawnPoint) {
    this.x = spawnPoint.x;
    this.y = spawnPoint.y;
    this.timeDied = null;
    this.timeToRespawn = 0;
  } else {
    this.x = 32;
    this.y = 32;
    this.timeDied = +new Date();
    this.timeToRespawn = this.getTimeUntilRespawn(this.timeDied);
  }

  this.dx = 0;
  this.dy = 0;
  this.hp = this.MAX_HP;
  this.isShieldActive = false;
  this.fireCooldown = 0;
  this.shieldEnergy = 1;
  this.weaponHeat = 0;
  this.overheated = false;
  this.points = 0;
  this.respawnTime = 4000;
};

Character.prototype.getState = function() {
  return {
    t: 'C',
    x: this.x,
    y: this.y,
    hp: this.hp,
    kills: this.kills,
    deaths: this.deaths,
    captures: this.captures,
    mouseDirection: this.mouseDirection,
    isShieldActive: this.isShieldActive,
    shieldEnergy: this.shieldEnergy,
    team: this.team,
    weaponHeat: this.weaponHeat,
    overheated: this.overheated,
    respawnTime: this.respawnTime,
    timeDied: this.timeDied,
    timeToRespawn: this.timeToRespawn
  };
};

Character.prototype.hit = function(bullet, soundsToPlay) {
  if (bullet.team == this.team){
    return;
  }

  if (this.canShieldTakeBullet(bullet)) {
    this.shieldEnergy -= 0.45;
    var shieldSoundIndex = Math.floor(3 * Math.random()) + 1;
    soundsToPlay['shield-hit-' + shieldSoundIndex + '.mp3'] = true;
  } else {
    this.dx += bullet.dx;
    this.dy += bullet.dy;

    this.hp --;
    if (this.hp <= 0){
      this.deaths++;
      if(bullet.character){
        bullet.character.killed(this);
      }
      this.die();
    }
  }
};

Character.prototype.killed = function(enemy){
  //YEEY
  this.kills++;
};

Character.prototype.die = function(){
  this.hp = 0;
  this.timeDied = +new Date();
  this.respawnTime = 1000 + this.points * 0.3;
};

Character.prototype.canShieldTakeBullet = function(bullet) {
  if (!this.isShieldActive) {
    return false;
  }
  var mouseDirection = this.mouseDirection;
  if (mouseDirection < 0) {
    mouseDirection += 2 * Math.PI;
  }
  var oppositeShieldDirection = mouseDirection + Math.PI;
  var minShieldDirection = oppositeShieldDirection - Character.MAX_SHIELD_ARC * Math.max(this.shieldEnergy, 0);
  var maxShieldDirection = oppositeShieldDirection + Character.MAX_SHIELD_ARC * Math.max(this.shieldEnergy, 0);
  var bulletDirection = bullet.direction + 2 * Math.PI;
  return bulletDirection <= maxShieldDirection && bulletDirection >= minShieldDirection;
};

Character.prototype.getTimeUntilRespawn = function(timeDied) {
  var currentTime = +new Date();
  return Math.max(timeDied + this.respawnTime - currentTime, 0);
};

var defaultSpawn = [{x:5, y:32}, {x:55, y:32}];
Character.getDefaultPoint = function(team) {
  return defaultSpawn[team];
};

Character.getClosestSpawnPoint = function(team, character, capturePoints) {
  var spawnPoint = defaultSpawn[team];
  var dist = 999999; //bigger than map.
  for (var i = 0; i < capturePoints.length; i++) {
    var capturePoint = capturePoints[i];
    if (team === 0 && capturePoint.ownage_d === -1 || team === 1 && capturePoint.ownage_d === 1) {
      if(capturePoint.sqDistanceTo(character) < dist){
        spawnPoint = capturePoint;
      }
    }
  }
  return spawnPoint;
};
Character.prototype.update = function(input, walls, utility, capturePoints, points) {
  this.points = points;
  if (this.timeDied) {
    this.timeToRespawn = this.getTimeUntilRespawn(this.timeDied);
    if (this.timeToRespawn <= 0) {
      var spawnPoint = Character.getClosestSpawnPoint(this.team,this, capturePoints);
      if (spawnPoint) {
        this.init(spawnPoint);
      }
    }
    return;
  }

  this.applyMovementForce(input);
  this.applyFrictionForce();
  this.mouseDirection = input[BUTTONS.MOUSE_DIR];

  this.isShieldActive = input[BUTTONS.ALTERNATE_FIRE];
  this.shieldEnergy += 0.003;
  if (this.shieldEnergy > 1) {
    this.shieldEnergy = 1;
  }

  this.weaponHeat -= this.overheated ? 0.005 : 0.01;
  if (this.weaponHeat < 0) {
    this.weaponHeat = 0;
  }
  if (this.weaponHeat < 1) {
    this.overheated = false;
  }

  for(var i = 0; i < walls.length; i++) {
    if(utility.intersectLineCircle(walls[i].start_x, walls[i].start_y, walls[i].end_x, walls[i].end_y, this.x, this.y, Character.BODY_RADIUS)) {
      var p = walls[i].getPushVector(this.x, this.y, Character.BODY_RADIUS);

      //Decompose velocity!
      var newDx = 0;
      var newDy = 0;

      var p_l = Math.sqrt(p.x * p.x + p.y * p.y);
      if(p_l > 0.0001){
        p = { x: p.x/p_l, y: p.y / p_l }

        var newSpeed = p.x * this.dx + p.y * this.dy;
        if(newSpeed > 0){ //Moving away from wall. this is ok.
          newDx += p.x * newSpeed;
          newDy += p.y * newSpeed;
        }

      }

      var n = { x: -p.y, y: p.x };
      var n_l = Math.sqrt(n.x * n.x + n.y * n.y);
      if(n_l > 0.0001){
        n = { x: n.x/n_l, y: n.y / n_l }

        var newSpeed = n.x * this.dx + n.y * this.dy;
        newDx += n.x * newSpeed;
        newDy += n.y * newSpeed;
      }

      this.dx = newDx;
      this.dy = newDy;
    }
  }

  this.x += this.dx;
  this.y += this.dy;

  // stay within bounds
  if (this.x < 0) {
    this.x = 0;
  } else if (this.x > 64) {
    this.x = 64;
  }
  if (this.y < 0) {
    this.y = 0;
  } else if (this.y > 64) {
    this.y = 64;
  }
};

Character.prototype.applyMovementForce = function(input) {
  var fx = 0;
  var fy = 0;
  if (input[BUTTONS.MOVE_UP]) { // W
    fy += -1;
  }
  if (input[BUTTONS.MOVE_DOWN]) { // S
    fy += 1;
  }
  if (input[BUTTONS.MOVE_LEFT]) { // A
    fx += -1;
  }
  if (input[BUTTONS.MOVE_RIGHT]) { // D
    fx += 1;
  }

  if (fx || fy) {
    var targetDirection = Math.atan2(fy, fx);

    fx = this.accelerationCoefficient * Math.cos(targetDirection);
    fy = this.accelerationCoefficient * Math.sin(targetDirection);

    this.dx += fx;
    this.dy += fy;
  }
};

Character.prototype.getCurrentDirection = function() {
  return Math.atan2(this.dy, this.dx);
};

Character.prototype.applyFrictionForce = function() {
  var currentDirection = this.getCurrentDirection();
  var currentSpeed = Math.sqrt(Math.pow(this.dx, 2) + Math.pow(this.dy, 2));
  var activeShieldFactor = this.isShieldActive ? 2.2 : 1; // more friction while shield is active
  var frictionScalar = - activeShieldFactor * this.breakingCoefficient * Math.pow(currentSpeed * 5 +.15, 2);
  var breakFx = frictionScalar * Math.cos(currentDirection);
  var breakFy = frictionScalar * Math.sin(currentDirection);
  this.dx += breakFx;
  this.dy += breakFy;
};

Character.prototype.render = function(ctx, player_next, coeff, lightImg, darkImg, name) {
  if (!player_next) {
    return;
  }
  var x = this.x * (1 - coeff) + player_next.x * coeff;
  var y = this.y * (1 - coeff) + player_next.y * coeff;

  if (this.timeToRespawn) {
    ctx.save();
    ctx.translate(x * GU, y * GU);
    ctx.scale(1.2, 1.2);
    ctx.font = GU + 'px Arial';
    ctx.fillStyle = 'white';
    ctx.textAlign = 'center';
    ctx.fillText(name + ' is dead (' + Math.ceil(this.timeToRespawn / 1000).toString() + ')', 0, 0);
    ctx.restore();
    return;
  }

  var hp = this.hp * (1 - coeff) + player_next.hp * coeff;

  ctx.save();
  ctx.translate(x * GU, y * GU);
  ctx.scale(0.6, 0.6);
  ctx.font = (.5 * GU) + 'px Arial';
  var padding = GU * 0.5;
  ctx.fillStyle = 'white';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'bottom';
  ctx.fillText(name , 0, -2.1 * GU);

  ctx.fillStyle = 'white';
  ctx.strokeStyle = '#888';
  ctx.lineWidth = 0.05 * GU;
  var hpWidth = 3 * GU;
  ctx.fillRect(
      -hpWidth / 2,
      -1.8 * GU,
      hpWidth * hp / 10, 0.2 * GU);

  ctx.strokeRect(
      -hpWidth / 2 - 0.1 * GU,
      -1.9 * GU,
      hpWidth + 0.2 * GU, 0.4 * GU);

  ctx.restore();
  ctx.save();

  ctx.translate(x * GU, y * GU);
  ctx.scale(GU * 0.005, GU * 0.005);
  ctx.rotate(this.mouseDirection);
  var img = this.team == 0 ? lightImg : darkImg;
  ctx.drawImage(img, -img.width / 2, -img.height / 2 - 52);

  ctx.restore();
  ctx.save();

  ctx.translate(x * GU, y * GU);
  ctx.scale(0.6, 0.6);
  ctx.rotate(this.mouseDirection);

  if (this.isShieldActive && this.shieldEnergy > 0) {
    ctx.beginPath();
    ctx.strokeStyle = '#BCBCBC';
    ctx.lineWidth = GU * (0.075  + 0.075 * this.shieldEnergy);
    ctx.arc(
      0,
      0,
      GU * (Character.BODY_RADIUS * + 0.2) * 12,
      -Character.MAX_SHIELD_ARC * Math.max(this.shieldEnergy, 0),
      Character.MAX_SHIELD_ARC * Math.max(this.shieldEnergy, 0),
      false
    );
    ctx.stroke();
  }
  ctx.restore();
};

Character.prototype.renderUi = function(ctx) {
  // draw overheat indicator
  ctx.save();
  var fillAlpha = 0.5;
  if (this.overheated) {
    fillAlpha += Math.sin(0.02 * t);
  }
  if(fillAlpha > 0.5) {
    ctx.fillStyle = 'rgba(255, 255, 255, ' + fillAlpha + ')';
  } else {
    ctx.fillStyle = 'rgba(255, 2555, 255, ' + fillAlpha + ')';
  }
  ctx.strokeStyle = 'rgba(255, 255, 255, .5)';
  ctx.strokeWidth = 0.1 * GU;
  ctx.fillRect(0.5 * GU, 8.5 * GU, GU * this.weaponHeat, 0.2 * GU);
  ctx.strokeRect(0.5 * GU, 8.5 * GU, GU * Character.OVERHEAT_THRESHOLD, 0.2 * GU);
  ctx.restore();
};

module.exports = Character;
<commit_msg>Remove code for staying within bounds, because we have walls now<commit_after>try {
  window;
} catch(e) {
  var BUTTONS = require('./input');
}

function Character(team, spawnPoint) {
  this.breakingCoefficient = 0.025;
  this.accelerationCoefficient = 0.012;
  this.MAX_HP = 10;
  this.team = team;
  this.onCP = false;
  this.kills = 0;
  this.deaths = 0;
  this.captures = 0;
  this.init(spawnPoint);
}

Character.MAX_SHIELD_ARC = 0.2 * Math.PI;
Character.OVERHEAT_THRESHOLD = 1.5;
Character.BODY_RADIUS = 0.6;

Character.prototype.init = function(spawnPoint) {
  if (spawnPoint) {
    this.x = spawnPoint.x;
    this.y = spawnPoint.y;
    this.timeDied = null;
    this.timeToRespawn = 0;
  } else {
    this.x = 32;
    this.y = 32;
    this.timeDied = +new Date();
    this.timeToRespawn = this.getTimeUntilRespawn(this.timeDied);
  }

  this.dx = 0;
  this.dy = 0;
  this.hp = this.MAX_HP;
  this.isShieldActive = false;
  this.fireCooldown = 0;
  this.shieldEnergy = 1;
  this.weaponHeat = 0;
  this.overheated = false;
  this.points = 0;
  this.respawnTime = 4000;
};

Character.prototype.getState = function() {
  return {
    t: 'C',
    x: this.x,
    y: this.y,
    hp: this.hp,
    kills: this.kills,
    deaths: this.deaths,
    captures: this.captures,
    mouseDirection: this.mouseDirection,
    isShieldActive: this.isShieldActive,
    shieldEnergy: this.shieldEnergy,
    team: this.team,
    weaponHeat: this.weaponHeat,
    overheated: this.overheated,
    respawnTime: this.respawnTime,
    timeDied: this.timeDied,
    timeToRespawn: this.timeToRespawn
  };
};

Character.prototype.hit = function(bullet, soundsToPlay) {
  if (bullet.team == this.team){
    return;
  }

  if (this.canShieldTakeBullet(bullet)) {
    this.shieldEnergy -= 0.45;
    var shieldSoundIndex = Math.floor(3 * Math.random()) + 1;
    soundsToPlay['shield-hit-' + shieldSoundIndex + '.mp3'] = true;
  } else {
    this.dx += bullet.dx;
    this.dy += bullet.dy;

    this.hp --;
    if (this.hp <= 0){
      this.deaths++;
      if(bullet.character){
        bullet.character.killed(this);
      }
      this.die();
    }
  }
};

Character.prototype.killed = function(enemy){
  //YEEY
  this.kills++;
};

Character.prototype.die = function(){
  this.hp = 0;
  this.timeDied = +new Date();
  this.respawnTime = 1000 + this.points * 0.3;
};

Character.prototype.canShieldTakeBullet = function(bullet) {
  if (!this.isShieldActive) {
    return false;
  }
  var mouseDirection = this.mouseDirection;
  if (mouseDirection < 0) {
    mouseDirection += 2 * Math.PI;
  }
  var oppositeShieldDirection = mouseDirection + Math.PI;
  var minShieldDirection = oppositeShieldDirection - Character.MAX_SHIELD_ARC * Math.max(this.shieldEnergy, 0);
  var maxShieldDirection = oppositeShieldDirection + Character.MAX_SHIELD_ARC * Math.max(this.shieldEnergy, 0);
  var bulletDirection = bullet.direction + 2 * Math.PI;
  return bulletDirection <= maxShieldDirection && bulletDirection >= minShieldDirection;
};

Character.prototype.getTimeUntilRespawn = function(timeDied) {
  var currentTime = +new Date();
  return Math.max(timeDied + this.respawnTime - currentTime, 0);
};

var defaultSpawn = [{x:5, y:32}, {x:55, y:32}];
Character.getDefaultPoint = function(team) {
  return defaultSpawn[team];
};

Character.getClosestSpawnPoint = function(team, character, capturePoints) {
  var spawnPoint = defaultSpawn[team];
  var dist = 999999; //bigger than map.
  for (var i = 0; i < capturePoints.length; i++) {
    var capturePoint = capturePoints[i];
    if (team === 0 && capturePoint.ownage_d === -1 || team === 1 && capturePoint.ownage_d === 1) {
      if(capturePoint.sqDistanceTo(character) < dist){
        spawnPoint = capturePoint;
      }
    }
  }
  return spawnPoint;
};
Character.prototype.update = function(input, walls, utility, capturePoints, points) {
  this.points = points;
  if (this.timeDied) {
    this.timeToRespawn = this.getTimeUntilRespawn(this.timeDied);
    if (this.timeToRespawn <= 0) {
      var spawnPoint = Character.getClosestSpawnPoint(this.team,this, capturePoints);
      if (spawnPoint) {
        this.init(spawnPoint);
      }
    }
    return;
  }

  this.applyMovementForce(input);
  this.applyFrictionForce();
  this.mouseDirection = input[BUTTONS.MOUSE_DIR];

  this.isShieldActive = input[BUTTONS.ALTERNATE_FIRE];
  this.shieldEnergy += 0.003;
  if (this.shieldEnergy > 1) {
    this.shieldEnergy = 1;
  }

  this.weaponHeat -= this.overheated ? 0.005 : 0.01;
  if (this.weaponHeat < 0) {
    this.weaponHeat = 0;
  }
  if (this.weaponHeat < 1) {
    this.overheated = false;
  }

  for(var i = 0; i < walls.length; i++) {
    if(utility.intersectLineCircle(walls[i].start_x, walls[i].start_y, walls[i].end_x, walls[i].end_y, this.x, this.y, Character.BODY_RADIUS)) {
      var p = walls[i].getPushVector(this.x, this.y, Character.BODY_RADIUS);

      //Decompose velocity!
      var newDx = 0;
      var newDy = 0;

      var p_l = Math.sqrt(p.x * p.x + p.y * p.y);
      if(p_l > 0.0001){
        p = { x: p.x/p_l, y: p.y / p_l }

        var newSpeed = p.x * this.dx + p.y * this.dy;
        if(newSpeed > 0){ //Moving away from wall. this is ok.
          newDx += p.x * newSpeed;
          newDy += p.y * newSpeed;
        }

      }

      var n = { x: -p.y, y: p.x };
      var n_l = Math.sqrt(n.x * n.x + n.y * n.y);
      if(n_l > 0.0001){
        n = { x: n.x/n_l, y: n.y / n_l }

        var newSpeed = n.x * this.dx + n.y * this.dy;
        newDx += n.x * newSpeed;
        newDy += n.y * newSpeed;
      }

      this.dx = newDx;
      this.dy = newDy;
    }
  }

  this.x += this.dx;
  this.y += this.dy;
};

Character.prototype.applyMovementForce = function(input) {
  var fx = 0;
  var fy = 0;
  if (input[BUTTONS.MOVE_UP]) { // W
    fy += -1;
  }
  if (input[BUTTONS.MOVE_DOWN]) { // S
    fy += 1;
  }
  if (input[BUTTONS.MOVE_LEFT]) { // A
    fx += -1;
  }
  if (input[BUTTONS.MOVE_RIGHT]) { // D
    fx += 1;
  }

  if (fx || fy) {
    var targetDirection = Math.atan2(fy, fx);

    fx = this.accelerationCoefficient * Math.cos(targetDirection);
    fy = this.accelerationCoefficient * Math.sin(targetDirection);

    this.dx += fx;
    this.dy += fy;
  }
};

Character.prototype.getCurrentDirection = function() {
  return Math.atan2(this.dy, this.dx);
};

Character.prototype.applyFrictionForce = function() {
  var currentDirection = this.getCurrentDirection();
  var currentSpeed = Math.sqrt(Math.pow(this.dx, 2) + Math.pow(this.dy, 2));
  var activeShieldFactor = this.isShieldActive ? 2.2 : 1; // more friction while shield is active
  var frictionScalar = - activeShieldFactor * this.breakingCoefficient * Math.pow(currentSpeed * 5 +.15, 2);
  var breakFx = frictionScalar * Math.cos(currentDirection);
  var breakFy = frictionScalar * Math.sin(currentDirection);
  this.dx += breakFx;
  this.dy += breakFy;
};

Character.prototype.render = function(ctx, player_next, coeff, lightImg, darkImg, name) {
  if (!player_next) {
    return;
  }
  var x = this.x * (1 - coeff) + player_next.x * coeff;
  var y = this.y * (1 - coeff) + player_next.y * coeff;

  if (this.timeToRespawn) {
    ctx.save();
    ctx.translate(x * GU, y * GU);
    ctx.scale(1.2, 1.2);
    ctx.font = GU + 'px Arial';
    ctx.fillStyle = 'white';
    ctx.textAlign = 'center';
    ctx.fillText(name + ' is dead (' + Math.ceil(this.timeToRespawn / 1000).toString() + ')', 0, 0);
    ctx.restore();
    return;
  }

  var hp = this.hp * (1 - coeff) + player_next.hp * coeff;

  ctx.save();
  ctx.translate(x * GU, y * GU);
  ctx.scale(0.6, 0.6);
  ctx.font = (.5 * GU) + 'px Arial';
  var padding = GU * 0.5;
  ctx.fillStyle = 'white';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'bottom';
  ctx.fillText(name , 0, -2.1 * GU);

  ctx.fillStyle = 'white';
  ctx.strokeStyle = '#888';
  ctx.lineWidth = 0.05 * GU;
  var hpWidth = 3 * GU;
  ctx.fillRect(
      -hpWidth / 2,
      -1.8 * GU,
      hpWidth * hp / 10, 0.2 * GU);

  ctx.strokeRect(
      -hpWidth / 2 - 0.1 * GU,
      -1.9 * GU,
      hpWidth + 0.2 * GU, 0.4 * GU);

  ctx.restore();
  ctx.save();

  ctx.translate(x * GU, y * GU);
  ctx.scale(GU * 0.005, GU * 0.005);
  ctx.rotate(this.mouseDirection);
  var img = this.team == 0 ? lightImg : darkImg;
  ctx.drawImage(img, -img.width / 2, -img.height / 2 - 52);

  ctx.restore();
  ctx.save();

  ctx.translate(x * GU, y * GU);
  ctx.scale(0.6, 0.6);
  ctx.rotate(this.mouseDirection);

  if (this.isShieldActive && this.shieldEnergy > 0) {
    ctx.beginPath();
    ctx.strokeStyle = '#BCBCBC';
    ctx.lineWidth = GU * (0.075  + 0.075 * this.shieldEnergy);
    ctx.arc(
      0,
      0,
      GU * (Character.BODY_RADIUS * + 0.2) * 12,
      -Character.MAX_SHIELD_ARC * Math.max(this.shieldEnergy, 0),
      Character.MAX_SHIELD_ARC * Math.max(this.shieldEnergy, 0),
      false
    );
    ctx.stroke();
  }
  ctx.restore();
};

Character.prototype.renderUi = function(ctx) {
  // draw overheat indicator
  ctx.save();
  var fillAlpha = 0.5;
  if (this.overheated) {
    fillAlpha += Math.sin(0.02 * t);
  }
  if(fillAlpha > 0.5) {
    ctx.fillStyle = 'rgba(255, 255, 255, ' + fillAlpha + ')';
  } else {
    ctx.fillStyle = 'rgba(255, 2555, 255, ' + fillAlpha + ')';
  }
  ctx.strokeStyle = 'rgba(255, 255, 255, .5)';
  ctx.strokeWidth = 0.1 * GU;
  ctx.fillRect(0.5 * GU, 8.5 * GU, GU * this.weaponHeat, 0.2 * GU);
  ctx.strokeRect(0.5 * GU, 8.5 * GU, GU * Character.OVERHEAT_THRESHOLD, 0.2 * GU);
  ctx.restore();
};

module.exports = Character;
<|endoftext|>


<commit_before>import { SYNC_RENDER, NO_RENDER, FORCE_RENDER, ASYNC_RENDER, EMPTY_BASE, ATTR_KEY } from '../constants';
import options from '../options';
import { isFunction, clone, extend, empty } from '../util';
import { enqueueRender } from '../render-queue';
import { getNodeProps } from './index';
import { diff, mounts, diffLevel, flushMounts, removeOrphanedChildren, recollectNodeTree } from './diff';
import { isFunctionalComponent, buildFunctionalComponent } from './functional-component';
import { createComponent, collectComponent } from './component-recycler';
import { removeNode } from '../dom/index';

/** Mark component as dirty and queue up a render.
 *	@param {Component} component
 *	@private
 */
export function triggerComponentRender(component) {
	if (!component._dirty) {
		component._dirty = true;
		enqueueRender(component);
	}
}

/** Set a component's `props` (generally derived from JSX attributes).
 *	@param {Object} props
 *	@param {Object} [opts]
 *	@param {boolean} [opts.renderSync=false]	If `true` and {@link options.syncComponentUpdates} is `true`, triggers synchronous rendering.
 *	@param {boolean} [opts.render=true]			If `false`, no render will be triggered.
 */
export function setComponentProps(component, props, opts, context, mountAll) {
	let d = component._disableRendering===true,
		b = component.base;
	component._disableRendering = true;

	if ((component.__ref = props.ref)) delete props.ref;
	if ((component.__key = props.key)) delete props.key;

	if (empty(b) || mountAll) {
		if (component.componentWillMount) component.componentWillMount();
	}
	else if (component.componentWillReceiveProps) {
		component.componentWillReceiveProps(props, context);
	}

	if (context && context!==component.context) {
		if (!component.prevContext) component.prevContext = component.context;
		component.context = context;
	}

	if (!component.prevProps) component.prevProps = component.props;
	component.props = props;

	component._disableRendering = d;

	if (opts!==NO_RENDER) {
		if (opts===SYNC_RENDER || options.syncComponentUpdates!==false || !b) {
			renderComponent(component, SYNC_RENDER, mountAll);
		}
		else {
			triggerComponentRender(component);
		}
	}

	if (component.__ref) component.__ref(component);
}

/** Render a Component, triggering necessary lifecycle events and taking High-Order Components into account.
 *	@param {Component} component
 *	@param {Object} [opts]
 *	@param {boolean} [opts.build=false]		If `true`, component will build and store a DOM node if not already associated with one.
 *	@private
 */
export function renderComponent(component, opts, mountAll) {
	if (component._disableRendering) return;

	let skip, rendered,
		props = component.props,
		state = component.state,
		context = component.context,
		previousProps = component.prevProps || props,
		previousState = component.prevState || state,
		previousContext = component.prevContext || context,
		isUpdate = component.base,
		initialBase = isUpdate || component.nextBase,
		initialComponent = initialBase && initialBase._component,
		initialChildComponent = component._component;

	// if updating
	if (isUpdate) {
		component.props = previousProps;
		component.state = previousState;
		component.context = previousContext;
		if (opts!==FORCE_RENDER
			&& component.shouldComponentUpdate
			&& component.shouldComponentUpdate(props, state, context) === false) {
			skip = true;
		}
		else if (component.componentWillUpdate) {
			component.componentWillUpdate(props, state, context);
		}
		component.props = props;
		component.state = state;
		component.context = context;
	}

	component.prevProps = component.prevState = component.prevContext = component.nextBase = null;
	component._dirty = false;

	if (!skip) {
		if (component.render) rendered = component.render(props, state, context);

		// context to pass to the child, can be updated via (grand-)parent component
		if (component.getChildContext) {
			context = extend(clone(context), component.getChildContext());
		}

		while (isFunctionalComponent(rendered)) {
			rendered = buildFunctionalComponent(rendered, context);
		}

		let childComponent = rendered && rendered.nodeName,
			toUnmount, base;

		if (isFunction(childComponent) && childComponent.prototype.render) {
			// set up high order component link

			let inst = initialChildComponent,
				childProps = getNodeProps(rendered);

			if (inst && inst.constructor===childComponent) {
				setComponentProps(inst, childProps, SYNC_RENDER, context);
			}
			else {
				toUnmount = inst;
				inst = createComponent(childComponent, childProps, context);
				inst._parentComponent = component;
				component._component = inst;
				setComponentProps(inst, childProps, NO_RENDER, context);
				renderComponent(inst, SYNC_RENDER);
			}

			base = inst.base;
		}
		else {
			let cbase = initialBase;

			// destroy high order component link
			toUnmount = initialChildComponent;
			if (toUnmount) {
				cbase = component._component = null;
			}

			if (initialBase || opts===SYNC_RENDER) {
				if (cbase) cbase._component = null;
				base = diff(cbase, rendered || EMPTY_BASE, context, mountAll || !isUpdate, true);
			}
		}

		if (initialBase && base!==initialBase) {
			let p = initialBase.parentNode;
			if (p && base!==p) p.replaceChild(base, initialBase);
			if (!toUnmount && initialComponent===component && !initialChildComponent) {
				initialBase._component = null;
				recollectNodeTree(initialBase);
			}
		}

		if (toUnmount) {
			unmountComponent(toUnmount, true);
		}

		component.base = base;
		if (base) {
			let componentRef = component,
				t = component;
			while ((t=t._parentComponent)) { componentRef = t; }
			base._component = componentRef;
			base._componentConstructor = componentRef.constructor;
		}

	}

	if (!isUpdate || mountAll) {
		mounts.splice(0, 0, component);
		if (!diffLevel) flushMounts();
	}
	else if (!skip && component.componentDidUpdate) {
		component.componentDidUpdate(previousProps, previousState, previousContext);
	}

	let cb = component._renderCallbacks, fn;
	if (cb) while ( (fn = cb.pop()) ) fn.call(component);

	return rendered;
}

/** Apply the Component referenced by a VNode to the DOM.
 *	@param {Element} dom	The DOM node to mutate
 *	@param {VNode} vnode	A Component-referencing VNode
 *	@returns {Element} dom	The created/mutated element
 *	@private
 */
export function buildComponentFromVNode(dom, vnode, context, mountAll) {
	let c = dom && dom._component,
		oldDom = dom,
		isDirectOwner = c && dom._componentConstructor===vnode.nodeName,
		isOwner = isDirectOwner,
		props = getNodeProps(vnode);
	while (c && !isOwner && (c=c._parentComponent)) {
		isOwner = c.constructor===vnode.nodeName;
	}

	if (isOwner && (!mountAll || c._component)) {
		setComponentProps(c, props, ASYNC_RENDER, context, mountAll);
		dom = c.base;
	}
	else {
		if (c && !isDirectOwner) {
			unmountComponent(c, true);
			dom = oldDom = null;
		}

		c = createComponent(vnode.nodeName, props, context);
		if (dom && !c.nextBase) c.nextBase = dom;
		setComponentProps(c, props, SYNC_RENDER, context, mountAll);
		dom = c.base;

		if (oldDom && dom!==oldDom) {
			oldDom._component = null;
			recollectNodeTree(oldDom);
		}
	}

	return dom;
}

/** Remove a component from the DOM and recycle it.
 *	@param {Element} dom			A DOM node from which to unmount the given Component
 *	@param {Component} component	The Component instance to unmount
 *	@private
 */
export function unmountComponent(component, remove) {
	// console.log(`${remove?'Removing':'Unmounting'} component: ${component.constructor.name}`);

	if (component.componentWillUnmount) component.componentWillUnmount();

	// recursively tear down & recollect high-order component children:
	let inner = component._component;
	if (inner) {
		unmountComponent(inner, remove);
	}
	else {
		let base = component.base;
		if (base) {
			component.nextBase = base;
			component.base = null;
			if (base[ATTR_KEY] && base[ATTR_KEY].ref) base[ATTR_KEY].ref(null);
			if (remove) {
				removeNode(base);
				collectComponent(component);
			}
			removeOrphanedChildren(base.childNodes, !remove);
		}

	}

	if (component.__ref) component.__ref(null);
	if (component.componentDidUnmount) component.componentDidUnmount();
}
<commit_msg>Disable rendering on unmount /cc @Madumo<commit_after>import { SYNC_RENDER, NO_RENDER, FORCE_RENDER, ASYNC_RENDER, EMPTY_BASE, ATTR_KEY } from '../constants';
import options from '../options';
import { isFunction, clone, extend, empty } from '../util';
import { enqueueRender } from '../render-queue';
import { getNodeProps } from './index';
import { diff, mounts, diffLevel, flushMounts, removeOrphanedChildren, recollectNodeTree } from './diff';
import { isFunctionalComponent, buildFunctionalComponent } from './functional-component';
import { createComponent, collectComponent } from './component-recycler';
import { removeNode } from '../dom/index';

/** Mark component as dirty and queue up a render.
 *	@param {Component} component
 *	@private
 */
export function triggerComponentRender(component) {
	if (!component._dirty) {
		component._dirty = true;
		enqueueRender(component);
	}
}

/** Set a component's `props` (generally derived from JSX attributes).
 *	@param {Object} props
 *	@param {Object} [opts]
 *	@param {boolean} [opts.renderSync=false]	If `true` and {@link options.syncComponentUpdates} is `true`, triggers synchronous rendering.
 *	@param {boolean} [opts.render=true]			If `false`, no render will be triggered.
 */
export function setComponentProps(component, props, opts, context, mountAll) {
	let b = component.base;
	if (component._disableRendering) return;
	component._disableRendering = true;

	if ((component.__ref = props.ref)) delete props.ref;
	if ((component.__key = props.key)) delete props.key;

	if (empty(b) || mountAll) {
		if (component.componentWillMount) component.componentWillMount();
	}
	else if (component.componentWillReceiveProps) {
		component.componentWillReceiveProps(props, context);
	}

	if (context && context!==component.context) {
		if (!component.prevContext) component.prevContext = component.context;
		component.context = context;
	}

	if (!component.prevProps) component.prevProps = component.props;
	component.props = props;

	component._disableRendering = false;

	if (opts!==NO_RENDER) {
		if (opts===SYNC_RENDER || options.syncComponentUpdates!==false || !b) {
			renderComponent(component, SYNC_RENDER, mountAll);
		}
		else {
			triggerComponentRender(component);
		}
	}

	if (component.__ref) component.__ref(component);
}

/** Render a Component, triggering necessary lifecycle events and taking High-Order Components into account.
 *	@param {Component} component
 *	@param {Object} [opts]
 *	@param {boolean} [opts.build=false]		If `true`, component will build and store a DOM node if not already associated with one.
 *	@private
 */
export function renderComponent(component, opts, mountAll) {
	if (component._disableRendering) return;

	let skip, rendered,
		props = component.props,
		state = component.state,
		context = component.context,
		previousProps = component.prevProps || props,
		previousState = component.prevState || state,
		previousContext = component.prevContext || context,
		isUpdate = component.base,
		initialBase = isUpdate || component.nextBase,
		initialComponent = initialBase && initialBase._component,
		initialChildComponent = component._component;

	// if updating
	if (isUpdate) {
		component.props = previousProps;
		component.state = previousState;
		component.context = previousContext;
		if (opts!==FORCE_RENDER
			&& component.shouldComponentUpdate
			&& component.shouldComponentUpdate(props, state, context) === false) {
			skip = true;
		}
		else if (component.componentWillUpdate) {
			component.componentWillUpdate(props, state, context);
		}
		component.props = props;
		component.state = state;
		component.context = context;
	}

	component.prevProps = component.prevState = component.prevContext = component.nextBase = null;
	component._dirty = false;

	if (!skip) {
		if (component.render) rendered = component.render(props, state, context);

		// context to pass to the child, can be updated via (grand-)parent component
		if (component.getChildContext) {
			context = extend(clone(context), component.getChildContext());
		}

		while (isFunctionalComponent(rendered)) {
			rendered = buildFunctionalComponent(rendered, context);
		}

		let childComponent = rendered && rendered.nodeName,
			toUnmount, base;

		if (isFunction(childComponent) && childComponent.prototype.render) {
			// set up high order component link

			let inst = initialChildComponent,
				childProps = getNodeProps(rendered);

			if (inst && inst.constructor===childComponent) {
				setComponentProps(inst, childProps, SYNC_RENDER, context);
			}
			else {
				toUnmount = inst;
				inst = createComponent(childComponent, childProps, context);
				inst._parentComponent = component;
				component._component = inst;
				setComponentProps(inst, childProps, NO_RENDER, context);
				renderComponent(inst, SYNC_RENDER);
			}

			base = inst.base;
		}
		else {
			let cbase = initialBase;

			// destroy high order component link
			toUnmount = initialChildComponent;
			if (toUnmount) {
				cbase = component._component = null;
			}

			if (initialBase || opts===SYNC_RENDER) {
				if (cbase) cbase._component = null;
				base = diff(cbase, rendered || EMPTY_BASE, context, mountAll || !isUpdate, true);
			}
		}

		if (initialBase && base!==initialBase) {
			let p = initialBase.parentNode;
			if (p && base!==p) p.replaceChild(base, initialBase);
			if (!toUnmount && initialComponent===component && !initialChildComponent) {
				initialBase._component = null;
				recollectNodeTree(initialBase);
			}
		}

		if (toUnmount) {
			unmountComponent(toUnmount, true);
		}

		component.base = base;
		if (base) {
			let componentRef = component,
				t = component;
			while ((t=t._parentComponent)) { componentRef = t; }
			base._component = componentRef;
			base._componentConstructor = componentRef.constructor;
		}

	}

	if (!isUpdate || mountAll) {
		mounts.splice(0, 0, component);
		if (!diffLevel) flushMounts();
	}
	else if (!skip && component.componentDidUpdate) {
		component.componentDidUpdate(previousProps, previousState, previousContext);
	}

	let cb = component._renderCallbacks, fn;
	if (cb) while ( (fn = cb.pop()) ) fn.call(component);

	return rendered;
}

/** Apply the Component referenced by a VNode to the DOM.
 *	@param {Element} dom	The DOM node to mutate
 *	@param {VNode} vnode	A Component-referencing VNode
 *	@returns {Element} dom	The created/mutated element
 *	@private
 */
export function buildComponentFromVNode(dom, vnode, context, mountAll) {
	let c = dom && dom._component,
		oldDom = dom,
		isDirectOwner = c && dom._componentConstructor===vnode.nodeName,
		isOwner = isDirectOwner,
		props = getNodeProps(vnode);
	while (c && !isOwner && (c=c._parentComponent)) {
		isOwner = c.constructor===vnode.nodeName;
	}

	if (isOwner && (!mountAll || c._component)) {
		setComponentProps(c, props, ASYNC_RENDER, context, mountAll);
		dom = c.base;
	}
	else {
		if (c && !isDirectOwner) {
			unmountComponent(c, true);
			dom = oldDom = null;
		}

		c = createComponent(vnode.nodeName, props, context);
		if (dom && !c.nextBase) c.nextBase = dom;
		setComponentProps(c, props, SYNC_RENDER, context, mountAll);
		dom = c.base;

		if (oldDom && dom!==oldDom) {
			oldDom._component = null;
			recollectNodeTree(oldDom);
		}
	}

	return dom;
}

/** Remove a component from the DOM and recycle it.
 *	@param {Element} dom			A DOM node from which to unmount the given Component
 *	@param {Component} component	The Component instance to unmount
 *	@private
 */
export function unmountComponent(component, remove) {
	// console.log(`${remove?'Removing':'Unmounting'} component: ${component.constructor.name}`);

	component._disableRendering = true;

	if (component.componentWillUnmount) component.componentWillUnmount();

	// recursively tear down & recollect high-order component children:
	let inner = component._component;
	if (inner) {
		unmountComponent(inner, remove);
	}
	else {
		let base = component.base;
		if (base) {
			component.nextBase = base;
			component.base = null;
			if (base[ATTR_KEY] && base[ATTR_KEY].ref) base[ATTR_KEY].ref(null);
			if (remove) {
				removeNode(base);
				collectComponent(component);
			}
			removeOrphanedChildren(base.childNodes, !remove);
		}

	}

	if (component.__ref) component.__ref(null);
	if (component.componentDidUnmount) component.componentDidUnmount();
}
<|endoftext|>


<commit_before>'use strict';

export const _cachedApplicationRef = Symbol('_cachedApplicationRef');
export const _mixinRef = Symbol('_mixinRef');
export const _originalMixin = Symbol('_originalMixin');

/**
 * Sets the prototype of mixin to wrapper so that properties set on mixin are
 * inherited by the wrapper.
 *
 * This is needed in order to implement @@hasInstance as a decorator function.
 */
export const wrap = (mixin, wrapper) => {
  Object.setPrototypeOf(wrapper, mixin);
  if (!mixin[_originalMixin]) {
    mixin[_originalMixin] = mixin;
  }
  return wrapper;
};

/**
 * Decorates mixin so that it caches its applications. When applied multiple
 * times to the same superclass, mixin will only create one subclass and
 * memoize it.
 */
export const Cached = (mixin) => wrap(mixin, (superclass) => {
  // Get or create a symbol used to look up a previous application of mixin
  // to the class. This symbol is unique per mixin definition, so a class will have N
  // applicationRefs if it has had N mixins applied to it. A mixin will have
  // exactly one _cachedApplicationRef used to store its applications.
  let applicationRef = mixin[_cachedApplicationRef];
  if (!applicationRef) {
    applicationRef = mixin[_cachedApplicationRef] = Symbol(mixin.name);
  }
  // Look up an existing application of `mixin` to `c`, return it if found.
  if (superclass.hasOwnProperty(applicationRef)) {
    return superclass[applicationRef];
  }
  // Apply the mixin
  let application = mixin(superclass);
  // Cache the mixin application on the superclass
  superclass[applicationRef] = application;
  return application;
});

/**
 * Adds @@hasInstance (ES2015 instanceof support) to mixin.
 * Note: @@hasInstance is not supported in any browsers yet.
 */
export const HasInstance = (mixin) => {
  if (Symbol.hasInstance && !mixin.hasOwnProperty(Symbol.hasInstance)) {
    Object.defineProperty(mixin, Symbol.hasInstance, {
      value: function(o) {
        var originalMixin = this[_originalMixin];
        while (o != null) {
          if (o.hasOwnProperty(_mixinRef) && o[_mixinRef] === originalMixin) {
            return true;
          }
          o = Object.getPrototypeOf(o);
        }
        return false;
      }
    });
  }
  return mixin;
};

/**
 * A basic mixin decorator that sets up a reference from mixin applications
 * to the mixin defintion for use by other mixin decorators.
 */
export const BareMixin = (mixin) => wrap(mixin, (superclass) => {
  // Apply the mixin
  let application = mixin(superclass);

  // Attach a reference from mixin applition to wrapped mixin for RTTI
  // mixin[@@hasInstance] should use this.
  application.prototype[_mixinRef] = mixin[_originalMixin];
  return application;
});

/**
 * Decorates a mixin function to add application caching and instanceof
 * support.
 */
export const Mixin = (mixin) => Cached(HasInstance(BareMixin(mixin)));

export const mix = (superClass) => new MixinBuilder(superClass);

class MixinBuilder {

  constructor(superclass) {
    this.superclass = superclass;
  }

  with() {
    return Array.from(arguments).reduce((c, m) => m(c), this.superclass);
  }
}
<commit_msg>Remove unused parts of mixwith<commit_after>'use strict';

export const mix = (superClass) => new MixinBuilder(superClass);

class MixinBuilder {

  constructor(superclass) {
    this.superclass = superclass;
  }

  with() {
    return Array.from(arguments).reduce((c, m) => m(c), this.superclass);
  }
}
<|endoftext|>