<commit_before>/**
 * zrender
 *
 * @author Kener (@Kener-林峰, linzhifeng@baidu.com)
 *
 * shape类：大规模散点图图形
 * 可配图形属性：
   {
       // 基础属性
       shape  : 'symbol',       // 必须，shape类标识，需要显式指定
       id     : {string},       // 必须，图形唯一标识，可通过zrender实例方法newShapeId生成
       zlevel : {number},       // 默认为0，z层level，决定绘画在哪层canvas中
       invisible : {boolean},   // 默认为false，是否可见

       // 样式属性，默认状态样式样式属性
       style  : {
           pointList     : {Array},   // 必须，二维数组，二维内容如下
               x         : {number},  // 必须，横坐标
               y         : {number},  // 必须，纵坐标数组
               size      : {number},  // 必须，半宽
               type      : {string=}, // 默认为'circle',图形类型
           color         : {color},   // 默认为'#000'，填充颜色，支持rgba
           strokeColor   : {color},   // 默认为'#000'，描边颜色（轮廓），支持rgba
           lineWidth     : {number},  // 默认为1，线条宽度，描边下有效

           opacity       : {number},  // 默认为1，透明度设置，如果color为rgba，则最终透明度效果叠加
           shadowBlur    : {number},  // 默认为0，阴影模糊度，大于0有效
           shadowColor   : {color},   // 默认为'#000'，阴影色彩，支持rgba
           shadowOffsetX : {number},  // 默认为0，阴影横向偏移，正值往右，负值往左
           shadowOffsetY : {number},  // 默认为0，阴影纵向偏移，正值往下，负值往上

           text          : {string},  // 默认为null，附加文本
           textFont      : {string},  // 默认为null，附加文本样式，eg:'bold 18px verdana'
           textPosition  : {string},  // 默认为top，附加文本位置。
                                      // inside | left | right | top | bottom
           textAlign     : {string},  // 默认根据textPosition自动设置，附加文本水平对齐。
                                      // start | end | left | right | center
           textBaseline  : {string},  // 默认根据textPosition自动设置，附加文本垂直对齐。
                                      // top | bottom | middle |
                                      // alphabetic | hanging | ideographic
           textColor     : {color},   // 默认根据textPosition自动设置，默认策略如下，附加文本颜色
                                      // 'inside' ? '#fff' : color
       },

       // 样式属性，高亮样式属性，当不存在highlightStyle时使用基于默认样式扩展显示
       highlightStyle : {
           // 同style
       }

       // 交互属性，详见shape.Base

       // 事件属性，详见shape.Base
   }
         例子：
   {
       shape  : 'symbol',
       id     : '123456',
       zlevel : 1,
       style  : {
           x : 200,
           y : [100,123,90,125],
           width : 150,
           color : '#eee',
           text : 'Baidu'
       },
       myName : 'kener',  // 可自带任何有效自定义属性

       clickable : true,
       onClick : function(eventPacket) {
           alert(eventPacket.target.myName);
       }
   }
 */
define(
    function(require) {
        function Symbol() {
            this.type = 'symbol';
        }

        Symbol.prototype =  {
            /*
             * pointlist=[
             *      0  x,
             *      1  y,
             *      2  图形大小
             *      3  图形类型
             *      4  数据index
             *      5  名称
             * ]
             */
            _buildSinglePoint : function(ctx, singlePoint) {
                switch (singlePoint[3]) {
                    case 'circle' :
                    case 'emptyCircle' :
                        ctx.arc(
                            singlePoint[0],
                            singlePoint[1],
                            singlePoint[2],
                            0,
                            Math.PI * 2,
                            true
                        );
                        break;
                    case 'rectangle' :
                    case 'emptyRectangle' :
                        ctx.rect(
                            singlePoint[0] - singlePoint[2],
                            singlePoint[1] - singlePoint[2],
                            singlePoint[2] * 2,
                            singlePoint[2] * 2
                        );
                        break;
                    case 'triangle' :
                    case 'emptyTriangle' :
                        itemShape = {
                            shape : 'polygon',
                            style : {
                                pointList : [
                                    [x, y - symbolSize],
                                    [x + symbolSize, y + symbolSize],
                                    [x - symbolSize, y + symbolSize]
                                ],
                                brushType : symbolType == 'triangle'
                                            ? 'fill' : 'stroke'
                            }
                        };
                        break;
                    case 'diamond' :
                    case 'emptyDiamond' :
                        itemShape = {
                            shape : 'polygon',
                            style : {
                                pointList : [
                                    [x, y - symbolSize],
                                    [x + symbolSize, y],
                                    [x, y + symbolSize],
                                    [x - symbolSize, y]
                                ],
                                brushType : symbolType == 'diamond'
                                            ? 'fill' : 'stroke'
                            }
                        };
                        break;
                    default:
                        itemShape = {
                            shape : 'circle',
                            style : {
                                x : x,
                                y : y,
                                r : symbolSize,
                                brushType : 'fill'
                            }
                        };
                        break;
                }
            },

            /**
             * 创建矩形路径
             * @param {Context2D} ctx Canvas 2D上下文
             * @param {Object} style 样式
             */
            buildPath : function(ctx, style) {
                var pointList = style.pointList;
                var rect = this.getRect(style);
                var ratio = window.devicePixelRatio || 1;
                // console.log(rect)
                // var ti = new Date();
                // bbox取整
                rect = {
                    x : Math.floor(rect.x),
                    y : Math.floor(rect.y),
                    width : Math.floor(rect.width),
                    height : Math.floor(rect.height)
                };
                var pixels = ctx.getImageData(
                    rect.x * ratio, rect.y * ratio,
                    rect.width * ratio, rect.height * ratio
                );
                var data = pixels.data;
                var idx;
                var zrColor = require('zrender/tool/color');
                var color = zrColor.toArray(style.color);
                var r = color[0];
                var g = color[1];
                var b = color[2];
                var width = rect.width;

                for (var i = 1, l = pointList.length; i < l; i++) {
                    idx = ( (pointList[i][0] - rect.x) * ratio
                           + (pointList[i][1]- rect.y) * width * ratio * ratio
                          ) * 4;
                    data[idx] = r;
                    data[idx + 1] = g;
                    data[idx + 2] = b;
                    data[idx + 3] = 255;
                }
                ctx.putImageData(pixels, rect.x * ratio, rect.y * ratio);
                // console.log(new Date() - ti);
                return;
            },

            /**
             * 返回矩形区域，用于局部刷新和文字定位
             * @param {Object} style
             */
            getRect : function(style) {
                var shape = require('zrender/shape');
                return shape.get('polygon').getRect(style);
            },

            isCover : function() {
                return false;
            }
        };

        require('zrender/shape/base').derive(Symbol);
        require('zrender/shape').define('symbol', new Symbol());

        return Symbol;
    }
);<commit_msg>bug fixed<commit_after>/**
 * zrender
 *
 * @author Kener (@Kener-林峰, linzhifeng@baidu.com)
 *
 * shape类：大规模散点图图形
 * 可配图形属性：
   {
       // 基础属性
       shape  : 'symbol',       // 必须，shape类标识，需要显式指定
       id     : {string},       // 必须，图形唯一标识，可通过zrender实例方法newShapeId生成
       zlevel : {number},       // 默认为0，z层level，决定绘画在哪层canvas中
       invisible : {boolean},   // 默认为false，是否可见

       // 样式属性，默认状态样式样式属性
       style  : {
           pointList     : {Array},   // 必须，二维数组，二维内容如下
               x         : {number},  // 必须，横坐标
               y         : {number},  // 必须，纵坐标数组
               size      : {number},  // 必须，半宽
               type      : {string=}, // 默认为'circle',图形类型
           color         : {color},   // 默认为'#000'，填充颜色，支持rgba
           strokeColor   : {color},   // 默认为'#000'，描边颜色（轮廓），支持rgba
           lineWidth     : {number},  // 默认为1，线条宽度，描边下有效

           opacity       : {number},  // 默认为1，透明度设置，如果color为rgba，则最终透明度效果叠加
           shadowBlur    : {number},  // 默认为0，阴影模糊度，大于0有效
           shadowColor   : {color},   // 默认为'#000'，阴影色彩，支持rgba
           shadowOffsetX : {number},  // 默认为0，阴影横向偏移，正值往右，负值往左
           shadowOffsetY : {number},  // 默认为0，阴影纵向偏移，正值往下，负值往上

           text          : {string},  // 默认为null，附加文本
           textFont      : {string},  // 默认为null，附加文本样式，eg:'bold 18px verdana'
           textPosition  : {string},  // 默认为top，附加文本位置。
                                      // inside | left | right | top | bottom
           textAlign     : {string},  // 默认根据textPosition自动设置，附加文本水平对齐。
                                      // start | end | left | right | center
           textBaseline  : {string},  // 默认根据textPosition自动设置，附加文本垂直对齐。
                                      // top | bottom | middle |
                                      // alphabetic | hanging | ideographic
           textColor     : {color},   // 默认根据textPosition自动设置，默认策略如下，附加文本颜色
                                      // 'inside' ? '#fff' : color
       },

       // 样式属性，高亮样式属性，当不存在highlightStyle时使用基于默认样式扩展显示
       highlightStyle : {
           // 同style
       }

       // 交互属性，详见shape.Base

       // 事件属性，详见shape.Base
   }
         例子：
   {
       shape  : 'symbol',
       id     : '123456',
       zlevel : 1,
       style  : {
           x : 200,
           y : [100,123,90,125],
           width : 150,
           color : '#eee',
           text : 'Baidu'
       },
       myName : 'kener',  // 可自带任何有效自定义属性

       clickable : true,
       onClick : function(eventPacket) {
           alert(eventPacket.target.myName);
       }
   }
 */
define(
    function(require) {
        function Symbol() {
            this.type = 'symbol';
        }

        Symbol.prototype =  {
            /*
             * pointlist=[
             *      0  x,
             *      1  y,
             *      2  图形大小
             *      3  图形类型
             *      4  数据index
             *      5  名称
             * ]
             */
            _buildSinglePoint : function(ctx, singlePoint) {
                switch (singlePoint[3]) {
                    case 'circle' :
                    case 'emptyCircle' :
                        ctx.arc(
                            singlePoint[0],
                            singlePoint[1],
                            singlePoint[2],
                            0,
                            Math.PI * 2,
                            true
                        );
                        break;
                    case 'rectangle' :
                    case 'emptyRectangle' :
                        ctx.rect(
                            singlePoint[0] - singlePoint[2],
                            singlePoint[1] - singlePoint[2],
                            singlePoint[2] * 2,
                            singlePoint[2] * 2
                        );
                        break;
                    case 'triangle' :
                    case 'emptyTriangle' :
                        itemShape = {
                            shape : 'polygon',
                            style : {
                                pointList : [
                                    [x, y - symbolSize],
                                    [x + symbolSize, y + symbolSize],
                                    [x - symbolSize, y + symbolSize]
                                ],
                                brushType : symbolType == 'triangle'
                                            ? 'fill' : 'stroke'
                            }
                        };
                        break;
                    case 'diamond' :
                    case 'emptyDiamond' :
                        itemShape = {
                            shape : 'polygon',
                            style : {
                                pointList : [
                                    [x, y - symbolSize],
                                    [x + symbolSize, y],
                                    [x, y + symbolSize],
                                    [x - symbolSize, y]
                                ],
                                brushType : symbolType == 'diamond'
                                            ? 'fill' : 'stroke'
                            }
                        };
                        break;
                    default:
                        itemShape = {
                            shape : 'circle',
                            style : {
                                x : x,
                                y : y,
                                r : symbolSize,
                                brushType : 'fill'
                            }
                        };
                        break;
                }
            },

            /**
             * 创建矩形路径
             * @param {Context2D} ctx Canvas 2D上下文
             * @param {Object} style 样式
             */
            buildPath : function(ctx, style) {
                var pointList = style.pointList;
                var rect = this.getRect(style);
                var ratio = window.devicePixelRatio || 1;
                // console.log(rect)
                // var ti = new Date();
                // bbox取整
                rect = {
                    x : Math.floor(rect.x),
                    y : Math.floor(rect.y),
                    width : Math.floor(rect.width),
                    height : Math.floor(rect.height)
                };
                var pixels = ctx.getImageData(
                    rect.x * ratio, rect.y * ratio,
                    rect.width * ratio, rect.height * ratio
                );
                var data = pixels.data;
                var idx;
                var zrColor = require('zrender/tool/color');
                var color = zrColor.toArray(style.color);
                var r = color[0];
                var g = color[1];
                var b = color[2];
                var width = rect.width;

                for (var i = 1, l = pointList.length; i < l; i++) {
                    idx = ((Math.floor(pointList[i][0]) - rect.x) * ratio
                           + (Math.floor(pointList[i][1])- rect.y) * width * ratio * ratio
                          ) * 4;
                    data[idx] = r;
                    data[idx + 1] = g;
                    data[idx + 2] = b;
                    data[idx + 3] = 255;
                }
                ctx.putImageData(pixels, rect.x * ratio, rect.y * ratio);
                // console.log(new Date() - ti);
                return;
            },

            /**
             * 返回矩形区域，用于局部刷新和文字定位
             * @param {Object} style
             */
            getRect : function(style) {
                var shape = require('zrender/shape');
                return shape.get('polygon').getRect(style);
            },

            isCover : function() {
                return false;
            }
        };

        require('zrender/shape/base').derive(Symbol);
        require('zrender/shape').define('symbol', new Symbol());

        return Symbol;
    }
);<|endoftext|>


<commit_before>define([], function () {
    /**
     * A loader for Javascript <script/> tags
     */
    function LoadScript () {

        var script, head,
            onLoadHandler,
            $this = this,
            done = false;

        this.addListeners = function (onload, onerror) {
            onLoadHandler = onload;
            script.onload = script.onreadystatechange = $this.onload;
            if (script.onerror) {
                script.onerror = onerror;
            }

            return script;
        };

        this.init = function () {
            script = this.getScript();

            return script;
        };

        this.load = function (src) {
            script.src = src;
            this.render();

            return script;
        };

        this.onload = function (event) {
            var state = script.readyState,
                ready = (!state) || (state === 'loaded') ||
                        (state === 'complete');
            if (!done && ready) {
                if (onLoadHandler) {
                    onLoadHandler(event);
                }
                done = true;
                script.onload = script.onreadystatechange = null;
            }
        };

        this.render = function () {
            head = document.getElementsByTagName('head')[0];
            (document.body || head).appendChild(script);

            return script;
        };

        this.getScript = function () {
            var s = document.createElement('script');
            s.type = 'text/javascript';

            return s;
        };

        this.init();
    }

    return LoadScript;
});
<commit_msg>Fix issue where load script was failing in ie8.<commit_after>define([], function () {
    /**
     * A loader for Javascript <script/> tags
     */
    function LoadScript () {

        var script, head,
            onLoadHandler,
            $this = this,
            done = false;

        this.addListeners = function (onload, onerror) {
            onLoadHandler = onload;
            script.onload = script.onreadystatechange = $this.onload;
            if (script.onerror) {
                script.onerror = onerror;
            }

            return script;
        };

        this.init = function () {
            script = this.getScript();

            return script;
        };

        this.load = function (src) {
            script.src = src;
            this.render();

            return script;
        };

        this.onload = function (event) {
            var s = (event && event.target) ? event.target : script,
                state = s.readyState,
                ready = (!state) || (state === 'loaded') ||
                    (state === 'complete');

            if (!done && ready) {
                if (onLoadHandler) {
                    onLoadHandler(event);
                }
                done = true;
                s.onload = s.onreadystatechange = null;
            }
        };

        this.render = function () {
            head = document.getElementsByTagName('head')[0];
            (document.body || head).appendChild(script);

            return script;
        };

        this.getScript = function () {
            var s = document.createElement('script');
            s.type = 'text/javascript';

            return s;
        };

        this.init();
    }

    return LoadScript;
});
<|endoftext|>


<commit_before>import {isStream} from './streamy';

const TEXT_NODE = '#text';

export function render({vdom$}, parentElement) {
	return vdom$.reduce(
		function renderUpdate({element:oldElement, version:oldVersion, children:oldChildren}, {tag, props, children, version}) {
			if (oldElement === null) {
				oldElement = createNode(tag, children);
				if (parentElement) {
					parentElement.appendChild(oldElement);
				}
			}
			diff(oldElement, tag, props, children, version, oldChildren, oldVersion);

			// signalise mount of root element on initial render
			if (parentElement && version === 0) {
				triggerLifecycle(oldElement, props, 'mounted');
			}
			return {
				element: oldElement,
				version,
				children: copyChildren(children)
			}
		}, {
			element: null,
			version: -1,
			children: []
		})
}

export function diff(oldElement, tag, props, newChildren, newVersion, oldChildren, oldVersion) {
	// if the dom-tree hasn't changed, don't process it
	if (newVersion === undefined && newVersion === oldVersion) {
		return oldElement;
	}
	let newElement = oldElement;

	if (oldElement instanceof window.Text && tag === TEXT_NODE && oldElement.nodeValue !== newChildren[0]) {
		oldElement.nodeValue = newChildren[0];
		return newElement;
	}

	if (oldElement.nodeName.toLowerCase() !== tag) {
		newElement = createNode(tag, newChildren);
		oldElement.parentElement.replaceChild(newElement, oldElement);
		oldChildren = [];
		oldVersion = -1;
	}

	diffAttributes(newElement, props);
	if (tag !== TEXT_NODE && !(newChildren.length === 0 && oldChildren.length === 0)) {
		diffChildren(newElement, newChildren, oldChildren);
	}

	if (newVersion === 0) {
		triggerLifecycle(newElement, props, 'created');
	}

	if (newVersion > 0) {
		triggerLifecycle(newElement, props, 'updated');
	}

	return newElement;
}

function diffAttributes(element, props) {
	if (props !== undefined) {
		Object.getOwnPropertyNames(props).map(function applyPropertyToElement(attribute) {
			applyAttribute(element, attribute, props[attribute])
		});
		cleanupAttributes(element, props);
	}
}

function applyAttribute(element, attribute, value) {
	if (attribute === 'class' || attribute === 'className') {
		element.className = value;
	// we leave the possibility to define styles as strings
	// but we allow styles to be defined as an object
	} else if (attribute === 'style' && typeof value !== "string" ) {
		Object.assign(element.style, value);
	// other propertys are just added as is to the DOM
	} else {
		// also remove attributes on null to allow better handling of streams
		// streams don't emit on undefined
		if (value === null) {
			element[attribute] = undefined;
		} else {
			// element.setAttribute(attribute, value);
			element[attribute] = value;
		}
	}
}

// remove attributes that are not in props anymore
function cleanupAttributes(element, props) {
	if (element.props !== undefined) {
		for(let attribute in element.props) {
			if (props[attribute] === undefined) {
				element.removeAttribute(attribute);
			}
		}
	}
}

function unifyChildren(children) {
	return children.map(child => {
		// if there is no tag we assume it's a number or a string
		if (!isStream(child) && child.tag === undefined) {
			return {
				tag: TEXT_NODE,
				children: [child],
				version: 0,
				cycle: child.cycle || {}
			}
		} else {
			return child;
		}
	})
}

function diffChildren(element, newChildren, oldChildren) {
	let oldChildNodes = element.childNodes;
	let unifiedChildren = unifyChildren(newChildren);
	let unifiedOldChildren = unifyChildren(oldChildren);

	let i = 0;
	// diff existing nodes
	for(; i < oldChildren.length && i < newChildren.length; i++) {
		let oldElement = oldChildNodes[i];
		let {version: oldVersion, children: oldChildChildren} = unifiedOldChildren[i];
		let {tag, props, children, version} = unifiedChildren[i];

		diff(oldElement, tag, props, children, version, oldChildChildren, oldVersion);
	}

	// remove not needed nodes at the end
	for(let remaining = element.childNodes.length; remaining > newChildren.length; remaining--) {
		let childToRemove = element.childNodes[remaining - 1];
		element.removeChild(childToRemove);

		if (unifiedOldChildren.length < remaining) {
			console.log("ZLIQ: Something other then ZLIQ has manipulated the children of the element", element, ". This can lead to sideffects. Please check your code.");
			continue;
		} else {
			let {props} = unifiedOldChildren[remaining - 1];

			triggerLifecycle(childToRemove, props, 'removed');
		}
	}

	// add new nodes
	for(; i < newChildren.length; i++) {
		let {tag, props, children, version} = unifiedChildren[i];
		let newElement = createNode(tag, children);

		element.appendChild(newElement);
		diff(newElement, tag, props, children, version, [], -1);
		triggerLifecycle(newElement, props, 'mounted');
	}
}

// create text_nodes from numbers or strings
// create domNodes from regular vdom descriptions
export function createNode(tag, children) {
	if (tag === TEXT_NODE) {
		return document.createTextNode(children[0]);
	} else {
		return document.createElement(tag);
	}
}

function copyChildren(oldChildren) {
	if (oldChildren === undefined) return [];

	let newChildren = JSON.parse(JSON.stringify(oldChildren));
	newChildren.forEach((child, index) => {
		if (oldChildren[index].cycle) {
			child.cycle = oldChildren[index].cycle;
		}

		if (typeof oldChildren[index] === 'object') {
			child.children = copyChildren(oldChildren[index].children);
		}
	});
	return newChildren;
}

function triggerLifecycle(element, props, event) {
	if(props && props.cycle && props.cycle[event]) {
		props.cycle[event](element);
	}
}<commit_msg>removed not working version check<commit_after>import {isStream} from './streamy';

const TEXT_NODE = '#text';

export function render({vdom$}, parentElement) {
	return vdom$.reduce(
		function renderUpdate({element:oldElement, version:oldVersion, children:oldChildren}, {tag, props, children, version}) {
			if (oldElement === null) {
				oldElement = createNode(tag, children);
				if (parentElement) {
					parentElement.appendChild(oldElement);
				}
			}
			diff(oldElement, tag, props, children, version, oldChildren, oldVersion);

			// signalise mount of root element on initial render
			if (parentElement && version === 0) {
				triggerLifecycle(oldElement, props, 'mounted');
			}
			return {
				element: oldElement,
				version,
				children: copyChildren(children)
			}
		}, {
			element: null,
			version: -1,
			children: []
		})
}

export function diff(oldElement, tag, props, newChildren, newVersion, oldChildren, oldVersion) {
	// if the dom-tree hasn't changed, don't process it
	// !! does not work
	// if (newVersion === oldVersion) {
	// // if (newVersion === oldVersion) {
	// 	return oldElement;
	// }
	let newElement = oldElement;

	if (isTextNode(oldElement) && tag === TEXT_NODE ) {
		updateTextNode(newElement, newChildren[0]);
		return newElement;
	}

	// if the node types do not differ, we reuse the old node
	if (nodeTypeDiffers(oldElement, tag)) {
		newElement = createNode(tag, newChildren);
		oldElement.parentElement.replaceChild(newElement, oldElement);
		oldChildren = [];
		oldVersion = -1;
	}

	diffAttributes(newElement, props);

	// text nodes have no real child-nodes, but have a string value as first child
	if (tag !== TEXT_NODE) {
		diffChildren(newElement, newChildren, oldChildren);
	}

	if (newVersion === 0) {
		triggerLifecycle(newElement, props, 'created');
	}

	if (newVersion > 0) {
		triggerLifecycle(newElement, props, 'updated');
	}

	return newElement;
}

function diffAttributes(element, props) {
	if (props !== undefined) {
		Object.getOwnPropertyNames(props).map(function applyPropertyToElement(attribute) {
			applyAttribute(element, attribute, props[attribute])
		});
		cleanupAttributes(element, props);
	}
}

function applyAttribute(element, attribute, value) {
	if (attribute === 'class' || attribute === 'className') {
		element.className = value;
	// we leave the possibility to define styles as strings
	// but we allow styles to be defined as an object
	} else if (attribute === 'style' && typeof value !== "string" ) {
		Object.assign(element.style, value);
	// other propertys are just added as is to the DOM
	} else {
		// also remove attributes on null to allow better handling of streams
		// streams don't emit on undefined
		if (value === null) {
			element[attribute] = undefined;
		} else {
			// element.setAttribute(attribute, value);
			element[attribute] = value;
		}
	}
}

// remove attributes that are not in props anymore
function cleanupAttributes(element, props) {
	if (element.props !== undefined) {
		for(let attribute in element.props) {
			if (props[attribute] === undefined) {
				element.removeAttribute(attribute);
			}
		}
	}
}

function unifyChildren(children) {
	return children.map(child => {
		// if there is no tag we assume it's a number or a string
		if (!isStream(child) && child.tag === undefined) {
			return {
				tag: TEXT_NODE,
				children: [child],
				version: 0,
				cycle: child.cycle || {}
			}
		} else {
			return child;
		}
	})
}

function diffChildren(element, newChildren, oldChildren) {
	let oldChildNodes = element.childNodes;
	let unifiedChildren = unifyChildren(newChildren);
	let unifiedOldChildren = unifyChildren(oldChildren);

	if (newChildren.length === 0 && oldChildren.length === 0) {
		return;
	}

	let i = 0;
	// diff existing nodes
	for(; i < oldChildren.length && i < newChildren.length; i++) {
		let oldElement = oldChildNodes[i];
		let {version: oldVersion, children: oldChildChildren} = unifiedOldChildren[i];
		let {tag, props, children, version} = unifiedChildren[i];

		diff(oldElement, tag, props, children, version, oldChildChildren, oldVersion);
	}

	// remove not needed nodes at the end
	for(let remaining = element.childNodes.length; remaining > newChildren.length; remaining--) {
		let childToRemove = element.childNodes[remaining - 1];
		element.removeChild(childToRemove);

		if (unifiedOldChildren.length < remaining) {
			console.log("ZLIQ: Something other then ZLIQ has manipulated the children of the element", element, ". This can lead to sideffects. Please check your code.");
			continue;
		} else {
			let {props} = unifiedOldChildren[remaining - 1];

			triggerLifecycle(childToRemove, props, 'removed');
		}
	}

	// add new nodes
	for(; i < newChildren.length; i++) {
		let {tag, props, children, version} = unifiedChildren[i];
		let newElement = createNode(tag, children);

		element.appendChild(newElement);
		diff(newElement, tag, props, children, version, [], -1);
		triggerLifecycle(newElement, props, 'mounted');
	}
}

// create text_nodes from numbers or strings
// create domNodes from regular vdom descriptions
export function createNode(tag, children) {
	if (tag === TEXT_NODE) {
		return document.createTextNode(children[0]);
	} else {
		return document.createElement(tag);
	}
}

function copyChildren(oldChildren) {
	if (oldChildren === undefined) return [];

	let newChildren = JSON.parse(JSON.stringify(oldChildren));
	newChildren.forEach((child, index) => {
		if (oldChildren[index].cycle) {
			child.cycle = oldChildren[index].cycle;
		}

		if (typeof oldChildren[index] === 'object') {
			child.children = copyChildren(oldChildren[index].children);
		}
	});
	return newChildren;
}

function triggerLifecycle(element, props, event) {
	if(props && props.cycle && props.cycle[event]) {
		props.cycle[event](element);
	}
}

function nodeTypeDiffers(element, tag) {
	return element.nodeName.toLowerCase() !== tag;
}

function isTextNode(element) {
	return element instanceof window.Text
}

function updateTextNode(element, value) {
	if (element.nodeValue !== value) {
		element.nodeValue = value;
	}
}<|endoftext|>


<commit_before>import React from 'react';
import { Route, IndexRedirect } from 'react-router';
import Loom from 'loom-data';
import AuthService from '../../utils/AuthService';
import Container from './Container';
import { DataModel } from './Schemas/DataModel';
import { Login } from './Login/Login';
import HomeComponent from '../../containers/home/HomeComponent';
import { Settings } from './Settings/Settings';
import { Visualize } from './Visualizations/Visualize';
import { Link } from './Link/Link';
import CatalogComponent from '../../containers/catalog/CatalogComponent';
import EntitySetDataSearch from '../../containers/entitysetsearch/EntitySetDataSearch';
import EntitySetDetailComponent from '../../containers/entitysetdetail/EntitySetDetailComponent';
import DatasourcesComponent from '../../containers/datasets/DatasetsComponent';
import PageConsts from '../../utils/Consts/PageConsts';
import EnvConsts from '../../utils/Consts/EnvConsts';
import { ADMIN } from '../../utils/Consts/UserRoleConsts';
import StringConsts from '../../utils/Consts/StringConsts';
import { configure as edmApiConfigure } from '../../containers/Api';
import { getDisplayName } from '../../containers/principals/PrincipalUtils';

import OrganizationsComponent from '../../containers/organizations/components/OrganizationsComponent';
import OrganizationDetailsComponent from '../../containers/organizations/components/OrganizationDetailsComponent';

// injected by Webpack.DefinePlugin
declare var __AUTH0_CLIENT_ID__;
declare var __AUTH0_DOMAIN__;
declare var __DEV__;

const auth = new AuthService(__AUTH0_CLIENT_ID__, __AUTH0_DOMAIN__, __DEV__);

// onEnter callback to validate authentication in private routes
const requireAuth = (nextState, replace) => {
  if (!auth.loggedIn()) {
    replace({ pathname: `/${PageConsts.LOGIN}` });
  }
  else {
    const authToken = auth.getToken();
    const host = window.location.host;
    const hostName = (host.startsWith('www.')) ? host.substring('www.'.length) : host;
    const baseUrl = (__DEV__) ? EnvConsts.LOCAL : `https://api.${hostName}`;
    Loom.configure({ baseUrl, authToken });
    // TODO: Remove once loom-data-js upgrades
    edmApiConfigure(baseUrl, authToken);
  }
};

const requireAdmin = (nextState, replace) => {
  requireAuth(nextState, replace);
  if (!auth.getProfile().roles.includes(ADMIN)) {
    replace({ pathname: `/${PageConsts.HOME}` });
  }
};

const isAdmin = () => {
  return (auth.loggedIn() && auth.getProfile().hasOwnProperty('roles') && auth.getProfile().roles.includes(ADMIN));
};

const getName = () => {

  if (auth.loggedIn()) {
    return getDisplayName(auth.getProfile());
  } else {
    return null;
  }
};

const getProfileStatus = () => {
  return {
    isAdmin: isAdmin(),
    name: getName()
  };
};

export const makeMainRoutes = () => {
  return (
    <Route path={'/'} component={Container} auth={auth} profileFn={getProfileStatus}>
      <IndexRedirect to={`/${PageConsts.HOME}`} />
      <Route path={PageConsts.HOME} component={HomeComponent} onEnter={requireAuth} />
      <Route path={PageConsts.CATALOG} component={CatalogComponent} onEnter={requireAuth} />
      <Route path={`${PageConsts.SEARCH}/:entitySetId`} component={EntitySetDataSearch} onEnter={requireAuth} />
      <Route path={'entitysets/:id'} component={EntitySetDetailComponent} onEnter={requireAuth} />
      <Route path={PageConsts.DATA_MODEL} component={DataModel} onEnter={requireAuth} />
      <Route path={PageConsts.SETTINGS} component={Settings} onEnter={requireAdmin} />
      <Route path={PageConsts.VISUALIZE} component={Visualize} onEnter={requireAuth} />
      <Route path={PageConsts.DATASOURCES} component={DatasourcesComponent} onEnter={requireAuth} />
      <Route path={PageConsts.ORG} component={OrganizationsComponent} onEnter={requireAuth}>
        <Route path=":orgId" component={OrganizationDetailsComponent} onEnter={requireAuth} />
      </Route>
      <Route path={PageConsts.LOGIN} component={Login} />
      <Route path={'access_token=:token'} component={Login} /> {/* to prevent router errors*/}
      <Route path={PageConsts.LINK} component={Link} onEnter={requireAuth} />
    </Route>
  );
};

export default makeMainRoutes;
<commit_msg>Fix race conditions for auth & redirect in Safari<commit_after>import React from 'react';
import { hashHistory, Route, IndexRedirect } from 'react-router';
import Loom from 'loom-data';
import AuthService from '../../utils/AuthService';
import Container from './Container';
import { DataModel } from './Schemas/DataModel';
import { Login } from './Login/Login';
import HomeComponent from '../../containers/home/HomeComponent';
import { Settings } from './Settings/Settings';
import { Visualize } from './Visualizations/Visualize';
import { Link } from './Link/Link';
import CatalogComponent from '../../containers/catalog/CatalogComponent';
import EntitySetDataSearch from '../../containers/entitysetsearch/EntitySetDataSearch';
import EntitySetDetailComponent from '../../containers/entitysetdetail/EntitySetDetailComponent';
import DatasourcesComponent from '../../containers/datasets/DatasetsComponent';
import PageConsts from '../../utils/Consts/PageConsts';
import EnvConsts from '../../utils/Consts/EnvConsts';
import { ADMIN } from '../../utils/Consts/UserRoleConsts';
import StringConsts from '../../utils/Consts/StringConsts';
import { configure as edmApiConfigure } from '../../containers/Api';
import { getDisplayName } from '../../containers/principals/PrincipalUtils';

import OrganizationsComponent from '../../containers/organizations/components/OrganizationsComponent';
import OrganizationDetailsComponent from '../../containers/organizations/components/OrganizationDetailsComponent';

// injected by Webpack.DefinePlugin
declare var __AUTH0_CLIENT_ID__;
declare var __AUTH0_DOMAIN__;
declare var __DEV__;

const auth = new AuthService(__AUTH0_CLIENT_ID__, __AUTH0_DOMAIN__, __DEV__);

// onEnter callback to validate authentication in private routes
const requireAuth = (nextState, replace) => {
  console.log('requireAuth');
  if (!auth.loggedIn()) {
    replace({ pathname: `/${PageConsts.LOGIN}` });
  }
  else {
    const authToken = auth.getToken();
    const host = window.location.host;
    const hostName = (host.startsWith('www.')) ? host.substring('www.'.length) : host;
    const baseUrl = (__DEV__) ? EnvConsts.LOCAL : `https://api.${hostName}`;
    Loom.configure({ baseUrl, authToken });
    // TODO: Remove once loom-data-js upgrades
    edmApiConfigure(baseUrl, authToken);
  }
};

const requireAdmin = (nextState, replace) => {
  requireAuth(nextState, replace);
  if (!auth.getProfile().roles.includes(ADMIN)) {
    replace({ pathname: `/${PageConsts.HOME}` });
  }
};

const isAdmin = () => {
  return (auth.loggedIn() && auth.getProfile().hasOwnProperty('roles') && auth.getProfile().roles.includes(ADMIN));
};

const getName = () => {
  if (auth.loggedIn()) {
    return getDisplayName(auth.getProfile());
  } else {
    return null;
  }
};

const getProfileStatus = () => {
  return {
    isAdmin: isAdmin(),
    name: getName()
  };
};

//Bugfix for race conditions on Safari: redirect triggers before auth
const checkToken = () => {
  if (auth.loggedIn()) {
    hashHistory.push('/' + PageConsts.HOME);
  }
}

export const makeMainRoutes = () => {
  return (
    <Route path={'/'} component={Container} auth={auth} profileFn={getProfileStatus}>
      <IndexRedirect to={`/${PageConsts.HOME}`} />
      <Route path={PageConsts.HOME} component={HomeComponent} onEnter={requireAuth} />
      <Route path={PageConsts.CATALOG} component={CatalogComponent} onEnter={requireAuth} />
      <Route path={`${PageConsts.SEARCH}/:entitySetId`} component={EntitySetDataSearch} onEnter={requireAuth} />
      <Route path={'entitysets/:id'} component={EntitySetDetailComponent} onEnter={requireAuth} />
      <Route path={PageConsts.DATA_MODEL} component={DataModel} onEnter={requireAuth} />
      <Route path={PageConsts.SETTINGS} component={Settings} onEnter={requireAdmin} />
      <Route path={PageConsts.VISUALIZE} component={Visualize} onEnter={requireAuth} />
      <Route path={PageConsts.DATASOURCES} component={DatasourcesComponent} onEnter={requireAuth} />
      <Route path={PageConsts.ORG} component={OrganizationsComponent} onEnter={requireAuth}>
        <Route path=":orgId" component={OrganizationDetailsComponent} onEnter={requireAuth} />
      </Route>
      <Route path={PageConsts.LOGIN} component={Login} onChange={checkToken}/>
      <Route path={'access_token=:token'} component={Login} /> {/* to prevent router errors*/}
      <Route path={PageConsts.LINK} component={Link} onEnter={requireAuth} />
    </Route>
  );
};

export default makeMainRoutes;
<|endoftext|>


<commit_before>document.getElementById('lookupform').onsubmit = function() {

    var q = document.getElementById('lookup').value;

    var isSubmittable = false;
    if (q.match(/\@/)) {
        isSubmittable = true;
    }

    if (!isSubmittable) {
        document.getElementById('lookup').focus();
        document.getElementById('lookup_results').style.display='none';
        return false;
    }

    var service;
    if (q.match(/^@/)) {
        service = 'twitter';
    } else {
        service = 'email';
    }
    var hash = hex_sha1(q);
    var r = new XMLHttpRequest();
    r.open('GET', 'http://lookup.addressmachine.com/addresses/'+service+'/bitcoin/user/'+hash+'/', true);

    r.onreadystatechange = function () {

        if (r.readyState != 4) {
            return;
        }
        if (r.status == 404) {
            display_no_address(service, q);
            return false;
        } else if (r.status != 200) {
            // Currently the apache server at lookup.addressmachine.com isn't setting CORS headers for 404s.
            // This means that a response that should come back with a 404 status appear to JavaScript to have a status of 0.
            // For now, we'll treat zero status as if it's a 404, ie as if the search was fine, but showed a negative result.
            // Later, we'll fix this by either persuading apache to send us CORS headers even on 404s or by making it send us an empty list instead.
            display_no_address(service, q);
            //alert('wonky status:'+r.status);
            return false;
        }

        document.getElementById('lookup_results').innerHTML += '';

        console.log(r.responseText);
        var data = JSON.parse(r.responseText);
        for (var i=0; i<data.length; i++) {
            var item = data[i];
            if (typeof item == 'string') {
                display_address(service, hash, q, item);
            }
        }

        return false;
    };

    r.send();
    return false;

}

function display_no_address(service, term) {

    document.getElementById('lookup_result_term').innerHTML = 'We couldn\'t find an address for:
';
    document.getElementById('lookup_result_term').appendChild(document.createTextNode(term));
    if (service == 'email') {
        document.getElementById('lookup_result_term').innerHTML += '
Why not ask them to add one?';
    }
    if (service == 'twitter') {
        document.getElementById('lookup_result_term').innerHTML += '
Why not ask them to add one?';
    }
    document.getElementById('lookup_result_address').innerHTML = '';
    document.getElementById('lookup_results').style.display='block';
    document.getElementById('lookup_result_signed_data_textarea').innerHTML = '';
    document.getElementById('lookup_result_signed_data').style.display='none';
    document.getElementById('lookup_result_show_hide').style.display='none';
    //////////////////document.getElementById('lookup_result_gpg_link').innerHTML = '';

}

function display_address(service, id, term, addr) {

    if (id == '') {
        return false;
    }
    if (addr == '') {
        return false;
    }
    console.log("need to validate address "+addr+" for id "+id);

    var r = new XMLHttpRequest();
    r.open('GET', "/addresses/"+service+"/bitcoin/user/"+id+"/"+addr, true);
    r.onreadystatechange = function () {

        if (r.readyState != 4) {
            return;
        }
        if (r.status == 404) {
            alert('GPG-signed data not found');
            return false;
        } else if (r.status != 200) {
            alert('Error:'+r.status);
            return false;
        }
        console.log(r.responseText);
        var data = JSON.parse(r.responseText);
        for (var i=0; i<data.length; i++) {
            var item = data[i];
            if (typeof item == 'string') {
                validate_address(hash, item);
            }
        }

        console.log(data);
        var address = data.payload.address;
        // TODO: Ideally we'd verify this data...
        //var gpg_signed_data = data.gpg_signed_data;
        if (address) {
            document.getElementById('lookup_result_term').innerHTML = '';
            document.getElementById('lookup_result_term').appendChild(document.createTextNode(term));
            document.getElementById('lookup_result_address').innerHTML = '';
            document.getElementById('lookup_result_address').appendChild(document.createTextNode(address));
            document.getElementById('lookup_results').style.display='block';
            document.getElementById('lookup_result_signed_data_textarea').innerHTML = '';
            document.getElementById('lookup_result_signed_data_textarea').appendChild(document.createTextNode(data.gpg_signed_data));
            document.getElementById('lookup_result_show_hide').style.display='block';
            document.getElementById('lookup_result_gpg_link').onclick = function() {
                if (document.getElementById('lookup_result_signed_data').style.display == 'block') {
                    document.getElementById('lookup_result_signed_data').style.display='none';
                } else {
                    document.getElementById('lookup_result_signed_data').style.display='block';
                }
            }
            //document.getElementById('lookup_result_signed_data').style.display = 'block';
            //document.getElementById('lookup_results').innerHTML += '
'+address+ '
 ';
            //document.getElementById('lookup_results').innerHTML += '<textarea>'+gpg_signed_data+'</textarea>';
        }

        return false;

    }

    r.send();

}
<commit_msg>Fix gpg fetch url<commit_after>document.getElementById('lookupform').onsubmit = function() {

    var q = document.getElementById('lookup').value;

    var isSubmittable = false;
    if (q.match(/\@/)) {
        isSubmittable = true;
    }

    if (!isSubmittable) {
        document.getElementById('lookup').focus();
        document.getElementById('lookup_results').style.display='none';
        return false;
    }

    var service;
    if (q.match(/^@/)) {
        service = 'twitter';
    } else {
        service = 'email';
    }
    var hash = hex_sha1(q);
    var r = new XMLHttpRequest();
    r.open('GET', 'http://lookup.addressmachine.com/addresses/'+service+'/bitcoin/user/'+hash+'/', true);

    r.onreadystatechange = function () {

        if (r.readyState != 4) {
            return;
        }
        if (r.status == 404) {
            display_no_address(service, q);
            return false;
        } else if (r.status != 200) {
            // Currently the apache server at lookup.addressmachine.com isn't setting CORS headers for 404s.
            // This means that a response that should come back with a 404 status appear to JavaScript to have a status of 0.
            // For now, we'll treat zero status as if it's a 404, ie as if the search was fine, but showed a negative result.
            // Later, we'll fix this by either persuading apache to send us CORS headers even on 404s or by making it send us an empty list instead.
            display_no_address(service, q);
            //alert('wonky status:'+r.status);
            return false;
        }

        document.getElementById('lookup_results').innerHTML += '';

        console.log(r.responseText);
        var data = JSON.parse(r.responseText);
        for (var i=0; i<data.length; i++) {
            var item = data[i];
            if (typeof item == 'string') {
                display_address(service, hash, q, item);
            }
        }

        return false;
    };

    r.send();
    return false;

}

function display_no_address(service, term) {

    document.getElementById('lookup_result_term').innerHTML = 'We couldn\'t find an address for:
';
    document.getElementById('lookup_result_term').appendChild(document.createTextNode(term));
    if (service == 'email') {
        document.getElementById('lookup_result_term').innerHTML += '
Why not ask them to add one?';
    }
    if (service == 'twitter') {
        document.getElementById('lookup_result_term').innerHTML += '
Why not ask them to add one?';
    }
    document.getElementById('lookup_result_address').innerHTML = '';
    document.getElementById('lookup_results').style.display='block';
    document.getElementById('lookup_result_signed_data_textarea').innerHTML = '';
    document.getElementById('lookup_result_signed_data').style.display='none';
    document.getElementById('lookup_result_show_hide').style.display='none';
    //////////////////document.getElementById('lookup_result_gpg_link').innerHTML = '';

}

function display_address(service, id, term, addr) {

    if (id == '') {
        return false;
    }
    if (addr == '') {
        return false;
    }
    console.log("need to validate address "+addr+" for id "+id);

    var r = new XMLHttpRequest();
    r.open('GET', "http://lookup.addressmachine.com/addresses/"+service+"/bitcoin/user/"+id+"/"+addr, true);
    r.onreadystatechange = function () {

        if (r.readyState != 4) {
            return;
        }
        if (r.status == 404) {
            alert('GPG-signed data not found');
            return false;
        } else if (r.status != 200) {
            alert('Error:'+r.status);
            return false;
        }
        console.log(r.responseText);
        var data = JSON.parse(r.responseText);
        for (var i=0; i<data.length; i++) {
            var item = data[i];
            if (typeof item == 'string') {
                validate_address(hash, item);
            }
        }

        console.log(data);
        var address = data.payload.address;
        // TODO: Ideally we'd verify this data...
        //var gpg_signed_data = data.gpg_signed_data;
        if (address) {
            document.getElementById('lookup_result_term').innerHTML = '';
            document.getElementById('lookup_result_term').appendChild(document.createTextNode(term));
            document.getElementById('lookup_result_address').innerHTML = '';
            document.getElementById('lookup_result_address').appendChild(document.createTextNode(address));
            document.getElementById('lookup_results').style.display='block';
            document.getElementById('lookup_result_signed_data_textarea').innerHTML = '';
            document.getElementById('lookup_result_signed_data_textarea').appendChild(document.createTextNode(data.gpg_signed_data));
            document.getElementById('lookup_result_show_hide').style.display='block';
            document.getElementById('lookup_result_gpg_link').onclick = function() {
                if (document.getElementById('lookup_result_signed_data').style.display == 'block') {
                    document.getElementById('lookup_result_signed_data').style.display='none';
                } else {
                    document.getElementById('lookup_result_signed_data').style.display='block';
                }
            }
            //document.getElementById('lookup_result_signed_data').style.display = 'block';
            //document.getElementById('lookup_results').innerHTML += '
'+address+ '
 ';
            //document.getElementById('lookup_results').innerHTML += '<textarea>'+gpg_signed_data+'</textarea>';
        }

        return false;

    }

    r.send();

}
<|endoftext|>


<commit_before>export default {
    install(Vue){
        Vue.mixin({
            beforeCreate:function(){
                const options = this.$options;
                const config = options.config;
                if(config && typeof config === 'object'){
                    let keys = Object.keys(config);
                    keys.forEach((key)=>{
                        Object.defineProperty(this,key,{
                            value:config[key]
                        })
                    })
                }
            }
        })
    }
}<commit_msg>fix bug for vue-config in mixin<commit_after>export default {
    install(Vue){
        // mixin的时候会用到
        Vue.config.optionMergeStrategies.config = Vue.config.optionMergeStrategies.computed;

        Vue.mixin({
            beforeCreate:function(){
                const config = this.$options.config;
                if(config && typeof config === 'object'){
                    let keys = Object.keys(config);
                    keys.forEach((key)=>{
                        Object.defineProperty(this,key,{
                            value:config[key]
                        })
                    })
                }
            }
        })
    }
}<|endoftext|>


<commit_before>/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window, document, Mustache */

/**
 * A status bar with support for file information and busy and status indicators.
 */
define(function (require, exports, module) {
    'use strict';

    var AppInit         = require("utils/AppInit"),
        StatusBarHTML   = require("text!widgets/StatusBar.html"),
        EditorManager   = require("editor/EditorManager"),
        Strings         = require("strings");

    var _init = false;

    // Indicates if the busy cursor is active to avoid unnecesary operations
    var _busyCursor = false;

    // A simple regexp to sanitize indicator ids
    var _indicatorIDRegexp = new RegExp("[^a-zA-Z 0-9]+", "g");

    // These vars are initialized by the AppInit.htmlReady handler
    // below since they refer to DOM elements
    var $editorContainer,
        $statusBar,
        $indicators,
        $busyIndicator;

    /**
     * Shows the 'busy' indicator
     * @param {boolean} updateCursor Sets the cursor to "wait"
     */
    function showBusyIndicator(updateCursor) {
        if (!_init) {
            return;
        }

        if (updateCursor) {
            _busyCursor = true;
            $("*").addClass("busyCursor");
        }

        $busyIndicator.addClass("spin");
    }

    /**
     * Hides the 'busy' indicator
     */
    function hideBusyIndicator() {
        if (!_init) {
            return;
        }

        // Check if we are using the busyCursor class to avoid
        // unnecesary calls to $('*').removeClass()
        if (_busyCursor) {
            _busyCursor = false;
            $("*").removeClass("busyCursor");
        }

        $busyIndicator.removeClass("spin");
    }

    /**
     * Registers a new status indicator
     * @param {string} id Registration id of the indicator to be updated.
     * @param {DOMNode} indicator Optional DOMNode for the indicator
     * @param {boolean} visible Shows or hides the indicator over the statusbar.
     * @param {string} style Sets the attribute "class" of the indicator.
     * @param {string} tooltip Sets the attribute "title" of the indicator.
     * @param {string} command Optional command name to execute on the indicator click.
     * TODO Unused command parameter. Include command functionality for statusbar indicators.
     */
    function addIndicator(id, indicator, visible, style, tooltip, command) {
        if (!_init) {
            return;
        }

        indicator = indicator || document.createElement("div");
        tooltip = tooltip || "";
        style = style || "";
        id = id.replace(_indicatorIDRegexp, "-") || "";

        var $indicator = $(indicator);

        $indicator.attr("id", id);
        $indicator.attr("title", tooltip);
        $indicator.addClass("indicator");
        $indicator.addClass("style");

        if (!visible) {
            $indicator.hide();
        }

        $indicators.prepend($indicator);
    }

    /**
     * Updates a status indicator
     * @param {string} id Registration id of the indicator to be updated.
     * @param {boolean} visible Shows or hides the indicator over the statusbar.
     * @param {string} style Sets the attribute "class" of the indicator.
     * @param {string} tooltip Sets the attribute "title" of the indicator.
     * @param {string} command Optional command name to execute on the indicator click.
     */
    function updateIndicator(id, visible, style, tooltip, command) {
        if (!_init) {
            return;
        }

        var $indicator = $("#" + id.replace(_indicatorIDRegexp, "-"));

        if ($indicator) {

            if (visible) {
                $indicator.show();
            } else {
                $indicator.hide();
            }

            if (style) {
                $indicator.removeClass();
                $indicator.addClass(style);
            } else {
                $indicator.removeClass();
                $indicator.addClass("indicator");
            }

            if (tooltip) {
                $indicator.attr("title", tooltip);
            }
        }
    }

    /**
     * Hide the statusbar
     */
    function hide() {
        if (!_init) {
            return;
        }

        if ($statusBar.is(":visible")) {
            $statusBar.hide();
            EditorManager.resizeEditor();  // changes available ht for editor area
        }
    }

    /**
     * Show the statusbar
     */
    function show() {
        if (!_init) {
            return;
        }

        if (!$statusBar.is(":visible")) {
            $statusBar.show();
            EditorManager.resizeEditor();  // changes available ht for editor area
        }
    }

    function init($parent) {
        // check if status bar already exists
        if (_init) {
            return;
        }

        $parent = $parent || $("body");
        $parent.append(Mustache.render(StatusBarHTML, Strings));

        // Initialize items dependent on HTML DOM
        $statusBar          = $("#status-bar");
        $indicators         = $("#status-indicators");
        $busyIndicator      = $("#busy-indicator");

        _init = true;

        // hide on init
        hide();
    }

    function getModeDisplayString(mode) {
        // mode is either a string or an object with a name property string
        var s = (typeof mode === "string") ? mode : mode.name,
            slash,
            result;

        s = s.toLowerCase();

        // Handle special cases
        if (s === "javascript") {
            return "JavaScript";
        } else if (s === "html" || s === "htmlmixed") {
            return "HTML";
        } else if (s === "css") {
            return "CSS";
        } else if (s === "less") {
            return "LESS";
        } else if (s === "text/plain") {
            return "Text";
        } else if (s === "php") {
            return "PHP";
        } else if (s === "xml") {
            return "XML";
        }

        // Generic case

        // Strip "text/" or "application/" from beginning
        s = s.replace(/^(text\/|application\/)/, "");

        // Strip "x-" from beginning
        s = s.replace(/^x-/, "");

        // Strip any remaining "/" sections from end
        slash = s.indexOf("/");
        if (slash !== -1) {
            s = s.substr(0, slash);
        }

        // Uppercase first char and rest is (already) lowercase
        result = s[0].toUpperCase();
        result += s.substr(1);

        return result;
    }

    exports.init = init;
    exports.showBusyIndicator = showBusyIndicator;
    exports.hideBusyIndicator = hideBusyIndicator;
    exports.addIndicator = addIndicator;
    exports.updateIndicator = updateIndicator;
    exports.getModeDisplayString = getModeDisplayString;
    exports.hide = hide;
    exports.show = show;
});<commit_msg>add more special types<commit_after>/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window, document, Mustache */

/**
 * A status bar with support for file information and busy and status indicators.
 */
define(function (require, exports, module) {
    'use strict';

    var AppInit         = require("utils/AppInit"),
        StatusBarHTML   = require("text!widgets/StatusBar.html"),
        EditorManager   = require("editor/EditorManager"),
        Strings         = require("strings");

    var _init = false;

    // Indicates if the busy cursor is active to avoid unnecesary operations
    var _busyCursor = false;

    // A simple regexp to sanitize indicator ids
    var _indicatorIDRegexp = new RegExp("[^a-zA-Z 0-9]+", "g");

    // These vars are initialized by the AppInit.htmlReady handler
    // below since they refer to DOM elements
    var $editorContainer,
        $statusBar,
        $indicators,
        $busyIndicator;

    /**
     * Shows the 'busy' indicator
     * @param {boolean} updateCursor Sets the cursor to "wait"
     */
    function showBusyIndicator(updateCursor) {
        if (!_init) {
            return;
        }

        if (updateCursor) {
            _busyCursor = true;
            $("*").addClass("busyCursor");
        }

        $busyIndicator.addClass("spin");
    }

    /**
     * Hides the 'busy' indicator
     */
    function hideBusyIndicator() {
        if (!_init) {
            return;
        }

        // Check if we are using the busyCursor class to avoid
        // unnecesary calls to $('*').removeClass()
        if (_busyCursor) {
            _busyCursor = false;
            $("*").removeClass("busyCursor");
        }

        $busyIndicator.removeClass("spin");
    }

    /**
     * Registers a new status indicator
     * @param {string} id Registration id of the indicator to be updated.
     * @param {DOMNode} indicator Optional DOMNode for the indicator
     * @param {boolean} visible Shows or hides the indicator over the statusbar.
     * @param {string} style Sets the attribute "class" of the indicator.
     * @param {string} tooltip Sets the attribute "title" of the indicator.
     * @param {string} command Optional command name to execute on the indicator click.
     * TODO Unused command parameter. Include command functionality for statusbar indicators.
     */
    function addIndicator(id, indicator, visible, style, tooltip, command) {
        if (!_init) {
            return;
        }

        indicator = indicator || document.createElement("div");
        tooltip = tooltip || "";
        style = style || "";
        id = id.replace(_indicatorIDRegexp, "-") || "";

        var $indicator = $(indicator);

        $indicator.attr("id", id);
        $indicator.attr("title", tooltip);
        $indicator.addClass("indicator");
        $indicator.addClass("style");

        if (!visible) {
            $indicator.hide();
        }

        $indicators.prepend($indicator);
    }

    /**
     * Updates a status indicator
     * @param {string} id Registration id of the indicator to be updated.
     * @param {boolean} visible Shows or hides the indicator over the statusbar.
     * @param {string} style Sets the attribute "class" of the indicator.
     * @param {string} tooltip Sets the attribute "title" of the indicator.
     * @param {string} command Optional command name to execute on the indicator click.
     */
    function updateIndicator(id, visible, style, tooltip, command) {
        if (!_init) {
            return;
        }

        var $indicator = $("#" + id.replace(_indicatorIDRegexp, "-"));

        if ($indicator) {

            if (visible) {
                $indicator.show();
            } else {
                $indicator.hide();
            }

            if (style) {
                $indicator.removeClass();
                $indicator.addClass(style);
            } else {
                $indicator.removeClass();
                $indicator.addClass("indicator");
            }

            if (tooltip) {
                $indicator.attr("title", tooltip);
            }
        }
    }

    /**
     * Hide the statusbar
     */
    function hide() {
        if (!_init) {
            return;
        }

        if ($statusBar.is(":visible")) {
            $statusBar.hide();
            EditorManager.resizeEditor();  // changes available ht for editor area
        }
    }

    /**
     * Show the statusbar
     */
    function show() {
        if (!_init) {
            return;
        }

        if (!$statusBar.is(":visible")) {
            $statusBar.show();
            EditorManager.resizeEditor();  // changes available ht for editor area
        }
    }

    function init($parent) {
        // check if status bar already exists
        if (_init) {
            return;
        }

        $parent = $parent || $("body");
        $parent.append(Mustache.render(StatusBarHTML, Strings));

        // Initialize items dependent on HTML DOM
        $statusBar          = $("#status-bar");
        $indicators         = $("#status-indicators");
        $busyIndicator      = $("#busy-indicator");

        _init = true;

        // hide on init
        hide();
    }

    function getModeDisplayString(mode) {
        // mode is either a string or an object with a name property string
        var s = (typeof mode === "string") ? mode : mode.name,
            slash,
            result;

        s = s.toLowerCase();

        // Handle special cases (in order of likely occurrance)
        if (s === "javascript") {
            return "JavaScript";
        } else if (s === "html" || s === "htmlmixed") {
            return "HTML";
        } else if (s === "css") {
            return "CSS";
        } else if (s === "less") {
            return "LESS";
        } else if (s === "text/plain") {
            return "Text";
        } else if (s === "php") {
            return "PHP";
        } else if (s === "xml") {
            return "XML";
        } else if (s === "yaml") {
            return "YAML";
        } else if (s === "coffeescript") {
            return "CoffeeScript";
        } else if (s === "mysql") {
            return "SQL";
        }

        // Generic case

        // Strip "text/" or "application/" from beginning
        s = s.replace(/^(text\/|application\/)/, "");

        // Strip "x-" from beginning
        s = s.replace(/^x-/, "");

        // Strip any remaining "/" sections from end
        slash = s.indexOf("/");
        if (slash !== -1) {
            s = s.substr(0, slash);
        }

        // Uppercase first char and rest is (already) lowercase
        result = s[0].toUpperCase();
        result += s.substr(1);

        return result;
    }

    exports.init = init;
    exports.showBusyIndicator = showBusyIndicator;
    exports.hideBusyIndicator = hideBusyIndicator;
    exports.addIndicator = addIndicator;
    exports.updateIndicator = updateIndicator;
    exports.getModeDisplayString = getModeDisplayString;
    exports.hide = hide;
    exports.show = show;
});<|endoftext|>


<commit_before>import React, { Component, createElement } from 'react'
import PropTypes from 'prop-types'
import ResizeObserver from 'resize-observer-polyfill'
import getContentRect from './get-content-rect'

const types = ['client', 'offset', 'scroll', 'bounds', 'margin']

function getTypes(props) {
  const allowedTypes = []
  types.forEach(type => {
    if (props[type]) {
      allowedTypes.push(type)
    }
  })
  return allowedTypes
}

function withContentRect(types) {
  return WrappedComponent =>
    class extends Component {
      static propTypes = {
        client: PropTypes.bool,
        offset: PropTypes.bool,
        scroll: PropTypes.bool,
        bounds: PropTypes.bool,
        margin: PropTypes.bool,
        innerRef: PropTypes.func,
        onResize: PropTypes.func,
      }

      state = {
        contentRect: {
          entry: {},
          client: {},
          offset: {},
          scroll: {},
          bounds: {},
          margin: {},
        },
      }

      componentDidMount() {
        if (typeof window !== 'object') return

        if (this._node) {
          this._resizeObserver = new ResizeObserver(this.measure)
          this._resizeObserver.observe(this._node)
        } else {
          console.error(
            'No ref found, attach the `measureRef` prop to the component you want to measure.'
          )
        }
      }

      componentWillUnmount() {
        if (this.resizeObserver && this._node) {
          this._resizeObserver.disconnect(this._node)
        }
      }

      measure = entries => {
        const contentRect = getContentRect(
          this._node,
          types || getTypes(this.props)
        )

        if (entries) {
          contentRect.entry = entries[0].contentRect
        }

        this.setState({ contentRect })

        if (typeof this.props.onResize === 'function') {
          this.props.onResize(contentRect)
        }
      }

      _handleRef = component => {
        this._node = component

        if (typeof this.props.innerRef === 'function') {
          this.props.innerRef(component)
        }
      }

      render() {
        const { innerRef, onResize, ...props } = this.props
        return createElement(WrappedComponent, {
          ...props,
          measure: this.measure,
          measureRef: this._handleRef,
          contentRect: this.state.contentRect,
        })
      }
    }
}

export default withContentRect
<commit_msg>add children propType<commit_after>import React, { Component, createElement } from 'react'
import PropTypes from 'prop-types'
import ResizeObserver from 'resize-observer-polyfill'
import getContentRect from './get-content-rect'

const types = ['client', 'offset', 'scroll', 'bounds', 'margin']

function getTypes(props) {
  const allowedTypes = []
  types.forEach(type => {
    if (props[type]) {
      allowedTypes.push(type)
    }
  })
  return allowedTypes
}

function withContentRect(types) {
  return WrappedComponent =>
    class extends Component {
      static propTypes = {
        client: PropTypes.bool,
        offset: PropTypes.bool,
        scroll: PropTypes.bool,
        bounds: PropTypes.bool,
        margin: PropTypes.bool,
        innerRef: PropTypes.func,
        onResize: PropTypes.func,
        children: PropTypes.func,
      }

      state = {
        contentRect: {
          entry: {},
          client: {},
          offset: {},
          scroll: {},
          bounds: {},
          margin: {},
        },
      }

      componentDidMount() {
        if (typeof window !== 'object') return

        if (this._node) {
          this._resizeObserver = new ResizeObserver(this.measure)
          this._resizeObserver.observe(this._node)
        } else {
          console.error(
            'No ref found, attach the `measureRef` prop to the component you want to measure.'
          )
        }
      }

      componentWillUnmount() {
        if (this.resizeObserver && this._node) {
          this._resizeObserver.disconnect(this._node)
        }
      }

      measure = entries => {
        const contentRect = getContentRect(
          this._node,
          types || getTypes(this.props)
        )

        if (entries) {
          contentRect.entry = entries[0].contentRect
        }

        this.setState({ contentRect })

        if (typeof this.props.onResize === 'function') {
          this.props.onResize(contentRect)
        }
      }

      _handleRef = component => {
        this._node = component

        if (typeof this.props.innerRef === 'function') {
          this.props.innerRef(component)
        }
      }

      render() {
        const { innerRef, onResize, ...props } = this.props
        return createElement(WrappedComponent, {
          ...props,
          measureRef: this._handleRef,
          measure: this.measure,
          contentRect: this.state.contentRect,
        })
      }
    }
}

export default withContentRect
<|endoftext|>


<commit_before>/*global define, require*/
/*jslint nomen: true*/
define([
    'jquery',
    'underscore',
    'orotranslation/js/translator',
    'oro/filter/datetime-filter',
    'oro/filter/choice-filter',
    'oroentity/js/field-choice',
    'oroquerydesigner/js/field-condition'
], function($, _, __, DateTimeFilter, ChoiceFilter) {
    'use strict';

    $.widget('oroauditquerydesigner.dataAuditCondition', $.oroquerydesigner.fieldCondition, {
        options: {
            changeStateTpl: _.template($('#template-audit-condition-type-select').html())
        },

        _create: function() {
            this._superApply(arguments);

            var data = this.element.data('value');
            if (data && data.columnName) {
                this.element.one('changed', _.bind(this._renderChangeStateChoice, this, data));
            } else {
                this.element.data('value', data);
            }

            this._on(this.$fieldChoice, {
                changed: function (e, fieldId) {
                    if (this.auditFilter) {
                        this.auditFilter.reset();
                    }
                    this._renderChangeStateChoice();
                }
            });
        },

        _renderChangeStateChoice: function (data) {
            if (this.$changeStateChoice) {
                return;
            }

            data = data || $.extend(true, {
                criterion: {
                    data: {
                        auditFilter: {
                            type: 'changed'
                        }
                    }
                }
            }, this.element.data('value'));

            this.auditTypeFilter = new ChoiceFilter({
                caret: '',
                templateSelector: '#simple-choice-filter-template-embedded',
                choices: {
                    changed: __('oro.dataaudit.data_audit_condition.changed'),
                    changed_to_value: __('oro.dataaudit.data_audit_condition.changed_to_value')
                }
            });
            this.auditTypeFilter.setValue({
                type: data.criterion.data.auditFilter.type
            });
            this.auditTypeFilter.on('update', _.bind(this._onUpdate, this));

            this.$changeStateChoice = $('')
                .css('display', 'inline-block')
                .html(this.auditTypeFilter.render().$el);
            this.$interval = $('').html(__('oro.dataaudit.data_audit_condition.in_the_interval'));
            this.$value = $('').html(__('oro.dataaudit.data_audit_condition.value'));
            this.$valueThat = $('').html(__('oro.dataaudit.data_audit_condition.value_that'));

            var filterOptions = _.findWhere(this.options.filters, {
                type: 'datetime'
            });

            if (!filterOptions) {
                throw new Error('Cannot find filter "datetime"');
            }

            filterOptions.criteriaValueSelectors = {};
            $.extend(filterOptions.criteriaValueSelectors, DateTimeFilter.prototype.criteriaValueSelectors, {
                date_type: 'select[name=datetime]'
            });

            this.auditFilter = new (DateTimeFilter.extend(filterOptions))();
            this.auditFilter.value = data.criterion.data.auditFilter.data;
            this.auditFilter.on('update', _.bind(this._onUpdate, this));

            this.$auditFilterContainer = $('
').html(this.auditFilter.render().$el);
            this.$filterContainer.after(this.$auditFilterContainer);

            this._on(this.auditFilter.$el, {
                change: function () {
                    this.auditFilter.applyValue();
                }
            });
            var onChangeCb = {
                'changed': this._renderChangedChoice,
                'changed_to_value': this._renderChangedToValueChoice
            };
            this._on(this.auditTypeFilter.$el, {
                change: function () {
                    this.auditTypeFilter.applyValue();
                    onChangeCb[this.auditTypeFilter.value.type].apply(this);
                }
            });
            onChangeCb[this.auditTypeFilter.value.type].apply(this);

            this.element.data('value', data);
        },

        _renderChangedChoice: function () {
            this.$filterContainer.hide();
            this.$auditFilterContainer.css('display', 'inline');
            this.auditFilter.$el.find('> .dropdown:last').before(this.$changeStateChoice);
            this.$interval.prevUntil().show();
            this.$changeStateChoice.after(this.$interval);
        },

        _renderChangedToValueChoice: function () {
            this.$filterContainer.show();
            this.$auditFilterContainer.css('display', 'block');
            this.filter.$el.find('> .dropdown:last').before(this.$changeStateChoice);

            var selectedField = this.element.find('input.select').select2('val');
            var conditions = this.$fieldChoice.fieldChoice('getApplicableConditions', selectedField);

            if (_.contains(['date', 'datetime'], conditions.type)) {
                this.$changeStateChoice.after(this.$value);
            } else {
                this.$changeStateChoice.after(this.$valueThat);
            }

            this.auditFilter.$el.find('> .dropdown:last').before(this.$interval);
            this.$interval.prevUntil().hide();
        },

        _getFilterCriterion: function () {
            var filter = {
                filter: this.filter.name,
                data: this.filter.getValue()
            };

            if (this.filter.filterParams) {
                filter.params = this.filter.filterParams;
            }

            var auditFilter = {};
            if (this.auditFilter) {
                auditFilter.columnName = this.element.find('input.select').select2('val');
                auditFilter.data = this.auditFilter.getValue();

                if (this.auditFilter.filterParams) {
                    auditFilter.params = this.auditFilter.filterParams;
                }
            }
            if (this.$changeStateChoice) {
                auditFilter.type = this.auditTypeFilter.value.type;
            }

            return {
                filter: 'audit',
                data: {
                    filter: filter,
                    auditFilter: auditFilter
                }
            };
        },

        _appendFilter: function() {
            var data = this.element.data('value');

            if (data && data.criterion && data.criterion.data.filter) {
                var fieldConditionData = $.extend(true, {
                    criterion: {
                        data: {
                            filter: {
                                columnName: data.columnName
                            }
                        }
                    }
                }, data);

                fieldConditionData.columnName = data.columnName;
                this.element.data('value', {
                    columnName: data.columnName,
                    criterion: fieldConditionData.criterion.data.filter
                });
            } else {
                this.element.data('value', {});
            }

            if (this.$changeStateChoice) {
                this.$changeStateChoice.detach();
            }

            this._superApply(arguments);

            if (this.auditTypeFilter) {
                this.auditTypeFilter.$el.trigger('change');
            }

            this.element.data('value', data);
        },

        _onUpdate: function () {
            if (!this.auditFilter || !this.auditFilter.value || this.auditFilter.isEmptyValue()) {
                return this._superApply(arguments);
            }

            var value = {
                columnName: this.element.find('input.select').select2('val'),
                criterion: this._getFilterCriterion()
            };

            this.element.data('value', value);
            this.element.trigger('changed');
        },

        _destroy: function () {
            this._superApply(arguments);
            if (this.auditFilter) {
                this.auditFilter.dispose();
                delete this.auditFilter;
            }
        }
    });

    return $;
});
<commit_msg>BAP-8391: Fix github comments<commit_after>/*global define, require*/
/*jslint nomen: true*/
define([
    'jquery',
    'underscore',
    'orotranslation/js/translator',
    'oro/filter/datetime-filter',
    'oro/filter/choice-filter',
    'oroentity/js/field-choice',
    'oroquerydesigner/js/field-condition'
], function($, _, __, DateTimeFilter, ChoiceFilter) {
    'use strict';

    $.widget('oroauditquerydesigner.dataAuditCondition', $.oroquerydesigner.fieldCondition, {
        options: {
            changeStateTpl: _.template($('#template-audit-condition-type-select').html())
        },

        _create: function() {
            this._superApply(arguments);

            var data = this.element.data('value');
            if (data && data.columnName) {
                this.element.one('changed', _.bind(this._renderChangeStateChoice, this, data));
            } else {
                this.element.data('value', data);
            }

            this._on(this.$fieldChoice, {
                changed: function (e, fieldId) {
                    this.element.data('value', {});
                    if (this.auditFilter) {
                        this.element.on('changed', _.bind(this.auditFilter.reset, this.auditFilter));
                    }
                    this._renderChangeStateChoice();
                }
            });
        },

        _renderChangeStateChoice: function (data) {
            if (this.$changeStateChoice) {
                return;
            }

            data = data || $.extend(true, {
                criterion: {
                    data: {
                        auditFilter: {
                            type: 'changed'
                        }
                    }
                }
            }, this.element.data('value'));

            this.auditTypeFilter = new ChoiceFilter({
                caret: '',
                templateSelector: '#simple-choice-filter-template-embedded',
                choices: {
                    changed: __('oro.dataaudit.data_audit_condition.changed'),
                    changed_to_value: __('oro.dataaudit.data_audit_condition.changed_to_value')
                }
            });
            this.auditTypeFilter.setValue({
                type: data.criterion.data.auditFilter.type
            });
            this.auditTypeFilter.on('update', _.bind(this._onUpdate, this));

            this.$changeStateChoice = $('')
                .css('display', 'inline-block')
                .html(this.auditTypeFilter.render().$el);
            this.$interval = $('').html(__('oro.dataaudit.data_audit_condition.in_the_interval'));
            this.$value = $('').html(__('oro.dataaudit.data_audit_condition.value'));
            this.$valueThat = $('').html(__('oro.dataaudit.data_audit_condition.value_that'));

            var filterOptions = _.findWhere(this.options.filters, {
                type: 'datetime'
            });

            if (!filterOptions) {
                throw new Error('Cannot find filter "datetime"');
            }

            filterOptions.criteriaValueSelectors = {};
            $.extend(filterOptions.criteriaValueSelectors, DateTimeFilter.prototype.criteriaValueSelectors, {
                date_type: 'select[name=datetime]'
            });

            this.auditFilter = new (DateTimeFilter.extend(filterOptions))();
            this.auditFilter.value = data.criterion.data.auditFilter.data;
            this.auditFilter.on('update', _.bind(this._onUpdate, this));

            this.$auditFilterContainer = $('
').html(this.auditFilter.render().$el);
            this.$filterContainer.after(this.$auditFilterContainer);

            this._on(this.auditFilter.$el, {
                change: function () {
                    this.auditFilter.applyValue();
                }
            });
            var onChangeCb = {
                'changed': this._renderChangedChoice,
                'changed_to_value': this._renderChangedToValueChoice
            };
            this._on(this.auditTypeFilter.$el, {
                change: function () {
                    this.auditTypeFilter.applyValue();
                    onChangeCb[this.auditTypeFilter.value.type].apply(this);
                }
            });
            onChangeCb[this.auditTypeFilter.value.type].apply(this);

            this.element.data('value', data);
        },

        _renderChangedChoice: function () {
            this.$filterContainer.hide();
            this.$auditFilterContainer.css('display', 'inline');
            this.auditFilter.$el.find('> .dropdown:last').before(this.$changeStateChoice);
            this.$interval.prevUntil().show();
            this.$changeStateChoice.after(this.$interval);
        },

        _renderChangedToValueChoice: function () {
            this.$filterContainer.show();
            this.$auditFilterContainer.css('display', 'block');
            this.filter.$el.find('> .dropdown:last').before(this.$changeStateChoice);

            var selectedField = this.element.find('input.select').select2('val');
            var conditions = this.$fieldChoice.fieldChoice('getApplicableConditions', selectedField);

            if (_.contains(['date', 'datetime'], conditions.type)) {
                this.$changeStateChoice.after(this.$value);
            } else {
                this.$changeStateChoice.after(this.$valueThat);
            }

            this.auditFilter.$el.find('> .dropdown:last').before(this.$interval);
            this.$interval.prevUntil().hide();
        },

        _getFilterCriterion: function () {
            var filter = {
                filter: this.filter.name,
                data: this.filter.getValue()
            };

            if (this.filter.filterParams) {
                filter.params = this.filter.filterParams;
            }

            var auditFilter = {};
            if (this.auditFilter) {
                auditFilter.columnName = this.element.find('input.select').select2('val');
                auditFilter.data = this.auditFilter.getValue();

                if (this.auditFilter.filterParams) {
                    auditFilter.params = this.auditFilter.filterParams;
                }
            }
            if (this.$changeStateChoice) {
                auditFilter.type = this.auditTypeFilter.value.type;
            }

            return {
                filter: 'audit',
                data: {
                    filter: filter,
                    auditFilter: auditFilter
                }
            };
        },

        _appendFilter: function() {
            var data = this.element.data('value');

            if (data && data.criterion && data.criterion.data.filter) {
                var fieldConditionData = $.extend(true, {
                    criterion: {
                        data: {
                            filter: {
                                columnName: data.columnName
                            }
                        }
                    }
                }, data);

                fieldConditionData.columnName = data.columnName;
                this.element.data('value', {
                    columnName: data.columnName,
                    criterion: fieldConditionData.criterion.data.filter
                });
            } else {
                this.element.data('value', {});
            }

            if (this.$changeStateChoice) {
                this.$changeStateChoice.detach();
            }

            this._superApply(arguments);

            if (this.auditTypeFilter) {
                this.auditTypeFilter.$el.trigger('change');
            }

            this.element.data('value', data);
        },

        _onUpdate: function () {
            if (!this.auditFilter || !this.auditFilter.value || this.auditFilter.isEmptyValue()) {
                return this._superApply(arguments);
            }

            var value = {
                columnName: this.element.find('input.select').select2('val'),
                criterion: this._getFilterCriterion()
            };

            this.element.data('value', value);
            this.element.trigger('changed');
        },

        _destroy: function () {
            this._superApply(arguments);
            if (this.auditFilter) {
                this.auditFilter.dispose();
                delete this.auditFilter;
            }
        }
    });

    return $;
});
<|endoftext|>