<commit_before>//Title: Custom DropDown plugin by PC
//Documentation: http://designwithpc.com/Plugins/ddslick
//Author: PC
//Website: http://designwithpc.com
//Twitter: http://twitter.com/chaudharyp

(function ($) {

    var methods = {},

    //Set defauls for the control
    defaults = {
        data: [],
        keepJSONItemsOnTop: false,
        width: 260,
        height: null,
        background: "#eee",
        selectText: "",
        defaultSelectedIndex: null,
        truncateDescription: true,
        imagePosition: "left",
        showSelectedHTML: true,
        clickOffToClose: true,
		embedCSS: true,
        onSelected: function () { return; }
    },

    ddSelectHtml = '
<input class="dd-selected-value" type="hidden" />
',
    ddOptionsHtml = '

',

    //CSS for ddSlick
    ddslickCSS = '';

    $.fn.ddslick = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exists.');
        }
    };

    //Public methods
    methods.init = function (optz) {
        //Preserve the original defaults by passing an empty object as the target
        //The object is used to get global flags like embedCSS.
        var opts = $.extend({}, defaults, optz);

        //CSS styles are only added once.
	    if ($('#css-ddslick').length <= 0 && opts.embedCSS) {
	        $(ddslickCSS).appendTo('head');
	    }

        //Apply on all selected elements
        return this.each(function () {
            //Preserve the original defaults by passing an empty object as the target
            //The object is used to save drop-down's corresponding settings and data.
            var options = $.extend({}, defaults, opts);

            var obj = $(this),
                data = obj.data('ddslick');
            //If the plugin has not been initialized yet
            if (!data) {

                var ddSelect = [], ddJson = options.data;

                //Get data from HTML select options
                obj.find('option').each(function () {
                    var $this = $(this), thisData = $this.data();
                    ddSelect.push({
                        text: $.trim($this.text()),
                        value: $this.val(),
                        selected: $this.is(':selected'),
                        description: thisData.description,
                        imageSrc: thisData.imagesrc //keep it lowercase for HTML5 data-attributes
                    });
                });

                //Update Plugin data merging both HTML select data and JSON data for the dropdown
                if (options.keepJSONItemsOnTop) {
                    $.merge(options.data, ddSelect);
                } else {
                    options.data = $.merge(ddSelect, options.data);
                }

                //Replace HTML select with empty placeholder, keep the original
                var original = obj, placeholder = $('

');
                obj.replaceWith(placeholder);
                obj = placeholder;

                //Add classes and append ddSelectHtml & ddOptionsHtml to the container
                obj.addClass('dd-container').append(ddSelectHtml).append(ddOptionsHtml);

                // Inherit name attribute from original element
                obj.find("input.dd-selected-value").attr("name", $(original).attr("name")).removeClass('dd-selected-value').addClass($(original).attr("class")).addClass('dd-selected-value');

                //Get newly created ddOptions and ddSelect to manipulate
                var ddSelect = obj.find('.dd-select'),
                    ddOptions = obj.find('.dd-options');

                //Set widths
                ddOptions.css({ width: options.width });
                ddSelect.css({ width: options.width, background: options.background });
                obj.css({ width: options.width });

                //Set height
                if (options.height !== null) {
                    ddOptions.css({ height: options.height, overflow: 'auto' });
                }

                //Add ddOptions to the container. Replace with template engine later.
                $.each(options.data, function (index, item) {
                    if (item.selected) { options.defaultSelectedIndex = index; }
                    ddOptions.append('
' +
                        '' +
                            (item.value ? ' <input class="dd-option-value" type="hidden" value="' + item.value + '" />' : '') +
                            (item.imageSrc ? ' ' : '') +
                            (item.text ? ' ' + item.text + '' : '') +
                            (item.description ? ' ' + item.description + '' : '') +
                        '' +
                    '
');
                });

                //Save plugin data.
                var pluginData = {
                    settings: options,
                    original: original,
                    selectedIndex: -1,
                    selectedItem: null,
                    selectedData: null
                };

                obj.data('ddslick', pluginData);

                //Check if needs to show the select text, otherwise show selected or default selection
                if (options.selectText.length > 0 && options.defaultSelectedIndex === null) {
                    obj.find('.dd-selected').html(options.selectText);
                }
                else {
                    var index = (options.defaultSelectedIndex !== null && options.defaultSelectedIndex >= 0 && options.defaultSelectedIndex < options.data.length)
                                ? options.defaultSelectedIndex
                                : 0;
                    selectIndex(obj, index);
                }

                //EVENTS
                //Displaying options
                obj.find('.dd-select').on('click.ddslick', function () {
                    open(obj);
                });

                //Selecting an option
                obj.find('.dd-option').on('click.ddslick', function () {
                    selectIndex(obj, $(this).closest('li').index());
                });

                //Click anywhere to close
                if (options.clickOffToClose) {
                    ddOptions.addClass('dd-click-off-close');
                    obj.on('click.ddslick', function (e) { e.stopPropagation(); });
                    $('body').on('click', function () {
                        $('.dd-click-off-close').slideUp(50).siblings('.dd-select').find('.dd-pointer').removeClass('dd-pointer-up');
                    });
                }
            }
        });
    };

    //Public method to select an option by its index
    methods.select = function (options) {
        return this.each(function () {
            if (options.index!==undefined)
                selectIndex($(this), options.index);
            if (options.id)
                selectId($(this), options.id);
        });
    }

    //Public method to open drop down
    methods.open = function () {
        return this.each(function () {
            var $this = $(this),
                pluginData = $this.data('ddslick');

            //Check if plugin is initialized
            if (pluginData)
                open($this);
        });
    };

    //Public method to close drop down
    methods.close = function () {
        return this.each(function () {
            var $this = $(this),
                pluginData = $this.data('ddslick');

            //Check if plugin is initialized
            if (pluginData)
                close($this);
        });
    };

    //Public method to destroy. Unbind all events and restore the original Html select/options
    methods.destroy = function () {
        return this.each(function () {
            var $this = $(this),
                pluginData = $this.data('ddslick');

            //Check if already destroyed
            if (pluginData) {
                var originalElement = pluginData.original;
                $this.removeData('ddslick').unbind('.ddslick').replaceWith(originalElement);
            }
        });
    }

     //Private: Select id
    function selectId(obj, id) {

       var index = obj.find(".dd-option-value[value= '" + id + "']").parents("li").prevAll().length;
       selectIndex(obj, index);

    }

    //Private: Select index
    function selectIndex(obj, index) {

        //Get plugin data
        var pluginData = obj.data('ddslick');

        //Get required elements
        var ddSelected = obj.find('.dd-selected'),
            ddSelectedValue = ddSelected.siblings('.dd-selected-value'),
            ddOptions = obj.find('.dd-options'),
            ddPointer = ddSelected.siblings('.dd-pointer'),
            selectedOption = obj.find('.dd-option').eq(index),
            selectedLiItem = selectedOption.closest('li'),
            settings = pluginData.settings,
            selectedData = pluginData.settings.data[index];

        //Highlight selected option
        obj.find('.dd-option').removeClass('dd-option-selected');
        selectedOption.addClass('dd-option-selected');

        //Update or Set plugin data with new selection
        pluginData.selectedIndex = index;
        pluginData.selectedItem = selectedLiItem;
        pluginData.selectedData = selectedData;

        //If set to display to full html, add html
        if (settings.showSelectedHTML) {
            ddSelected.html(
                    (selectedData.imageSrc ? '' : '') +
                    (selectedData.text ? '' + selectedData.text + '' : '') +
                    (selectedData.description ? '' + selectedData.description + '' : '')
                );

        }
            //Else only display text as selection
        else ddSelected.html(selectedData.text);

        //Updating selected option value
        ddSelectedValue.val(selectedData.value);

        //BONUS! Update the original element attribute with the new selection
        pluginData.original.val(selectedData.value);
        obj.data('ddslick', pluginData);

        //Close options on selection
        close(obj);

        //Adjust appearence for selected option
        adjustSelectedHeight(obj);

        //Callback function on selection
        if (typeof settings.onSelected == 'function') {
            settings.onSelected.call(this, pluginData);
        }
    }

    //Private: Close the drop down options
    function open(obj) {

        var $this = obj.find('.dd-select'),
            ddOptions = $this.siblings('.dd-options'),
            ddPointer = $this.find('.dd-pointer'),
            wasOpen = ddOptions.is(':visible');

        //Close all open options (multiple plugins) on the page
        $('.dd-click-off-close').not(ddOptions).slideUp(50);
        $('.dd-pointer').removeClass('dd-pointer-up');

        if (wasOpen) {
            ddOptions.slideUp('fast');
            ddPointer.removeClass('dd-pointer-up');
        }
        else {
            ddOptions.slideDown('fast');
            ddPointer.addClass('dd-pointer-up');
        }

        //Fix text height (i.e. display title in center), if there is no description
        adjustOptionsHeight(obj);
    }

    //Private: Close the drop down options
    function close(obj) {
        //Close drop down and adjust pointer direction
        obj.find('.dd-options').slideUp(50);
        obj.find('.dd-pointer').removeClass('dd-pointer-up').removeClass('dd-pointer-up');
    }

    //Private: Adjust appearence for selected option (move title to middle), when no desripction
    function adjustSelectedHeight(obj) {

        //Get height of dd-selected
        var lSHeight = obj.find('.dd-select').css('height');

        //Check if there is selected description
        var descriptionSelected = obj.find('.dd-selected-description');
        var imgSelected = obj.find('.dd-selected-image');
        if (descriptionSelected.length <= 0 && imgSelected.length > 0) {
            obj.find('.dd-selected-text').css('lineHeight', lSHeight);
        }
    }

    //Private: Adjust appearence for drop down options (move title to middle), when no desripction
    function adjustOptionsHeight(obj) {
        obj.find('.dd-option').each(function () {
            var $this = $(this);
            var lOHeight = $this.css('height');
            var descriptionOption = $this.find('.dd-option-description');
            var imgOption = obj.find('.dd-option-image');
            if (descriptionOption.length <= 0 && imgOption.length > 0) {
                $this.find('.dd-option-text').css('lineHeight', lOHeight);
            }
        });
    }

})(jQuery);
<commit_msg>enqueue jquery.ddslick in admin<commit_after>//Title: Custom DropDown plugin by PC
//Documentation: http://designwithpc.com/Plugins/ddslick
//Author: PC
//Website: http://designwithpc.com
//Twitter: http://twitter.com/chaudharyp

(function ($) {

    $.fn.ddslick = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exists.');
        }
    };

    var methods = {},

    //Set defauls for the control
    defaults = {
        data: [],
        keepJSONItemsOnTop: false,
        width: 260,
        height: null,
        background: "#eee",
        selectText: "",
        defaultSelectedIndex: null,
        truncateDescription: true,
        imagePosition: "left",
        showSelectedHTML: true,
        clickOffToClose: true,
		embedCSS: true,
        onSelected: function () { }
    },

    ddSelectHtml = '
<input class="dd-selected-value" type="hidden" />
',
    ddOptionsHtml = '

',

    //CSS for ddSlick
    ddslickCSS = '';

    //Public methods
    methods.init = function (opts) {
        //Preserve the original defaults by passing an empty object as the target
        //The object is used to get global flags like embedCSS.
        var options = $.extend({}, defaults, opts);

        //CSS styles are only added once.
	    if ($('#css-ddslick').length <= 0 && options.embedCSS) {
	        $(ddslickCSS).appendTo('head');
	    }

        //Apply on all selected elements
        return this.each(function () {
            //Preserve the original defaults by passing an empty object as the target
            //The object is used to save drop-down's corresponding settings and data.
            var options = $.extend({}, defaults, options);

            var obj = $(this),
                data = obj.data('ddslick');
            //If the plugin has not been initialized yet
            if (!data) {

                var ddSelect = [], ddJson = options.data;

                //Get data from HTML select options
                obj.find('option').each(function () {
                    var $this = $(this), thisData = $this.data();
                    ddSelect.push({
                        text: $.trim($this.text()),
                        value: $this.val(),
                        selected: $this.is(':selected'),
                        description: thisData.description,
                        imageSrc: thisData.imagesrc //keep it lowercase for HTML5 data-attributes
                    });
                });

                //Update Plugin data merging both HTML select data and JSON data for the dropdown
                if (options.keepJSONItemsOnTop)
                    $.merge(options.data, ddSelect);
                else options.data = $.merge(ddSelect, options.data);

                //Replace HTML select with empty placeholder, keep the original
                var original = obj, placeholder = $('

');
                obj.replaceWith(placeholder);
                obj = placeholder;

                //Add classes and append ddSelectHtml & ddOptionsHtml to the container
                obj.addClass('dd-container').append(ddSelectHtml).append(ddOptionsHtml);

                // Inherit name attribute from original element
                obj.find("input.dd-selected-value").attr("name", $(original).attr("name"))

                //Get newly created ddOptions and ddSelect to manipulate
                var ddSelect = obj.find('.dd-select'),
                    ddOptions = obj.find('.dd-options');

                //Set widths
                ddOptions.css({ width: options.width });
                ddSelect.css({ width: options.width, background: options.background });
                obj.css({ width: options.width });

                //Set height
                if (options.height != null)
                    ddOptions.css({ height: options.height, overflow: 'auto' });

                //Add ddOptions to the container. Replace with template engine later.
                $.each(options.data, function (index, item) {
                    if (item.selected) options.defaultSelectedIndex = index;
                    ddOptions.append('
' +
                        '' +
                            (item.value ? ' <input class="dd-option-value" type="hidden" value="' + item.value + '" />' : '') +
                            (item.imageSrc ? ' ' : '') +
                            (item.text ? ' ' + item.text + '' : '') +
                            (item.description ? ' ' + item.description + '' : '') +
                        '' +
                    '
');
                });

                //Save plugin data.
                var pluginData = {
                    settings: options,
                    original: original,
                    selectedIndex: -1,
                    selectedItem: null,
                    selectedData: null
                }
                obj.data('ddslick', pluginData);

                //Check if needs to show the select text, otherwise show selected or default selection
                if (options.selectText.length > 0 && options.defaultSelectedIndex == null) {
                    obj.find('.dd-selected').html(options.selectText);
                }
                else {
                    var index = (options.defaultSelectedIndex != null && options.defaultSelectedIndex >= 0 && options.defaultSelectedIndex < options.data.length)
                                ? options.defaultSelectedIndex
                                : 0;
                    selectIndex(obj, index);
                }

                //EVENTS
                //Displaying options
                obj.find('.dd-select').on('click.ddslick', function () {
                    open(obj);
                });

                //Selecting an option
                obj.find('.dd-option').on('click.ddslick', function () {
                    selectIndex(obj, $(this).closest('li').index());
                });

                //Click anywhere to close
                if (options.clickOffToClose) {
                    ddOptions.addClass('dd-click-off-close');
                    obj.on('click.ddslick', function (e) { e.stopPropagation(); });
                    $('body').on('click', function () {
                        $('.dd-click-off-close').slideUp(50).siblings('.dd-select').find('.dd-pointer').removeClass('dd-pointer-up');
                    });
                }
            }
        });
    };

    //Public method to select an option by its index
    methods.select = function (options) {
        return this.each(function () {
            if (options.index!==undefined)
                selectIndex($(this), options.index);
            if (options.id)
                selectId($(this), options.id);
        });
    }

    //Public method to open drop down
    methods.open = function () {
        return this.each(function () {
            var $this = $(this),
                pluginData = $this.data('ddslick');

            //Check if plugin is initialized
            if (pluginData)
                open($this);
        });
    };

    //Public method to close drop down
    methods.close = function () {
        return this.each(function () {
            var $this = $(this),
                pluginData = $this.data('ddslick');

            //Check if plugin is initialized
            if (pluginData)
                close($this);
        });
    };

    //Public method to destroy. Unbind all events and restore the original Html select/options
    methods.destroy = function () {
        return this.each(function () {
            var $this = $(this),
                pluginData = $this.data('ddslick');

            //Check if already destroyed
            if (pluginData) {
                var originalElement = pluginData.original;
                $this.removeData('ddslick').unbind('.ddslick').replaceWith(originalElement);
            }
        });
    }

     //Private: Select id
    function selectId(obj, id) {

       var index = obj.find(".dd-option-value[value= '" + id + "']").parents("li").prevAll().length;
       selectIndex(obj, index);

    }

    //Private: Select index
    function selectIndex(obj, index) {

        //Get plugin data
        var pluginData = obj.data('ddslick');

        //Get required elements
        var ddSelected = obj.find('.dd-selected'),
            ddSelectedValue = ddSelected.siblings('.dd-selected-value'),
            ddOptions = obj.find('.dd-options'),
            ddPointer = ddSelected.siblings('.dd-pointer'),
            selectedOption = obj.find('.dd-option').eq(index),
            selectedLiItem = selectedOption.closest('li'),
            settings = pluginData.settings,
            selectedData = pluginData.settings.data[index];

        //Highlight selected option
        obj.find('.dd-option').removeClass('dd-option-selected');
        selectedOption.addClass('dd-option-selected');

        //Update or Set plugin data with new selection
        pluginData.selectedIndex = index;
        pluginData.selectedItem = selectedLiItem;
        pluginData.selectedData = selectedData;

        //If set to display to full html, add html
        if (settings.showSelectedHTML) {
            ddSelected.html(
                    (selectedData.imageSrc ? '' : '') +
                    (selectedData.text ? '' + selectedData.text + '' : '') +
                    (selectedData.description ? '' + selectedData.description + '' : '')
                );

        }
            //Else only display text as selection
        else ddSelected.html(selectedData.text);

        //Updating selected option value
        ddSelectedValue.val(selectedData.value);

        //BONUS! Update the original element attribute with the new selection
        pluginData.original.val(selectedData.value);
        obj.data('ddslick', pluginData);

        //Close options on selection
        close(obj);

        //Adjust appearence for selected option
        adjustSelectedHeight(obj);

        //Callback function on selection
        if (typeof settings.onSelected == 'function') {
            settings.onSelected.call(this, pluginData);
        }
    }

    //Private: Close the drop down options
    function open(obj) {

        var $this = obj.find('.dd-select'),
            ddOptions = $this.siblings('.dd-options'),
            ddPointer = $this.find('.dd-pointer'),
            wasOpen = ddOptions.is(':visible');

        //Close all open options (multiple plugins) on the page
        $('.dd-click-off-close').not(ddOptions).slideUp(50);
        $('.dd-pointer').removeClass('dd-pointer-up');

        if (wasOpen) {
            ddOptions.slideUp('fast');
            ddPointer.removeClass('dd-pointer-up');
        }
        else {
            ddOptions.slideDown('fast');
            ddPointer.addClass('dd-pointer-up');
        }

        //Fix text height (i.e. display title in center), if there is no description
        adjustOptionsHeight(obj);
    }

    //Private: Close the drop down options
    function close(obj) {
        //Close drop down and adjust pointer direction
        obj.find('.dd-options').slideUp(50);
        obj.find('.dd-pointer').removeClass('dd-pointer-up').removeClass('dd-pointer-up');
    }

    //Private: Adjust appearence for selected option (move title to middle), when no desripction
    function adjustSelectedHeight(obj) {

        //Get height of dd-selected
        var lSHeight = obj.find('.dd-select').css('height');

        //Check if there is selected description
        var descriptionSelected = obj.find('.dd-selected-description');
        var imgSelected = obj.find('.dd-selected-image');
        if (descriptionSelected.length <= 0 && imgSelected.length > 0) {
            obj.find('.dd-selected-text').css('lineHeight', lSHeight);
        }
    }

    //Private: Adjust appearence for drop down options (move title to middle), when no desripction
    function adjustOptionsHeight(obj) {
        obj.find('.dd-option').each(function () {
            var $this = $(this);
            var lOHeight = $this.css('height');
            var descriptionOption = $this.find('.dd-option-description');
            var imgOption = obj.find('.dd-option-image');
            if (descriptionOption.length <= 0 && imgOption.length > 0) {
                $this.find('.dd-option-text').css('lineHeight', lOHeight);
            }
        });
    }

})(jQuery);
<|endoftext|>


<commit_before>import {element} from 'deku';

import Headbox from './headbox';

let ITEM_HEIGHT = 22; // test

function wheelHandler(event, {props, state}) {
  event.preventDefault();

  // control scrolling speed
  this.scrollTop -= ITEM_HEIGHT * event.wheelDelta / 120 >> 0;
}

function render({props, state}) {
  return (

      <Headbox />

        {props.treeItems}

  );
}

function scrollHandler(event, {props, state}) {
  console.log(event);
}

export default {render};
<commit_msg>Sort event alphabetically and remove test code from box_template<commit_after>import {element} from 'deku';

import Headbox from './headbox';

function render({props, state}) {
  return (

      <Headbox />

        {props.treeItems}

  );
}

function scrollHandler(event, {props, state}) {
}

function wheelHandler(event, {props, state}) {
  event.preventDefault();
}

export default {render};
<|endoftext|>


<commit_before>if (App.namespace) {
	App.namespace('Action.Changecolor', function (App) {
		/** @type {App.Module.DataStore} */

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

			$(document).ready(function () {

				var Usercolors = function (baseUrl) {
					this._baseUrl = baseUrl;
					this._usercolors = [];
					this._activeUsercolor = undefined;
				};

				Usercolors.prototype = {
					getAll: function () {
						return this._usercolors;
					},
					loadAll: function () {
						var deferred = $.Deferred();
						var self = this;
						$.get(this._baseUrl).done(function (usercolors) {
							self._activeUsercolor = undefined;
							self._usercolors = usercolors;
							deferred.resolve();
						}).fail(function () {
							deferred.reject();
						});
						return deferred.promise();
					},
				};

				$('#sidebar_tab_3').click(function () {
					if ($('#userlist').length == 0) {
						var DataStore = App.Module.DataStore;
						var fragment = document.createDocumentFragment();
						var groupsusers = DataStore.get('groupsusers');
						var deprecatedUsers = ['collab_user'];
						var _table = document.createElement('table');
						_table.innerHTML += '

Group-/ Username	Color

';
						_table.innerHTML += '

';
						_table.id = 'userlist';
						_table.width = '100%';
						var _tableRef = _table.getElementsByTagName('tbody')[0];

						for (var groupName in groupsusers) {
							var _lineGroup = document.createElement('div'),
								_lineUsers = document.createElement('div'),
								_inputGroup = document.createElement('input'),
								_inputLabel = document.createElement('label'),
								_inputSpan = document.createElement('span'),
								users = groupsusers[groupName],
								usersCount = users.length;
							_inputGroup.name = String(groupName).trim();
							_inputGroup.type = 'checkbox';
							_inputGroup.className = 'group';
							_inputGroup.setAttribute('data-type', 'group');
							_lineGroup.appendChild(_inputGroup);
							_inputLabel.appendChild(_inputSpan);
							_lineGroup.appendChild(_inputLabel);
							_inputGroup.id = 'group' + groupName;
							_inputLabel.setAttribute('for', 'group' + groupName);
							_inputLabel.innerHTML += ' ' + Util.ucfirst(groupName) + '';
							var rowCount = _tableRef.rows.length;
							var row = _tableRef.insertRow(rowCount);
							var colorId = 'col_g_' + groupName;
							row.insertCell(0).innerHTML = '' + Util.ucfirst(groupName) + '';
							row.insertCell(1).innerHTML = '<input type="text" id="' + colorId + '" />';

							for (var i = 0; i < usersCount; i++) {
								if (deprecatedUsers.indexOf(users[i]['uid']) !== -1) continue;
								var _inlineUser = document.createElement('span'),
									_inputUser = document.createElement('input'),
									_inputUserLabel = document.createElement('label'),
									_inputUserSpan = document.createElement('span');
								_inputUser.name = users[i]['uid'];
								_inputUser.type = 'checkbox';
								_inputUser.className = 'user';
								_inputUser.setAttribute('data-type', 'user');
								_inputUser.setAttribute('data-gid', users[i]['gid']);
								_inputUser.id = 'u_' + users[i]['uid'];
								_inputUserLabel.setAttribute('for', 'u_' + users[i]['uid']);
								_inputUserLabel.appendChild(_inputUserSpan);
								_inputUserLabel.innerHTML += users[i]['uid'];
								_inlineUser.appendChild(_inputUser);
								_inlineUser.appendChild(_inputUserLabel);
								_lineUsers.appendChild(_inlineUser);
								var rowCount = _tableRef.rows.length;
								var row = _tableRef.insertRow(rowCount);
								var uid = users[i]['uid'];
								var colorId = 'col_u_' + uid;
								row.insertCell(0).innerHTML = uid;
								row.insertCell(1).innerHTML = '<input type="text" id="' + colorId + '" />';
							}
							$('#chart_coloring').append(_table);
						}
					}

					$.fn.renderColors function() {
						for (var groupName in groupsusers) {
							var users = groupsusers[groupName],
								usersCount = users.length;

							$("#col_g_" + groupName).spectrum({
								color: "rgb(244, 204, 204)",
								showPaletteOnly: true,
								palette: [
									["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)",
										"rgb(204, 204, 204)", "rgb(217, 217, 217)", "rgb(255, 255, 255)"],
									["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
										"rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
									["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
										"rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
										"rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
										"rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
										"rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
										"rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
										"rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
										"rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
										"rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
										"rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
								]
							});

							for (var i = 0; i < usersCount; i++) {
								if (deprecatedUsers.indexOf(users[i]['uid']) !== -1) continue;
								var uid = users[i]['uid'];
								var cindex = usercolors._usercolors.indexOf(uid);
								console.log(cindex);
								$("#col_u_" + uid).spectrum({
									color: "rgb(244, 204, 204)",
									showPaletteOnly: true,
									palette: [
										["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)",
											"rgb(204, 204, 204)", "rgb(217, 217, 217)", "rgb(255, 255, 255)"],
										["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
											"rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
										["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
											"rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
											"rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
											"rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
											"rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
											"rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
											"rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
											"rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
											"rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
											"rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
									]
								});
							}
						}
					});
			}

				var baseUrl = OC.generateUrl('apps/owncollab_chart');
			var usercolor = {
				user: 'new user',
				colorcode: 'rgb(255, 255, 255)'
			};

			var usercolors = new Usercolors(OC.generateUrl('/apps/owncollab_chart/colors'));
			usercolors.loadAll().done(function () {
				renderColors();
				$.each(usercolors._usercolors, function (i, data) {
					console.log('username: ' + data.user + ' color: ' + data.colorcode);
				});
			}).fail(function () {
				alert('Could not load usercolors');
			});
			//				console.log(baseUrl);
			//				$.getJSON(baseUrl + '/colors', function(result){
			//					var items="";
			//					$.each(result, function(i, data){
			//						console.log('uid:' + data.user + ' color:' + data.colorcode)
			//					});
			//				});

		});
	})(OC, window, jQuery);
})
}
<commit_msg>added missing =<commit_after>if (App.namespace) {
	App.namespace('Action.Changecolor', function (App) {
		/** @type {App.Module.DataStore} */

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

			$(document).ready(function () {

				var Usercolors = function (baseUrl) {
					this._baseUrl = baseUrl;
					this._usercolors = [];
					this._activeUsercolor = undefined;
				};

				Usercolors.prototype = {
					getAll: function () {
						return this._usercolors;
					},
					loadAll: function () {
						var deferred = $.Deferred();
						var self = this;
						$.get(this._baseUrl).done(function (usercolors) {
							self._activeUsercolor = undefined;
							self._usercolors = usercolors;
							deferred.resolve();
						}).fail(function () {
							deferred.reject();
						});
						return deferred.promise();
					},
				};

				$('#sidebar_tab_3').click(function () {
					if ($('#userlist').length == 0) {
						var DataStore = App.Module.DataStore;
						var fragment = document.createDocumentFragment();
						var groupsusers = DataStore.get('groupsusers');
						var deprecatedUsers = ['collab_user'];
						var _table = document.createElement('table');
						_table.innerHTML += '

Group-/ Username	Color

';
						_table.innerHTML += '

';
						_table.id = 'userlist';
						_table.width = '100%';
						var _tableRef = _table.getElementsByTagName('tbody')[0];

						for (var groupName in groupsusers) {
							var _lineGroup = document.createElement('div'),
								_lineUsers = document.createElement('div'),
								_inputGroup = document.createElement('input'),
								_inputLabel = document.createElement('label'),
								_inputSpan = document.createElement('span'),
								users = groupsusers[groupName],
								usersCount = users.length;
							_inputGroup.name = String(groupName).trim();
							_inputGroup.type = 'checkbox';
							_inputGroup.className = 'group';
							_inputGroup.setAttribute('data-type', 'group');
							_lineGroup.appendChild(_inputGroup);
							_inputLabel.appendChild(_inputSpan);
							_lineGroup.appendChild(_inputLabel);
							_inputGroup.id = 'group' + groupName;
							_inputLabel.setAttribute('for', 'group' + groupName);
							_inputLabel.innerHTML += ' ' + Util.ucfirst(groupName) + '';
							var rowCount = _tableRef.rows.length;
							var row = _tableRef.insertRow(rowCount);
							var colorId = 'col_g_' + groupName;
							row.insertCell(0).innerHTML = '' + Util.ucfirst(groupName) + '';
							row.insertCell(1).innerHTML = '<input type="text" id="' + colorId + '" />';

							for (var i = 0; i < usersCount; i++) {
								if (deprecatedUsers.indexOf(users[i]['uid']) !== -1) continue;
								var _inlineUser = document.createElement('span'),
									_inputUser = document.createElement('input'),
									_inputUserLabel = document.createElement('label'),
									_inputUserSpan = document.createElement('span');
								_inputUser.name = users[i]['uid'];
								_inputUser.type = 'checkbox';
								_inputUser.className = 'user';
								_inputUser.setAttribute('data-type', 'user');
								_inputUser.setAttribute('data-gid', users[i]['gid']);
								_inputUser.id = 'u_' + users[i]['uid'];
								_inputUserLabel.setAttribute('for', 'u_' + users[i]['uid']);
								_inputUserLabel.appendChild(_inputUserSpan);
								_inputUserLabel.innerHTML += users[i]['uid'];
								_inlineUser.appendChild(_inputUser);
								_inlineUser.appendChild(_inputUserLabel);
								_lineUsers.appendChild(_inlineUser);
								var rowCount = _tableRef.rows.length;
								var row = _tableRef.insertRow(rowCount);
								var uid = users[i]['uid'];
								var colorId = 'col_u_' + uid;
								row.insertCell(0).innerHTML = uid;
								row.insertCell(1).innerHTML = '<input type="text" id="' + colorId + '" />';
							}
							$('#chart_coloring').append(_table);
						}
					}

					$.fn.renderColors = function() {
						for (var groupName in groupsusers) {
							var users = groupsusers[groupName],
								usersCount = users.length;

							$("#col_g_" + groupName).spectrum({
								color: "rgb(244, 204, 204)",
								showPaletteOnly: true,
								palette: [
									["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)",
										"rgb(204, 204, 204)", "rgb(217, 217, 217)", "rgb(255, 255, 255)"],
									["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
										"rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
									["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
										"rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
										"rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
										"rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
										"rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
										"rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
										"rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
										"rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
										"rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
										"rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
								]
							});

							for (var i = 0; i < usersCount; i++) {
								if (deprecatedUsers.indexOf(users[i]['uid']) !== -1) continue;
								var uid = users[i]['uid'];
								var cindex = usercolors._usercolors.indexOf(uid);
								console.log(cindex);
								$("#col_u_" + uid).spectrum({
									color: "rgb(244, 204, 204)",
									showPaletteOnly: true,
									palette: [
										["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)",
											"rgb(204, 204, 204)", "rgb(217, 217, 217)", "rgb(255, 255, 255)"],
										["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
											"rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
										["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
											"rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
											"rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
											"rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
											"rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
											"rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
											"rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
											"rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
											"rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
											"rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
									]
								});
							}
						}
					});
			}

				var baseUrl = OC.generateUrl('apps/owncollab_chart');
			var usercolor = {
				user: 'new user',
				colorcode: 'rgb(255, 255, 255)'
			};

			var usercolors = new Usercolors(OC.generateUrl('/apps/owncollab_chart/colors'));
			usercolors.loadAll().done(function () {
				renderColors();
				$.each(usercolors._usercolors, function (i, data) {
					console.log('username: ' + data.user + ' color: ' + data.colorcode);
				});
			}).fail(function () {
				alert('Could not load usercolors');
			});
			//				console.log(baseUrl);
			//				$.getJSON(baseUrl + '/colors', function(result){
			//					var items="";
			//					$.each(result, function(i, data){
			//						console.log('uid:' + data.user + ' color:' + data.colorcode)
			//					});
			//				});

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


<commit_before>function CodeDisplayManager(language, algorithmOrDataStructure) {

    this.codeRoot;
    this.currentClass;
    this.currentFunction;
	this.currentLine;
	this.variables;
	this.variableMap;

    var self = this;

    $.ajax({
        url: "./js/codedisplay/code.json",
        dataType: "json",
        async: false,
        success: function (data) {
            self.codeRoot = data;
			self.currentClass = data[language][algorithmOrDataStructure];
			self.variables = data[language][algorithmOrDataStructure]["variables"];
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
}

CodeDisplayManager.prototype.loadFunctions = function () {
    $("#code-text").empty();
    for (var i = 0; i < arguments.length; i++) {
        $("#code-text").append("" + this.currentClass[arguments[i]].header + "\n");
        for(var j = 0; j < this.currentClass[arguments[i]].lines.length; j++)
            $("#" + arguments[i]).append(this.makeHighlightSpan(this.currentClass[arguments[i]].lines[j]));

        $("#code-text").append("\n\n");
    }

    hljs.initHighlighting.called = false;
    hljs.initHighlighting();
    this.addVariableTooltips();
};

CodeDisplayManager.prototype.makeHighlightSpan = function (line) {
    var textStartIndex = line.search(/\S|$/);
	return line.slice(0, textStartIndex) + "" + line.slice(textStartIndex) + "\n";
};

CodeDisplayManager.prototype.addVariableTooltips = function () {
	// Make a map containing variable name and corresponding value if it is not already done.
	if (this.variableMap === undefined) {
		this.variableMap = this.variables.reduce(function (map, obj) {
			map[obj.name] = "Var";
			return map;
		}, {});
	}

	var words = this.variables.map(function (a) { return a.name; });

	var regexp = new RegExp('( ?' + words.join('?| ?') + '?)', 'g');

	var text = $("#code-text").html();

	text = text.replace(regexp, '$&');

	$("#code-text").html(text);

	$(".variable").qtip({
		style: { classes: "qtip-tipsy" }
	});
};

CodeDisplayManager.prototype.updateVariable = function (varName, value) {
	if (varName in this.variableMap) {
		oldValue = this.variableMap[varName];
		this.variableMap[varName] = value;
		return {
			e: ".tooltip-" + varName, p: {
				onComplete: function () {
					$(".tooltip-" + varName).qtip('option', 'content.text', value);
				},
				onReverseComplete: function () {
					$(".tooltip-" + varName).qtip('option', 'content.text', oldValue);
				}
			}
		};
	}
	else {
		console.error("Variable " + varName + " does not exist");
		return null;
	}
};

CodeDisplayManager.prototype.setVariable = function (varName, value) {
	if (varName in this.variableMap) {
		this.variableMap[varName] = value;
		$(".tooltip-" + varName).qtip('option', 'content.text', value);
	}
	else {
		console.error("Variable " + varName + " does not exist");
	}
};

CodeDisplayManager.prototype.changeFunction = function (functionName, line) {
    if (line == null)
        line = 0;

    this.currentFunction = functionName;
    this.currentLine = line;
};

CodeDisplayManager.prototype.highlightNextLine = function (highlightTime, initialDelay) {
    this.highlightLine(this.currentLine, highlightTime, initialDelay);
    this.currentLine++;
};

CodeDisplayManager.prototype.getHighlightInfo = function (index, highlightTime) {
    if (highlightTime == null) highlightTime = 1000;

    var lineToDisplay = $("#" + this.currentFunction).find(".highlighted-code");

    this.currentLine = index++;

    return [
        { e: lineToDisplay[index - 1], p: { backgroundColor: 'rgba(255,255,0,1)' }, o: { duration: highlightTime / 2 } },
        { e: lineToDisplay[index - 1], p: { backgroundColor: 'transparent' }, o: { duration: highlightTime / 2 } }
    ];
};

CodeDisplayManager.prototype.getMultiHighlightInfo = function (indexArray, highlightTime) {
    var frames = [];

    for (var i = 0; i < indexArray.length; i++) {
        frames = frames.concat(this.getHighlightInfo(indexArray[i], highlightTime));
    }

    return frames;
};<commit_msg>Prevented error when variables are not defined for visualization<commit_after>function CodeDisplayManager(language, algorithmOrDataStructure) {

    this.codeRoot;
    this.currentClass;
    this.currentFunction;
	this.currentLine;
	this.variables;
	this.variableMap;

    var self = this;

    $.ajax({
        url: "./js/codedisplay/code.json",
        dataType: "json",
        async: false,
        success: function (data) {
            self.codeRoot = data;
			self.currentClass = data[language][algorithmOrDataStructure];
			self.variables = data[language][algorithmOrDataStructure]["variables"];
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
}

CodeDisplayManager.prototype.loadFunctions = function () {
    $("#code-text").empty();
    for (var i = 0; i < arguments.length; i++) {
        $("#code-text").append("" + this.currentClass[arguments[i]].header + "\n");
        for(var j = 0; j < this.currentClass[arguments[i]].lines.length; j++)
            $("#" + arguments[i]).append(this.makeHighlightSpan(this.currentClass[arguments[i]].lines[j]));

        $("#code-text").append("\n\n");
    }

    hljs.initHighlighting.called = false;
    hljs.initHighlighting();
    this.addVariableTooltips();
};

CodeDisplayManager.prototype.makeHighlightSpan = function (line) {
    var textStartIndex = line.search(/\S|$/);
	return line.slice(0, textStartIndex) + "" + line.slice(textStartIndex) + "\n";
};

CodeDisplayManager.prototype.addVariableTooltips = function () {
	if (this.variables == null)
		return

	// Make a map containing variable name and corresponding value if it is not already done.
	if (this.variableMap === undefined) {
		this.variableMap = this.variables.reduce(function (map, obj) {
			map[obj.name] = "Var";
			return map;
		}, {});
	}

	var words = this.variables.map(function (a) { return a.name; });

	var regexp = new RegExp('( ?' + words.join('?| ?') + '?)', 'g');

	var text = $("#code-text").html();

	text = text.replace(regexp, '$&');

	$("#code-text").html(text);

	$(".variable").qtip({
		style: { classes: "qtip-tipsy" }
	});
};

CodeDisplayManager.prototype.updateVariable = function (varName, value) {
	if (varName in this.variableMap) {
		oldValue = this.variableMap[varName];
		this.variableMap[varName] = value;
		return {
			e: ".tooltip-" + varName, p: {
				onComplete: function () {
					$(".tooltip-" + varName).qtip('option', 'content.text', value);
				},
				onReverseComplete: function () {
					$(".tooltip-" + varName).qtip('option', 'content.text', oldValue);
				}
			}
		};
	}
	else {
		console.error("Variable " + varName + " does not exist");
		return null;
	}
};

CodeDisplayManager.prototype.setVariable = function (varName, value) {
	if (varName in this.variableMap) {
		this.variableMap[varName] = value;
		$(".tooltip-" + varName).qtip('option', 'content.text', value);
	}
	else {
		console.error("Variable " + varName + " does not exist");
	}
};

CodeDisplayManager.prototype.changeFunction = function (functionName, line) {
    if (line == null)
        line = 0;

    this.currentFunction = functionName;
    this.currentLine = line;
};

CodeDisplayManager.prototype.highlightNextLine = function (highlightTime, initialDelay) {
    this.highlightLine(this.currentLine, highlightTime, initialDelay);
    this.currentLine++;
};

CodeDisplayManager.prototype.getHighlightInfo = function (index, highlightTime) {
    if (highlightTime == null) highlightTime = 1000;

    var lineToDisplay = $("#" + this.currentFunction).find(".highlighted-code");

    this.currentLine = index++;

    return [
        { e: lineToDisplay[index - 1], p: { backgroundColor: 'rgba(255,255,0,1)' }, o: { duration: highlightTime / 2 } },
        { e: lineToDisplay[index - 1], p: { backgroundColor: 'transparent' }, o: { duration: highlightTime / 2 } }
    ];
};

CodeDisplayManager.prototype.getMultiHighlightInfo = function (indexArray, highlightTime) {
    var frames = [];

    for (var i = 0; i < indexArray.length; i++) {
        frames = frames.concat(this.getHighlightInfo(indexArray[i], highlightTime));
    }

    return frames;
};<|endoftext|>


<commit_before>/**
 * Module : Kero datetime
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-08-09 14:59:37
 */

import {BaseAdapter} from '../core/baseAdapter';
import {ValueMixin} from '../core/valueMixin';
import {EnableMixin} from '../core/enableMixin';
import {RequiredMixin} from '../core/requiredMixin';
import {ValidateMixin} from '../core/validateMixin';
import {on,off,stopEvent} from 'tinper-sparrow/js/event';
import {addClass,removeClass} from 'tinper-sparrow/js/dom';
import {core} from 'tinper-sparrow/js/core';

import {DataTable} from 'kero/js/dataTable/indexDataTable';
import {env} from 'tinper-sparrow/js/env';
import {DateTimePicker} from 'tinper-neoui/js/neoui-datetimepicker';
import {date} from 'tinper-sparrow/js/util/dateUtils';
import {compMgr} from 'tinper-sparrow/js/compMgr';
import {getFunction} from 'tinper-sparrow/js/util';

var DateTimeAdapter = BaseAdapter.extend({
	mixins: [ValueMixin,EnableMixin,RequiredMixin, ValidateMixin],
	init: function (options) {
		var self = this,adapterType,format;
		// DateTimeAdapter.superclass.initialize.apply(this, arguments);
		if (this.options.type === 'u-date'){
			this.adapterType = 'date';
		}else{
			this.adapterType = 'datetime'
			addClass(this.element,'time');
		}

		this.beforeValueChangeFun = getFunction(this.viewModel, this.options['beforeValueChangeFun']);

		this.maskerMeta = core.getMaskerMeta(this.adapterType) || {};
		this.maskerMeta.format = this.options['format'] || this.maskerMeta.format;
		if(this.dataModel){
			this.dataModel.on(this.field + '.format.' +  DataTable.ON_CURRENT_META_CHANGE, function(event){
				self.setFormat(event.newValue)
			});
		}

		if(this.dataModel && !this.options['format'])
			this.options.format = this.dataModel.getMeta(this.field, "format")

		if(!this.options['format']){
			if(this.options.type === 'u-date'){
				this.options.format = "YYYY-MM-DD";
			}else if(this.options.type === 'year'){
				this.options.format = "YYYY";
			}else if(this.options.type === 'month'){
				this.options.format = "MM";
			}else if(this.options.type === 'yearmonth'){
				this.options.format = "YYYY-MM";
			}else{
				this.options.format = "YYYY-MM-DD HH:mm:ss";
			}
		}
		format = this.options.format;
		this.maskerMeta.format = format || this.maskerMeta.format

		this.startField = this.options.startField?this.options.startField : this.dataModel.getMeta(this.field, "startField");

		this.endField = this.options.endField?this.options.endField : this.dataModel.getMeta(this.field, "endField");

		// this.formater = new $.DateFormater(this.maskerMeta.format);
		// this.masker = new DateTimeMasker(this.maskerMeta);
		this.op = {};
		var mobileDateFormat = "", mobileTimeFormat = "", mobileOrder = "";
		if(env.isMobile){
			switch (format) {
				case "YYYY-MM-DD":
					mobileDateFormat = "yy-mm-dd";
					mobileOrder = mobileDateFormat.replace(/-/g, '');
					break;
				case "YYYY-MM-DD HH:mm":
					mobileDateFormat = "yy-mm-dd";
					mobileTimeFormat = "HH:ii".replace(/\:/g, '');
					mobileOrder = mobileDateFormat.replace(/-/g, '') + mobileTimeFormat.replace(/\:/g, '');
					break;
				case "YYYY-MM":
					mobileDateFormat = "yy-mm";
					mobileOrder = mobileDateFormat.replace(/-/g, '');
					break;
				default:
					mobileDateFormat = "yy-mm-dd";
					mobileTimeFormat = "HH:ii:ss";
					mobileOrder = mobileDateFormat.replace(/-/g, '') + mobileTimeFormat.replace(/\:/g, '');
			}

			this.op = {
				theme:"ios",
				mode:"scroller",
				lang: "zh",
				cancelText: null,
				dateOrder: mobileOrder,
				dateFormat: mobileDateFormat,
				timeFormat: mobileTimeFormat,
				onSelect:function(val){
					if(typeof self.options.beforeValueChangeFun == 'function'){
				        if(!self.options.beforeValueChangeFun.call(this,this.pickerDate)){
				            return;
				        }
				    }
					self.setValue(val);
				}
			}
			this._span = this.element.querySelector("span");
			this.element = this.element.querySelector("input");
			this.element.setAttribute('readonly','readonly');
			if (this._span){
		        on(this._span, 'click', function(e){
		            self.element.focus();
		            stopEvent(e);
		        });
		    }
			if(this.adapterType == 'date'){
				$(this.element).mobiscroll().date(this.op);
			}else{
				$(this.element).mobiscroll().datetime(this.op);
			}
		}else{
			this.comp = new DateTimePicker({el:this.element,format:this.maskerMeta.format,showFix:this.options.showFix,beforeValueChangeFun:this.beforeValueChangeFun});
		}

		this.element['u.DateTimePicker'] = this.comp;

		if(!env.isMobile){
			this.comp.on('select', function(event){
				self.setValue(event.value);
			});
		}

		this.setStartField(this.startField);
		this.setEndField(this.endField);
        if(!env.isMobile){
			// 校验
			this.comp.on('validate', function(event){
				self.doValidate();
			});
		}
	},

	setEndField: function(endField){
		var self = this;
		self.endField = endField;
		if(self.dataModel){
			if(self.endField){
				self.dataModel.ref(self.endField).subscribe(function(value) {
					if(env.isMobile){
						var valueObj = date.getDateObj(value);
						self.op.minDate = valueObj;
						if(self.adapterType == 'date'){
							$(self.element).mobiscroll().date(self.op);
						}else{
							$(self.element).mobiscroll().datetime(self.op);
						}
						var nowDate = date.getDateObj(self.dataModel.getValue(self.field));
						if(nowDate < valueObj || !value){
							self.dataModel.setValue(self.field,'');
						}
					}else{
						self.comp.setEndDate(value);
						if(self.comp.date > date.getDateObj(value) || !value){
							self.dataModel.setValue(self.field,'');
						}
					}

				});
			}

			if(self.endField){
				var endValue = self.dataModel.getValue(self.endField);
				if(endValue){
					if(env.isMobile){
						self.op.minDate = date.getDateObj(endValue);
						if(self.adapterType == 'date'){
							$(self.element).mobiscroll().date(self.op);
						}else{
							$(self.element).mobiscroll().datetime(self.op);
						}
					}else{
						self.comp.setEndDate(endValue);
					}
				}
			}
		}
	},

	setStartField: function(startField){
		var self = this;
		self.startField = startField;
		if(self.dataModel){
			if(self.startField){
				self.dataModel.ref(self.startField).subscribe(function(value) {
					if(env.isMobile){
						value = date.getDateObj(value);

						var valueObj = self.setMobileStartDate(value, self.options.format);
						self.op.minDate = valueObj;
						if(self.adapterType == 'date'){
							$(self.element).mobiscroll().date(self.op);
						}else{
							$(self.element).mobiscroll().datetime(self.op);
						}
						var nowDate = date.getDateObj(self.dataModel.getValue(self.field));
						if(nowDate < valueObj || !value){
							self.dataModel.setValue(self.field,'');
						}
					}else{
						self.comp.setStartDate(value, self.options.format);
						if(self.comp.date < date.getDateObj(value) || !value){
							self.dataModel.setValue(self.field,'');
						}
					}

				});
			}
			if(self.startField){
				var startValue = self.dataModel.getValue(self.startField);
				if(startValue){
					if(env.isMobile){
						startValue = date.getDateObj(startValue);
						self.op.minDate = self.setMobileStartDate(startValue, self.options.format);
						if(self.adapterType == 'date'){
							$(self.element).mobiscroll().date(self.op);
						}else{
							$(self.element).mobiscroll().datetime(self.op);
						}
					}else{
						self.comp.setStartDate(startValue, self.options.format);
					}
				}
			}
		}
	},

	setMobileStartDate: function (startDate, type) {

	    if(startDate){
	        switch (type) {
	            case 'YYYY-MM':
	                startDate = date.add(startDate, 'M', 1);
	                break;
	            case 'YYYY-MM-DD':
	                startDate = date.add(startDate, 'd', 1);
	                break;
	        }
	    }
	    return startDate;
	},

	modelValueChange: function(value){
		if (this.slice) return;
		this.trueValue = value;
		if(env.isMobile){
			if(value){
				value = date.format(value,this.options.format);
				$(this.element).scroller('setDate', date.getDateObj(value), true);
			}
		}else{
			this.comp.setDate(value);
		}

	},
	setFormat: function(format){
		if (this.maskerMeta.format == format) return;
		this.options.format = format;
		this.maskerMeta.format = format;
		if(!env.isMobile)
			this.comp.setFormat(format);
		// this.formater = new $.DateFormater(this.maskerMeta.format);
		// this.masker = new DateTimeMasker(this.maskerMeta);
	},
	setValue: function (value) {
		value = date.format(value,this.options.format);
        this.trueValue = this.formater ? this.formater.format(value) : value;
        this.showValue = this.masker ? this.masker.format(this.trueValue).value : this.trueValue;
        this.setShowValue(this.showValue);
        this.slice = true;
        this.dataModel.setValue(this.field, this.trueValue);
        this.slice = false;
    },
    setEnable: function(enable){
        if (enable === true || enable === 'true') {
            this.enable = true;
            if(env.isMobile){
            	this.element.removeAttribute('disabled');
            }else{
            	this.comp._input.removeAttribute('readonly');
            }
            removeClass(this.element.parentNode,'disablecover');
        } else if (enable === false || enable === 'false') {
            this.enable = false;
            if(env.isMobile){
            	this.element.setAttribute('disabled','disabled');
            }else{
            	this.comp._input.setAttribute('readonly', 'readonly');
            }
            addClass(this.element.parentNode,'disablecover');
        }
        if(!env.isMobile)
        	this.comp.setEnable(enable);
    }

});

compMgr.addDataAdapter({
	adapter: DateTimeAdapter,
	name: 'u-date'
});

compMgr.addDataAdapter({
	adapter: DateTimeAdapter,
	name: 'u-datetime'
});

export {DateTimeAdapter};
<commit_msg>add ios datetimewheel<commit_after>/**
 * Module : Kero datetime
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-08-09 14:59:37
 */

import {BaseAdapter} from '../core/baseAdapter';
import {ValueMixin} from '../core/valueMixin';
import {EnableMixin} from '../core/enableMixin';
import {RequiredMixin} from '../core/requiredMixin';
import {ValidateMixin} from '../core/validateMixin';
import {on,off,stopEvent} from 'tinper-sparrow/js/event';
import {addClass,removeClass} from 'tinper-sparrow/js/dom';
import {core} from 'tinper-sparrow/js/core';

import {DataTable} from 'kero/js/dataTable/indexDataTable';
import {env} from 'tinper-sparrow/js/env';
import {DateTimePicker} from 'tinper-neoui/js/neoui-datetimepicker';
import {date} from 'tinper-sparrow/js/util/dateUtils';
import {compMgr} from 'tinper-sparrow/js/compMgr';
import {getFunction} from 'tinper-sparrow/js/util';

var DateTimeAdapter = BaseAdapter.extend({
	mixins: [ValueMixin,EnableMixin,RequiredMixin, ValidateMixin],
	init: function (options) {
		var self = this,adapterType,format;
		// DateTimeAdapter.superclass.initialize.apply(this, arguments);
		if (this.options.type === 'u-date'){
			this.adapterType = 'date';
		}else{
			this.adapterType = 'datetime'
			addClass(this.element,'time');
		}

		this.beforeValueChangeFun = getFunction(this.viewModel, this.options['beforeValueChangeFun']);

		this.maskerMeta = core.getMaskerMeta(this.adapterType) || {};
		this.maskerMeta.format = this.options['format'] || this.maskerMeta.format;
		if(this.dataModel){
			this.dataModel.on(this.field + '.format.' +  DataTable.ON_CURRENT_META_CHANGE, function(event){
				self.setFormat(event.newValue)
			});
		}

		if(this.dataModel && !this.options['format'])
			this.options.format = this.dataModel.getMeta(this.field, "format")

		if(!this.options['format']){
			if(this.options.type === 'u-date'){
				this.options.format = "YYYY-MM-DD";
			}else if(this.options.type === 'year'){
				this.options.format = "YYYY";
			}else if(this.options.type === 'month'){
				this.options.format = "MM";
			}else if(this.options.type === 'yearmonth'){
				this.options.format = "YYYY-MM";
			}else{
				this.options.format = "YYYY-MM-DD HH:mm:ss";
			}
		}
		format = this.options.format;
		this.maskerMeta.format = format || this.maskerMeta.format

		this.startField = this.options.startField?this.options.startField : this.dataModel.getMeta(this.field, "startField");

		this.endField = this.options.endField?this.options.endField : this.dataModel.getMeta(this.field, "endField");

		// this.formater = new $.DateFormater(this.maskerMeta.format);
		// this.masker = new DateTimeMasker(this.maskerMeta);
		this.op = {};
		var mobileDateFormat = "", mobileTimeFormat = "", dateOrder = "", timeOrder = "";
		if(env.isMobile){
			switch (format) {
				case "YYYY-MM-DD":
					mobileDateFormat = "yy-mm-dd";
					dateOrder = mobileDateFormat.replace(/-/g, '');
					break;
				case "YYYY-MM-DD HH:mm":
					mobileDateFormat = "yy-mm-dd";
					mobileTimeFormat = "HH:ii".replace(/\:/g, '');
					dateOrder = mobileDateFormat.replace(/-/g, '');
					timeOrder = mobileTimeFormat.replace(/\:/g, '');
					break;
				case "YYYY-MM":
					mobileDateFormat = "yy-mm";
					dateOrder = mobileDateFormat.replace(/-/g, '');
					break;
				default:
					mobileDateFormat = "yy-mm-dd";
					mobileTimeFormat = "HH:ii:ss";
					dateOrder = mobileDateFormat.replace(/-/g, '');
					timeOrder = mobileTimeFormat.replace(/\:/g, '');
			}

			this.op = {
				theme:"ios",
				mode:"scroller",
				lang: "zh",
				cancelText: null,
				dateFormat: mobileDateFormat,
				timeWheels: timeOrder,
				dateWheels: dateOrder,
				timeFormat: mobileTimeFormat,
				onSelect:function(val){
					if(typeof self.options.beforeValueChangeFun == 'function'){
				        if(!self.options.beforeValueChangeFun.call(this,this.pickerDate)){
				            return;
				        }
				    }
					self.setValue(val);
				}
			}
			this._span = this.element.querySelector("span");
			this.element = this.element.querySelector("input");
			this.element.setAttribute('readonly','readonly');
			if (this._span){
		        on(this._span, 'click', function(e){
		            self.element.focus();
		            stopEvent(e);
		        });
		    }
			if(this.adapterType == 'date'){
				$(this.element).mobiscroll().date(this.op);
			}else{
				$(this.element).mobiscroll().datetime(this.op);
			}
		}else{
			this.comp = new DateTimePicker({el:this.element,format:this.maskerMeta.format,showFix:this.options.showFix,beforeValueChangeFun:this.beforeValueChangeFun});
		}

		this.element['u.DateTimePicker'] = this.comp;

		if(!env.isMobile){
			this.comp.on('select', function(event){
				self.setValue(event.value);
			});
		}

		this.setStartField(this.startField);
		this.setEndField(this.endField);
        if(!env.isMobile){
			// 校验
			this.comp.on('validate', function(event){
				self.doValidate();
			});
		}
	},

	setEndField: function(endField){
		var self = this;
		self.endField = endField;
		if(self.dataModel){
			if(self.endField){
				self.dataModel.ref(self.endField).subscribe(function(value) {
					if(env.isMobile){
						var valueObj = date.getDateObj(value);
						self.op.minDate = valueObj;
						if(self.adapterType == 'date'){
							$(self.element).mobiscroll().date(self.op);
						}else{
							$(self.element).mobiscroll().datetime(self.op);
						}
						var nowDate = date.getDateObj(self.dataModel.getValue(self.field));
						if(nowDate < valueObj || !value){
							self.dataModel.setValue(self.field,'');
						}
					}else{
						self.comp.setEndDate(value);
						if(self.comp.date > date.getDateObj(value) || !value){
							self.dataModel.setValue(self.field,'');
						}
					}

				});
			}

			if(self.endField){
				var endValue = self.dataModel.getValue(self.endField);
				if(endValue){
					if(env.isMobile){
						self.op.minDate = date.getDateObj(endValue);
						if(self.adapterType == 'date'){
							$(self.element).mobiscroll().date(self.op);
						}else{
							$(self.element).mobiscroll().datetime(self.op);
						}
					}else{
						self.comp.setEndDate(endValue);
					}
				}
			}
		}
	},

	setStartField: function(startField){
		var self = this;
		self.startField = startField;
		if(self.dataModel){
			if(self.startField){
				self.dataModel.ref(self.startField).subscribe(function(value) {
					if(env.isMobile){
						value = date.getDateObj(value);

						var valueObj = self.setMobileStartDate(value, self.options.format);
						self.op.minDate = valueObj;
						if(self.adapterType == 'date'){
							$(self.element).mobiscroll().date(self.op);
						}else{
							$(self.element).mobiscroll().datetime(self.op);
						}
						var nowDate = date.getDateObj(self.dataModel.getValue(self.field));
						if(nowDate < valueObj || !value){
							self.dataModel.setValue(self.field,'');
						}
					}else{
						self.comp.setStartDate(value, self.options.format);
						if(self.comp.date < date.getDateObj(value) || !value){
							self.dataModel.setValue(self.field,'');
						}
					}

				});
			}
			if(self.startField){
				var startValue = self.dataModel.getValue(self.startField);
				if(startValue){
					if(env.isMobile){
						startValue = date.getDateObj(startValue);
						self.op.minDate = self.setMobileStartDate(startValue, self.options.format);
						if(self.adapterType == 'date'){
							$(self.element).mobiscroll().date(self.op);
						}else{
							$(self.element).mobiscroll().datetime(self.op);
						}
					}else{
						self.comp.setStartDate(startValue, self.options.format);
					}
				}
			}
		}
	},

	setMobileStartDate: function (startDate, type) {

	    if(startDate){
	        switch (type) {
	            case 'YYYY-MM':
	                startDate = date.add(startDate, 'M', 1);
	                break;
	            case 'YYYY-MM-DD':
	                startDate = date.add(startDate, 'd', 1);
	                break;
	        }
	    }
	    return startDate;
	},

	modelValueChange: function(value){
		if (this.slice) return;
		this.trueValue = value;
		if(env.isMobile){
			if(value){
				value = date.format(value,this.options.format);
				$(this.element).scroller('setDate', date.getDateObj(value), true);
			}
		}else{
			this.comp.setDate(value);
		}

	},
	setFormat: function(format){
		if (this.maskerMeta.format == format) return;
		this.options.format = format;
		this.maskerMeta.format = format;
		if(!env.isMobile)
			this.comp.setFormat(format);
		// this.formater = new $.DateFormater(this.maskerMeta.format);
		// this.masker = new DateTimeMasker(this.maskerMeta);
	},
	setValue: function (value) {
		value = date.format(value,this.options.format);
        this.trueValue = this.formater ? this.formater.format(value) : value;
        this.showValue = this.masker ? this.masker.format(this.trueValue).value : this.trueValue;
        this.setShowValue(this.showValue);
        this.slice = true;
        this.dataModel.setValue(this.field, this.trueValue);
        this.slice = false;
    },
    setEnable: function(enable){
        if (enable === true || enable === 'true') {
            this.enable = true;
            if(env.isMobile){
            	this.element.removeAttribute('disabled');
            }else{
            	this.comp._input.removeAttribute('readonly');
            }
            removeClass(this.element.parentNode,'disablecover');
        } else if (enable === false || enable === 'false') {
            this.enable = false;
            if(env.isMobile){
            	this.element.setAttribute('disabled','disabled');
            }else{
            	this.comp._input.setAttribute('readonly', 'readonly');
            }
            addClass(this.element.parentNode,'disablecover');
        }
        if(!env.isMobile)
        	this.comp.setEnable(enable);
    }

});

compMgr.addDataAdapter({
	adapter: DateTimeAdapter,
	name: 'u-date'
});

compMgr.addDataAdapter({
	adapter: DateTimeAdapter,
	name: 'u-datetime'
});

export {DateTimeAdapter};
<|endoftext|>


<commit_before>/**
 * @module ol/renderer/canvas/ImageLayer
 */
import CanvasLayerRenderer from './Layer.js';
import ViewHint from '../../ViewHint.js';
import {ENABLE_RASTER_REPROJECTION} from '../../reproj/common.js';
import {IMAGE_SMOOTHING_DISABLED, IMAGE_SMOOTHING_ENABLED} from './common.js';
import {
  apply as applyTransform,
  compose as composeTransform,
  makeInverse,
  toString as toTransformString,
} from '../../transform.js';
import {assign} from '../../obj.js';
import {
  containsCoordinate,
  containsExtent,
  getHeight,
  getIntersection,
  getWidth,
  intersects as intersectsExtent,
  isEmpty,
} from '../../extent.js';
import {fromUserExtent} from '../../proj.js';

/**
 * @classdesc
 * Canvas renderer for image layers.
 * @api
 */
class CanvasImageLayerRenderer extends CanvasLayerRenderer {
  /**
   * @param {import("../../layer/Image.js").default} imageLayer Image layer.
   */
  constructor(imageLayer) {
    super(imageLayer);

    /**
     * @protected
     * @type {?import("../../ImageBase.js").default}
     */
    this.image_ = null;
  }

  /**
   * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.
   */
  getImage() {
    return !this.image_ ? null : this.image_.getImage();
  }

  /**
   * Determine whether render should be called.
   * @param {import("../../PluggableMap.js").FrameState} frameState Frame state.
   * @return {boolean} Layer is ready to be rendered.
   */
  prepareFrame(frameState) {
    const layerState = frameState.layerStatesArray[frameState.layerIndex];
    const pixelRatio = frameState.pixelRatio;
    const viewState = frameState.viewState;
    const viewResolution = viewState.resolution;

    const imageSource = this.getLayer().getSource();

    const hints = frameState.viewHints;

    let renderedExtent = frameState.extent;
    if (layerState.extent !== undefined) {
      renderedExtent = getIntersection(
        renderedExtent,
        fromUserExtent(layerState.extent, viewState.projection)
      );
    }

    if (
      !hints[ViewHint.ANIMATING] &&
      !hints[ViewHint.INTERACTING] &&
      !isEmpty(renderedExtent)
    ) {
      if (imageSource) {
        let projection = viewState.projection;
        if (!ENABLE_RASTER_REPROJECTION) {
          const sourceProjection = imageSource.getProjection();
          if (sourceProjection) {
            projection = sourceProjection;
          }
        }
        const image = imageSource.getImage(
          renderedExtent,
          viewResolution,
          pixelRatio,
          projection
        );
        if (image && this.loadImage(image)) {
          this.image_ = image;
        } else {
          this.image_ = null;
        }
      } else {
        this.image_ = null;
      }
    }

    return !!this.image_;
  }

  /**
   * @param {import("../../pixel.js").Pixel} pixel Pixel.
   * @return {Uint8ClampedArray} Data at the pixel location.
   */
  getData(pixel) {
    const frameState = this.frameState;
    if (!frameState) {
      return null;
    }

    const layer = this.getLayer();
    const coordinate = applyTransform(
      frameState.pixelToCoordinateTransform,
      pixel.slice()
    );

    const layerExtent = layer.getExtent();
    if (layerExtent) {
      if (!containsCoordinate(layerExtent, coordinate)) {
        return null;
      }
    }

    const imageExtent = this.image_.getExtent();
    const img = this.image_.getImage();

    const imageMapWidth = getWidth(imageExtent);
    const col = Math.floor(
      img.width * ((coordinate[0] - imageExtent[0]) / imageMapWidth)
    );
    if (col < 0 || col >= img.width) {
      return null;
    }

    const imageMapHeight = getHeight(imageExtent);
    const row = Math.floor(
      img.height * ((imageExtent[3] - coordinate[1]) / imageMapHeight)
    );
    if (row < 0 || row >= img.height) {
      return null;
    }

    return this.getImageData(img, col, row);
  }

  /**
   * Render the layer.
   * @param {import("../../PluggableMap.js").FrameState} frameState Frame state.
   * @param {HTMLElement} target Target that may be used to render content to.
   * @return {HTMLElement} The rendered element.
   */
  renderFrame(frameState, target) {
    const image = this.image_;
    const imageExtent = image.getExtent();
    const imageResolution = image.getResolution();
    const imagePixelRatio = image.getPixelRatio();
    const layerState = frameState.layerStatesArray[frameState.layerIndex];
    const pixelRatio = frameState.pixelRatio;
    const viewState = frameState.viewState;
    const viewCenter = viewState.center;
    const viewResolution = viewState.resolution;
    const size = frameState.size;
    const scale =
      (pixelRatio * imageResolution) / (viewResolution * imagePixelRatio);

    let width = Math.round(size[0] * pixelRatio);
    let height = Math.round(size[1] * pixelRatio);
    const rotation = viewState.rotation;
    if (rotation) {
      const size = Math.round(Math.sqrt(width * width + height * height));
      width = size;
      height = size;
    }

    // set forward and inverse pixel transforms
    composeTransform(
      this.pixelTransform,
      frameState.size[0] / 2,
      frameState.size[1] / 2,
      1 / pixelRatio,
      1 / pixelRatio,
      rotation,
      -width / 2,
      -height / 2
    );
    makeInverse(this.inversePixelTransform, this.pixelTransform);

    const canvasTransform = toTransformString(this.pixelTransform);

    this.useContainer(
      target,
      canvasTransform,
      layerState.opacity,
      this.getBackground(frameState)
    );

    const context = this.context;
    const canvas = context.canvas;

    if (canvas.width != width || canvas.height != height) {
      canvas.width = width;
      canvas.height = height;
    } else if (!this.containerReused) {
      context.clearRect(0, 0, width, height);
    }

    // clipped rendering if layer extent is set
    let clipped = false;
    let render = true;
    if (layerState.extent) {
      const layerExtent = fromUserExtent(
        layerState.extent,
        viewState.projection
      );
      render = intersectsExtent(layerExtent, frameState.extent);
      clipped = render && !containsExtent(layerExtent, frameState.extent);
      if (clipped) {
        this.clipUnrotated(context, frameState, layerExtent);
      }
    }

    const img = image.getImage();

    const transform = composeTransform(
      this.tempTransform,
      width / 2,
      height / 2,
      scale,
      scale,
      0,
      (imagePixelRatio * (imageExtent[0] - viewCenter[0])) / imageResolution,
      (imagePixelRatio * (viewCenter[1] - imageExtent[3])) / imageResolution
    );

    this.renderedResolution = (imageResolution * pixelRatio) / imagePixelRatio;

    const dw = img.width * transform[0];
    const dh = img.height * transform[3];

    if (!this.getLayer().getSource().getInterpolate()) {
      assign(context, IMAGE_SMOOTHING_DISABLED);
    }

    this.preRender(context, frameState);
    if (render && dw >= 0.5 && dh >= 0.5) {
      const dx = transform[4];
      const dy = transform[5];
      const opacity = layerState.opacity;
      let previousAlpha;
      if (opacity !== 1) {
        previousAlpha = context.globalAlpha;
        context.globalAlpha = opacity;
      }
      context.drawImage(
        img,
        0,
        0,
        +img.width,
        +img.height,
        Math.round(dx),
        Math.round(dy),
        Math.round(dw),
        Math.round(dh)
      );
      if (opacity !== 1) {
        context.globalAlpha = previousAlpha;
      }
    }
    this.postRender(context, frameState);

    if (clipped) {
      context.restore();
    }
    assign(context, IMAGE_SMOOTHING_ENABLED);

    if (canvasTransform !== canvas.style.transform) {
      canvas.style.transform = canvasTransform;
    }

    return this.container;
  }
}

export default CanvasImageLayerRenderer;
<commit_msg>Revert "Merge pull request #13398 from yonda-yonda/update_static_image_change_projection"<commit_after>/**
 * @module ol/renderer/canvas/ImageLayer
 */
import CanvasLayerRenderer from './Layer.js';
import ViewHint from '../../ViewHint.js';
import {ENABLE_RASTER_REPROJECTION} from '../../reproj/common.js';
import {IMAGE_SMOOTHING_DISABLED, IMAGE_SMOOTHING_ENABLED} from './common.js';
import {
  apply as applyTransform,
  compose as composeTransform,
  makeInverse,
  toString as toTransformString,
} from '../../transform.js';
import {assign} from '../../obj.js';
import {
  containsCoordinate,
  containsExtent,
  getHeight,
  getIntersection,
  getWidth,
  intersects as intersectsExtent,
  isEmpty,
} from '../../extent.js';
import {fromUserExtent} from '../../proj.js';

/**
 * @classdesc
 * Canvas renderer for image layers.
 * @api
 */
class CanvasImageLayerRenderer extends CanvasLayerRenderer {
  /**
   * @param {import("../../layer/Image.js").default} imageLayer Image layer.
   */
  constructor(imageLayer) {
    super(imageLayer);

    /**
     * @protected
     * @type {?import("../../ImageBase.js").default}
     */
    this.image_ = null;
  }

  /**
   * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.
   */
  getImage() {
    return !this.image_ ? null : this.image_.getImage();
  }

  /**
   * Determine whether render should be called.
   * @param {import("../../PluggableMap.js").FrameState} frameState Frame state.
   * @return {boolean} Layer is ready to be rendered.
   */
  prepareFrame(frameState) {
    const layerState = frameState.layerStatesArray[frameState.layerIndex];
    const pixelRatio = frameState.pixelRatio;
    const viewState = frameState.viewState;
    const viewResolution = viewState.resolution;

    const imageSource = this.getLayer().getSource();

    const hints = frameState.viewHints;

    let renderedExtent = frameState.extent;
    if (layerState.extent !== undefined) {
      renderedExtent = getIntersection(
        renderedExtent,
        fromUserExtent(layerState.extent, viewState.projection)
      );
    }

    if (
      !hints[ViewHint.ANIMATING] &&
      !hints[ViewHint.INTERACTING] &&
      !isEmpty(renderedExtent)
    ) {
      if (imageSource) {
        let projection = viewState.projection;
        if (!ENABLE_RASTER_REPROJECTION) {
          const sourceProjection = imageSource.getProjection();
          if (sourceProjection) {
            projection = sourceProjection;
          }
        }
        const image = imageSource.getImage(
          renderedExtent,
          viewResolution,
          pixelRatio,
          projection
        );
        if (image && this.loadImage(image)) {
          this.image_ = image;
        }
      } else {
        this.image_ = null;
      }
    }

    return !!this.image_;
  }

  /**
   * @param {import("../../pixel.js").Pixel} pixel Pixel.
   * @return {Uint8ClampedArray} Data at the pixel location.
   */
  getData(pixel) {
    const frameState = this.frameState;
    if (!frameState) {
      return null;
    }

    const layer = this.getLayer();
    const coordinate = applyTransform(
      frameState.pixelToCoordinateTransform,
      pixel.slice()
    );

    const layerExtent = layer.getExtent();
    if (layerExtent) {
      if (!containsCoordinate(layerExtent, coordinate)) {
        return null;
      }
    }

    const imageExtent = this.image_.getExtent();
    const img = this.image_.getImage();

    const imageMapWidth = getWidth(imageExtent);
    const col = Math.floor(
      img.width * ((coordinate[0] - imageExtent[0]) / imageMapWidth)
    );
    if (col < 0 || col >= img.width) {
      return null;
    }

    const imageMapHeight = getHeight(imageExtent);
    const row = Math.floor(
      img.height * ((imageExtent[3] - coordinate[1]) / imageMapHeight)
    );
    if (row < 0 || row >= img.height) {
      return null;
    }

    return this.getImageData(img, col, row);
  }

  /**
   * Render the layer.
   * @param {import("../../PluggableMap.js").FrameState} frameState Frame state.
   * @param {HTMLElement} target Target that may be used to render content to.
   * @return {HTMLElement} The rendered element.
   */
  renderFrame(frameState, target) {
    const image = this.image_;
    const imageExtent = image.getExtent();
    const imageResolution = image.getResolution();
    const imagePixelRatio = image.getPixelRatio();
    const layerState = frameState.layerStatesArray[frameState.layerIndex];
    const pixelRatio = frameState.pixelRatio;
    const viewState = frameState.viewState;
    const viewCenter = viewState.center;
    const viewResolution = viewState.resolution;
    const size = frameState.size;
    const scale =
      (pixelRatio * imageResolution) / (viewResolution * imagePixelRatio);

    let width = Math.round(size[0] * pixelRatio);
    let height = Math.round(size[1] * pixelRatio);
    const rotation = viewState.rotation;
    if (rotation) {
      const size = Math.round(Math.sqrt(width * width + height * height));
      width = size;
      height = size;
    }

    // set forward and inverse pixel transforms
    composeTransform(
      this.pixelTransform,
      frameState.size[0] / 2,
      frameState.size[1] / 2,
      1 / pixelRatio,
      1 / pixelRatio,
      rotation,
      -width / 2,
      -height / 2
    );
    makeInverse(this.inversePixelTransform, this.pixelTransform);

    const canvasTransform = toTransformString(this.pixelTransform);

    this.useContainer(
      target,
      canvasTransform,
      layerState.opacity,
      this.getBackground(frameState)
    );

    const context = this.context;
    const canvas = context.canvas;

    if (canvas.width != width || canvas.height != height) {
      canvas.width = width;
      canvas.height = height;
    } else if (!this.containerReused) {
      context.clearRect(0, 0, width, height);
    }

    // clipped rendering if layer extent is set
    let clipped = false;
    let render = true;
    if (layerState.extent) {
      const layerExtent = fromUserExtent(
        layerState.extent,
        viewState.projection
      );
      render = intersectsExtent(layerExtent, frameState.extent);
      clipped = render && !containsExtent(layerExtent, frameState.extent);
      if (clipped) {
        this.clipUnrotated(context, frameState, layerExtent);
      }
    }

    const img = image.getImage();

    const transform = composeTransform(
      this.tempTransform,
      width / 2,
      height / 2,
      scale,
      scale,
      0,
      (imagePixelRatio * (imageExtent[0] - viewCenter[0])) / imageResolution,
      (imagePixelRatio * (viewCenter[1] - imageExtent[3])) / imageResolution
    );

    this.renderedResolution = (imageResolution * pixelRatio) / imagePixelRatio;

    const dw = img.width * transform[0];
    const dh = img.height * transform[3];

    if (!this.getLayer().getSource().getInterpolate()) {
      assign(context, IMAGE_SMOOTHING_DISABLED);
    }

    this.preRender(context, frameState);
    if (render && dw >= 0.5 && dh >= 0.5) {
      const dx = transform[4];
      const dy = transform[5];
      const opacity = layerState.opacity;
      let previousAlpha;
      if (opacity !== 1) {
        previousAlpha = context.globalAlpha;
        context.globalAlpha = opacity;
      }
      context.drawImage(
        img,
        0,
        0,
        +img.width,
        +img.height,
        Math.round(dx),
        Math.round(dy),
        Math.round(dw),
        Math.round(dh)
      );
      if (opacity !== 1) {
        context.globalAlpha = previousAlpha;
      }
    }
    this.postRender(context, frameState);

    if (clipped) {
      context.restore();
    }
    assign(context, IMAGE_SMOOTHING_ENABLED);

    if (canvasTransform !== canvas.style.transform) {
      canvas.style.transform = canvasTransform;
    }

    return this.container;
  }
}

export default CanvasImageLayerRenderer;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.demos.olympics',
  name: 'Controller',
  extendsModel: 'foam.ui.View',

  requires: [
    'foam.dao.EasyDAO',
    'foam.demos.olympics.Medal',
    'foam.ui.TextFieldView',
    'foam.ui.search.GroupBySearchView',
    'foam.ui.search.SearchMgr',
    'foam.ui.search.TextSearchView'
  ],

  exports: [ 'searchMgr' ],

  properties: [
    {
      model_: 'IntProperty',
      name: 'count'
    },
    {
      model_: 'IntProperty',
      name: 'totalCount'
    },
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'dao',
      factory: function() {
        var Medal = foam.demos.olympics.Medal;
        return foam.dao.EasyDAO.create({
          model: Medal,
          daoType: 'MDAO',
          seqNo: true,
          autoIndex: true
        })/*.addIndex(Medal.CITY).addIndex(Medal.COLOR).addIndex(Medal.SPORT)*/;
      }
    },
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'filteredDAO',
      view: { factory_: 'foam.ui.TableView', scrollEnabled: true, xxxeditColumnsEnabled: true, xxxrows: 30}
    },
    {
      name: 'searchMgr',
      lazyFactory: function() {
        return this.SearchMgr.create({dao: this.dao, filteredDAO$: this.filteredDAO$});
      }
    },
    {
      name: 'query',
      factory: function() {
        return this.searchMgr.add(this.TextSearchView.create({model: this.Medal, richSearch: true}));
      }
    },
    'fromYear', 'toYear', 'color', 'city', 'gender', 'discipline', 'event',
    {
      model_: 'StringProperty',
      name: 'sql',
      displayWidth: 35,
      displayHeight: 8
    }
  ],

  methods: [
    function addGroup(prop, opt_name, opt_map) {
      var map = opt_map || {};
      map.property = prop;
      map.size = map.size || 1;
      this[opt_name || prop.name] = this.searchMgr.add(this.GroupBySearchView.create(map));
    },

    function init() {
      this.SUPER();

      GLOBAL.ctrl = this; // for debugging
      var Medal = this.Medal;
      var self  = this;

      axhr('js/foam/demos/olympics/MedalData.json')(function (data) {
        data.limit(50000).select(function(m) { self.dao.put(self.Medal.create(m)); });
        self.count = self.totalCount = data.length;
        self.searchMgr.dao = self.dao;
      });

      this.addGroup(Medal.COLOR, null,      {size: 4});
      this.addGroup(Medal.GENDER, null,     {size: 3});
      this.addGroup(Medal.YEAR, 'fromYear', {label: 'From', op: GTE});
      this.addGroup(Medal.YEAR, 'toYear',   {label: 'To',   op: LTE});
      this.addGroup(Medal.COUNTRY);
      this.addGroup(Medal.CITY);
      this.addGroup(Medal.DISCIPLINE);
      this.addGroup(Medal.EVENT);

      this.searchMgr.predicate$.addListener(this.onPredicateChange);
    }
  ],

  listeners: [
    {
      name: 'onPredicateChange',
      isFramed: true,
      code: function(_, _, _, predicate) {
        this.sql = 'SELECT * FROM Medal' +
          (predicate !== TRUE ? ' WHERE (' + predicate.toSQL() + ')' : '');

        this.filteredDAO.select(COUNT())(function(c) {
          this.count = c.count;
        }.bind(this));
      }
    }
  ],

  actions: [
    {
      name: 'clear',
      action: function() { this.searchMgr.clear(); }
    }
  ],

  templates: [
    function CSS() {/*
      html { overflow: hidden; }
      .tableView {
        outline: none;
        height: 93%;
      }
      .medalController { display: flex; }
      .foamSearchView select { width: 300px; }
      .tableView { width: auto !important; }
      .MedalTable { width: auto !important; }
      .searchPanel { margin: 15px; }
      .searchResults { margin-left: 40px; }
      .counts {
        color: #555;
        font-size: 22px;
        margin: 20px;
      }
      input[type='search'] {
        margin-bottom: 15px;
        width: 300px;
      }
      .Gold   { color: #C98910; }
      .Silver { color: #A8A8A8; }
      .Bronze { color: #965A38; }
    */},
    function toHTML() {/*

          %%query
          %%fromYear %%toYear %%city %%discipline %%event %%country %%color %%gender
          $$clear

SQL:
$$sql{mode: 'read-only'}

<%= FOAM_POWERED %>

          $$filteredDAO

$$count{mode: 'read-only'} of $$totalCount{mode: 'read-only'} selected

    */}
  ]
});
<commit_msg>Medal demo.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.demos.olympics',
  name: 'Controller',
  extendsModel: 'foam.ui.View',

  requires: [
    'foam.dao.EasyDAO',
    'foam.demos.olympics.Medal',
    'foam.ui.TextFieldView',
    'foam.ui.search.GroupBySearchView',
    'foam.ui.search.SearchMgr',
    'foam.ui.search.TextSearchView'
  ],

  exports: [ 'searchMgr' ],

  properties: [
    {
      model_: 'IntProperty',
      name: 'count'
    },
    {
      model_: 'IntProperty',
      name: 'totalCount'
    },
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'dao',
      factory: function() {
        var Medal = foam.demos.olympics.Medal;
        return foam.dao.EasyDAO.create({
          model: Medal,
          daoType: 'MDAO',
          seqNo: true,
          autoIndex: true
        })/*.addIndex(Medal.CITY).addIndex(Medal.COLOR).addIndex(Medal.SPORT)*/;
      }
    },
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'filteredDAO',
      view: { factory_: 'foam.ui.TableView', scrollEnabled: true, xxxeditColumnsEnabled: true, xxxrows: 30}
    },
    {
      name: 'searchMgr',
      lazyFactory: function() {
        return this.SearchMgr.create({dao: this.dao, filteredDAO$: this.filteredDAO$});
      }
    },
    {
      name: 'query',
      factory: function() {
        return this.searchMgr.add(this.TextSearchView.create({model: this.Medal, richSearch: true}));
      }
    },
    {
      model_: 'StringProperty',
      name: 'sql',
      displayWidth: 35,
      displayHeight: 8
    },
    'fromYear', 'toYear', 'color', 'city', 'gender', 'discipline', 'event',
  ],

  methods: [
    function init() {
      this.SUPER();

      GLOBAL.ctrl = this; // for debugging
      var Medal = this.Medal;
      var self  = this;

      axhr('js/foam/demos/olympics/MedalData.json')(function (data) {
        data.limit(50000).select(function(m) { self.dao.put(self.Medal.create(m)); });
        self.count = self.totalCount = data.length;
        self.searchMgr.dao = self.dao;
      });

      this.addGroup(Medal.COLOR, null,      {size: 4});
      this.addGroup(Medal.GENDER, null,     {size: 3});
      this.addGroup(Medal.YEAR, 'fromYear', {label: 'From', op: GTE});
      this.addGroup(Medal.YEAR, 'toYear',   {label: 'To',   op: LTE});
      this.addGroup(Medal.COUNTRY);
      this.addGroup(Medal.CITY);
      this.addGroup(Medal.DISCIPLINE);
      this.addGroup(Medal.EVENT);

      this.searchMgr.predicate$.addListener(this.onPredicateChange);
    },

    function addGroup(prop, opt_name, opt_map) {
      var map = opt_map || {};
      map.property = prop;
      map.size = map.size || 1;
      this[opt_name || prop.name] = this.searchMgr.add(this.GroupBySearchView.create(map));
    }
  ],

  listeners: [
    {
      name: 'onPredicateChange',
      isFramed: true,
      code: function(_, _, _, predicate) {
        this.sql = 'SELECT * FROM Medal' +
          (predicate !== TRUE ? ' WHERE (' + predicate.toSQL() + ')' : '');

        this.filteredDAO.select(COUNT())(function(c) {
          this.count = c.count;
        }.bind(this));
      }
    }
  ],

  actions: [
    {
      name: 'clear',
      action: function() { this.searchMgr.clear(); }
    }
  ],

  templates: [
    function CSS() {/*
      html { overflow: hidden; }
      .tableView {
        outline: none;
        height: 93%;
      }
      .medalController { display: flex; }
      .foamSearchView select { width: 300px; }
      .tableView { width: auto !important; }
      .MedalTable { width: auto !important; }
      .searchPanel { margin: 15px; }
      .searchResults { margin-left: 40px; }
      .counts {
        color: #555;
        font-size: 22px;
        margin: 20px;
      }
      input[type='search'] {
        margin-bottom: 15px;
        width: 300px;
      }
      .Gold   { color: #C98910; }
      .Silver { color: #A8A8A8; }
      .Bronze { color: #965A38; }
    */},
    function toHTML() {/*

          %%query
          %%fromYear %%toYear %%city %%discipline %%event %%country %%color %%gender
          $$clear

SQL:
$$sql{mode: 'read-only'}

<%= FOAM_POWERED %>

          $$filteredDAO

$$count{mode: 'read-only'} of $$totalCount{mode: 'read-only'} selected

    */}
  ]
});
<|endoftext|>