<commit_before>/*
  Copyright 2012 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.
*/

define([
  'jquery',
  './constants',
  './globals',
  './utils',
  './config',
  './player',
  'ytdl/panels/existing',
  'ytdl/panels/login',
  'ytdl/panels/logout',
  'ytdl/panels/postupload',
  'ytdl/panels/select',
  'ytdl/panels/upload',
  'ytdl/panels/webcam',
  'ytdl/panels/admin',
  'ytdl/panels/embed-codes',
  'ytdl/panels/pending',
  'ytdl/panels/approved',
  'ytdl/panels/rejected'
], function($, constants, globals, utils, config, player) {
  return {
    onLoad: function(defaultTab) {
      if (config.GOOGLE_ANALYTICS_ID) {
        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', config.GOOGLE_ANALYTICS_ID]);
        _gaq.push(['_trackPageview']);

        var analyticsScriptSrc = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        $.getScript(analyticsScriptSrc);
      }

      if (!config.OAUTH2_CLIENT_ID || !config.DEVELOPER_KEY) {
        utils.showHtmlMessage('YouTube Direct Lite isn\'t configured. Please see the setup guide for more info.');
        return;
      }

      if (!$.support.cors) {
        utils.showHtmlMessage('Unfortunately, your browser is not supported. Please try visiting this page using a recent version of Firefox, Safari, Opera, or Chrome.');
        return;
      }

      utils.updateHashParams();

      $('body').on({
        click: function() {
          utils.redirect($(this).attr('data-state'), $(this).attr('data-playlist-id'));
        }
      }, '[data-state]');

      $('#message').click(function() {
        $(this).hide();
      });

      $('body').on({
        click: function() {
          player.playVideo(this, $(this).data('video-id'));
        },
        mouseenter: function() {
          $(this).find('.play-overlay').fadeIn();
        },
        mouseleave: function() {
          $(this).find('.play-overlay').fadeOut();
        }
      }, '.thumbnail-container');

      $(window).bind('hashchange', function() {
        utils.updateHashParams();
        var state = globals.hashParams.state || defaultTab;

        $('#profile-picture').attr('src', lscache.get(constants.PROFILE_PICTURE_CACHE_KEY) || constants.GENERIC_PROFILE_PICTURE_URL);
        var displayName = lscache.get(constants.DISPLAY_NAME_CACHE_KEY);
        $('#display-name').text(displayName);
        if (displayName) {
          $('.login-required').show();
        } else {
          $('.login-required').hide();
        }

        var panel;
        try {
          panel = require(utils.format('ytdl/panels/{0}', state));
        } catch (e) {
          utils.showMessage(utils.format('Unknown panel: {0}', state));
          return;
        }

        utils.hideMessage();

        if (panel.needsPlaylist && !globals.hashParams.playlist) {
          utils.showMessage('The "playlist" URL parameter is missing.');
          return;
        }

        if ('init' in panel) {
          panel.init();
          delete panel.init;
        }

        if ('display' in panel) {
          panel.display();
        }

        $('.panel').hide();
        $(utils.format('#{0}-panel', state)).show();
        $('#tabs > li').removeClass('selected');
        $(utils.format('#tabs > li[data-state={0}]', state)).addClass('selected');
      });
    }
  };
});<commit_msg>Fixed the Google Analytics tracking so that it a) actually works and b) will register pageviews for each hash change.<commit_after>/*
  Copyright 2012 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.
*/

define([
  'jquery',
  './constants',
  './globals',
  './utils',
  './config',
  './player',
  'ytdl/panels/existing',
  'ytdl/panels/login',
  'ytdl/panels/logout',
  'ytdl/panels/postupload',
  'ytdl/panels/select',
  'ytdl/panels/upload',
  'ytdl/panels/webcam',
  'ytdl/panels/admin',
  'ytdl/panels/embed-codes',
  'ytdl/panels/pending',
  'ytdl/panels/approved',
  'ytdl/panels/rejected'
], function($, constants, globals, utils, config, player) {
  return {
    onLoad: function(defaultTab) {
      window._gaq = window._gaq || [];

      if (config.GOOGLE_ANALYTICS_ID) {
        window._gaq.push(['_setAccount', config.GOOGLE_ANALYTICS_ID]);

        var analyticsScriptSrc = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        $.getScript(analyticsScriptSrc);
      }

      if (!config.OAUTH2_CLIENT_ID || !config.DEVELOPER_KEY) {
        utils.showHtmlMessage('YouTube Direct Lite isn\'t configured. Please see the setup guide for more info.');
        return;
      }

      if (!$.support.cors) {
        utils.showHtmlMessage('Unfortunately, your browser is not supported. Please try visiting this page using a recent version of Firefox, Safari, Opera, or Chrome.');
        return;
      }

      utils.updateHashParams();

      $('body').on({
        click: function() {
          utils.redirect($(this).attr('data-state'), $(this).attr('data-playlist-id'));
        }
      }, '[data-state]');

      $('#message').click(function() {
        $(this).hide();
      });

      $('body').on({
        click: function() {
          player.playVideo(this, $(this).data('video-id'));
        },
        mouseenter: function() {
          $(this).find('.play-overlay').fadeIn();
        },
        mouseleave: function() {
          $(this).find('.play-overlay').fadeOut();
        }
      }, '.thumbnail-container');

      $(window).bind('hashchange', function() {
        utils.updateHashParams();
        var state = globals.hashParams.state || defaultTab;

        $('#profile-picture').attr('src', lscache.get(constants.PROFILE_PICTURE_CACHE_KEY) || constants.GENERIC_PROFILE_PICTURE_URL);
        var displayName = lscache.get(constants.DISPLAY_NAME_CACHE_KEY);
        $('#display-name').text(displayName);
        if (displayName) {
          $('.login-required').show();
        } else {
          $('.login-required').hide();
        }

        var panel;
        try {
          panel = require(utils.format('ytdl/panels/{0}', state));
        } catch (e) {
          utils.showMessage(utils.format('Unknown panel: {0}', state));
          return;
        }

        utils.hideMessage();

        if (panel.needsPlaylist && !globals.hashParams.playlist) {
          utils.showMessage('The "playlist" URL parameter is missing.');
          return;
        }

        if ('init' in panel) {
          panel.init();
          delete panel.init;
        }

        if ('display' in panel) {
          panel.display();
        }

        $('.panel').hide();
        $(utils.format('#{0}-panel', state)).show();
        $('#tabs > li').removeClass('selected');
        $(utils.format('#tabs > li[data-state={0}]', state)).addClass('selected');

        window._gaq.push(['_trackPageview', utils.format('{0}#state={1}', location.pathname, state)]);
      });
    }
  };
});<|endoftext|>


<commit_before>/*
---

name: Element.defineCustomEvent

description: Allows to create custom events based on other custom events.

authors: Christoph Pojer (@cpojer)

license: MIT-style license.

requires: [Core/Element.Event]

provides: Element.defineCustomEvent

...
*/

(function(){

[Element, Window, Document].invoke('implement', {hasEvent: function(event){
	var events = this.retrieve('events'),
		list = (events && events[event]) ? events[event].values : null;
	if (list){
		for (var i = list.length; i--;) if (i in list){
			return true;
		}
	}
	return false;
}});

var wrap = function(custom, method, extended, name){
	method = custom[method];
	extended = custom[extended];

	return function(fn, customName){
		if (!customName) customName = name;

		if (extended && !this.hasEvent(customName)) extended.call(this, fn, customName);
		if (method) method.call(this, fn, customName);
	};
};

var inherit = function(custom, base, method, name){
	return function(fn, customName){
		base[method].call(this, fn, customName || name);
		custom[method].call(this, fn, customName || name);
	};
};

var events = Element.Events;

Element.defineCustomEvent = function(name, custom){

	var base = events[custom.base];

	custom.onAdd = wrap(custom, 'onAdd', 'onSetup', name);
	custom.onRemove = wrap(custom, 'onRemove', 'onTeardown', name);

	events[name] = base ? Object.append({}, custom, {

		base: base.base,

		condition: function(event){
			return (!base.condition || base.condition.call(this, event)) &&
				(!custom.condition || custom.condition.call(this, event));
		},

		onAdd: inherit(custom, base, 'onAdd', name),
		onRemove: inherit(custom, base, 'onRemove', name)

	}) : custom;

	return this;

};

var loop = function(name){
	var method = 'on' + name.capitalize();
	Element[name + 'CustomEvents'] = function(){
		Object.each(events, function(event, name){
			if (event[method]) event[method].call(event, name);
		});
	};
	return loop;
};

loop('enable')('disable');

})();
<commit_msg>Simplify defineCustomEvent by using some new 1.4 APIs.<commit_after>/*
---

name: Element.defineCustomEvent

description: Allows to create custom events based on other custom events.

authors: Christoph Pojer (@cpojer)

license: MIT-style license.

requires: [Core/Element.Event]

provides: Element.defineCustomEvent

...
*/

(function(){

[Element, Window, Document].invoke('implement', {hasEvent: function(event){
	var events = this.retrieve('events'),
		list = (events && events[event]) ? events[event].values : null;
	if (list){
		var i = list.length;
		while (i--) if (i in list){
			return true;
		}
	}
	return false;
}});

var wrap = function(custom, method, extended){
	method = custom[method];
	extended = custom[extended];

	return function(fn, name){
		if (extended && !this.hasEvent(name)) extended.call(this, fn, name);
		if (method) method.call(this, fn, name);
	};
};

var inherit = function(custom, base, method){
	return function(fn, name){
		base[method].call(this, fn, name);
		custom[method].call(this, fn, name);
	};
};

var events = Element.Events;

Element.defineCustomEvent = function(name, custom){
	var base = events[custom.base];

	custom.onAdd = wrap(custom, 'onAdd', 'onSetup');
	custom.onRemove = wrap(custom, 'onRemove', 'onTeardown');

	events[name] = base ? Object.append({}, custom, {

		base: base.base,

		condition: function(event, name){
			return (!base.condition || base.condition.call(this, event, name)) &&
				(!custom.condition || custom.condition.call(this, event, name));
		},

		onAdd: inherit(custom, base, 'onAdd'),
		onRemove: inherit(custom, base, 'onRemove')

	}) : custom;

	return this;
};

Element.enableCustomEvents = function(){
  Object.each(events, function(event, name){
    if (event.onEnable) event.onEnable.call(event, name);
  });
};

Element.disableCustomEvents = function(){
  Object.each(events, function(event, name){
    if (event.onDisable) event.onDisable.call(event, name);
  });
};

})();
<|endoftext|>


<commit_before>define([
        './AttributeType',
        '../Core/Cartesian3',
        '../Core/ComponentDatatype',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/LinearSpline',
        '../Core/Matrix4',
        '../Core/Quaternion',
        '../Core/QuaternionSpline',
        '../Core/WebGLConstants',
        '../Core/WeightSpline',
        '../ThirdParty/GltfPipeline/getAccessorByteStride',
        '../ThirdParty/GltfPipeline/numberOfComponentsForType'
    ], function(
        AttributeType,
        Cartesian3,
        ComponentDatatype,
        defaultValue,
        defined,
        LinearSpline,
        Matrix4,
        Quaternion,
        QuaternionSpline,
        WebGLConstants,
        WeightSpline,
        getAccessorByteStride,
        numberOfComponentsForType) {
    'use strict';

    /**
     * @private
     */
    function ModelAnimationCache() {
    }

    var dataUriRegex = /^data\:/i;

    function getAccessorKey(model, accessor) {
        var gltf = model.gltf;
        var buffers = gltf.buffers;
        var bufferViews = gltf.bufferViews;

        var bufferView = bufferViews[accessor.bufferView];
        var buffer = buffers[bufferView.buffer];

        var byteOffset = bufferView.byteOffset + accessor.byteOffset;
        var byteLength = accessor.count * numberOfComponentsForType(accessor.type);

        var uriKey = dataUriRegex.test(buffer.uri) ? '' : buffer.uri;
        return model.cacheKey + '//' + uriKey + '/' + byteOffset + '/' + byteLength;
    }

    var cachedAnimationParameters = {
    };

    ModelAnimationCache.getAnimationParameterValues = function(model, accessor) {
        var key = getAccessorKey(model, accessor);
        var values = cachedAnimationParameters[key];

        if (!defined(values)) {
            // Cache miss
            var gltf = model.gltf;

            var buffers = gltf.buffers;
            var bufferViews = gltf.bufferViews;

            var bufferView = bufferViews[accessor.bufferView];
            var bufferId = bufferView.buffer;
            var buffer = buffers[bufferId];
            var source = buffer.extras._pipeline.source;

            var componentType = accessor.componentType;
            var type = accessor.type;
            var numberOfComponents = numberOfComponentsForType(type);
            var count = accessor.count;
            var byteStride = getAccessorByteStride(gltf, accessor);

            values = new Array(count);
            var accessorByteOffset = defaultValue(accessor.byteOffset, 0);
            var byteOffset = bufferView.byteOffset + accessorByteOffset;
            for (var i = 0; i < count; i++) {
                var typedArrayView = ComponentDatatype.createArrayBufferView(componentType, source.buffer, byteOffset, numberOfComponents);
                if (type === 'SCALAR') {
                    values[i] = typedArrayView[0];
                } else if (type === 'VEC3') {
                    values[i] = Cartesian3.fromArray(typedArrayView);
                } else if (type === 'VEC4') {
                    values[i] = Quaternion.unpack(typedArrayView);
                }
                byteOffset += byteStride;
            }
            // GLTF_SPEC: Support more parameter types when glTF supports targeting materials. https://github.com/KhronosGroup/glTF/issues/142

            if (defined(model.cacheKey)) {
                // Only cache when we can create a unique id
                cachedAnimationParameters[key] = values;
            }
        }

        return values;
    };

    var cachedAnimationSplines = {
    };

    function getAnimationSplineKey(model, animationName, samplerName) {
        return model.cacheKey + '//' + animationName + '/' + samplerName;
    }

 // GLTF_SPEC: https://github.com/KhronosGroup/glTF/issues/185
    function ConstantSpline(value) {
        this._value = value;
    }
    ConstantSpline.prototype.evaluate = function(time, result) {
        return this._value;
    };
 // END GLTF_SPEC

    ModelAnimationCache.getAnimationSpline = function(model, animationName, animation, samplerName, sampler, input, path, output) {
        var key = getAnimationSplineKey(model, animationName, samplerName);
        var spline = cachedAnimationSplines[key];

        if (!defined(spline)) {
            var times = input;
            var controlPoints = output;

// GLTF_SPEC: https://github.com/KhronosGroup/glTF/issues/185
            if ((times.length === 1) && (controlPoints.length === 1)) {
                spline = new ConstantSpline(controlPoints[0]);
            } else if (sampler.interpolation === 'LINEAR') {
// END GLTF_SPEC
                if (path === 'translation' || path === 'scale') {
                    spline = new LinearSpline({
                        times : times,
                        points : controlPoints
                    });
                } else if (path === 'rotation') {
                    spline = new QuaternionSpline({
                        times : times,
                        points : controlPoints
                    });
                } else if (path === 'weights') {
                    spline = new WeightSpline({
                        times : times,
                        points : controlPoints
                    });
                }
                // GLTF_SPEC: Support more parameter types when glTF supports targeting materials. https://github.com/KhronosGroup/glTF/issues/142
            }
            // GLTF_SPEC: Support new interpolators. https://github.com/KhronosGroup/glTF/issues/156

            if (defined(model.cacheKey)) {
                // Only cache when we can create a unique id
                cachedAnimationSplines[key] = spline;
            }
        }

        return spline;
    };

    var cachedSkinInverseBindMatrices = {
    };

    ModelAnimationCache.getSkinInverseBindMatrices = function(model, accessor) {
        var key = getAccessorKey(model, accessor);
        var matrices = cachedSkinInverseBindMatrices[key];

        if (!defined(matrices)) {
            // Cache miss
            var gltf = model.gltf;
            var buffers = gltf.buffers;
            var bufferViews = gltf.bufferViews;

            var bufferViewId = accessor.bufferView;
            var bufferView = bufferViews[bufferViewId];
            var bufferId = bufferView.buffer;
            var buffer = buffers[bufferId];
            var source = buffer.extras._pipeline.source;

            var componentType = accessor.componentType;
            var type = accessor.type;
            var count = accessor.count;
            var byteStride = getAccessorByteStride(gltf, accessor);
            var byteOffset = bufferView.byteOffset + accessor.byteOffset;
            var numberOfComponents = numberOfComponentsForType(type);

            matrices = new Array(count);

            if ((componentType === WebGLConstants.FLOAT) && (type === AttributeType.MAT4)) {
                for (var i = 0; i < count; ++i) {
                    var typedArrayView = ComponentDatatype.createArrayBufferView(componentType, source.buffer, byteOffset, numberOfComponents);
                    matrices[i] = Matrix4.fromArray(typedArrayView);
                    byteOffset += byteStride;
                }
            }

            cachedSkinInverseBindMatrices[key] = matrices;
        }

        return matrices;
    };

    return ModelAnimationCache;
});
<commit_msg>Removed old GLTF_SPEC comments<commit_after>define([
        './AttributeType',
        '../Core/Cartesian3',
        '../Core/ComponentDatatype',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/LinearSpline',
        '../Core/Matrix4',
        '../Core/Quaternion',
        '../Core/QuaternionSpline',
        '../Core/WebGLConstants',
        '../Core/WeightSpline',
        '../ThirdParty/GltfPipeline/getAccessorByteStride',
        '../ThirdParty/GltfPipeline/numberOfComponentsForType'
    ], function(
        AttributeType,
        Cartesian3,
        ComponentDatatype,
        defaultValue,
        defined,
        LinearSpline,
        Matrix4,
        Quaternion,
        QuaternionSpline,
        WebGLConstants,
        WeightSpline,
        getAccessorByteStride,
        numberOfComponentsForType) {
    'use strict';

    /**
     * @private
     */
    function ModelAnimationCache() {
    }

    var dataUriRegex = /^data\:/i;

    function getAccessorKey(model, accessor) {
        var gltf = model.gltf;
        var buffers = gltf.buffers;
        var bufferViews = gltf.bufferViews;

        var bufferView = bufferViews[accessor.bufferView];
        var buffer = buffers[bufferView.buffer];

        var byteOffset = bufferView.byteOffset + accessor.byteOffset;
        var byteLength = accessor.count * numberOfComponentsForType(accessor.type);

        var uriKey = dataUriRegex.test(buffer.uri) ? '' : buffer.uri;
        return model.cacheKey + '//' + uriKey + '/' + byteOffset + '/' + byteLength;
    }

    var cachedAnimationParameters = {
    };

    ModelAnimationCache.getAnimationParameterValues = function(model, accessor) {
        var key = getAccessorKey(model, accessor);
        var values = cachedAnimationParameters[key];

        if (!defined(values)) {
            // Cache miss
            var gltf = model.gltf;

            var buffers = gltf.buffers;
            var bufferViews = gltf.bufferViews;

            var bufferView = bufferViews[accessor.bufferView];
            var bufferId = bufferView.buffer;
            var buffer = buffers[bufferId];
            var source = buffer.extras._pipeline.source;

            var componentType = accessor.componentType;
            var type = accessor.type;
            var numberOfComponents = numberOfComponentsForType(type);
            var count = accessor.count;
            var byteStride = getAccessorByteStride(gltf, accessor);

            values = new Array(count);
            var accessorByteOffset = defaultValue(accessor.byteOffset, 0);
            var byteOffset = bufferView.byteOffset + accessorByteOffset;
            for (var i = 0; i < count; i++) {
                var typedArrayView = ComponentDatatype.createArrayBufferView(componentType, source.buffer, byteOffset, numberOfComponents);
                if (type === 'SCALAR') {
                    values[i] = typedArrayView[0];
                } else if (type === 'VEC3') {
                    values[i] = Cartesian3.fromArray(typedArrayView);
                } else if (type === 'VEC4') {
                    values[i] = Quaternion.unpack(typedArrayView);
                }
                byteOffset += byteStride;
            }
            // GLTF_SPEC: Support more parameter types when glTF supports targeting materials. https://github.com/KhronosGroup/glTF/issues/142

            if (defined(model.cacheKey)) {
                // Only cache when we can create a unique id
                cachedAnimationParameters[key] = values;
            }
        }

        return values;
    };

    var cachedAnimationSplines = {
    };

    function getAnimationSplineKey(model, animationName, samplerName) {
        return model.cacheKey + '//' + animationName + '/' + samplerName;
    }

    function ConstantSpline(value) {
        this._value = value;
    }
    ConstantSpline.prototype.evaluate = function(time, result) {
        return this._value;
    };

    ModelAnimationCache.getAnimationSpline = function(model, animationName, animation, samplerName, sampler, input, path, output) {
        var key = getAnimationSplineKey(model, animationName, samplerName);
        var spline = cachedAnimationSplines[key];

        if (!defined(spline)) {
            var times = input;
            var controlPoints = output;

            if ((times.length === 1) && (controlPoints.length === 1)) {
                spline = new ConstantSpline(controlPoints[0]);
            } else if (sampler.interpolation === 'LINEAR') {
                if (path === 'translation' || path === 'scale') {
                    spline = new LinearSpline({
                        times : times,
                        points : controlPoints
                    });
                } else if (path === 'rotation') {
                    spline = new QuaternionSpline({
                        times : times,
                        points : controlPoints
                    });
                } else if (path === 'weights') {
                    spline = new WeightSpline({
                        times : times,
                        points : controlPoints
                    });
                }
                // GLTF_SPEC: Support more parameter types when glTF supports targeting materials. https://github.com/KhronosGroup/glTF/issues/142
            }
            // GLTF_SPEC: Support new interpolators. https://github.com/KhronosGroup/glTF/issues/156

            if (defined(model.cacheKey)) {
                // Only cache when we can create a unique id
                cachedAnimationSplines[key] = spline;
            }
        }

        return spline;
    };

    var cachedSkinInverseBindMatrices = {
    };

    ModelAnimationCache.getSkinInverseBindMatrices = function(model, accessor) {
        var key = getAccessorKey(model, accessor);
        var matrices = cachedSkinInverseBindMatrices[key];

        if (!defined(matrices)) {
            // Cache miss
            var gltf = model.gltf;
            var buffers = gltf.buffers;
            var bufferViews = gltf.bufferViews;

            var bufferViewId = accessor.bufferView;
            var bufferView = bufferViews[bufferViewId];
            var bufferId = bufferView.buffer;
            var buffer = buffers[bufferId];
            var source = buffer.extras._pipeline.source;

            var componentType = accessor.componentType;
            var type = accessor.type;
            var count = accessor.count;
            var byteStride = getAccessorByteStride(gltf, accessor);
            var byteOffset = bufferView.byteOffset + accessor.byteOffset;
            var numberOfComponents = numberOfComponentsForType(type);

            matrices = new Array(count);

            if ((componentType === WebGLConstants.FLOAT) && (type === AttributeType.MAT4)) {
                for (var i = 0; i < count; ++i) {
                    var typedArrayView = ComponentDatatype.createArrayBufferView(componentType, source.buffer, byteOffset, numberOfComponents);
                    matrices[i] = Matrix4.fromArray(typedArrayView);
                    byteOffset += byteStride;
                }
            }

            cachedSkinInverseBindMatrices[key] = matrices;
        }

        return matrices;
    };

    return ModelAnimationCache;
});
<|endoftext|>


<commit_before>/*
---

name: Scroller.IScroll

description: Provides a scroller that uses the iScroll scroller.

license: MIT-style license.

authors:
	- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)

requires:
	- Scroller

provides:
	- Scroller.IScroll

...
*/

(function() {

var touchid = null;

var fixtouch = function(e) {

	var touch = {
		identifier: touchid,
		target: e.target,
		pageX: e.pageX,
		pageY: e.pageY,
		clientX: e.clientX,
		clientY: e.clientY
	};

	e.touches = e.targetTouches = e.changedTouches = [touch];
};

/**
 * @see    http://moobilejs.com/doc/latest/Scroller/Scroller.IScroll
 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
 * @since  0.2.0
 */
Moobile.Scroller.IScroll = new Class({

	Extends: Moobile.Scroller,

	/**
	 * @see    http://moobilejs.com/doc/latest/Scroller/Scroller.IScroll#scroller
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	scroller: null,

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	initialize: function(contentElement, contentWrapperElement, options) {

		this.parent(contentElement, contentWrapperElement, options)

		this.scroller = new iScroll(contentWrapperElement, {
			scrollbarClass: 'scrollbar-',
			hScroll: this.options.scroll === 'both' || this.options.scroll === 'horizontal',
			vScroll: this.options.scroll === 'both' || this.options.scroll === 'vertical',
			hScrollbar: this.options.scrollbar === 'both' || this.options.scrollbar === 'horizontal',
			vScrollbar: this.options.scrollbar === 'both' || this.options.scrollbar === 'vertical',
			momentum: this.options.momentum,
			bounce: this.options.bounce,
			hideScrollbar: true,
			fadeScrollbar: true,
			checkDOMChanges: true,
			onBeforeScrollStart: this.bound('_onBeforeScrollStart'),
			onScrollStart: this.bound('_onScrollStart'),
			onScrollMove: this.bound('_onScrollMove'),
			onScrollEnd: this.bound('_onScrollEnd'),
			onTouchEnd: this.bound('_onTouchEnd')
		});

		window.addEvent('resize', this.bound('refresh'));

		return this;
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	destroy: function() {
		window.removeEvent('resize', this.bound('refresh'));
		this.scroller.destroy();
		this.scroller = null;
		return this.parent();
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	getName: function() {
		return 'iscroll';
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	scrollTo: function(x, y, time) {
		this.scroller.scrollTo(-x, -y, time || 0);
		return this;
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	scrollToElement: function(element, time) {
		this.scroller.scrollToElement(document.id(element), time || 0);
		return this;
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	refresh: function() {
		this.scroller.refresh();
		return this;
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	getScroll: function() {
		return {
			x: -this.scroller.x,
			y: -this.scroller.y
		};
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onBeforeScrollStart: function(e) {
		var target = e.target.get('tag');
		if (target !== 'input' &&
			target !== 'select' &&
			target !== 'textarea') {
			e.preventDefault();
		}
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onScrollStart: function(e) {

		if (!('touches' in e)) {

			if (touchid)
				return this;

			if (touchid === null) {
				touchid = String.uniqueID();
				fixtouch(e);
			}
		}

		this.fireEvent('touchstart', e);
		this.fireEvent('scrollstart');
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onScrollMove: function(e) {

		if (touchid) {
			fixtouch(e);
		}

		this.fireEvent('touchmove', e);
		this.fireEvent('scroll');
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onScrollEnd: function() {
		this.fireEvent('scroll');
		this.fireEvent('scrollend');
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onTouchEnd:  function(e) {

		if (touchid) {
			fixtouch(e);
			touchid = null;
		}

		this.fireEvent('touchend', e);
	}

});

Moobile.Scroller.IScroll.supportsCurrentPlatform = function() {
	return true;
};

})();<commit_msg>Added TODO message<commit_after>/*
---

name: Scroller.IScroll

description: Provides a scroller that uses the iScroll scroller.

license: MIT-style license.

authors:
	- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)

requires:
	- Scroller

provides:
	- Scroller.IScroll

...
*/

(function() {

var touchid = null;

var fixtouch = function(e) {

	var touch = {
		identifier: touchid,
		target: e.target,
		pageX: e.pageX,
		pageY: e.pageY,
		clientX: e.clientX,
		clientY: e.clientY
	};

	e.touches = e.targetTouches = e.changedTouches = [touch];
};

/**
 * @see    http://moobilejs.com/doc/latest/Scroller/Scroller.IScroll
 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
 * @since  0.2.0
 */
Moobile.Scroller.IScroll = new Class({

	Extends: Moobile.Scroller,

	/**
	 * @see    http://moobilejs.com/doc/latest/Scroller/Scroller.IScroll#scroller
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	scroller: null,

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	initialize: function(contentElement, contentWrapperElement, options) {

		this.parent(contentElement, contentWrapperElement, options)

		this.scroller = new iScroll(contentWrapperElement, {
			scrollbarClass: 'scrollbar-',
			hScroll: this.options.scroll === 'both' || this.options.scroll === 'horizontal',
			vScroll: this.options.scroll === 'both' || this.options.scroll === 'vertical',
			hScrollbar: this.options.scrollbar === 'both' || this.options.scrollbar === 'horizontal',
			vScrollbar: this.options.scrollbar === 'both' || this.options.scrollbar === 'vertical',
			momentum: this.options.momentum,
			bounce: this.options.bounce,
			hideScrollbar: true,
			fadeScrollbar: true,
			checkDOMChanges: true,
			onBeforeScrollStart: this.bound('_onBeforeScrollStart'),
			onScrollStart: this.bound('_onScrollStart'),
			onScrollMove: this.bound('_onScrollMove'),
			onScrollEnd: this.bound('_onScrollEnd'),
			onTouchEnd: this.bound('_onTouchEnd')
		});

		window.addEvent('resize', this.bound('refresh'));

		return this;
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	destroy: function() {
		window.removeEvent('resize', this.bound('refresh'));
		this.scroller.destroy();
		this.scroller = null;
		return this.parent();
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	getName: function() {
		return 'iscroll';
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	scrollTo: function(x, y, time) {
		this.scroller.scrollTo(-x, -y, time || 0);
		return this;
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	scrollToElement: function(element, time) {
		this.scroller.scrollToElement(document.id(element), time || 0);
		return this;
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	refresh: function() {
		this.scroller.refresh();
		return this;
	},

	/**
	 * @overridden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	getScroll: function() {
		return {
			x: -this.scroller.x,
			y: -this.scroller.y
		};
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onBeforeScrollStart: function(e) {
		var target = e.target.get('tag');
		if (target !== 'input' &&
			target !== 'select' &&
			target !== 'textarea') {
			e.preventDefault();
		}
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onScrollStart: function(e) {
		// TODO: Is this really needed ?
		if (!('touches' in e)) {

			if (touchid)
				return this;

			if (touchid === null) {
				touchid = String.uniqueID();
				fixtouch(e);
			}
		}

		this.fireEvent('touchstart', e);
		this.fireEvent('scrollstart');
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onScrollMove: function(e) {

		if (touchid) {
			fixtouch(e);
		}

		this.fireEvent('touchmove', e);
		this.fireEvent('scroll');
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onScrollEnd: function() {
		this.fireEvent('scroll');
		this.fireEvent('scrollend');
	},

	/**
	 * @hidden
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2.0
	 */
	_onTouchEnd:  function(e) {

		if (touchid) {
			fixtouch(e);
			touchid = null;
		}

		this.fireEvent('touchend', e);
	}

});

Moobile.Scroller.IScroll.supportsCurrentPlatform = function() {
	return true;
};

})();<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import ListSubheader from 'material-ui/List/ListSubheader';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Collapse from '@material-ui/core/Collapse';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import DraftsIcon from '@material-ui/icons/Drafts';
import SendIcon from '@material-ui/icons/Send';
import ExpandLess from '@material-ui/icons/ExpandLess';
import ExpandMore from '@material-ui/icons/ExpandMore';
import StarBorder from '@material-ui/icons/StarBorder';

const styles = theme => ({
  root: {
    width: '100%',
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper,
  },
  nested: {
    paddingLeft: theme.spacing.unit * 4,
  },
});

class NestedList extends React.Component {
  state = { open: true };

  handleClick = () => {
    this.setState({ open: !this.state.open });
  };

  render() {
    const { classes } = this.props;

    return (

        <List
          component="nav"
          subheader={<ListSubheader component="div">Nested List Items</ListSubheader>}
        >
          <ListItem button>
            <ListItemIcon>
              <SendIcon />
            </ListItemIcon>
            <ListItemText inset primary="Sent mail" />
          </ListItem>
          <ListItem button>
            <ListItemIcon>
              <DraftsIcon />
            </ListItemIcon>
            <ListItemText inset primary="Drafts" />
          </ListItem>
          <ListItem button onClick={this.handleClick}>
            <ListItemIcon>
              <InboxIcon />
            </ListItemIcon>
            <ListItemText inset primary="Inbox" />
            {this.state.open ? <ExpandLess /> : <ExpandMore />}
          </ListItem>
          <Collapse in={this.state.open} timeout="auto" unmountOnExit>
            <List component="div" disablePadding>
              <ListItem button className={classes.nested}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText inset primary="Starred" />
              </ListItem>
            </List>
          </Collapse>
        </List>

    );
  }
}

NestedList.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(NestedList);
<commit_msg>[ListSubheader] Fix demo import path (#11468)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import ListSubheader from '@material-ui/core/ListSubheader';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Collapse from '@material-ui/core/Collapse';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import DraftsIcon from '@material-ui/icons/Drafts';
import SendIcon from '@material-ui/icons/Send';
import ExpandLess from '@material-ui/icons/ExpandLess';
import ExpandMore from '@material-ui/icons/ExpandMore';
import StarBorder from '@material-ui/icons/StarBorder';

const styles = theme => ({
  root: {
    width: '100%',
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper,
  },
  nested: {
    paddingLeft: theme.spacing.unit * 4,
  },
});

class NestedList extends React.Component {
  state = { open: true };

  handleClick = () => {
    this.setState({ open: !this.state.open });
  };

  render() {
    const { classes } = this.props;

    return (

        <List
          component="nav"
          subheader={<ListSubheader component="div">Nested List Items</ListSubheader>}
        >
          <ListItem button>
            <ListItemIcon>
              <SendIcon />
            </ListItemIcon>
            <ListItemText inset primary="Sent mail" />
          </ListItem>
          <ListItem button>
            <ListItemIcon>
              <DraftsIcon />
            </ListItemIcon>
            <ListItemText inset primary="Drafts" />
          </ListItem>
          <ListItem button onClick={this.handleClick}>
            <ListItemIcon>
              <InboxIcon />
            </ListItemIcon>
            <ListItemText inset primary="Inbox" />
            {this.state.open ? <ExpandLess /> : <ExpandMore />}
          </ListItem>
          <Collapse in={this.state.open} timeout="auto" unmountOnExit>
            <List component="div" disablePadding>
              <ListItem button className={classes.nested}>
                <ListItemIcon>
                  <StarBorder />
                </ListItemIcon>
                <ListItemText inset primary="Starred" />
              </ListItem>
            </List>
          </Collapse>
        </List>

    );
  }
}

NestedList.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(NestedList);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007, 2008 Apple Inc.  All rights reserved.
 * Copyright (C) 2009 Joseph Pecoraro
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.View}
 * @param {!WebInspector.SplitView} splitView
 */
WebInspector.Drawer = function(splitView)
{
    WebInspector.View.call(this);
    this.element.id = "drawer-contents";

    this._splitView = splitView;
    splitView.hideDefaultResizer();
    this.show(splitView.sidebarElement());

    this._drawerEditorSplitView = new WebInspector.SplitView(true, true, "editorInDrawerSplitViewState", 0.5, 0.5);
    this._drawerEditorSplitView.hideSidebar();
    this._drawerEditorSplitView.addEventListener(WebInspector.SplitView.Events.ShowModeChanged, this._drawerEditorSplitViewShowModeChanged, this);
    this._drawerEditorShownSetting = WebInspector.settings.createSetting("drawerEditorShown", true);
    this._drawerEditorSplitView.show(this.element);

    this._toggleDrawerButton = new WebInspector.StatusBarButton(WebInspector.UIString("Show drawer."), "console-status-bar-item");
    this._toggleDrawerButton.addEventListener("click", this.toggle, this);

    this._tabbedPane = new WebInspector.TabbedPane();
    this._tabbedPane.element.id = "drawer-tabbed-pane";
    this._tabbedPane.closeableTabs = false;
    this._tabbedPane.setRetainTabOrder(true, WebInspector.moduleManager.orderComparator(WebInspector.Drawer.ViewFactory, "name", "order"));

    this._toggleDrawerEditorButton = this._drawerEditorSplitView.createShowHideSidebarButton("editor in drawer", "drawer-editor-show-hide-button");
    this._tabbedPane.element.appendChild(this._toggleDrawerEditorButton.element);
    if (!WebInspector.experimentsSettings.showEditorInDrawer.isEnabled())
        this.setDrawerEditorAvailable(false);

    this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this);
    splitView.installResizer(this._tabbedPane.headerElement());
    this._lastSelectedViewSetting = WebInspector.settings.createSetting("WebInspector.Drawer.lastSelectedView", "console");
    this._initializeViewFactories();
}

WebInspector.Drawer.prototype = {
    _initializeViewFactories: function()
    {
        this._viewFactories = {};
        var extensions = WebInspector.moduleManager.extensions(WebInspector.Drawer.ViewFactory);

        for (var i = 0; i < extensions.length; ++i) {
            var descriptor = extensions[i].descriptor();
            var id = descriptor["name"];
            var title = WebInspector.UIString(descriptor["title"]);
            var settingName = descriptor["setting"];
            var setting = settingName ? /** @type {!WebInspector.Setting|undefined} */ (WebInspector.settings[settingName]) : null;

            this._viewFactories[id] = extensions[i];

            if (setting) {
                setting.addChangeListener(this._toggleSettingBasedView.bind(this, id, title, setting));
                if (setting.get())
                    this._tabbedPane.appendTab(id, title, new WebInspector.View());
            } else {
                this._tabbedPane.appendTab(id, title, new WebInspector.View());
            }
        }
        this._tabbedPane.show(this._drawerEditorSplitView.mainElement());
    },

    /**
     * @param {string} id
     * @param {string} title
     * @param {!WebInspector.Setting} setting
     */
    _toggleSettingBasedView: function(id, title, setting)
    {
        this._tabbedPane.closeTab(id);
        if (setting.get())
            this._tabbedPane.appendTab(id, title, new WebInspector.View());
    },

    /**
     * @return {!Element}
     */
    toggleButtonElement: function()
    {
        return this._toggleDrawerButton.element;
    },

    /**
     * @param {string} id
     */
    closeView: function(id)
    {
        this._tabbedPane.closeTab(id);
    },

    /**
     * @param {string} id
     * @param {boolean=} immediate
     */
    showView: function(id, immediate)
    {
        if (!this._tabbedPane.hasTab(id)) {
            // Hidden tab.
            this._innerShow(immediate);
            return;
        }
        var viewFactory = this._viewFactory(id);
        if (viewFactory)
            this._tabbedPane.changeTabView(id, viewFactory.createView());
        this._innerShow(immediate);
        this._tabbedPane.selectTab(id, true);
        // In case this id is already selected, anyways persist it as the last saved value.
        this._lastSelectedViewSetting.set(id);
    },

    /**
     * @param {string} id
     * @param {string} title
     * @param {!WebInspector.View} view
     */
    showCloseableView: function(id, title, view)
    {
        if (!this._tabbedPane.hasTab(id)) {
            this._tabbedPane.appendTab(id, title, view, undefined, false, true);
        } else {
            this._tabbedPane.changeTabView(id, view);
            this._tabbedPane.changeTabTitle(id, title);
        }
        this._innerShow();
        this._tabbedPane.selectTab(id, true);
    },

    showDrawer: function()
    {
        this.showView(this._lastSelectedViewSetting.get());
    },

    wasShown: function()
    {
        this.showView(this._lastSelectedViewSetting.get());
        this._toggleDrawerButton.toggled = true;
        this._toggleDrawerButton.title = WebInspector.UIString("Hide drawer.");
        this._ensureDrawerEditorEsistsIfNeeded();
    },

    willHide: function()
    {
        this._toggleDrawerButton.toggled = false;
        this._toggleDrawerButton.title = WebInspector.UIString("Show drawer.");
    },

    /**
     * @param {boolean=} immediate
     */
    _innerShow: function(immediate)
    {
        if (this.isShowing())
            return;

        this._splitView.showBoth(!immediate);

        if (this._visibleView())
            this._visibleView().focus();
    },

    closeDrawer: function()
    {
        if (!this.isShowing())
            return;

        WebInspector.restoreFocusFromElement(this.element);
        this._splitView.hideSidebar(true);
    },

    /**
     * @return {!WebInspector.View} view
     */
    _visibleView: function()
    {
        return this._tabbedPane.visibleView;
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _tabSelected: function(event)
    {
        var tabId = this._tabbedPane.selectedTabId;
        if (event.data["isUserGesture"] && !this._tabbedPane.isTabCloseable(tabId))
            this._lastSelectedViewSetting.set(tabId);
        var viewFactory = this._viewFactory(tabId);
        if (viewFactory)
            this._tabbedPane.changeTabView(tabId, viewFactory.createView());
    },

    toggle: function()
    {
        if (this._toggleDrawerButton.toggled)
            this.closeDrawer();
        else
            this.showDrawer();
    },

    /**
     * @return {boolean}
     */
    visible: function()
    {
        return this._toggleDrawerButton.toggled;
    },

    /**
     * @return {string}
     */
    selectedViewId: function()
    {
        return this._tabbedPane.selectedTabId;
    },

    /**
     * @return {?WebInspector.Drawer.ViewFactory}
     */
    _viewFactory: function(id)
    {
        return this._viewFactories[id] ? /** @type {!WebInspector.Drawer.ViewFactory} */ (this._viewFactories[id].instance()) : null;
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _drawerEditorSplitViewShowModeChanged: function(event)
    {
        var mode = /** @type {string} */ (event.data);
        var shown = mode === WebInspector.SplitView.ShowMode.Both;

        if (this._isHidingDrawerEditor)
            return;

        this._drawerEditorShownSetting.set(shown);

        if (!shown)
            return;

        this._ensureDrawerEditor();
        this._drawerEditor.view().show(this._drawerEditorSplitView.sidebarElement());
    },

    initialPanelShown: function()
    {
        this._initialPanelWasShown = true;
        this._ensureDrawerEditorEsistsIfNeeded();
    },

    _ensureDrawerEditorEsistsIfNeeded: function()
    {
        if (!this._initialPanelWasShown || !this.isShowing() || !this._drawerEditorShownSetting.get())
            return;
        this._ensureDrawerEditor();
    },

    _ensureDrawerEditor: function()
    {
        if (this._drawerEditor)
            return;
        this._drawerEditor = WebInspector.moduleManager.instance(WebInspector.DrawerEditor);
        this._drawerEditor.installedIntoDrawer();
    },

    /**
     * @param {boolean} available
     */
    setDrawerEditorAvailable: function(available)
    {
        if (!WebInspector.experimentsSettings.showEditorInDrawer.isEnabled())
            available = false;
        this._toggleDrawerEditorButton.element.classList.toggle("hidden", !available);
    },

    showDrawerEditor: function()
    {
        if (!WebInspector.experimentsSettings.showEditorInDrawer.isEnabled())
            return;

        this._splitView.showBoth();
        this._drawerEditorSplitView.showBoth();
    },

    hideDrawerEditor: function()
    {
        this._isHidingDrawerEditor = true;
        this._drawerEditorSplitView.hideSidebar();
        this._isHidingDrawerEditor = false;
    },

    /**
     * @return {boolean}
     */
    isDrawerEditorShown: function()
    {
        return this._drawerEditorShownSetting.get();
    },

    __proto__: WebInspector.View.prototype
}

/**
 * @interface
 */
WebInspector.Drawer.ViewFactory = function()
{
}

WebInspector.Drawer.ViewFactory.prototype = {
    /**
     * @return {!WebInspector.View}
     */
    createView: function() {}
}

/**
 * @constructor
 * @implements {WebInspector.Drawer.ViewFactory}
 * @param {function(new:T)} constructor
 * @template T
 */
WebInspector.Drawer.SingletonViewFactory = function(constructor)
{
    this._constructor = constructor;
}

WebInspector.Drawer.SingletonViewFactory.prototype = {
    /**
     * @return {!WebInspector.View}
     */
    createView: function()
    {
        if (!this._instance)
            this._instance = /** @type {!WebInspector.View} */(new this._constructor());
        return this._instance;
    }
}

/**
 * @interface
 */
WebInspector.DrawerEditor = function()
{
}

WebInspector.DrawerEditor.prototype = {
    /**
     * @return {!WebInspector.View}
     */
    view: function() { },

    installedIntoDrawer: function() { },
}
<commit_msg>DevTools: Do not load editor in drawer if corresponding experiment is turned off<commit_after>/*
 * Copyright (C) 2007, 2008 Apple Inc.  All rights reserved.
 * Copyright (C) 2009 Joseph Pecoraro
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.View}
 * @param {!WebInspector.SplitView} splitView
 */
WebInspector.Drawer = function(splitView)
{
    WebInspector.View.call(this);
    this.element.id = "drawer-contents";

    this._splitView = splitView;
    splitView.hideDefaultResizer();
    this.show(splitView.sidebarElement());

    this._drawerEditorSplitView = new WebInspector.SplitView(true, true, "editorInDrawerSplitViewState", 0.5, 0.5);
    this._drawerEditorSplitView.hideSidebar();
    this._drawerEditorSplitView.addEventListener(WebInspector.SplitView.Events.ShowModeChanged, this._drawerEditorSplitViewShowModeChanged, this);
    this._drawerEditorShownSetting = WebInspector.settings.createSetting("drawerEditorShown", true);
    this._drawerEditorSplitView.show(this.element);

    this._toggleDrawerButton = new WebInspector.StatusBarButton(WebInspector.UIString("Show drawer."), "console-status-bar-item");
    this._toggleDrawerButton.addEventListener("click", this.toggle, this);

    this._tabbedPane = new WebInspector.TabbedPane();
    this._tabbedPane.element.id = "drawer-tabbed-pane";
    this._tabbedPane.closeableTabs = false;
    this._tabbedPane.setRetainTabOrder(true, WebInspector.moduleManager.orderComparator(WebInspector.Drawer.ViewFactory, "name", "order"));

    this._toggleDrawerEditorButton = this._drawerEditorSplitView.createShowHideSidebarButton("editor in drawer", "drawer-editor-show-hide-button");
    this._tabbedPane.element.appendChild(this._toggleDrawerEditorButton.element);
    if (!WebInspector.experimentsSettings.showEditorInDrawer.isEnabled())
        this.setDrawerEditorAvailable(false);

    this._tabbedPane.addEventListener(WebInspector.TabbedPane.EventTypes.TabSelected, this._tabSelected, this);
    splitView.installResizer(this._tabbedPane.headerElement());
    this._lastSelectedViewSetting = WebInspector.settings.createSetting("WebInspector.Drawer.lastSelectedView", "console");
    this._initializeViewFactories();
}

WebInspector.Drawer.prototype = {
    _initializeViewFactories: function()
    {
        this._viewFactories = {};
        var extensions = WebInspector.moduleManager.extensions(WebInspector.Drawer.ViewFactory);

        for (var i = 0; i < extensions.length; ++i) {
            var descriptor = extensions[i].descriptor();
            var id = descriptor["name"];
            var title = WebInspector.UIString(descriptor["title"]);
            var settingName = descriptor["setting"];
            var setting = settingName ? /** @type {!WebInspector.Setting|undefined} */ (WebInspector.settings[settingName]) : null;

            this._viewFactories[id] = extensions[i];

            if (setting) {
                setting.addChangeListener(this._toggleSettingBasedView.bind(this, id, title, setting));
                if (setting.get())
                    this._tabbedPane.appendTab(id, title, new WebInspector.View());
            } else {
                this._tabbedPane.appendTab(id, title, new WebInspector.View());
            }
        }
        this._tabbedPane.show(this._drawerEditorSplitView.mainElement());
    },

    /**
     * @param {string} id
     * @param {string} title
     * @param {!WebInspector.Setting} setting
     */
    _toggleSettingBasedView: function(id, title, setting)
    {
        this._tabbedPane.closeTab(id);
        if (setting.get())
            this._tabbedPane.appendTab(id, title, new WebInspector.View());
    },

    /**
     * @return {!Element}
     */
    toggleButtonElement: function()
    {
        return this._toggleDrawerButton.element;
    },

    /**
     * @param {string} id
     */
    closeView: function(id)
    {
        this._tabbedPane.closeTab(id);
    },

    /**
     * @param {string} id
     * @param {boolean=} immediate
     */
    showView: function(id, immediate)
    {
        if (!this._tabbedPane.hasTab(id)) {
            // Hidden tab.
            this._innerShow(immediate);
            return;
        }
        var viewFactory = this._viewFactory(id);
        if (viewFactory)
            this._tabbedPane.changeTabView(id, viewFactory.createView());
        this._innerShow(immediate);
        this._tabbedPane.selectTab(id, true);
        // In case this id is already selected, anyways persist it as the last saved value.
        this._lastSelectedViewSetting.set(id);
    },

    /**
     * @param {string} id
     * @param {string} title
     * @param {!WebInspector.View} view
     */
    showCloseableView: function(id, title, view)
    {
        if (!this._tabbedPane.hasTab(id)) {
            this._tabbedPane.appendTab(id, title, view, undefined, false, true);
        } else {
            this._tabbedPane.changeTabView(id, view);
            this._tabbedPane.changeTabTitle(id, title);
        }
        this._innerShow();
        this._tabbedPane.selectTab(id, true);
    },

    showDrawer: function()
    {
        this.showView(this._lastSelectedViewSetting.get());
    },

    wasShown: function()
    {
        this.showView(this._lastSelectedViewSetting.get());
        this._toggleDrawerButton.toggled = true;
        this._toggleDrawerButton.title = WebInspector.UIString("Hide drawer.");
        this._ensureDrawerEditorExistsIfNeeded();
    },

    willHide: function()
    {
        this._toggleDrawerButton.toggled = false;
        this._toggleDrawerButton.title = WebInspector.UIString("Show drawer.");
    },

    /**
     * @param {boolean=} immediate
     */
    _innerShow: function(immediate)
    {
        if (this.isShowing())
            return;

        this._splitView.showBoth(!immediate);

        if (this._visibleView())
            this._visibleView().focus();
    },

    closeDrawer: function()
    {
        if (!this.isShowing())
            return;

        WebInspector.restoreFocusFromElement(this.element);
        this._splitView.hideSidebar(true);
    },

    /**
     * @return {!WebInspector.View} view
     */
    _visibleView: function()
    {
        return this._tabbedPane.visibleView;
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _tabSelected: function(event)
    {
        var tabId = this._tabbedPane.selectedTabId;
        if (event.data["isUserGesture"] && !this._tabbedPane.isTabCloseable(tabId))
            this._lastSelectedViewSetting.set(tabId);
        var viewFactory = this._viewFactory(tabId);
        if (viewFactory)
            this._tabbedPane.changeTabView(tabId, viewFactory.createView());
    },

    toggle: function()
    {
        if (this._toggleDrawerButton.toggled)
            this.closeDrawer();
        else
            this.showDrawer();
    },

    /**
     * @return {boolean}
     */
    visible: function()
    {
        return this._toggleDrawerButton.toggled;
    },

    /**
     * @return {string}
     */
    selectedViewId: function()
    {
        return this._tabbedPane.selectedTabId;
    },

    /**
     * @return {?WebInspector.Drawer.ViewFactory}
     */
    _viewFactory: function(id)
    {
        return this._viewFactories[id] ? /** @type {!WebInspector.Drawer.ViewFactory} */ (this._viewFactories[id].instance()) : null;
    },

    /**
     * @param {!WebInspector.Event} event
     */
    _drawerEditorSplitViewShowModeChanged: function(event)
    {
        var mode = /** @type {string} */ (event.data);
        var shown = mode === WebInspector.SplitView.ShowMode.Both;

        if (this._isHidingDrawerEditor)
            return;

        this._drawerEditorShownSetting.set(shown);

        if (!shown)
            return;

        this._ensureDrawerEditor();
        this._drawerEditor.view().show(this._drawerEditorSplitView.sidebarElement());
    },

    initialPanelShown: function()
    {
        this._initialPanelWasShown = true;
        this._ensureDrawerEditorExistsIfNeeded();
    },

    _ensureDrawerEditorExistsIfNeeded: function()
    {
        if (!this._initialPanelWasShown || !this.isShowing() || !this._drawerEditorShownSetting.get() || !WebInspector.experimentsSettings.showEditorInDrawer.isEnabled())
            return;
        this._ensureDrawerEditor();
    },

    _ensureDrawerEditor: function()
    {
        if (this._drawerEditor)
            return;
        this._drawerEditor = WebInspector.moduleManager.instance(WebInspector.DrawerEditor);
        this._drawerEditor.installedIntoDrawer();
    },

    /**
     * @param {boolean} available
     */
    setDrawerEditorAvailable: function(available)
    {
        if (!WebInspector.experimentsSettings.showEditorInDrawer.isEnabled())
            available = false;
        this._toggleDrawerEditorButton.element.classList.toggle("hidden", !available);
    },

    showDrawerEditor: function()
    {
        if (!WebInspector.experimentsSettings.showEditorInDrawer.isEnabled())
            return;

        this._splitView.showBoth();
        this._drawerEditorSplitView.showBoth();
    },

    hideDrawerEditor: function()
    {
        this._isHidingDrawerEditor = true;
        this._drawerEditorSplitView.hideSidebar();
        this._isHidingDrawerEditor = false;
    },

    /**
     * @return {boolean}
     */
    isDrawerEditorShown: function()
    {
        return this._drawerEditorShownSetting.get();
    },

    __proto__: WebInspector.View.prototype
}

/**
 * @interface
 */
WebInspector.Drawer.ViewFactory = function()
{
}

WebInspector.Drawer.ViewFactory.prototype = {
    /**
     * @return {!WebInspector.View}
     */
    createView: function() {}
}

/**
 * @constructor
 * @implements {WebInspector.Drawer.ViewFactory}
 * @param {function(new:T)} constructor
 * @template T
 */
WebInspector.Drawer.SingletonViewFactory = function(constructor)
{
    this._constructor = constructor;
}

WebInspector.Drawer.SingletonViewFactory.prototype = {
    /**
     * @return {!WebInspector.View}
     */
    createView: function()
    {
        if (!this._instance)
            this._instance = /** @type {!WebInspector.View} */(new this._constructor());
        return this._instance;
    }
}

/**
 * @interface
 */
WebInspector.DrawerEditor = function()
{
}

WebInspector.DrawerEditor.prototype = {
    /**
     * @return {!WebInspector.View}
     */
    view: function() { },

    installedIntoDrawer: function() { },
}
<|endoftext|>


<commit_before>$(document).ready(function() {
    $('.mainitems, .secondaryitems').each(function() {
	var cleanclass = $(this).children('td:first').text().replace('/','').trim();
	$(this).addClass(cleanclass);
    });

    $('tr.mainitems').on('click', function() {
	var num = $(this).children("td:first").text().replace('/', '').trim();
	$('.secondaryitems.' + num).toggle();
    });

    $(document).on('click', '.editbutton', function() {
	//need to build an ajax call which will populate the modal with the data from the item
	var objId = parseInt($(this).parent().parent().attr('id'));
	//setup the AJAX request
	$.ajaxSetup({
	    type: 'POST',
	    dataType: 'json'
	});

	//the real AJAX request
	$.ajax({
	    url: '/ajax/',
	    data: {
		form_type: 'edit',
		id: objId
	    },
	    success: function(json_data) {
		modalEdit(json_data);
		},
	    error: function (ajaxObj, textStatus, error) {
		alert(error);
	    }
	});
	return true;
    });
});

function modalEdit(dataEdit) {
    //populate the field with the values from DB
    changedItem = dataEdit;
    var iid = dataEdit.itemid;

    $('h4').append(''+iid+'');
    $('#id_market').val(dataEdit.market);
    $('#id_ccode').show();
    $('#id_ccode').val(dataEdit.ccode);
    $('#dln').val(dataEdit.remindernumber);
    $('#invn').val(dataEdit.invoicenumber);
    $('#id_invoicestatus').val(dataEdit.invoicestatus);
    $('#id_rejectreason').val(dataEdit.rejectreason);
    $('#id_paidon').val(dataEdit.paidon);
    $('#vendm').val(dataEdit.mailvendor);
    $('#vendn').val(dataEdit.vendor);
    $('#id_level').val(dataEdit.level);
    $('#dld').val(dataEdit.reminderdate);
    $('#modalreview').modal();
    $('#dld').datepicker();

    $('#save').on('click', function() {
	var obj = {
	    itemid: $('#itemid').text(),
	    mailvendor: $('#vendm').val(),
	    paidon: $('#id_paidon').val(),
	    vendor: $('#vendn').val(),
	    ccode: $('#id_ccode').val(),
	    market: $('#id_market').val(),
	    remindernumber: $('#dln').val(),
	    invoicenumber: $('#invn').val(),
	    invoicestatus: $('#id_invoicestatus').val(),
	    //actiontaken: $('#id_actiontaken').val(),
	    rejectreason: $('#id_rejectreason').val(),
	    level: $('#id_level').val(),
	    reminderdate: $('#dld').val(),
	    };

	$.each(obj, function(key, value) {
	    if (key !== "success" || key !== "error") {
		if (obj[key] !== changedItem[key]) {
		    changedStuff++;
		};
	    };
	});
	if (changedStuff != 0) {Update(obj)};
    });
};
<commit_msg>Ajax call to initiate the update.<commit_after>$(document).ready(function() {
    $('.mainitems, .secondaryitems').each(function() {
	var cleanclass = $(this).children('td:first').text().replace('/','').trim();
	$(this).addClass(cleanclass);
    });

    $('tr.mainitems').on('click', function() {
	var num = $(this).children("td:first").text().replace('/', '').trim();
	$('.secondaryitems.' + num).toggle();
    });

    $(document).on('click', '.editbutton', function() {
	//need to build an ajax call which will populate the modal with the data from the item
	var objId = parseInt($(this).parent().parent().attr('id'));
	//setup the AJAX request
	$.ajaxSetup({
	    type: 'POST',
	    dataType: 'json'
	});

	//the real AJAX request
	$.ajax({
	    url: '/ajax/',
	    data: {
		form_type: 'edit',
		id: objId
	    },
	    success: function(json_data) {
		modalEdit(json_data);
		},
	    error: function (ajaxObj, textStatus, error) {
		alert(error);
	    }
	});
	return true;
    });
});

function modalEdit(dataEdit) {
    //populate the field with the values from DB
    changedItem = dataEdit;
    var iid = dataEdit.itemid;

    $('h4').append(''+iid+'');
    $('#id_market').val(dataEdit.market);
    $('#id_ccode').show();
    $('#id_ccode').val(dataEdit.ccode);
    $('#dln').val(dataEdit.remindernumber);
    $('#invn').val(dataEdit.invoicenumber);
    $('#id_invoicestatus').val(dataEdit.invoicestatus);
    $('#id_rejectreason').val(dataEdit.rejectreason);
    $('#id_paidon').val(dataEdit.paidon);
    $('#vendm').val(dataEdit.mailvendor);
    $('#vendn').val(dataEdit.vendor);
    $('#id_level').val(dataEdit.level);
    $('#dld').val(dataEdit.reminderdate);
    $('#modalreview').modal();
    $('#dld').datepicker();

    $('#save').on('click', function() {
	var obj = {
	    itemid: $('#itemid').text(),
	    mailvendor: $('#vendm').val(),
	    paidon: $('#id_paidon').val(),
	    vendor: $('#vendn').val(),
	    ccode: $('#id_ccode').val(),
	    market: $('#id_market').val(),
	    remindernumber: $('#dln').val(),
	    invoicenumber: $('#invn').val(),
	    invoicestatus: $('#id_invoicestatus').val(),
	    //actiontaken: $('#id_actiontaken').val(),
	    rejectreason: $('#id_rejectreason').val(),
	    level: $('#id_level').val(),
	    reminderdate: $('#dld').val(),
	    };

	$.each(obj, function(key, value) {
	    if (key !== "success" || key !== "error") {
		if (obj[key] !== changedItem[key]) {
		    changedStuff++;
		};
	    };
	});
	if (changedStuff != 0) {Update(obj)};
    });
};

function Update(item) {
    $.ajaxSetup({
	type: 'POST',
	dataType: 'json'
    });

    //the real AJAX request
    $.ajax({
	url: '/ajax/',
	data: {
	    form_type: 'update',
	    mass_data: JSON.stringify(item)
	},
	success: alert("success"), //todo
	error: function (ajaxObj, textStatus, error) {
	    alert(error);
	}
    });
    return true;
}
<|endoftext|>


<commit_before>Vps.onContentReady(function()
{
    var MarqueeComponents = Ext.query('div.vpsMarqueeElements');
    Ext.each(MarqueeComponents, function(c) {
        var config = Ext.decode(Ext.query('> input.settings', c)[0].value);
        config.selectorRoot = new Ext.Element(c);
        var Marquee = new Vps.Marquee.Elements(config);
        Marquee.start();
    });
});

Ext.namespace("Vps.Marquee");
Vps.Marquee.Elements = function(cfg) {
    this.selector = cfg.selector;
    this.selectorRoot = cfg.selectorRoot;
    this.scrollAmount = cfg.scrollAmount;
    this.scrollDelay = cfg.scrollDelay;
    this.scrollDirection = cfg.scrollDirection;
};

Vps.Marquee.Elements.prototype = {

    _elSize: function(el)
    {
        if (this.scrollDirection == 'down' || this.scrollDirection == 'up') {
            return el.getHeight();
        } else {
            return el.getWidth();
        }
    },

    start: function() {
        this.sumSize = 0;
        this.elements = [];
        this.selectorRoot.query(this.selector).each(function(el) {
            el = new Ext.Element(el);
            this.elements.push({
                el: el,
                size: this._elSize(el)
            });
            this.sumSize += this._elSize(el);
        }, this);
        if (!this.elements.length) return;
        this.currentPosition = 0;
        this.doScroll.defer(this.scrollDelay, this);
    },

    doScroll: function() {
        this.currentPosition += this.scrollAmount;
        if (this.currentPosition > this.sumSize) this.currentPosition = 0;

        var offset = 0;
        this.elements.each(function(i) {
            var pos = offset - this.currentPosition;
            if (pos < -i.size) {
                pos = pos + this.sumSize;
            }
            if (this.scrollDirection == 'up') {
                i.el.setY(pos + this.selectorRoot.getY());
            } else if (this.scrollDirection == 'left') {
                i.el.setX(pos + this.selectorRoot.getX());
            } else {
                //TODO
            }
            offset += i.size;
        }, this);

        this.doScroll.defer(this.scrollDelay, this);
    }
};
<commit_msg>aktuelle position in cookie merken<commit_after>Vps.onContentReady(function()
{
    var MarqueeComponents = Ext.query('div.vpsMarqueeElements');
    Ext.each(MarqueeComponents, function(c) {
        var config = Ext.decode(Ext.query('> input.settings', c)[0].value);
        config.selectorRoot = new Ext.Element(c);
        var Marquee = new Vps.Marquee.Elements(config);
        Marquee.start();
    });
});

Ext.namespace("Vps.Marquee");
Vps.Marquee.Elements = function(cfg) {
    this.selector = cfg.selector;
    this.selectorRoot = cfg.selectorRoot;
    this.scrollAmount = cfg.scrollAmount;
    this.scrollDelay = cfg.scrollDelay;
    this.scrollDirection = cfg.scrollDirection;
};

Vps.Marquee.Elements.prototype = {

    _elSize: function(el)
    {
        if (this.scrollDirection == 'down' || this.scrollDirection == 'up') {
            return el.getHeight();
        } else {
            return el.getWidth();
        }
    },

    start: function() {
        this.sumSize = 0;
        this.elements = [];
        this.selectorRoot.query(this.selector).each(function(el) {
            el = new Ext.Element(el);
            this.elements.push({
                el: el,
                size: this._elSize(el)
            });
            this.sumSize += this._elSize(el);
        }, this);
        if (!this.elements.length) return;
        this.currentPosition = parseInt(this.readCookie()) || 0;
        this.doScroll();
    },

    doScroll: function() {
        var offset = 0;
        this.elements.each(function(i) {
            var pos = offset - this.currentPosition;
            if (pos < -i.size) {
                pos = pos + this.sumSize;
            }
            if (this.scrollDirection == 'up') {
                i.el.setY(pos + this.selectorRoot.getY());
            } else if (this.scrollDirection == 'left') {
                i.el.setX(pos + this.selectorRoot.getX());
            } else {
                //TODO
            }
            offset += i.size;
        }, this);

        this.currentPosition += this.scrollAmount;
        if (this.currentPosition > this.sumSize) this.currentPosition = 0;
        this.doScroll.defer(this.scrollDelay, this);

        this.setCookie(this.currentPosition);
    },

    // private
    readCookie : function(){
        var c = document.cookie + ";";
        var re = /\s?(.*?)=(.*?);/g;
        var matches;
        while((matches = re.exec(c)) != null){
            var name = matches[1];
            var value = matches[2];
            if(name == "vpsMarqueePosition"){
                return value;
            }
        }
        return null;
    },

    // private
    setCookie : function(value){
        //TODO: möglicherweise mal mehrere marquees auf einer seite ermöglichen
        document.cookie = "vpsMarqueePosition="+value+"; path=/; domain="+document.location.host+";";
    },
};
<|endoftext|>


<commit_before>/*
 * ext-server_opensave.js
 *
 * Licensed under the MIT License
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */

svgEditor.addExtension("server_opensave", {
	callback: function() {

		var save_svg_action = 'extensions/filesave.php';
		var save_img_action = 'extensions/filesave.php';

		// Create upload target (hidden iframe)
		var target = $('').hide().appendTo('body');

		svgEditor.setCustomHandlers({
			save: function(win, data) {
				var svg = "<?xml version=\"1.0\"?>\n" + data;

				var title = svgCanvas.getDocumentTitle();
				var filename = $.trim(title).replace(/[^a-z0-9\.\_\-]+/gi, '_');

				var form = $('<form>').attr({
					method: 'post',
					action: save_svg_action,
					target: 'output_frame'
				})	.append('<input type="hidden" name="output_svg" value="' + encodeURI(svg) + '">')
					.append('<input type="hidden" name="filename" value="' + filename + '">')
					.appendTo('body')
					.submit().remove();
			},
			exportImage: function(win, data) {
				var issues = data.issues,
                    mimeType = data.mimeType,
                    quality = data.quality;

				if(!$('#export_canvas').length) {
					$('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
				}
				var c = $('#export_canvas')[0];

				c.width = svgCanvas.contentW;
				c.height = svgCanvas.contentH;
				canvg(c, data.svg, {renderCallback: function() {
					var datauri = quality ? c.toDataURL(mimeType, quality) : c.toDataURL(mimeType);

					var uiStrings = svgEditor.uiStrings;
					var note = '';

					// Check if there's issues
					if(issues.length) {
						var pre = "\n \u2022 ";
						note += ("\n\n" + pre + issues.join(pre));
					}

					if(note.length) {
						alert(note);
					}

					var title = svgCanvas.getDocumentTitle();
					var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

					var form = $('<form>').attr({
						method: 'post',
						action: save_img_action,
						target: 'output_frame'
					})	.append('<input type="hidden" name="output_img" value="' + datauri + '">')
                        .append('<input type="hidden" name="mime" value="' + mimeType + '">')
						.append('<input type="hidden" name="filename" value="' + filename + '">')
						.appendTo('body')
						.submit().remove();
				}});

			}
		});

		// Do nothing if client support is found
		if(window.FileReader) return;

		var cancelled = false;

		// Change these to appropriate script file
		var open_svg_action = 'extensions/fileopen.php?type=load_svg';
		var import_svg_action = 'extensions/fileopen.php?type=import_svg';
		var import_img_action = 'extensions/fileopen.php?type=import_img';

		// Set up function for PHP uploader to use
		svgEditor.processFile = function(str64, type) {
			if(cancelled) {
				cancelled = false;
				return;
			}

			$('#dialog_box').hide();

			if(type != 'import_img') {
				var xmlstr = svgCanvas.Utils.decode64(str64);
			}

			switch ( type ) {
				case 'load_svg':
					svgCanvas.clear();
					svgCanvas.setSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_svg':
					svgCanvas.importSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_img':
					svgCanvas.setGoodImage(str64);
					break;
			}
		}

		// Create upload form
		var open_svg_form = $('<form>');
		open_svg_form.attr({
			enctype: 'multipart/form-data',
			method: 'post',
			action: open_svg_action,
			target: 'output_frame'
		});

		// Create import form
		var import_svg_form = open_svg_form.clone().attr('action', import_svg_action);

		// Create image form
		var import_img_form = open_svg_form.clone().attr('action', import_img_action);

		// It appears necessory to rebuild this input every time a file is
		// selected so the same file can be picked and the change event can fire.
		function rebuildInput(form) {
			form.empty();
			var inp = $('<input type="file" name="svg_file">').appendTo(form);

			function submit() {
				// This submits the form, which returns the file data using svgEditor.uploadSVG
				form.submit();

				rebuildInput(form);
				$.process_cancel("Uploading...", function() {
					cancelled = true;
					$('#dialog_box').hide();
				});
			}

			if(form[0] == open_svg_form[0]) {
				inp.change(function() {
					// This takes care of the "are you sure" dialog box
					svgEditor.openPrep(function(ok) {
						if(!ok) {
							rebuildInput(form);
							return;
						}
						submit();
					});
				});
			} else {
				inp.change(function() {
					// This submits the form, which returns the file data using svgEditor.uploadSVG
					submit();
				});
			}
		}

		// Create the input elements
		rebuildInput(open_svg_form);
		rebuildInput(import_svg_form);
		rebuildInput(import_img_form);

		// Add forms to buttons
		$("#tool_open").show().prepend(open_svg_form);
		$("#tool_import").show().prepend(import_svg_form);
		$("#tool_image").prepend(import_img_form);
	}
});

<commit_msg>Change ext-server_opensave.js to work wholly client-side if download attribute supported (and JSLint in process)<commit_after>/*globals svgEditor, svgCanvas, canvg, $*/
/*
 * ext-server_opensave.js
 *
 * Licensed under the MIT License
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */

svgEditor.addExtension("server_opensave", {
	callback: function() {
        'use strict';
        function getFileNameFromTitle () {
            var title = svgCanvas.getDocumentTitle();
            return $.trim(title).replace(/[^a-z0-9\.\_\-]+/gi, '_');
        }
        function clientDownloadSupport (filename, suffix, uri) {
            var a,
                support = $('')[0].download === '';
            if (support) {
                a = $('hidden').attr({download: (filename || 'image') + suffix, href: uri}).css('display', 'none').appendTo('body');
                a[0].click();
                return true;
            }
        }
		var open_svg_action, import_svg_action, import_img_action,
            open_svg_form, import_svg_form, import_img_form,
            save_svg_action = 'extensions/filesave.php',
            save_img_action = 'extensions/filesave.php',
            // Create upload target (hidden iframe)
            cancelled = false;

        $('').hide().appendTo('body');
		svgEditor.setCustomHandlers({
			save: function(win, data) {
				var svg = "<?xml version=\"1.0\"?>\n" + data,
                    filename = getFileNameFromTitle();

                //if (clientDownloadSupport(filename, '.svg', 'data:image/svg+xml,' + encodeURI(data))) { // Firefox limits size of file
                if (clientDownloadSupport(filename, '.svg', 'data:image/svg+xml;base64,' + window.btoa(data))) {
                    return;
                }

				$('<form>').attr({
					method: 'post',
					action: save_svg_action,
					target: 'output_frame'
				})	.append('<input type="hidden" name="output_svg" value="' + encodeURI(svg) + '">')
					.append('<input type="hidden" name="filename" value="' + filename + '">')
					.appendTo('body')
					.submit().remove();
			},
			exportImage: function(win, data) {
				var c,
                    issues = data.issues,
                    mimeType = data.mimeType,
                    quality = data.quality;

				if(!$('#export_canvas').length) {
					$('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
				}
				c = $('#export_canvas')[0];

				c.width = svgCanvas.contentW;
				c.height = svgCanvas.contentH;
				canvg(c, data.svg, {renderCallback: function() {
					var pre, filename, suffix,
                        datauri = quality ? c.toDataURL(mimeType, quality) : c.toDataURL(mimeType),
                        uiStrings = svgEditor.uiStrings,
                        note = '';

					// Check if there's issues
					if(issues.length) {
						pre = "\n \u2022 ";
						note += ("\n\n" + pre + issues.join(pre));
					}

					if(note.length) {
						alert(note);
					}

					filename = getFileNameFromTitle();
                    suffix = '.' + data.type.toLowerCase();

                    if (clientDownloadSupport(filename, suffix, datauri)) {
                        return;
                    }

					$('<form>').attr({
						method: 'post',
						action: save_img_action,
						target: 'output_frame'
					})	.append('<input type="hidden" name="output_img" value="' + datauri + '">')
                        .append('<input type="hidden" name="mime" value="' + mimeType + '">')
						.append('<input type="hidden" name="filename" value="' + filename + '">')
						.appendTo('body')
						.submit().remove();
				}});

			}
		});

		// Do nothing if client support is found
		if(window.FileReader) {return;}

		// Change these to appropriate script file
		open_svg_action = 'extensions/fileopen.php?type=load_svg';
		import_svg_action = 'extensions/fileopen.php?type=import_svg';
		import_img_action = 'extensions/fileopen.php?type=import_img';

		// Set up function for PHP uploader to use
		svgEditor.processFile = function(str64, type) {
            var xmlstr;
			if(cancelled) {
				cancelled = false;
				return;
			}

			$('#dialog_box').hide();

			if (type !== 'import_img') {
				xmlstr = svgCanvas.Utils.decode64(str64);
			}

			switch (type) {
				case 'load_svg':
					svgCanvas.clear();
					svgCanvas.setSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_svg':
					svgCanvas.importSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_img':
					svgCanvas.setGoodImage(str64);
					break;
			}
		};

		// Create upload form
		open_svg_form = $('<form>');
		open_svg_form.attr({
			enctype: 'multipart/form-data',
			method: 'post',
			action: open_svg_action,
			target: 'output_frame'
		});

		// Create import form
		import_svg_form = open_svg_form.clone().attr('action', import_svg_action);

		// Create image form
		import_img_form = open_svg_form.clone().attr('action', import_img_action);

		// It appears necessory to rebuild this input every time a file is
		// selected so the same file can be picked and the change event can fire.
		function rebuildInput(form) {
			form.empty();
			var inp = $('<input type="file" name="svg_file">').appendTo(form);

			function submit() {
				// This submits the form, which returns the file data using svgEditor.uploadSVG
				form.submit();

				rebuildInput(form);
				$.process_cancel("Uploading...", function() {
					cancelled = true;
					$('#dialog_box').hide();
				});
			}

			if(form[0] == open_svg_form[0]) {
				inp.change(function() {
					// This takes care of the "are you sure" dialog box
					svgEditor.openPrep(function(ok) {
						if(!ok) {
							rebuildInput(form);
							return;
						}
						submit();
					});
				});
			} else {
				inp.change(function() {
					// This submits the form, which returns the file data using svgEditor.uploadSVG
					submit();
				});
			}
		}

		// Create the input elements
		rebuildInput(open_svg_form);
		rebuildInput(import_svg_form);
		rebuildInput(import_img_form);

		// Add forms to buttons
		$("#tool_open").show().prepend(open_svg_form);
		$("#tool_import").show().prepend(import_svg_form);
		$("#tool_image").prepend(import_img_form);
	}
});

<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import {Treebeard, decorators} from 'react-treebeard';
import {Form} from 'tabler-react';

const Header = ({style, node}) => {
  const iconType = node.children ? 'folder' : 'file';
  const iconClass = `fe fe-${iconType}`;
  const iconStyle = {marginRight: '5px'};

  return (

              {node.name}

  );
};

Header.propTypes = {
  style: PropTypes.object,
  node: PropTypes.object
};

decorators.Header = Header;

class FileExplorer extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      files: this.props.files
    };
  }

  onToggle(node, toggled){
    let oldNode = this.state.cursor;
    if(oldNode) {
      oldNode.active = false;
    }
    node.active = true;
    if(node.children) {
      node.toggled = toggled;
    } else {
      this.props.fetchFile(node);
    }
    this.setState({ cursor: node });
  }

  onHiddenToggle(value){
    this.setState({files: this.props.files.filter((file) => {
        return;
      })
    });
  }

  render(){
    return (
      <React.Fragment>
        <Form.Switch type="checkbox" name="toggle" value={true} label="Show hidden files" ref={(input) => { this.showHidden = input; }} onToggle={this.onHiddenToggle.bind(this)} />
        <Treebeard
          data={this.props.files}
          decorators={decorators}
          onToggle={this.onToggle.bind(this)}
        />
      </React.Fragment>
    );
  }
}

FileExplorer.propTypes = {
  files: PropTypes.array,
  fetchFile: PropTypes.func
};

export default FileExplorer;
<commit_msg>Finish adding show/hide of hidden files<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import {Treebeard, decorators} from 'react-treebeard';
import {Form} from 'tabler-react';

const Header = ({style, node}) => {
  const iconType = node.children ? 'folder' : 'file';
  const iconClass = `fe fe-${iconType}`;
  const iconStyle = {marginRight: '5px'};

  return (

        {node.name}

  );
};

Header.propTypes = {
  style: PropTypes.object,
  node: PropTypes.object
};

decorators.Header = Header;

class FileExplorer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showHidden: false
    };
  }

  onToggle(node, toggled) {
    node.active = true;
    if (node.children) {
      node.toggled = toggled;
    } else {
      this.props.fetchFile(node);
    }
    this.setState({cursor: node});
  }

  onHiddenToggle(e) {
    this.setState({showHidden: e.target.checked});
  }

  nodeEquals(a, b) {
    return a && b && a.path && b.path && a.name && b.name &&
      a.path === b.path &&
      a.name === b.name;
  }

  isNodeInPath(a, b) {
    return a && b && a.path && b.path &&
      a.path !== b.path &&
      b.path.indexOf(a.path) > -1;
  }

  filterHidden(nodes) {
    let filtered = [];
    if (!Array.isArray(nodes)) return filtered;

    // we need a foreach to build an array instead of a
    // filter to prevent mutating the original object (in props)
    nodes.forEach(node => {
      const {showHidden, cursor} = this.state;
      if (!showHidden && node.isHidden) return;
      let updatedNode = {...node};

      // if it's a folder, filter the children
      if (node.children) {
        let children = this.filterHidden(node.children);
        if (children.length) {
          updatedNode.children = children;
        }
      }

      // if this is the selected node, set it as active
      if (this.nodeEquals(node, cursor)) {
        updatedNode.active = cursor.active;
        // if this node has children, set it as toggled
        if (node.children) updatedNode.toggled = cursor.toggled;
      }
      // if this is a directory, and it lies in the path
      // of the selected node, ensure it's toggled
      if (node.children && this.isNodeInPath(node, cursor)) {
        updatedNode.toggled = true;
      }
      filtered.push(updatedNode);
    });

    return filtered;
  }

  render() {
    return (
      <React.Fragment>
        <Form.Switch type="checkbox" name="toggle" value={true} label="Show hidden files" onChange={this.onHiddenToggle.bind(this)} />
        <Treebeard
          data={this.filterHidden(this.props.files)}
          decorators={decorators}
          onToggle={this.onToggle.bind(this)}
        />
      </React.Fragment>
    );
  }
}

FileExplorer.propTypes = {
  files: PropTypes.array,
  fetchFile: PropTypes.func
};

export default FileExplorer;
<|endoftext|>